mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Store the hidden flag and allowed hosts on a secret
This commit is contained in:
1 parent
d7131dd895
commit
0a5c514062
9 files changed
+378
-23
No files matched your search
@@ -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
|
||||
@@ -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,
|
||||
]
|
||||
@@ -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)
|
||||
|
||||
@@ -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<typeof secretRowSchema>
|
||||
export interface ResolvedSecretValues {
|
||||
secrets: Record<string, string>
|
||||
vars: Record<string, string>
|
||||
hidden: Record<string, string[]>
|
||||
}
|
||||
|
||||
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<string, string> = {}
|
||||
const vars: Record<string, string> = {}
|
||||
const hidden: Record<string, string[]> = {}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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)')
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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<typeof SetSecretRequestSchema>
|
||||
|
||||
@@ -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<typeof SecretEntrySchema>
|
||||
|
||||
Reference in new issue
Block a user