From 0a5c51406224a5e0a063da53a34170bfa562d5a9 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:26:27 -0500 Subject: [PATCH] Store the hidden flag and allowed hosts on a secret --- .../202612031800-secrets-agent-hidden.ts | 20 +++++ backend/src/db/migrations/index.ts | 2 + backend/src/routes/secrets.ts | 5 +- backend/src/services/secrets.ts | 67 +++++++++++++-- .../db/secrets-agent-hidden-migration.test.ts | 73 +++++++++++++++++ .../test/db/secrets-scope-migration.test.ts | 11 +-- backend/test/routes/secrets.test.ts | 77 +++++++++++++++++ backend/test/services/secrets.test.ts | 82 ++++++++++++++++++- shared/src/schemas/secrets.ts | 64 ++++++++++++++- 9 files changed, 378 insertions(+), 23 deletions(-) create mode 100644 backend/src/db/migrations/202612031800-secrets-agent-hidden.ts create mode 100644 backend/test/db/secrets-agent-hidden-migration.test.ts diff --git a/backend/src/db/migrations/202612031800-secrets-agent-hidden.ts b/backend/src/db/migrations/202612031800-secrets-agent-hidden.ts new file mode 100644 index 00000000..e76c335c --- /dev/null +++ b/backend/src/db/migrations/202612031800-secrets-agent-hidden.ts @@ -0,0 +1,20 @@ +import { selectTableColumns } from '../rows' +import type { Migration } from '../migration-runner' + +const migration: Migration = { + id: '202612031800-secrets-agent-hidden', + up(db) { + const columns = selectTableColumns(db, 'secrets') + if (!columns.some((column) => column.name === 'agent_hidden')) { + db.run('ALTER TABLE secrets ADD COLUMN agent_hidden INTEGER NOT NULL DEFAULT 0') + } + if (!columns.some((column) => column.name === 'allowed_hosts')) { + db.run("ALTER TABLE secrets ADD COLUMN allowed_hosts TEXT NOT NULL DEFAULT '[]'") + } + }, + down(db) { + void db + }, +} + +export default migration diff --git a/backend/src/db/migrations/index.ts b/backend/src/db/migrations/index.ts index 65fd0e26..6f5224f1 100644 --- a/backend/src/db/migrations/index.ts +++ b/backend/src/db/migrations/index.ts @@ -44,6 +44,7 @@ import migration202610231200 from './202610231200-push-subscription-session-id' import migration202610251900 from './202610251900-schedule-sandbox-config' import migration202610271800 from './202610271800-schedule-show-in-inbox' import migration202610291200 from './202610291200-drop-session-goals' +import migration202612031800 from './202612031800-secrets-agent-hidden' export const allMigrations: Migration[] = [ migration001, @@ -91,4 +92,5 @@ export const allMigrations: Migration[] = [ migration202610251900, migration202610271800, migration202610291200, + migration202612031800, ] diff --git a/backend/src/routes/secrets.ts b/backend/src/routes/secrets.ts index 3956e437..8ea9462f 100644 --- a/backend/src/routes/secrets.ts +++ b/backend/src/routes/secrets.ts @@ -42,7 +42,10 @@ async function putEntry( if (!body.ok) return body.response try { - secretsService.set(kind, repoId, body.data.environment ?? null, name.name, body.data.value) + secretsService.set(kind, repoId, body.data.environment ?? null, name.name, body.data.value, { + agentHidden: body.data.agentHidden === true, + allowedHosts: body.data.allowedHosts ?? [], + }) return c.body(null, 204) } catch (error: unknown) { return handleServiceError(c, error, 'Failed to store secret', SecretsServiceError) diff --git a/backend/src/services/secrets.ts b/backend/src/services/secrets.ts index ca2bce60..38763cbf 100644 --- a/backend/src/services/secrets.ts +++ b/backend/src/services/secrets.ts @@ -18,6 +18,8 @@ const secretValueRowSchema = z.object({ environment: z.string(), name: z.string(), value: z.string(), + agent_hidden: z.number(), + allowed_hosts: z.string(), }) const secretRowSchema = secretValueRowSchema.extend({ updated_at: z.number() }) @@ -29,6 +31,16 @@ type SecretRow = z.infer export interface ResolvedSecretValues { secrets: Record vars: Record + hidden: Record +} + +function parseAllowedHosts(row: SecretValueRow): string[] | null { + try { + const parsed = z.array(z.string()).safeParse(JSON.parse(row.allowed_hosts)) + return parsed.success ? parsed.data : null + } catch { + return null + } } export class SecretsService { @@ -38,22 +50,42 @@ export class SecretsService { return this.selectRows(kind, repoId).map((row) => this.toEntry(kind, row)) } - set(kind: SecretKind, repoId: number | null, environment: string | null, name: string, value: string): void { + set( + kind: SecretKind, + repoId: number | null, + environment: string | null, + name: string, + value: string, + hidden: { agentHidden: boolean; allowedHosts: string[] } = { agentHidden: false, allowedHosts: [] }, + ): void { const normalizedEnvironment = environment ?? '' if (repoId === null && normalizedEnvironment !== '') { throw new SecretsServiceError('Environments are only supported for repository secrets', 400) } + if (kind === 'variable' && hidden.agentHidden) { + throw new SecretsServiceError('Only secrets can be hidden from agents', 400) + } const now = Date.now() const storedValue = kind === 'secret' ? encryptSecret(value) : value this.db .prepare( - `INSERT INTO secrets (kind, repo_id, environment, name, value, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(kind, COALESCE(repo_id, ${GLOBAL_SECRETS_SCOPE_ID}), environment, name) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`, + `INSERT INTO secrets (kind, repo_id, environment, name, value, agent_hidden, allowed_hosts, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(kind, COALESCE(repo_id, ${GLOBAL_SECRETS_SCOPE_ID}), environment, name) DO UPDATE SET value = excluded.value, agent_hidden = excluded.agent_hidden, allowed_hosts = excluded.allowed_hosts, updated_at = excluded.updated_at`, + ) + .run( + kind, + repoId, + normalizedEnvironment, + name, + storedValue, + hidden.agentHidden ? 1 : 0, + JSON.stringify(hidden.allowedHosts), + now, + now, ) - .run(kind, repoId, normalizedEnvironment, name, storedValue, now, now) } delete(kind: SecretKind, repoId: number | null, environment: string | null, name: string): boolean { @@ -68,7 +100,7 @@ export class SecretsService { const rows: SecretValueRow[] = secretValueRowSchema.array().parse( this.db .prepare( - `SELECT kind, repo_id, environment, name, value FROM secrets + `SELECT kind, repo_id, environment, name, value, agent_hidden, allowed_hosts FROM secrets WHERE repo_id IS NULL OR repo_id = ? ORDER BY CASE WHEN repo_id IS NULL THEN 0 WHEN environment = '' THEN 1 ELSE 2 END`, ) @@ -77,6 +109,7 @@ export class SecretsService { const secrets: Record = {} const vars: Record = {} + const hidden: Record = {} for (const row of rows) { if (row.repo_id !== null && row.environment !== '' && row.environment !== environment) { @@ -88,20 +121,31 @@ export class SecretsService { secrets[row.name] = decryptSecret(row.value) } catch { logger.warn(`Skipping secret "${row.name}" because it could not be decrypted`) + continue + } + + const allowedHosts = parseAllowedHosts(row) + if (allowedHosts === null) { + logger.warn(`Skipping hidden settings for secret "${row.name}" because its allowed hosts are invalid`) + delete hidden[row.name] + } else if (row.agent_hidden === 1) { + hidden[row.name] = allowedHosts + } else { + delete hidden[row.name] } } else { vars[row.name] = row.value } } - return { secrets, vars } + return { secrets, vars, hidden } } private selectRows(kind: SecretKind, repoId: number | null): SecretRow[] { return secretRowSchema.array().parse( this.db .prepare( - 'SELECT kind, repo_id, environment, name, value, updated_at FROM secrets WHERE kind = ? AND repo_id IS ? ORDER BY name', + 'SELECT kind, repo_id, environment, name, value, agent_hidden, allowed_hosts, updated_at FROM secrets WHERE kind = ? AND repo_id IS ? ORDER BY name', ) .all(kind, repoId), ) @@ -113,7 +157,12 @@ export class SecretsService { environment: row.environment === '' ? null : row.environment, updatedAt: row.updated_at, } - if (kind === 'variable') entry.value = row.value + if (kind === 'variable') { + entry.value = row.value + return entry + } + entry.agentHidden = row.agent_hidden === 1 + entry.allowedHosts = parseAllowedHosts(row) ?? [] return entry } } diff --git a/backend/test/db/secrets-agent-hidden-migration.test.ts b/backend/test/db/secrets-agent-hidden-migration.test.ts new file mode 100644 index 00000000..23183275 --- /dev/null +++ b/backend/test/db/secrets-agent-hidden-migration.test.ts @@ -0,0 +1,73 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest' +import { Database } from 'bun:sqlite' +import { z } from 'zod' +import { migrate } from '../../src/db/migration-runner' +import { allMigrations } from '../../src/db/migrations' +import migration from '../../src/db/migrations/202612031800-secrets-agent-hidden' +import { selectRow } from '../../src/db/rows' +import { SecretsService } from '../../src/services/secrets' +import { encryptSecret } from '../../src/utils/crypto' + +const MIGRATION_ID = '202612031800-secrets-agent-hidden' + +const SecretAgentHiddenRowSchema = z.object({ agent_hidden: z.number(), allowed_hosts: z.string() }) +const AppliedMigrationRowSchema = z.object({ id: z.string() }) + +function migrateBeforeAgentHidden(db: Database): void { + const index = allMigrations.findIndex((entry) => entry.id === MIGRATION_ID) + migrate(db, allMigrations.slice(0, index)) +} + +function insertSecret(db: Database, kind: 'secret' | 'variable', name: string, value: string): void { + const now = Date.now() + db.prepare( + 'INSERT INTO secrets (kind, repo_id, environment, name, value, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)', + ).run(kind, null, '', name, value, now, now) +} + +describe('secrets agent hidden migration', () => { + let db: Database + + beforeEach(() => { + db = new Database(':memory:') + }) + + afterEach(() => { + db.close() + }) + + it('adds the hidden columns with safe defaults for existing rows', () => { + migrateBeforeAgentHidden(db) + insertSecret(db, 'variable', 'LOG_LEVEL', 'debug') + + migrate(db, allMigrations) + + expect( + selectRow(db, SecretAgentHiddenRowSchema, 'SELECT agent_hidden, allowed_hosts FROM secrets WHERE name = ?', 'LOG_LEVEL'), + ).toEqual({ agent_hidden: 0, allowed_hosts: '[]' }) + expect( + selectRow(db, AppliedMigrationRowSchema, 'SELECT id FROM applied_migrations WHERE id = ?', MIGRATION_ID), + ).toEqual({ id: MIGRATION_ID }) + }) + + it('reads an existing secret as visible with no allowed hosts', () => { + migrateBeforeAgentHidden(db) + insertSecret(db, 'secret', 'TOKEN', encryptSecret('super-secret')) + + migrate(db, allMigrations) + + const service = new SecretsService(db) + const resolved = service.resolveValues(1, null) + expect(resolved.secrets.TOKEN).toBe('super-secret') + expect(resolved.hidden).toEqual({}) + expect(service.list('secret', null)).toEqual([ + expect.objectContaining({ name: 'TOKEN', agentHidden: false, allowedHosts: [] }), + ]) + }) + + it('does not re-add columns when applied again', () => { + migrate(db, allMigrations) + + expect(() => migration.up(db)).not.toThrow() + }) +}) diff --git a/backend/test/db/secrets-scope-migration.test.ts b/backend/test/db/secrets-scope-migration.test.ts index a3f43693..3bc68a32 100644 --- a/backend/test/db/secrets-scope-migration.test.ts +++ b/backend/test/db/secrets-scope-migration.test.ts @@ -8,7 +8,6 @@ import { SecretsService } from '../../src/services/secrets' import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' import { selectRow, selectRows } from '../../src/db/rows' -const SECRETS_TABLE_MIGRATION_ID = '202610181400-secrets' const SCOPE_INDEX_MIGRATION_ID = '202610181410-secrets-global-scope-index' const IndexSqlRowSchema = z.object({ sql: z.string() }) @@ -20,11 +19,6 @@ function scopeIndexSql(db: Database): string { 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 @@ -39,11 +33,12 @@ describe('secrets global scope index migration', () => { }) it('rebuilds the scope index so global and Assistant repository entries coexist', () => { - migrateThroughSecretsTable(db) + migrate(db, allMigrations) + secretsGlobalScopeIndexMigration.down(db) expect(scopeIndexSql(db)).toContain('COALESCE(repo_id, 0)') expect(() => service.set('variable', null, null, 'LOG_LEVEL', 'global')).toThrow(/ON CONFLICT/) - migrate(db, allMigrations) + secretsGlobalScopeIndexMigration.up(db) expect(scopeIndexSql(db)).toContain('COALESCE(repo_id, -1)') diff --git a/backend/test/routes/secrets.test.ts b/backend/test/routes/secrets.test.ts index 22a6dde1..bbf200fc 100644 --- a/backend/test/routes/secrets.test.ts +++ b/backend/test/routes/secrets.test.ts @@ -158,6 +158,83 @@ describe('secret routes', () => { expect((await app.request('/secrets/token', { method: 'DELETE' })).status).toBe(404) }) + it('stores an agent hidden secret with normalized allowed hosts and never returns its value', async () => { + const put = await app.request('/secrets/token', { + method: 'PUT', + headers: jsonHeaders, + body: JSON.stringify({ + value: 'super-secret', + agentHidden: true, + allowedHosts: [' API.Example.com ', '*.example.org', 'api.example.com'], + }), + }) + expect(put.status).toBe(204) + + const items = await readItems(await app.request('/secrets')) + expect(items).toEqual([ + expect.objectContaining({ + name: 'TOKEN', + environment: null, + agentHidden: true, + allowedHosts: ['api.example.com', '*.example.org'], + }), + ]) + expect(items[0]).not.toHaveProperty('value') + }) + + it('rejects invalid hidden secret host configuration', async () => { + const bodies = [ + { value: 'v', agentHidden: true }, + { value: 'v', agentHidden: true, allowedHosts: ['*'] }, + { value: 'v', agentHidden: true, allowedHosts: ['https://example.com'] }, + { value: 'v', agentHidden: true, allowedHosts: ['example.com:443'] }, + { value: 'v', agentHidden: true, allowedHosts: ['example.com/path'] }, + { value: 'v', agentHidden: true, allowedHosts: ['10.0.0.1'] }, + { + value: 'v', + agentHidden: true, + allowedHosts: Array.from({ length: 21 }, (_, index) => `host${index}.example.com`), + }, + { value: 'v', allowedHosts: ['example.com'] }, + ] + + for (const body of bodies) { + const res = await app.request('/secrets/token', { + method: 'PUT', + headers: jsonHeaders, + body: JSON.stringify(body), + }) + expect(res.status, JSON.stringify(body)).toBe(400) + expect(await res.json()).toMatchObject({ error: expect.any(String) }) + } + }) + + it('rejects hiding a variable', async () => { + const res = await app.request('/variables/log_level', { + method: 'PUT', + headers: jsonHeaders, + body: JSON.stringify({ value: 'debug', agentHidden: true, allowedHosts: ['example.com'] }), + }) + expect(res.status).toBe(400) + expect(await res.json()).toMatchObject({ error: 'Only secrets can be hidden from agents' }) + }) + + it('clears hidden settings when a secret is saved again without them', async () => { + await app.request('/secrets/token', { + method: 'PUT', + headers: jsonHeaders, + body: JSON.stringify({ value: 'v', agentHidden: true, allowedHosts: ['example.com'] }), + }) + await app.request('/secrets/token', { + method: 'PUT', + headers: jsonHeaders, + body: JSON.stringify({ value: 'v2' }), + }) + + const items = await readItems(await app.request('/secrets')) + expect(items).toEqual([expect.objectContaining({ name: 'TOKEN', agentHidden: false, allowedHosts: [] })]) + }) + it('stores repository secrets against the repo and never returns values', async () => { const repoId = seedRepo(db).id diff --git a/backend/test/services/secrets.test.ts b/backend/test/services/secrets.test.ts index 5afcc58e..802113f4 100644 --- a/backend/test/services/secrets.test.ts +++ b/backend/test/services/secrets.test.ts @@ -3,7 +3,7 @@ import { z } from 'zod' import type { Database } from 'bun:sqlite' import { selectRow } from '../../src/db/rows' import { SecretsService, SecretsServiceError } from '../../src/services/secrets' -import { decryptSecret } from '../../src/utils/crypto' +import { decryptSecret, encryptSecret } from '../../src/utils/crypto' import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' import { createTestDatabase } from '../helpers/test-database' import { testLogEntries } from '../helpers/log-assertions' @@ -140,6 +140,86 @@ describe('SecretsService', () => { expect(otherRepo.vars).toEqual({ VAR_GLOBAL: 'vg' }) }) + it('stores hidden settings for secrets and exposes them without values', () => { + service.set('secret', null, null, 'TOKEN', 'super-secret', { + agentHidden: true, + allowedHosts: ['api.example.com', '*.example.org'], + }) + + expect(service.list('secret', null)).toEqual([ + expect.objectContaining({ + name: 'TOKEN', + environment: null, + agentHidden: true, + allowedHosts: ['api.example.com', '*.example.org'], + }), + ]) + expect(service.list('secret', null)[0]).not.toHaveProperty('value') + expect(service.resolveValues(1, null).hidden).toEqual({ + TOKEN: ['api.example.com', '*.example.org'], + }) + }) + + it('clears hidden settings when an entry is saved without them', () => { + service.set('secret', null, null, 'TOKEN', 'first', { + agentHidden: true, + allowedHosts: ['api.example.com'], + }) + service.set('secret', null, null, 'TOKEN', 'second') + + expect(service.list('secret', null)).toEqual([ + expect.objectContaining({ name: 'TOKEN', agentHidden: false, allowedHosts: [] }), + ]) + expect(service.resolveValues(1, null).hidden).toEqual({}) + }) + + it('rejects hiding a variable', () => { + const error = catchThrownError(() => + service.set('variable', null, null, 'LOG_LEVEL', 'debug', { + agentHidden: true, + allowedHosts: ['api.example.com'], + }), + ) + + expect(error).toBeInstanceOf(SecretsServiceError) + expect(error instanceof SecretsServiceError ? error.statusCode : null).toBe(400) + }) + + it('reports hidden state from the winning scope', () => { + service.set('secret', null, null, 'SHARED', 'global', { + agentHidden: true, + allowedHosts: ['global.example.com'], + }) + service.set('secret', 7, null, 'SHARED', 'repo') + + expect(service.resolveValues(7, null).hidden).not.toHaveProperty('SHARED') + expect(service.resolveValues(8, null).hidden.SHARED).toEqual(['global.example.com']) + + service.set('secret', 7, 'prod', 'SHARED', 'prod', { + agentHidden: true, + allowedHosts: ['prod.example.com'], + }) + + expect(service.resolveValues(7, 'prod').hidden.SHARED).toEqual(['prod.example.com']) + expect(service.resolveValues(7, null).hidden).not.toHaveProperty('SHARED') + }) + + it('treats malformed allowed hosts as not hidden and logs only the name', () => { + const now = Date.now() + db.prepare( + 'INSERT INTO secrets (kind, repo_id, environment, name, value, agent_hidden, allowed_hosts, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', + ).run('secret', null, '', 'BROKEN_HOSTS', encryptSecret('super-secret'), 1, 'not-json', now, now) + + const resolved = service.resolveValues(1, null) + expect(resolved.secrets.BROKEN_HOSTS).toBe('super-secret') + expect(resolved.hidden).not.toHaveProperty('BROKEN_HOSTS') + + const warnings = testLogEntries('warn') + expect(warnings).toHaveLength(1) + expect(warnings[0]?.message).toContain('BROKEN_HOSTS') + expect(warnings[0]?.message).not.toContain('super-secret') + }) + it('skips a secret that cannot be decrypted and logs only its name', () => { const now = Date.now() db.prepare( diff --git a/shared/src/schemas/secrets.ts b/shared/src/schemas/secrets.ts index d10f17d3..c94c5f40 100644 --- a/shared/src/schemas/secrets.ts +++ b/shared/src/schemas/secrets.ts @@ -59,10 +59,64 @@ export const SecretValueSchema = z `Value must be at most ${SECRET_VALUE_MAX_BYTES} bytes`, ) -export const SetSecretRequestSchema = z.object({ - value: SecretValueSchema, - environment: EnvironmentNameSchema.optional(), -}) +export const SECRET_ALLOWED_HOSTS_MAX = 20 + +const SECRET_ALLOWED_HOST_MAX_LENGTH = 253 + +const ALLOWED_HOST_LABEL_PATTERN = '[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?' + +const ALLOWED_HOST_PATTERN = new RegExp( + `^(?:\\*\\.)?(?:${ALLOWED_HOST_LABEL_PATTERN}\\.)*${ALLOWED_HOST_LABEL_PATTERN}$`, + 'i', +) + +export const SecretAllowedHostSchema = z + .string() + .trim() + .superRefine((host, ctx) => { + if (host.length > SECRET_ALLOWED_HOST_MAX_LENGTH) { + ctx.addIssue({ code: 'custom', message: `Host must be at most ${SECRET_ALLOWED_HOST_MAX_LENGTH} characters` }) + return + } + if (!ALLOWED_HOST_PATTERN.test(host) || /^\d+$/.test(host.split('.').pop() ?? '')) { + ctx.addIssue({ + code: 'custom', + message: 'Host must be a hostname or a *.wildcard hostname without a scheme, port, path, or IP address', + }) + } + }) + .transform((host) => host.toLowerCase()) + +export const SetSecretRequestSchema = z + .object({ + value: SecretValueSchema, + environment: EnvironmentNameSchema.optional(), + agentHidden: z.boolean().optional(), + allowedHosts: z.array(SecretAllowedHostSchema).max(SECRET_ALLOWED_HOSTS_MAX).optional(), + }) + .superRefine((data, ctx) => { + const hosts = data.allowedHosts ?? [] + if (data.agentHidden === true) { + if (hosts.length === 0) { + ctx.addIssue({ + code: 'custom', + message: 'Hidden secrets require at least one allowed host', + path: ['allowedHosts'], + }) + } + return + } + if (hosts.length > 0) { + ctx.addIssue({ + code: 'custom', + message: 'Allowed hosts require agentHidden to be true', + path: ['allowedHosts'], + }) + } + }) + .transform((data) => + data.allowedHosts ? { ...data, allowedHosts: [...new Set(data.allowedHosts)] } : data, + ) export type SetSecretRequest = z.infer @@ -71,6 +125,8 @@ export const SecretEntrySchema = z.object({ environment: z.string().nullable(), updatedAt: z.number(), value: z.string().optional(), + agentHidden: z.boolean().optional(), + allowedHosts: z.array(z.string()).optional(), }) export type SecretEntry = z.infer