diff --git a/backend/src/db/migrations/202610181410-secrets-global-scope-index.ts b/backend/src/db/migrations/202610181410-secrets-global-scope-index.ts index 9e424ae8..47b0fa88 100644 --- a/backend/src/db/migrations/202610181410-secrets-global-scope-index.ts +++ b/backend/src/db/migrations/202610181410-secrets-global-scope-index.ts @@ -11,14 +11,47 @@ function rebuildScopeIndex(db: Database, globalScopeId: number): void { ) } -const migration: Migration = { +/** + * Deletes the rows the legacy scope key cannot hold. + * + * The legacy index merged global rows (`repo_id IS NULL`) with the Assistant repository's scope + * (`repo_id = 0`), and the old upsert let the last write win, so the newest row of each merged + * group is the state legacy code would hold. Ordering by `updated_at`, then `id`, keeps that row + * and deletes the rest, which lets the legacy unique index be recreated. + */ +function collapseLegacyScopeDuplicates(db: Database): void { + db.run(` + DELETE FROM secrets + WHERE (repo_id IS NULL OR repo_id = ${LEGACY_GLOBAL_SCOPE_ID}) + AND EXISTS ( + SELECT 1 + FROM secrets AS newer + WHERE (newer.repo_id IS NULL OR newer.repo_id = ${LEGACY_GLOBAL_SCOPE_ID}) + AND newer.kind = secrets.kind + AND newer.environment = secrets.environment + AND newer.name = secrets.name + AND ( + newer.updated_at > secrets.updated_at + OR (newer.updated_at = secrets.updated_at AND newer.id > secrets.id) + ) + ) + `) +} + +export const secretsGlobalScopeIndexMigration: Migration = { id: '202610181410-secrets-global-scope-index', up(db) { rebuildScopeIndex(db, GLOBAL_SECRETS_SCOPE_ID) }, down(db) { - rebuildScopeIndex(db, LEGACY_GLOBAL_SCOPE_ID) + db.run('BEGIN TRANSACTION') + try { + collapseLegacyScopeDuplicates(db) + rebuildScopeIndex(db, LEGACY_GLOBAL_SCOPE_ID) + db.run('COMMIT') + } catch (error) { + db.run('ROLLBACK') + throw error + } }, } - -export default migration diff --git a/backend/src/db/migrations/index.ts b/backend/src/db/migrations/index.ts index 3f2c7c2b..56feebfb 100644 --- a/backend/src/db/migrations/index.ts +++ b/backend/src/db/migrations/index.ts @@ -38,7 +38,7 @@ import migration202610181300 from './202610181300-session-server-scope' import migration202610181310 from './202610181310-multi-run-targets' import migration202610181320 from './202610181320-remote-schedule-targets' import migration202610181400 from './202610181400-secrets' -import migration202610181410 from './202610181410-secrets-global-scope-index' +import { secretsGlobalScopeIndexMigration } from './202610181410-secrets-global-scope-index' export const allMigrations: Migration[] = [ migration001, @@ -80,5 +80,5 @@ export const allMigrations: Migration[] = [ migration202610181310, migration202610181320, migration202610181400, - migration202610181410, + secretsGlobalScopeIndexMigration, ] diff --git a/backend/src/services/repo.ts b/backend/src/services/repo.ts index 46057a45..da349ebb 100644 --- a/backend/src/services/repo.ts +++ b/backend/src/services/repo.ts @@ -1210,6 +1210,11 @@ export async function resolveRepoProjectId(openCodeClient: OpenCodeClient, direc return project.id } +/** + * Resolves the registered repository a directory belongs to. Beyond the repository's own + * location, a directory is only attributed to a repository that shares its Git metadata, so a + * separate clone of the same origin, whose project id matches, is not mistaken for it. + */ export async function resolveRepoForDirectory( database: Database, directory: string, @@ -1225,13 +1230,22 @@ export async function resolveRepoForDirectory( const readyRepos = listRepos(database).filter( (candidate) => candidate.cloneStatus === 'ready', ) + const candidates: Repo[] = [] for (const candidate of readyRepos) { const candidateProjectId = await resolveProjectId(candidate.fullPath).catch( () => null, ) - if (candidateProjectId === projectId) return candidate + if (candidateProjectId === projectId) candidates.push(candidate) } - return null + if (candidates.length === 0) return null + + const mainCheckout = await resolveMainCheckoutPath(directory) + if (!mainCheckout) return null + const canonicalMainCheckout = canonicalPathSync(path.resolve(mainCheckout)) + + return candidates.find( + (candidate) => canonicalPathSync(path.resolve(candidate.fullPath)) === canonicalMainCheckout, + ) ?? null } export function resolveRepoOrAssistant(database: Database, id: number): Repo | null { diff --git a/backend/test/db/secrets-scope-migration.test.ts b/backend/test/db/secrets-scope-migration.test.ts index 19e7b4eb..f466fac7 100644 --- a/backend/test/db/secrets-scope-migration.test.ts +++ b/backend/test/db/secrets-scope-migration.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest' import { Database } from 'bun:sqlite' import { migrate } from '../../src/db/migration-runner' import { allMigrations } from '../../src/db/migrations' -import scopeIndexMigration from '../../src/db/migrations/202610181410-secrets-global-scope-index' +import { secretsGlobalScopeIndexMigration } from '../../src/db/migrations/202610181410-secrets-global-scope-index' import { SecretsService } from '../../src/services/secrets' import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' @@ -68,8 +68,24 @@ describe('secrets global scope index migration', () => { it('restores the legacy index expression on rollback', () => { migrate(db, allMigrations) - scopeIndexMigration.down(db) + secretsGlobalScopeIndexMigration.down(db) expect(scopeIndexSql(db)).toContain('COALESCE(repo_id, 0)') }) + + it('collapses merged global and Assistant scopes to the newest row on rollback', () => { + migrate(db, allMigrations) + service.set('secret', null, null, 'TOKEN', 'global-token') + service.set('secret', ASSISTANT_REPO_ID, null, 'TOKEN', 'assistant-token') + db.prepare('UPDATE secrets SET updated_at = ? WHERE repo_id IS NULL').run(1_000) + db.prepare('UPDATE secrets SET updated_at = ? WHERE repo_id = ?').run(2_000, ASSISTANT_REPO_ID) + + expect(() => secretsGlobalScopeIndexMigration.down(db)).not.toThrow() + + expect(scopeIndexSql(db)).toContain('COALESCE(repo_id, 0)') + expect( + db.prepare('SELECT repo_id, name, updated_at FROM secrets').all(), + ).toEqual([{ repo_id: ASSISTANT_REPO_ID, name: 'TOKEN', updated_at: 2_000 }]) + expect(service.resolveValues(ASSISTANT_REPO_ID, null).secrets.TOKEN).toBe('assistant-token') + }) }) diff --git a/backend/test/services/repo-env.test.ts b/backend/test/services/repo-env.test.ts index 2ad91319..9dca0d74 100644 --- a/backend/test/services/repo-env.test.ts +++ b/backend/test/services/repo-env.test.ts @@ -181,6 +181,27 @@ describe('RepoEnvService', () => { expect(result.env).toEqual({ PLAIN: 'literal' }) }) + it('does not resolve a separate clone of the same origin to the registered repo', async () => { + const root = createTempDir('ocm-repo-env-') + initGitRepo(root) + execSync(`git -C "${root}" remote add origin https://github.com/test/shared.git`) + writeProjectFile(root, { version: 1, env: { TOKEN: '${{ secrets.TOKEN }}' } }) + const repo = registerRepo(root) + secretsService.set('secret', repo.id, null, 'TOKEN', 'registered-token') + await trust(root, repo) + + const clone = createTempDir('ocm-repo-env-clone-') + initGitRepo(clone) + execSync(`git -C "${clone}" remote add origin https://github.com/test/shared.git`) + writeProjectFile(clone, { version: 1, env: { TOKEN: '${{ secrets.TOKEN }}' } }) + + expect(await repoEnvService.resolveForDirectory(clone)).toEqual(EMPTY) + expect(await repoEnvService.resolveForDirectory(root)).toEqual({ + env: { TOKEN: 'registered-token' }, + maskValues: ['registered-token'], + }) + }) + it('returns an empty result for a non-git directory', async () => { const plain = createTempDir('ocm-repo-env-plain-') diff --git a/backend/test/services/repo.test.ts b/backend/test/services/repo.test.ts index e0fe9499..e58c8059 100644 --- a/backend/test/services/repo.test.ts +++ b/backend/test/services/repo.test.ts @@ -666,12 +666,34 @@ describe('resolveRepoForDirectory', () => { resolveProjectId.mockImplementation(async (directory: string) => directory === workspaceDirectory || directory === repo.fullPath ? 'commit-A' : null, ) + executeCommand.mockImplementation(async (args: string[]) => + args.includes('--git-common-dir') ? path.join(repo.fullPath, '.git') : '', + ) const result = await resolveRepoForDirectory({} as never, workspaceDirectory) expect(result).toBe(repo) }) + it('returns null for a matching project id that is not the registered checkout', async () => { + const { resolveRepoForDirectory } = await import('../../src/services/repo') + const repo = createReadyRepo(1, 'repo-a') + const cloneDirectory = '/clones/repo-a' + getRepoBySourcePath.mockReturnValue(null) + getRepoByLocalPath.mockReturnValue(null) + listRepos.mockReturnValue([repo]) + resolveProjectId.mockImplementation(async (directory: string) => + directory === cloneDirectory || directory === repo.fullPath ? 'commit-A' : null, + ) + executeCommand.mockImplementation(async (args: string[]) => + args.includes('--git-common-dir') ? path.join(cloneDirectory, '.git') : '', + ) + + const result = await resolveRepoForDirectory({} as never, cloneDirectory) + + expect(result).toBeNull() + }) + it('returns null for a directory that matches no repo', async () => { const { resolveRepoForDirectory } = await import('../../src/services/repo') getRepoBySourcePath.mockReturnValue(null)