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.
This commit is contained in:
Chris Scott committed 2026-10-24 10:37:45 -04:00
1 parent 3e51280894
commit e3557f8eec
9 files changed
+153 -5

No files matched your search

@@ -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
+2
View File
@@ -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,
]
+6
View File
@@ -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)
+7
View File
@@ -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
+2 -2
View File
@@ -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
+2 -1
View File
@@ -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)
}
@@ -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)')
})
})
+16 -2
View File
@@ -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)
+19
View File
@@ -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')