mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
refactor: extract CredentialProvider service and consolidate git-auth utilities (#283)
* refactor: extract CredentialProvider service and consolidate git-auth utilities * refactor: add git-credentials route and gh env plugin, pass internal token to OpenCode * refactor: update credential provider integration and git route * refactor: integrate credential provider across git auth, routes, and IPC
This commit is contained in:
1 parent
ba08f5c24a
commit
7c8a4fe64c
31 files changed
+1136
-132
No files matched your search
@@ -0,0 +1,146 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { SettingsService } from '../../src/services/settings'
|
||||
import { CredentialProvider } from '../../src/services/credential-provider'
|
||||
import { AskpassHandler } from '../../src/ipc/askpassHandler'
|
||||
import { createRepo, setRepoGitCredentialId } from '../../src/db/queries'
|
||||
import type { GitCredential } from '@opencode-manager/shared'
|
||||
|
||||
function createGitHubPatCredential(token: string = 'ghp_test_token', id?: string): GitCredential {
|
||||
return {
|
||||
...(id ? { id } : {}),
|
||||
name: 'github-pat',
|
||||
host: 'github.com',
|
||||
type: 'pat' as const,
|
||||
username: 'x-access-token',
|
||||
token,
|
||||
} as GitCredential
|
||||
}
|
||||
|
||||
describe('AskpassHandler', () => {
|
||||
let db: Database
|
||||
let settingsService: SettingsService
|
||||
let provider: CredentialProvider
|
||||
let handler: AskpassHandler
|
||||
|
||||
beforeEach(() => {
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
settingsService = new SettingsService(db)
|
||||
settingsService.updateSettings({
|
||||
gitCredentials: [createGitHubPatCredential()],
|
||||
})
|
||||
provider = new CredentialProvider(db)
|
||||
handler = new AskpassHandler(undefined, provider)
|
||||
})
|
||||
|
||||
it('returns username on Username prompt for configured host', async () => {
|
||||
const result = await handler.handle({
|
||||
askpassType: 'https',
|
||||
argv: ['', '', "Username for 'https://github.com'", '', 'https://github.com'],
|
||||
})
|
||||
expect(result).toBe('x-access-token')
|
||||
})
|
||||
|
||||
it('returns token on Password prompt after Username (cache path)', async () => {
|
||||
// First call to populate cache
|
||||
await handler.handle({
|
||||
askpassType: 'https',
|
||||
argv: ['', '', "Username for 'https://github.com'", '', 'https://github.com'],
|
||||
})
|
||||
|
||||
// Second call should use cache
|
||||
const result = await handler.handle({
|
||||
askpassType: 'https',
|
||||
argv: ['', '', "Password for 'https://github.com'", '', 'https://github.com'],
|
||||
})
|
||||
expect(result).toBe('ghp_test_token')
|
||||
})
|
||||
|
||||
it('returns empty string for unknown host', async () => {
|
||||
const result = await handler.handle({
|
||||
askpassType: 'https',
|
||||
argv: ['', '', "Username for 'https://unknown.example.com'", '', 'https://unknown.example.com'],
|
||||
})
|
||||
expect(result).toBe('')
|
||||
})
|
||||
|
||||
it('returns the repo-specific token for askpass requests with repo cwd', async () => {
|
||||
const defaultCredential = createGitHubPatCredential('default-token', 'default-id')
|
||||
const repoCredential = createGitHubPatCredential('repo-token', 'repo-id')
|
||||
settingsService.updateSettings({
|
||||
gitCredentials: [defaultCredential, repoCredential],
|
||||
defaultGitCredentialId: 'default-id',
|
||||
})
|
||||
const repo = createRepo(db, {
|
||||
repoUrl: 'https://github.com/acme/repo.git',
|
||||
localPath: 'repo',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: Date.now(),
|
||||
})
|
||||
setRepoGitCredentialId(db, repo.id, 'repo-id')
|
||||
|
||||
await handler.handle({
|
||||
askpassType: 'https',
|
||||
argv: ['', '', "Username for 'https://github.com'", '', 'https://github.com'],
|
||||
cwd: repo.fullPath,
|
||||
})
|
||||
const result = await handler.handle({
|
||||
askpassType: 'https',
|
||||
argv: ['', '', "Password for 'https://github.com'", '', 'https://github.com'],
|
||||
cwd: repo.fullPath,
|
||||
})
|
||||
|
||||
expect(result).toBe('repo-token')
|
||||
})
|
||||
|
||||
it('keeps askpass cache separate per repo cwd', async () => {
|
||||
const repoOneCredential = createGitHubPatCredential('repo-one-token', 'repo-one-id')
|
||||
const repoTwoCredential = createGitHubPatCredential('repo-two-token', 'repo-two-id')
|
||||
settingsService.updateSettings({ gitCredentials: [repoOneCredential, repoTwoCredential] })
|
||||
const repoOne = createRepo(db, {
|
||||
repoUrl: 'https://github.com/acme/one.git',
|
||||
localPath: 'one',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: Date.now(),
|
||||
})
|
||||
const repoTwo = createRepo(db, {
|
||||
repoUrl: 'https://github.com/acme/two.git',
|
||||
localPath: 'two',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: Date.now(),
|
||||
})
|
||||
setRepoGitCredentialId(db, repoOne.id, 'repo-one-id')
|
||||
setRepoGitCredentialId(db, repoTwo.id, 'repo-two-id')
|
||||
|
||||
await handler.handle({
|
||||
askpassType: 'https',
|
||||
argv: ['', '', "Username for 'https://github.com'", '', 'https://github.com'],
|
||||
cwd: repoOne.fullPath,
|
||||
})
|
||||
await handler.handle({
|
||||
askpassType: 'https',
|
||||
argv: ['', '', "Username for 'https://github.com'", '', 'https://github.com'],
|
||||
cwd: repoTwo.fullPath,
|
||||
})
|
||||
|
||||
const repoOnePassword = await handler.handle({
|
||||
askpassType: 'https',
|
||||
argv: ['', '', "Password for 'https://github.com'", '', 'https://github.com'],
|
||||
cwd: repoOne.fullPath,
|
||||
})
|
||||
const repoTwoPassword = await handler.handle({
|
||||
askpassType: 'https',
|
||||
argv: ['', '', "Password for 'https://github.com'", '', 'https://github.com'],
|
||||
cwd: repoTwo.fullPath,
|
||||
})
|
||||
|
||||
expect(repoOnePassword).toBe('repo-one-token')
|
||||
expect(repoTwoPassword).toBe('repo-two-token')
|
||||
})
|
||||
})
|
||||
@@ -17,6 +17,10 @@ export class Database {
|
||||
}
|
||||
}
|
||||
|
||||
query(sql: string) {
|
||||
return this.prepare(sql)
|
||||
}
|
||||
|
||||
exec(sql: string) {
|
||||
this.db.exec(sql)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../../src/db/migrations'
|
||||
import { SettingsService } from '../../../src/services/settings'
|
||||
import { createInternalGitCredentialsRoutes } from '../../../src/routes/internal/git-credentials'
|
||||
import type { GitCredential } from '@opencode-manager/shared'
|
||||
|
||||
describe('internal git-credentials routes', () => {
|
||||
let db: Database
|
||||
let settingsService: SettingsService
|
||||
let app: ReturnType<typeof createInternalGitCredentialsRoutes>
|
||||
|
||||
beforeEach(() => {
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
settingsService = new SettingsService(db)
|
||||
app = createInternalGitCredentialsRoutes(db)
|
||||
})
|
||||
|
||||
it('GET /gh-env returns GH_TOKEN and GITHUB_TOKEN for a GitHub PAT', async () => {
|
||||
settingsService.updateSettings({
|
||||
gitCredentials: [
|
||||
{ name: 'github', host: 'github.com', type: 'pat', token: 'ghp_test_token' } as GitCredential,
|
||||
],
|
||||
})
|
||||
|
||||
const res = await app.request('/gh-env')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ GH_TOKEN: 'ghp_test_token', GITHUB_TOKEN: 'ghp_test_token' })
|
||||
})
|
||||
|
||||
it('GET /gh-env returns an empty object when no GitHub credential exists', async () => {
|
||||
const res = await app.request('/gh-env')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,181 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { SettingsService } from '../../src/services/settings'
|
||||
import { CredentialProvider } from '../../src/services/credential-provider'
|
||||
import { createRepo, setRepoGitCredentialId } from '../../src/db/queries'
|
||||
import type { GitCredential } from '@opencode-manager/shared'
|
||||
|
||||
function createPatCredential(name: string, host: string, token: string, username?: string, id?: string): GitCredential {
|
||||
return {
|
||||
...(id ? { id } : {}),
|
||||
name,
|
||||
host,
|
||||
token,
|
||||
...(username ? { username } : {}),
|
||||
} as GitCredential
|
||||
}
|
||||
|
||||
function createSshCredential(name: string, host: string, sshPrivateKeyEncrypted?: string): GitCredential {
|
||||
return {
|
||||
name,
|
||||
host,
|
||||
type: 'ssh',
|
||||
...(sshPrivateKeyEncrypted ? { sshPrivateKeyEncrypted } : {}),
|
||||
} as GitCredential
|
||||
}
|
||||
|
||||
describe('CredentialProvider', () => {
|
||||
let db: Database
|
||||
let settingsService: SettingsService
|
||||
let provider: CredentialProvider
|
||||
|
||||
beforeEach(() => {
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
settingsService = new SettingsService(db)
|
||||
provider = new CredentialProvider(db)
|
||||
})
|
||||
|
||||
describe('with seeded credentials', () => {
|
||||
const githubPat: GitCredential = createPatCredential('github-pat', 'github.com', 'ghp_test_token')
|
||||
const gitlabPat: GitCredential = createPatCredential('gitlab-pat', 'gitlab.com', 'glpat_test_token', 'custom-user')
|
||||
const githubSsh: GitCredential = createSshCredential('github-ssh', 'github.com')
|
||||
|
||||
beforeEach(() => {
|
||||
settingsService.updateSettings({ gitCredentials: [githubPat, gitlabPat, githubSsh] })
|
||||
})
|
||||
|
||||
it('getPatCredentialForHost returns the matching PAT credential', () => {
|
||||
const result = provider.getPatCredentialForHost('github.com')
|
||||
expect(result).toEqual({ username: 'x-access-token', password: 'ghp_test_token' })
|
||||
})
|
||||
|
||||
it('getPatCredentialForHost uses custom username when provided', () => {
|
||||
const result = provider.getPatCredentialForHost('gitlab.com')
|
||||
expect(result).toEqual({ username: 'custom-user', password: 'glpat_test_token' })
|
||||
})
|
||||
|
||||
it('getPatCredentialForHost returns null for unmatched host', () => {
|
||||
expect(provider.getPatCredentialForHost('bitbucket.org')).toBeNull()
|
||||
})
|
||||
|
||||
it('getPatCredentialForHost prefers the configured default PAT for the host', () => {
|
||||
const first = createPatCredential('first', 'github.com', 'first-token', undefined, 'first-id')
|
||||
const second = createPatCredential('second', 'github.com', 'second-token', undefined, 'second-id')
|
||||
settingsService.updateSettings({ gitCredentials: [first, second], defaultGitCredentialId: 'second-id' })
|
||||
|
||||
expect(provider.getPatCredentialForHost('github.com')).toEqual({ username: 'x-access-token', password: 'second-token' })
|
||||
})
|
||||
|
||||
it('getPatCredentialForHost prefers repo-specific PAT for the cwd', () => {
|
||||
const first = createPatCredential('first', 'github.com', 'first-token', undefined, 'first-id')
|
||||
const second = createPatCredential('second', 'github.com', 'second-token', undefined, 'second-id')
|
||||
settingsService.updateSettings({ gitCredentials: [first, second], defaultGitCredentialId: 'first-id' })
|
||||
const repo = createRepo(db, {
|
||||
repoUrl: 'https://github.com/acme/repo.git',
|
||||
localPath: 'repo',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: Date.now(),
|
||||
})
|
||||
setRepoGitCredentialId(db, repo.id, 'second-id')
|
||||
|
||||
expect(provider.getPatCredentialForHost('github.com', { cwd: repo.fullPath })).toEqual({ username: 'x-access-token', password: 'second-token' })
|
||||
})
|
||||
|
||||
it('getPatCredentialForHost ignores selected credentials for other hosts', () => {
|
||||
const github = createPatCredential('github', 'github.com', 'github-token', undefined, 'github-id')
|
||||
const gitlab = createPatCredential('gitlab', 'gitlab.com', 'gitlab-token', 'custom-user', 'gitlab-id')
|
||||
settingsService.updateSettings({ gitCredentials: [github, gitlab], defaultGitCredentialId: 'github-id' })
|
||||
|
||||
expect(provider.getPatCredentialForHost('gitlab.com')).toEqual({ username: 'custom-user', password: 'gitlab-token' })
|
||||
})
|
||||
|
||||
it('getGhCliEnv returns GH_TOKEN and GITHUB_TOKEN for GitHub PAT', () => {
|
||||
const env = provider.getGhCliEnv()
|
||||
expect(env).toEqual({ GH_TOKEN: 'ghp_test_token', GITHUB_TOKEN: 'ghp_test_token' })
|
||||
})
|
||||
|
||||
it('getGhCliEnv prefers the configured default GitHub PAT', () => {
|
||||
const first = createPatCredential('first', 'github.com', 'first-token', undefined, 'first-id')
|
||||
const second = createPatCredential('second', 'github.com', 'second-token', undefined, 'second-id')
|
||||
settingsService.updateSettings({ gitCredentials: [first, second], defaultGitCredentialId: 'second-id' })
|
||||
|
||||
expect(provider.getGhCliEnv()).toEqual({ GH_TOKEN: 'second-token', GITHUB_TOKEN: 'second-token' })
|
||||
})
|
||||
|
||||
it('getGhCliEnv prefers repo-specific GitHub PAT for the cwd', () => {
|
||||
const first = createPatCredential('first', 'github.com', 'first-token', undefined, 'first-id')
|
||||
const second = createPatCredential('second', 'github.com', 'second-token', undefined, 'second-id')
|
||||
settingsService.updateSettings({ gitCredentials: [first, second], defaultGitCredentialId: 'first-id' })
|
||||
const repo = createRepo(db, {
|
||||
repoUrl: 'https://github.com/acme/repo.git',
|
||||
localPath: 'repo',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: Date.now(),
|
||||
})
|
||||
setRepoGitCredentialId(db, repo.id, 'second-id')
|
||||
|
||||
expect(provider.getGhCliEnv({ cwd: repo.fullPath })).toEqual({ GH_TOKEN: 'second-token', GITHUB_TOKEN: 'second-token' })
|
||||
})
|
||||
|
||||
it('getGitEnv returns git config env for configured PATs', () => {
|
||||
const env = provider.getGitEnv()
|
||||
expect(env.GIT_TERMINAL_PROMPT).toBe('0')
|
||||
expect(env.GIT_CONFIG_COUNT).toBe('2')
|
||||
})
|
||||
|
||||
it('getSshCredentialsForHost returns SSH credentials and excludes PATs', () => {
|
||||
const sshCreds = provider.getSshCredentialsForHost('github.com')
|
||||
expect(sshCreds).toHaveLength(1)
|
||||
expect(sshCreds[0]).toMatchObject({ name: 'github-ssh', type: 'ssh' })
|
||||
})
|
||||
|
||||
it('getSshCredentialsForHost returns empty array for unmatched host', () => {
|
||||
expect(provider.getSshCredentialsForHost('gitlab.com')).toEqual([])
|
||||
})
|
||||
|
||||
it('getSshCredentialsWithPrivateKey returns only encrypted SSH credentials', () => {
|
||||
const encryptedSsh = createSshCredential('encrypted-ssh', 'example.com', 'encrypted-key')
|
||||
settingsService.updateSettings({ gitCredentials: [githubPat, githubSsh, encryptedSsh] })
|
||||
expect(provider.getSshCredentialsWithPrivateKey()).toEqual([encryptedSsh])
|
||||
})
|
||||
})
|
||||
|
||||
describe('with no credentials', () => {
|
||||
it('getPatCredentialForHost returns null', () => {
|
||||
expect(provider.getPatCredentialForHost('github.com')).toBeNull()
|
||||
})
|
||||
|
||||
it('getGhCliEnv returns empty object', () => {
|
||||
expect(provider.getGhCliEnv()).toEqual({})
|
||||
})
|
||||
|
||||
it('getGitEnv returns disabled terminal prompt defaults', () => {
|
||||
expect(provider.getGitEnv()).toEqual({ GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_COUNT: '0' })
|
||||
})
|
||||
|
||||
it('getSshCredentialsForHost returns empty array', () => {
|
||||
expect(provider.getSshCredentialsForHost('github.com')).toEqual([])
|
||||
})
|
||||
|
||||
it('getSshCredentialsWithPrivateKey returns empty array', () => {
|
||||
expect(provider.getSshCredentialsWithPrivateKey()).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('getGitCredentials', () => {
|
||||
it('returns empty array when no credentials are stored', () => {
|
||||
expect(provider.getGitCredentials()).toEqual([])
|
||||
})
|
||||
|
||||
it('returns all stored credentials', () => {
|
||||
const creds = [createPatCredential('test', 'example.com', 'tok'), createSshCredential('ssh-test', 'example.com')]
|
||||
settingsService.updateSettings({ gitCredentials: creds })
|
||||
expect(provider.getGitCredentials()).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -89,7 +89,7 @@ vi.mock('../ipc/ipcServer', () => ({
|
||||
IPCServer: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../ipc/askpassHandler', () => ({
|
||||
vi.mock('../../src/ipc/askpassHandler', () => ({
|
||||
AskpassHandler: vi.fn().mockImplementation(() => ({
|
||||
getEnv: vi.fn().mockReturnValue({}),
|
||||
})),
|
||||
@@ -103,6 +103,15 @@ vi.mock('../../src/ipc/sshHostKeyHandler', () => ({
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/credential-provider', () => ({
|
||||
CredentialProvider: vi.fn().mockImplementation(() => ({
|
||||
getGhCliEnv: vi.fn().mockReturnValue({}),
|
||||
getSshCredentialsForHost: vi.fn().mockReturnValue([]),
|
||||
getPatCredentialForHost: vi.fn().mockReturnValue(null),
|
||||
getGitCredentials: vi.fn().mockReturnValue([]),
|
||||
})),
|
||||
}))
|
||||
|
||||
describe('GitAuthService with passphrase support', () => {
|
||||
let gitAuthService: GitAuthService
|
||||
let mockIpcServer: IPCServer
|
||||
|
||||
@@ -49,6 +49,7 @@ describe('GitService', () => {
|
||||
let database: Database
|
||||
let mockGitAuthService: GitAuthService
|
||||
let mockSettingsService: any
|
||||
let mockCredentialProvider: any
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
@@ -70,7 +71,10 @@ describe('GitService', () => {
|
||||
},
|
||||
}),
|
||||
}
|
||||
service = new GitService(mockGitAuthService, mockSettingsService)
|
||||
mockCredentialProvider = {
|
||||
getGitCredentials: vi.fn().mockReturnValue([]),
|
||||
}
|
||||
service = new GitService(mockGitAuthService, mockSettingsService, mockCredentialProvider)
|
||||
})
|
||||
|
||||
describe('getStatus', () => {
|
||||
@@ -639,7 +643,7 @@ describe('GitService', () => {
|
||||
expect(getRepoById).toHaveBeenCalledWith(database, 1)
|
||||
expect(executeCommand).toHaveBeenCalledWith(
|
||||
['git', '-C', '/path/to/repo', 'push'],
|
||||
{ env: expect.any(Object) }
|
||||
{ env: expect.objectContaining({ OCM_GIT_REPO_ID: '1', OCM_GIT_REPO_CWD: '/path/to/repo' }) }
|
||||
)
|
||||
expect(result).toBe('Everything up-to-date')
|
||||
})
|
||||
@@ -681,6 +685,10 @@ describe('GitService', () => {
|
||||
|
||||
const result = await service.fetch(1, database)
|
||||
|
||||
expect(executeCommand).toHaveBeenCalledWith(
|
||||
['git', '-C', '/path/to/repo', 'fetch', '--all', '--prune'],
|
||||
{ env: expect.objectContaining({ OCM_GIT_REPO_ID: '1', OCM_GIT_REPO_CWD: '/path/to/repo' }) }
|
||||
)
|
||||
expect(result).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -700,6 +708,10 @@ describe('GitService', () => {
|
||||
|
||||
const result = await service.pull(1, database)
|
||||
|
||||
expect(executeCommand).toHaveBeenCalledWith(
|
||||
['git', '-C', '/path/to/repo', 'pull'],
|
||||
{ env: expect.objectContaining({ OCM_GIT_REPO_ID: '1', OCM_GIT_REPO_CWD: '/path/to/repo' }) }
|
||||
)
|
||||
expect(result).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { promises as fs } from 'fs'
|
||||
import path from 'path'
|
||||
import os from 'os'
|
||||
import { pathToFileURL } from 'url'
|
||||
import { installGhEnvPlugin, getGhEnvPluginDir } from '../../src/services/opencode-gh-env-plugin'
|
||||
|
||||
type ShellEnvHook = (
|
||||
input: { cwd: string },
|
||||
output: { env: Record<string, string> },
|
||||
) => Promise<void>
|
||||
type PluginFactory = () => Promise<{ 'shell.env': ShellEnvHook }>
|
||||
|
||||
async function loadPlugin(configHome: string): Promise<PluginFactory> {
|
||||
const file = path.join(getGhEnvPluginDir(configHome), 'ocm-gh-env.js')
|
||||
const mod = await import(pathToFileURL(file).href)
|
||||
return mod.default as PluginFactory
|
||||
}
|
||||
|
||||
describe('ocm-gh-env plugin', () => {
|
||||
let configHome: string
|
||||
|
||||
beforeEach(async () => {
|
||||
configHome = await fs.mkdtemp(path.join(os.tmpdir(), 'ocm-ghenv-'))
|
||||
await installGhEnvPlugin(configHome)
|
||||
process.env.OCM_INTERNAL_API_URL = 'http://localhost:5003/api/internal'
|
||||
process.env.OCM_INTERNAL_TOKEN = 'secret-token'
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
vi.unstubAllGlobals()
|
||||
delete process.env.OCM_INTERNAL_API_URL
|
||||
delete process.env.OCM_INTERNAL_TOKEN
|
||||
await fs.rm(configHome, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('writes the plugin file into the auto-discovery dir', async () => {
|
||||
const file = path.join(getGhEnvPluginDir(configHome), 'ocm-gh-env.js')
|
||||
await expect(fs.access(file)).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('injects fetched GH env into output.env', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ GH_TOKEN: 'ghp', GITHUB_TOKEN: 'ghp' }),
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const factory = await loadPlugin(configHome)
|
||||
const hooks = await factory()
|
||||
const output = { env: {} as Record<string, string> }
|
||||
await hooks['shell.env']({ cwd: '/repo' }, output)
|
||||
|
||||
expect(output.env).toEqual({ GH_TOKEN: 'ghp', GITHUB_TOKEN: 'ghp' })
|
||||
const [url, options] = fetchMock.mock.calls[0]!
|
||||
expect(url.toString()).toBe('http://localhost:5003/api/internal/git-credentials/gh-env?cwd=%2Frepo')
|
||||
expect(options).toEqual({ headers: { Authorization: 'Bearer secret-token' } })
|
||||
})
|
||||
|
||||
it('does not fetch when the internal env vars are missing', async () => {
|
||||
delete process.env.OCM_INTERNAL_API_URL
|
||||
delete process.env.OCM_INTERNAL_TOKEN
|
||||
const fetchMock = vi.fn()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const factory = await loadPlugin(configHome)
|
||||
const hooks = await factory()
|
||||
const output = { env: {} as Record<string, string> }
|
||||
await hooks['shell.env']({ cwd: '/repo' }, output)
|
||||
|
||||
expect(output.env).toEqual({})
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('never throws when the fetch fails', async () => {
|
||||
const fetchMock = vi.fn().mockRejectedValue(new Error('network down'))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const factory = await loadPlugin(configHome)
|
||||
const hooks = await factory()
|
||||
const output = { env: {} as Record<string, string> }
|
||||
|
||||
await expect(hooks['shell.env']({ cwd: '/repo' }, output)).resolves.toBeUndefined()
|
||||
expect(output.env).toEqual({})
|
||||
})
|
||||
|
||||
it('caches results within the TTL so rapid calls fetch once', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ GH_TOKEN: 'ghp', GITHUB_TOKEN: 'ghp' }),
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const factory = await loadPlugin(configHome)
|
||||
const hooks = await factory()
|
||||
const out1 = { env: {} as Record<string, string> }
|
||||
const out2 = { env: {} as Record<string, string> }
|
||||
await hooks['shell.env']({ cwd: '/repo' }, out1)
|
||||
await hooks['shell.env']({ cwd: '/repo' }, out2)
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
expect(out2.env).toEqual({ GH_TOKEN: 'ghp', GITHUB_TOKEN: 'ghp' })
|
||||
})
|
||||
|
||||
it('caches results per cwd', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ GH_TOKEN: 'ghp', GITHUB_TOKEN: 'ghp' }),
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const factory = await loadPlugin(configHome)
|
||||
const hooks = await factory()
|
||||
await hooks['shell.env']({ cwd: '/repo-a' }, { env: {} })
|
||||
await hooks['shell.env']({ cwd: '/repo-b' }, { env: {} })
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -179,7 +179,7 @@ describe('OpenCodeServerManager - server auth', () => {
|
||||
function createPasswordDb(password: string | null) {
|
||||
const encrypted = password ? encryptSecret(password) : null
|
||||
|
||||
return {
|
||||
const db = {
|
||||
prepare: vi.fn((sql: string) => ({
|
||||
get: (key?: string) => {
|
||||
if (key === 'opencode_server_password' && sql.includes('SELECT value FROM app_secrets') && encrypted) {
|
||||
@@ -190,7 +190,10 @@ describe('OpenCodeServerManager - server auth', () => {
|
||||
run: vi.fn(),
|
||||
all: vi.fn(() => []),
|
||||
})),
|
||||
} as any
|
||||
query: vi.fn((sql: string) => db.prepare(sql)),
|
||||
}
|
||||
|
||||
return db as any
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { fetchGitHubUserInfo, findGitHubCredential, resolveGitIdentity, createGitIdentityEnv, getSSHCredentialsForHost, createGitEnv, getDefaultUsername, normalizeHost } from '../../src/utils/git-auth'
|
||||
import { fetchGitHubUserInfo, findGitHubCredential, findPatCredentialForHost, resolveGitIdentity, createGitIdentityEnv, getSSHCredentialsForHost, createGitEnv, createGhCliEnv, getDefaultUsername, normalizeHost } from '../../src/utils/git-auth'
|
||||
import type { GitCredential } from '@opencode-manager/shared'
|
||||
|
||||
describe('fetchGitHubUserInfo', () => {
|
||||
@@ -239,6 +239,48 @@ describe('createGitEnv', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('createGhCliEnv', () => {
|
||||
it('returns GH_TOKEN and GITHUB_TOKEN set to the token for a github PAT', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'https://github.com/', type: 'pat', token: 'gh-cli-token' },
|
||||
]
|
||||
|
||||
const env = createGhCliEnv(credentials)
|
||||
|
||||
expect(env).toEqual({ GH_TOKEN: 'gh-cli-token', GITHUB_TOKEN: 'gh-cli-token' })
|
||||
})
|
||||
|
||||
it('returns {} when no github credential exists', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'gitlab', host: 'https://gitlab.com/', type: 'pat', token: 'gl-token' },
|
||||
]
|
||||
|
||||
const env = createGhCliEnv(credentials)
|
||||
|
||||
expect(env).toEqual({})
|
||||
})
|
||||
|
||||
it('returns {} when github credential has an empty token', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'https://github.com/', type: 'pat', token: '' },
|
||||
]
|
||||
|
||||
const env = createGhCliEnv(credentials)
|
||||
|
||||
expect(env).toEqual({})
|
||||
})
|
||||
|
||||
it('returns {} when only an ssh github credential exists', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github-ssh', host: 'git@github.com', type: 'ssh', sshPrivateKey: 'key' },
|
||||
]
|
||||
|
||||
const env = createGhCliEnv(credentials)
|
||||
|
||||
expect(env).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
describe('normalizeHost', () => {
|
||||
it('returns a URL-form host prefix for git url matching', () => {
|
||||
expect(normalizeHost('github.com')).toBe('https://github.com/')
|
||||
@@ -325,6 +367,79 @@ describe('findGitHubCredential', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('findPatCredentialForHost', () => {
|
||||
it('matches by hostname when stored as full https URL', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'https://github.com/owner/repo.git', type: 'pat', token: 'gh-token' },
|
||||
]
|
||||
|
||||
const result = findPatCredentialForHost(credentials, 'github.com')
|
||||
|
||||
expect(result).toEqual({ username: 'x-access-token', password: 'gh-token' })
|
||||
})
|
||||
|
||||
it('uses explicit username when provided', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'github.com', type: 'pat', token: 'gh-token', username: 'custom-user' },
|
||||
]
|
||||
|
||||
const result = findPatCredentialForHost(credentials, 'github.com')
|
||||
|
||||
expect(result).toEqual({ username: 'custom-user', password: 'gh-token' })
|
||||
})
|
||||
|
||||
it('returns x-access-token default for github hosts', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'github.com', type: 'pat', token: 'gh-token' },
|
||||
]
|
||||
|
||||
const result = findPatCredentialForHost(credentials, 'github.com')
|
||||
|
||||
expect(result?.username).toBe('x-access-token')
|
||||
})
|
||||
|
||||
it('returns oauth2 default for non-github hosts', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'gitlab', host: 'gitlab.com', type: 'pat', token: 'gl-token' },
|
||||
]
|
||||
|
||||
const result = findPatCredentialForHost(credentials, 'gitlab.com')
|
||||
|
||||
expect(result?.username).toBe('oauth2')
|
||||
})
|
||||
|
||||
it('ignores ssh credentials', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github-ssh', host: 'github.com', type: 'ssh', sshPrivateKey: 'key' },
|
||||
{ name: 'github-pat', host: 'github.com', type: 'pat', token: 'pat-token' },
|
||||
]
|
||||
|
||||
const result = findPatCredentialForHost(credentials, 'github.com')
|
||||
|
||||
expect(result).toEqual({ username: 'x-access-token', password: 'pat-token' })
|
||||
})
|
||||
|
||||
it('returns null when no credential matches the host', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'gitlab', host: 'gitlab.com', type: 'pat', token: 'gl-token' },
|
||||
]
|
||||
|
||||
const result = findPatCredentialForHost(credentials, 'github.com')
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('returns empty password when matched credential has no token', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'github.com', type: 'pat' },
|
||||
]
|
||||
|
||||
const result = findPatCredentialForHost(credentials, 'github.com')
|
||||
|
||||
expect(result).toEqual({ username: 'x-access-token', password: '' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveGitIdentity', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
Reference in new issue
Block a user