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,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
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
Reference in new issue
Block a user