From e3557f8eec5cfea25886a3646e4274daa60bb708 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 24 Oct 2026 10:37:45 -0400 Subject: [PATCH] fix(secrets): separate global from assistant-repo scope and require an exact repo root Global secrets used COALESCE(repo_id, 0), the same key as the Assistant repo (id 0), so same-named values overwrote each other. A new migration rebuilds idx_secrets_scope with a -1 sentinel shared with the upsert target, so databases that already applied the secrets migration upgrade cleanly. Repo env resolution now requires an exact registered git root, so an unregistered nested repository no longer receives its ancestor's secrets. --- ...202610181410-secrets-global-scope-index.ts | 24 ++++++ backend/src/db/migrations/index.ts | 2 + backend/src/db/queries.ts | 6 ++ backend/src/db/secrets-scope.ts | 7 ++ backend/src/services/repo-env.ts | 4 +- backend/src/services/secrets.ts | 3 +- .../test/db/secrets-scope-migration.test.ts | 75 +++++++++++++++++++ backend/test/services/repo-env.test.ts | 18 ++++- backend/test/services/secrets.test.ts | 19 +++++ 9 files changed, 153 insertions(+), 5 deletions(-) create mode 100644 backend/src/db/migrations/202610181410-secrets-global-scope-index.ts create mode 100644 backend/src/db/secrets-scope.ts create mode 100644 backend/test/db/secrets-scope-migration.test.ts diff --git a/backend/src/db/migrations/202610181410-secrets-global-scope-index.ts b/backend/src/db/migrations/202610181410-secrets-global-scope-index.ts new file mode 100644 index 00000000..9e424ae8 --- /dev/null +++ b/backend/src/db/migrations/202610181410-secrets-global-scope-index.ts @@ -0,0 +1,24 @@ +import type { Database } from 'bun:sqlite' +import type { Migration } from '../migration-runner' +import { GLOBAL_SECRETS_SCOPE_ID } from '../secrets-scope' + +const LEGACY_GLOBAL_SCOPE_ID = 0 + +function rebuildScopeIndex(db: Database, globalScopeId: number): void { + db.run('DROP INDEX IF EXISTS idx_secrets_scope') + db.run( + `CREATE UNIQUE INDEX idx_secrets_scope ON secrets(kind, COALESCE(repo_id, ${globalScopeId}), environment, name)`, + ) +} + +const migration: Migration = { + id: '202610181410-secrets-global-scope-index', + up(db) { + rebuildScopeIndex(db, GLOBAL_SECRETS_SCOPE_ID) + }, + down(db) { + rebuildScopeIndex(db, LEGACY_GLOBAL_SCOPE_ID) + }, +} + +export default migration diff --git a/backend/src/db/migrations/index.ts b/backend/src/db/migrations/index.ts index d47c80b9..3f2c7c2b 100644 --- a/backend/src/db/migrations/index.ts +++ b/backend/src/db/migrations/index.ts @@ -38,6 +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' export const allMigrations: Migration[] = [ migration001, @@ -79,4 +80,5 @@ export const allMigrations: Migration[] = [ migration202610181310, migration202610181320, migration202610181400, + migration202610181410, ] diff --git a/backend/src/db/queries.ts b/backend/src/db/queries.ts index e45e5812..602b3aa3 100644 --- a/backend/src/db/queries.ts +++ b/backend/src/db/queries.ts @@ -94,6 +94,12 @@ export function setRepoSandboxGitCredentials(db: Database, repoId: number, allow setRepoSetting(db, repoId, REPO_SANDBOX_GIT_CREDENTIALS_SETTING_KEY, allowed === null ? null : String(allowed)) } +export function getRepoByExactDirectory(db: Database, directory: string): Repo | null { + const resolvedDirectory = canonicalPathSync(path.resolve(directory)) + + return listRepos(db).find((repo) => canonicalPathSync(path.resolve(repo.fullPath)) === resolvedDirectory) ?? null +} + export function getRepoByDirectory(db: Database, directory: string): Repo | null { const resolvedDirectory = canonicalPathSync(path.resolve(directory)) const repos = listRepos(db) diff --git a/backend/src/db/secrets-scope.ts b/backend/src/db/secrets-scope.ts new file mode 100644 index 00000000..1e1a0e9d --- /dev/null +++ b/backend/src/db/secrets-scope.ts @@ -0,0 +1,7 @@ +/** + * Repo scope stored in place of a NULL `repo_id` for global secrets, so the unique scope index + * and its conflict target treat every global entry as one scope while repository scopes keep + * their own. Real repo ids are `0` (the Assistant repository) or positive, so a negative + * sentinel can never collide with one. + */ +export const GLOBAL_SECRETS_SCOPE_ID = -1 diff --git a/backend/src/services/repo-env.ts b/backend/src/services/repo-env.ts index ff786866..d4a9caec 100644 --- a/backend/src/services/repo-env.ts +++ b/backend/src/services/repo-env.ts @@ -3,7 +3,7 @@ import path from 'node:path' import type { Database } from 'bun:sqlite' import type { Repo } from '@opencode-manager/shared/types' import { interpolateEnvExpressions, type EnvExpressionReference } from '@opencode-manager/shared/utils' -import { getRepoByDirectory } from '../db/queries' +import { getRepoByExactDirectory } from '../db/queries' import { canonicalPathSync } from '../utils/fs-safe' import { logger } from '../utils/logger' import { repoEnvCacheEpoch } from '../utils/repo-env-cache' @@ -133,7 +133,7 @@ export class RepoEnvService { const topLevel = await findGitRepoRoot(cwd) const repo = topLevel - ? getRepoByDirectory(this.db, topLevel) ?? (await resolveRepoForDirectory(this.db, topLevel)) + ? getRepoByExactDirectory(this.db, topLevel) ?? (await resolveRepoForDirectory(this.db, topLevel)) : null const projectRepo = repo ? await this.projectConfigService.resolveProjectRepo(repo) : null diff --git a/backend/src/services/secrets.ts b/backend/src/services/secrets.ts index 13951261..ca38c526 100644 --- a/backend/src/services/secrets.ts +++ b/backend/src/services/secrets.ts @@ -1,5 +1,6 @@ import type { Database } from 'bun:sqlite' import type { SecretEntry, SecretKind } from '@opencode-manager/shared/schemas' +import { GLOBAL_SECRETS_SCOPE_ID } from '../db/secrets-scope' import { decryptSecret, encryptSecret } from '../utils/crypto' import { logger } from '../utils/logger' @@ -46,7 +47,7 @@ export class SecretsService { .prepare( `INSERT INTO secrets (kind, repo_id, environment, name, value, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(kind, COALESCE(repo_id, 0), environment, name) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`, + ON CONFLICT(kind, COALESCE(repo_id, ${GLOBAL_SECRETS_SCOPE_ID}), environment, name) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`, ) .run(kind, repoId, normalizedEnvironment, name, storedValue, now, now) } diff --git a/backend/test/db/secrets-scope-migration.test.ts b/backend/test/db/secrets-scope-migration.test.ts new file mode 100644 index 00000000..19e7b4eb --- /dev/null +++ b/backend/test/db/secrets-scope-migration.test.ts @@ -0,0 +1,75 @@ +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 { SecretsService } from '../../src/services/secrets' +import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' + +const SECRETS_TABLE_MIGRATION_ID = '202610181400-secrets' +const SCOPE_INDEX_MIGRATION_ID = '202610181410-secrets-global-scope-index' + +function scopeIndexSql(db: Database): string { + const row = db + .prepare("SELECT sql FROM sqlite_master WHERE type = 'index' AND name = 'idx_secrets_scope'") + .get() as { sql: string } | null + + return row?.sql ?? '' +} + +function migrateThroughSecretsTable(db: Database): void { + const index = allMigrations.findIndex((migration) => migration.id === SECRETS_TABLE_MIGRATION_ID) + migrate(db, allMigrations.slice(0, index + 1)) +} + +describe('secrets global scope index migration', () => { + let db: Database + let service: SecretsService + + beforeEach(() => { + db = new Database(':memory:') + service = new SecretsService(db) + }) + + afterEach(() => { + db.close() + }) + + it('rebuilds the scope index so global and Assistant repository entries coexist', () => { + migrateThroughSecretsTable(db) + expect(scopeIndexSql(db)).toContain('COALESCE(repo_id, 0)') + expect(() => service.set('variable', null, null, 'LOG_LEVEL', 'global')).toThrow(/ON CONFLICT/) + + migrate(db, allMigrations) + + expect(scopeIndexSql(db)).toContain('COALESCE(repo_id, -1)') + + service.set('variable', null, null, 'LOG_LEVEL', 'global') + service.set('variable', ASSISTANT_REPO_ID, null, 'LOG_LEVEL', 'assistant') + service.set('variable', null, null, 'LOG_LEVEL', 'global-updated') + service.set('variable', ASSISTANT_REPO_ID, null, 'LOG_LEVEL', 'assistant-updated') + + expect(service.list('variable', null)).toEqual([ + expect.objectContaining({ name: 'LOG_LEVEL', value: 'global-updated' }), + ]) + expect(service.list('variable', ASSISTANT_REPO_ID)).toEqual([ + expect.objectContaining({ name: 'LOG_LEVEL', value: 'assistant-updated' }), + ]) + }) + + it('applies the scope index migration on a fresh database', () => { + migrate(db, allMigrations) + + const applied = db.prepare('SELECT id FROM applied_migrations WHERE id = ?').get(SCOPE_INDEX_MIGRATION_ID) + expect(applied).toBeTruthy() + expect(scopeIndexSql(db)).toContain('COALESCE(repo_id, -1)') + }) + + it('restores the legacy index expression on rollback', () => { + migrate(db, allMigrations) + + scopeIndexMigration.down(db) + + expect(scopeIndexSql(db)).toContain('COALESCE(repo_id, 0)') + }) +}) diff --git a/backend/test/services/repo-env.test.ts b/backend/test/services/repo-env.test.ts index c62e05bc..2ad91319 100644 --- a/backend/test/services/repo-env.test.ts +++ b/backend/test/services/repo-env.test.ts @@ -44,11 +44,11 @@ describe('RepoEnvService', () => { return dir } - function initGitRepo(dir: string): void { + function initGitRepo(dir: string, message = 'Initial commit'): void { execSync(`git init "${dir}"`) execSync(`git -C "${dir}" config user.email test@test.com`) execSync(`git -C "${dir}" config user.name Test`) - execSync(`git -C "${dir}" commit --allow-empty -m "Initial commit"`) + execSync(`git -C "${dir}" commit --allow-empty -m "${message}"`) } function writeProjectFile(dir: string, content: unknown): void { @@ -150,6 +150,20 @@ describe('RepoEnvService', () => { expect(result.env).toEqual({ PLAIN: 'literal' }) }) + it('ignores an unregistered nested git root inside a registered repository', async () => { + const root = createTempDir('ocm-repo-env-') + initGitRepo(root) + const repo = registerRepo(root) + secretsService.set('secret', repo.id, null, 'TOKEN', 'root-token') + const nested = path.join(root, 'packages', 'nested') + fs.mkdirSync(nested, { recursive: true }) + initGitRepo(nested, 'Nested initial commit') + writeProjectFile(nested, { version: 1, env: { TOKEN: '${{ secrets.TOKEN }}' } }) + await trust(nested, repo) + + expect(await repoEnvService.resolveForDirectory(nested)).toEqual(EMPTY) + }) + it('resolves a git worktree outside the repository folder to the main repo', async () => { const root = createTempDir('ocm-repo-env-') initGitRepo(root) diff --git a/backend/test/services/secrets.test.ts b/backend/test/services/secrets.test.ts index be70ee4c..1cc43df2 100644 --- a/backend/test/services/secrets.test.ts +++ b/backend/test/services/secrets.test.ts @@ -5,6 +5,7 @@ import { allMigrations } from '../../src/db/migrations' import { SecretsService, SecretsServiceError } from '../../src/services/secrets' import { decryptSecret } from '../../src/utils/crypto' import { logger } from '../../src/utils/logger' +import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' function createTestDb(): Database { const db = new Database(':memory:') @@ -106,6 +107,24 @@ describe('SecretsService', () => { ) }) + it('keeps global and Assistant repository entries with the same name independent', () => { + service.set('variable', null, null, 'LOG_LEVEL', 'global') + service.set('variable', ASSISTANT_REPO_ID, null, 'LOG_LEVEL', 'assistant') + + expect(service.list('variable', null)).toEqual([ + expect.objectContaining({ name: 'LOG_LEVEL', value: 'global' }), + ]) + expect(service.list('variable', ASSISTANT_REPO_ID)).toEqual([ + expect.objectContaining({ name: 'LOG_LEVEL', value: 'assistant' }), + ]) + + service.set('variable', null, null, 'LOG_LEVEL', 'global-updated') + service.set('variable', ASSISTANT_REPO_ID, null, 'LOG_LEVEL', 'assistant-updated') + + expect(service.list('variable', null)[0]?.value).toBe('global-updated') + expect(service.list('variable', ASSISTANT_REPO_ID)[0]?.value).toBe('assistant-updated') + }) + it('resolves values with global < repository < repository+environment precedence', () => { service.set('secret', null, null, 'GLOBAL_ONLY', 'g') service.set('secret', 7, null, 'SHARED', 'repo')