mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
fix(secrets): collapse legacy scope duplicates on rollback and verify repo worktrees
Rolling back the scope-index migration now keeps the newest of a colliding global and Assistant-repo secret, matching the legacy last-write-wins upsert, so the legacy unique index can be recreated. The repo-env fallback now returns a registered repo only when the directory shares its Git metadata, so a separate clone of the same origin no longer receives the registered repo's secrets; external worktrees still resolve. The migration uses a named export.
This commit is contained in:
1 parent
e3557f8eec
commit
21c60edd09
6 files changed
+116
-10
No files matched your search
@@ -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
|
||||
@@ -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,
|
||||
]
|
||||
@@ -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 {
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -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-')
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user