mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
Merge cloud/integration into SEC-6 (KMS unwrapper; kms_unavailable log via secretLog)
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -48,7 +48,7 @@ nudge_once() {
|
||||
local mark="${ORCA_GIT_NUDGE_DIR:-/dev/shm}/orca-git-nudge-$(id -u)"
|
||||
[ -e "$mark" ] && return 0
|
||||
: >"$mark" 2>/dev/null || return 0
|
||||
printf '%s\n' "orca: This commit uses Orca Cloud's name. Connect your GitHub in Settings › Account to use yours." >&2
|
||||
printf '%s\n' "orca: This commit uses Orca Cloud's name. Connect your GitHub in Settings → Account to use yours." >&2
|
||||
}
|
||||
# PUSH-RAW-PROMPT: a push, pull or fetch to github.com that no credential covers (neither the person's
|
||||
# connected GitHub nor the App installation) must never fall through to git's own "Username for
|
||||
@@ -91,7 +91,7 @@ github_remote_slug() {
|
||||
no_access_line() {
|
||||
local owner="${github_slug%%/*}" verb='push to'
|
||||
[ "$sub" = push ] || verb='read'
|
||||
printf '%s\n' "orca: Orca Cloud can't $verb $github_slug. Install the Orca GitHub App on $owner, or connect your GitHub in Settings › Account." >&2
|
||||
printf '%s\n' "orca: Orca Cloud can't $verb $github_slug. Install the Orca GitHub App on $owner, or connect your GitHub in Settings → Account." >&2
|
||||
}
|
||||
# GitHub's "not found" is a typo'd name or a private repo it won't confirm: say which half fits whom.
|
||||
not_found_line() {
|
||||
|
||||
@@ -99,6 +99,21 @@ export type Env = {
|
||||
SECRETS_KEK?: string
|
||||
SECRETS_KEK_ID?: string
|
||||
SECRETS_KEK_RETIRED?: string
|
||||
/**
|
||||
* `kms`: the KEKs are held encrypted by a Google Cloud KMS key and unwrapped once per isolate
|
||||
* (src/secrets-kms.ts). Unset (default): SECRETS_KEK / SECRETS_KEK_RETIRED above, unchanged.
|
||||
* With `kms`, SECRETS_KEK and SECRETS_KEK_RETIRED are ignored, and a KMS failure answers 503
|
||||
* `secrets_unavailable` (sessions do not start without their secrets).
|
||||
* SECRETS_KMS_KEY projects/<p>/locations/<l>/keyRings/<r>/cryptoKeys/<k>
|
||||
* SECRETS_KMS_SERVICE_ACCOUNT (secret) service-account JSON allowed to decrypt with that key only
|
||||
* SECRETS_KEK_WRAPPED base64 KMS ciphertext of the active KEK's 32 bytes, AAD `orca-secrets-kek:<id>`
|
||||
* SECRETS_KEK_RETIRED_WRAPPED JSON {"<id>":"<base64 KMS ciphertext>"} after a rotation
|
||||
*/
|
||||
SECRETS_KEK_SOURCE?: string
|
||||
SECRETS_KMS_KEY?: string
|
||||
SECRETS_KMS_SERVICE_ACCOUNT?: string
|
||||
SECRETS_KEK_WRAPPED?: string
|
||||
SECRETS_KEK_RETIRED_WRAPPED?: string
|
||||
/**
|
||||
* `v1` (default) | `v2`: the row format new secrets are sealed in (src/secrets-crypto.ts). With
|
||||
* v2 a KEK rotation re-wraps data keys only. Set it only once every Worker version that reads this
|
||||
|
||||
@@ -119,6 +119,7 @@ import { DEFAULT_RETENTION, type RetentionConfig } from './retention'
|
||||
import { reconcile } from './reconcile'
|
||||
import { egressAccountRoutes, egressSecretHosts, placeholderValues, secretPlaceholder } from './secret-egress'
|
||||
import { SecretError, handleSecretsRoute, keyringFor, type SecretChange } from './secrets'
|
||||
import { SecretsKmsError } from './secrets-kms'
|
||||
import { refreshAfterSecretChange, refreshSandboxEnv } from './env-refresh'
|
||||
import { ACCOUNT_PROVIDERS, accountProvider, isSharedWorkspace } from './account-providers'
|
||||
import { handleAccountUnauthorized, verifyAccountCredential } from './agent-credential-checks'
|
||||
@@ -880,7 +881,7 @@ export async function lifecycleDeps(env: Env, deps: Deps): Promise<LifecycleDeps
|
||||
provider,
|
||||
entitlements: deps.entitlements ?? withDevAccountBypass(env, createEntitlementClient(env)),
|
||||
github: deps.github ?? githubMinter(env),
|
||||
secrets: await secretsDeps(env),
|
||||
...(await secretsState(env)),
|
||||
memberIdentity: await memberIdentityFor(env, deps),
|
||||
now: deps.now ?? Date.now,
|
||||
sleep: deps.sleep,
|
||||
@@ -1113,17 +1114,22 @@ export function secretsEgressMode(env: Pick<Env, 'SECRETS_EGRESS_PLACEHOLDERS' |
|
||||
return { egressPlaceholders, egressPlaceholdersOff: off }
|
||||
}
|
||||
|
||||
async function secretsDeps(env: Env): Promise<LifecycleDeps['secrets']> {
|
||||
async function secretsState(env: Env): Promise<Pick<LifecycleDeps, 'secrets' | 'secretsUnavailable'>> {
|
||||
const keyring = keyringFor(env)
|
||||
if (!keyring) {
|
||||
return undefined
|
||||
return {}
|
||||
}
|
||||
try {
|
||||
return { keyring: await keyring, ...secretsEgressMode(env), accountProviders: providerEnabled(env) }
|
||||
} catch {
|
||||
return { secrets: { keyring: await keyring, ...secretsEgressMode(env), accountProviders: providerEnabled(env) } }
|
||||
} catch (error) {
|
||||
if (error instanceof SecretsKmsError) {
|
||||
// KMS holds the keys and is not handing them over. Routes that need no secrets keep working;
|
||||
// a session start and the secrets routes answer 503 (keyringFor logged the reason).
|
||||
return { secretsUnavailable: error.reason }
|
||||
}
|
||||
// A malformed KEK must not block sandbox starts; the secrets routes surface it as 503.
|
||||
console.log(JSON.stringify({ event: 'secrets_kek_invalid' }))
|
||||
return undefined
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1552,7 +1558,10 @@ async function routeRequest(request: Request, env: Env, deps: Deps): Promise<Res
|
||||
// ORG-TOKEN-STALE: minted before this member's role changed; the desktop re-mints and retries.
|
||||
return fail('unauthorized', 401, 'stale_token')
|
||||
}
|
||||
const secrets = await secretsDeps(env)
|
||||
const { secrets, secretsUnavailable } = await secretsState(env)
|
||||
if (secretsUnavailable) {
|
||||
return secretsUnavailableResponse()
|
||||
}
|
||||
if (!secrets) {
|
||||
return fail('not_configured', 503)
|
||||
}
|
||||
@@ -2315,6 +2324,13 @@ async function githubReturn(env: Env, deps: Deps, url: URL): Promise<Response> {
|
||||
}
|
||||
}
|
||||
|
||||
/** The KMS-held secret keys cannot be fetched right now (SECRETS_KEK_SOURCE=kms). Retryable. */
|
||||
function secretsUnavailableResponse(): Response {
|
||||
const response = fail('secrets_unavailable', 503)
|
||||
response.headers.set('retry-after', '30')
|
||||
return response
|
||||
}
|
||||
|
||||
function errorResponse(error: unknown): Response {
|
||||
if (error instanceof SyntaxError) {
|
||||
return fail('invalid_json', 400)
|
||||
@@ -2354,6 +2370,9 @@ function errorResponse(error: unknown): Response {
|
||||
if (error instanceof BillingUnavailableError) {
|
||||
return fail('billing_unavailable', 503)
|
||||
}
|
||||
if (error instanceof SecretsKmsError) {
|
||||
return secretsUnavailableResponse()
|
||||
}
|
||||
// Provider and VM failures are summarized; their bodies never reach the desktop.
|
||||
if (error instanceof ProviderError || error instanceof VmCommandError) {
|
||||
return fail('provider_unavailable', 502, error instanceof VmCommandError ? error.code : undefined)
|
||||
|
||||
@@ -24,6 +24,7 @@ import { ProviderError, type ProviderSandboxState, type SandboxProviderApi } fro
|
||||
import { egressAccountRoutes, egressSecretHosts, placeholderValues, secretPlaceholder } from './secret-egress'
|
||||
import { egressAllowHosts, sessionSecretEnv, type SessionSecrets } from './session-env'
|
||||
import type { Keyring } from './secrets-crypto'
|
||||
import type { SecretsKmsReason } from './secrets-kms'
|
||||
import { captureReadSnapshot, deleteReadSnapshot } from './read-snapshots'
|
||||
import {
|
||||
ORCAD_PORT,
|
||||
@@ -89,6 +90,8 @@ export type LifecycleDeps = {
|
||||
* egressPlaceholders: every account (`true`) or only the listed account ids (staged rollout);
|
||||
* egressPlaceholdersOff: per-account kill switch that wins over both.
|
||||
*/
|
||||
/** Set while the KMS-held keys cannot be fetched: a session start fails instead of running without its secrets. */
|
||||
secretsUnavailable?: SecretsKmsReason
|
||||
secrets?: {
|
||||
keyring: Keyring
|
||||
egressPlaceholders: boolean | ReadonlySet<string>
|
||||
|
||||
@@ -23,6 +23,7 @@ import { drainAll, housekeeping } from './retention'
|
||||
import { memberChangeTime, recordMemberChange } from './member-changes'
|
||||
import { memberEventActor, memberEventTarget, removeMember } from './member-removal'
|
||||
import type { Keyring } from './secrets-crypto'
|
||||
import { SecretsKmsError } from './secrets-kms'
|
||||
import { kekStatus, rewrapBatch, RewrapError, REWRAP_MAX_LIMIT } from './secrets-rewrap'
|
||||
import { fairUseReport, FAIR_USE_WINDOW_DAYS, sweepSessionCpu } from './session-cpu'
|
||||
import { listByStatus } from './store'
|
||||
@@ -174,7 +175,10 @@ export async function handleOperator(
|
||||
let keyring: Keyring | null
|
||||
try {
|
||||
keyring = (await deps.keyring?.()) ?? null
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (error instanceof SecretsKmsError) {
|
||||
return Response.json({ error: 'secrets_unavailable', reason: error.reason }, { status: 503, headers: noStore })
|
||||
}
|
||||
// A malformed SECRETS_KEK* value. The cause is not echoed: it could quote key material.
|
||||
return Response.json({ error: 'secrets_misconfigured' }, { status: 503, headers: noStore })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
// Google Cloud KMS unwrap of the secret store's KEKs (SECRETS_KEK_SOURCE=kms; off by default).
|
||||
// The Worker then holds no plaintext KEK in its config: it holds each KEK encrypted by a KMS key
|
||||
// (SECRETS_KEK_WRAPPED) and a service account that may only decrypt with that key. keyringFor
|
||||
// (secrets.ts) unwraps once per isolate and keeps the imported keys in memory.
|
||||
// Each wrapped KEK is bound to its key id through KMS additional authenticated data, so a blob
|
||||
// deployed under the wrong id fails to unwrap instead of sealing rows under a mislabelled key.
|
||||
// Nothing from a KMS or token response is logged or put in an error: only a reason and a status.
|
||||
import { SignJWT, importPKCS8 } from 'jose'
|
||||
import { z } from 'zod'
|
||||
|
||||
export type SecretsKmsReason =
|
||||
/** SECRETS_KEK_SOURCE=kms but a KMS setting is missing or malformed. */
|
||||
| 'config'
|
||||
/** Google refused the service account or its permission on the key (401/403). */
|
||||
| 'denied'
|
||||
/** KMS rejected the wrapped KEK: wrong key, wrong KEK id, or a corrupted blob (400/404). */
|
||||
| 'invalid'
|
||||
/** KMS or the token endpoint could not be reached, timed out or answered 5xx. */
|
||||
| 'unavailable'
|
||||
|
||||
/** The secret store cannot get its keys right now. Callers answer 503; they never fall back to another key. */
|
||||
export class SecretsKmsError extends Error {
|
||||
constructor(
|
||||
readonly reason: SecretsKmsReason,
|
||||
readonly status?: number
|
||||
) {
|
||||
super(`secrets_kms_${reason}`)
|
||||
this.name = 'SecretsKmsError'
|
||||
}
|
||||
}
|
||||
|
||||
const KEY_NAME = /^projects\/[a-z][a-z0-9-]{4,28}[a-z0-9]\/locations\/[a-z0-9-]{1,40}\/keyRings\/[A-Za-z0-9_-]{1,63}\/cryptoKeys\/[A-Za-z0-9_-]{1,63}$/
|
||||
// Fixed endpoints: the service-account file's own token_uri is not trusted.
|
||||
const TOKEN_URL = 'https://oauth2.googleapis.com/token'
|
||||
const KMS_URL = 'https://cloudkms.googleapis.com/v1'
|
||||
const SCOPE = 'https://www.googleapis.com/auth/cloudkms'
|
||||
const TIMEOUT_MS = 5000
|
||||
const ATTEMPTS = 2
|
||||
|
||||
const ServiceAccount = z.looseObject({ client_email: z.string().min(3).max(320), private_key: z.string().min(100) })
|
||||
const TokenResponse = z.looseObject({ access_token: z.string().min(1), expires_in: z.number().positive().optional() })
|
||||
const DecryptResponse = z.looseObject({ plaintext: z.string().min(1) })
|
||||
|
||||
/** The AAD a KEK is wrapped with (`gcloud kms encrypt --additional-authenticated-data-file`). */
|
||||
export function kekWrapAad(kekId: string): string {
|
||||
return `orca-secrets-kek:${kekId}`
|
||||
}
|
||||
|
||||
export type KekUnwrapper = (wrapped: string, kekId: string) => Promise<string>
|
||||
|
||||
/**
|
||||
* Returns `unwrap(wrapped, kekId)`: the base64 KEK inside a base64 KMS ciphertext. Throws
|
||||
* SecretsKmsError; a 5xx or network failure is retried once.
|
||||
*/
|
||||
export function createKekUnwrapper(config: { keyName: string; serviceAccountJson: string; fetch?: typeof fetch; now?: () => number }): KekUnwrapper {
|
||||
const doFetch = config.fetch ?? fetch
|
||||
const now = config.now ?? Date.now
|
||||
if (!KEY_NAME.test(config.keyName)) {
|
||||
throw new SecretsKmsError('config')
|
||||
}
|
||||
let account: z.infer<typeof ServiceAccount>
|
||||
try {
|
||||
account = ServiceAccount.parse(JSON.parse(config.serviceAccountJson))
|
||||
} catch {
|
||||
// The parse error could quote the credential; it is dropped.
|
||||
throw new SecretsKmsError('config')
|
||||
}
|
||||
let signingKey: CryptoKey | null = null
|
||||
let token: { value: string; expiresAt: number } | null = null
|
||||
|
||||
async function send(url: string, init: RequestInit): Promise<Response> {
|
||||
let failure = new SecretsKmsError('unavailable')
|
||||
for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
|
||||
let response: Response
|
||||
try {
|
||||
response = await doFetch(url, { ...init, signal: AbortSignal.timeout(TIMEOUT_MS) })
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (response.ok) {
|
||||
return response
|
||||
}
|
||||
await response.body?.cancel().catch(() => {})
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new SecretsKmsError('denied', response.status)
|
||||
}
|
||||
if (response.status < 500 && response.status !== 429) {
|
||||
throw new SecretsKmsError('invalid', response.status)
|
||||
}
|
||||
failure = new SecretsKmsError('unavailable', response.status)
|
||||
}
|
||||
throw failure
|
||||
}
|
||||
|
||||
async function accessToken(): Promise<string> {
|
||||
if (token && token.expiresAt > now() + 60_000) {
|
||||
return token.value
|
||||
}
|
||||
try {
|
||||
signingKey ??= await importPKCS8(account.private_key, 'RS256')
|
||||
} catch {
|
||||
throw new SecretsKmsError('config')
|
||||
}
|
||||
const iat = Math.floor(now() / 1000) - 30
|
||||
const assertion = await new SignJWT({ scope: SCOPE })
|
||||
.setProtectedHeader({ alg: 'RS256', typ: 'JWT' })
|
||||
.setIssuer(account.client_email)
|
||||
.setAudience(TOKEN_URL)
|
||||
.setIssuedAt(iat)
|
||||
.setExpirationTime(iat + 600)
|
||||
.sign(signingKey)
|
||||
let response: Response
|
||||
try {
|
||||
response = await send(TOKEN_URL, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion }).toString()
|
||||
})
|
||||
} catch (error) {
|
||||
// Google answers a bad or disabled service account with 400 invalid_grant: that is a refusal, not a bad KEK.
|
||||
throw error instanceof SecretsKmsError && error.reason === 'invalid' ? new SecretsKmsError('denied', error.status) : error
|
||||
}
|
||||
const parsed = TokenResponse.safeParse(await response.json().catch(() => null))
|
||||
if (!parsed.success) {
|
||||
throw new SecretsKmsError('unavailable')
|
||||
}
|
||||
token = { value: parsed.data.access_token, expiresAt: now() + (parsed.data.expires_in ?? 3600) * 1000 }
|
||||
return token.value
|
||||
}
|
||||
|
||||
return async (wrapped, kekId) => {
|
||||
const response = await send(`${KMS_URL}/${config.keyName}:decrypt`, {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${await accessToken()}`, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ ciphertext: wrapped, additionalAuthenticatedData: btoa(kekWrapAad(kekId)) })
|
||||
})
|
||||
const parsed = DecryptResponse.safeParse(await response.json().catch(() => null))
|
||||
if (!parsed.success) {
|
||||
throw new SecretsKmsError('unavailable')
|
||||
}
|
||||
return parsed.data.plaintext
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,8 @@
|
||||
import { z } from 'zod'
|
||||
import type { SandboxCaller } from './auth'
|
||||
import type { Env } from './env'
|
||||
import { createKeyring, type Keyring, type SecretBinding } from './secrets-crypto'
|
||||
import { createKeyring, type Keyring, type SealFormat, type SecretBinding } from './secrets-crypto'
|
||||
import { createKekUnwrapper, SecretsKmsError } from './secrets-kms'
|
||||
import { AUTH_IAT_BACKDATE_MS } from './member-changes'
|
||||
import { BASE_URL_NAMES, baseUrlHost } from './provider-env'
|
||||
import type { SandboxRow } from './store'
|
||||
@@ -458,21 +459,80 @@ export async function effectiveSecrets(db: D1Database, caller: SandboxCaller, re
|
||||
})
|
||||
}
|
||||
|
||||
let cachedKeyring: { source: string; keyring: Promise<Keyring> } | null = null
|
||||
let cachedKeyring: { source: string; keyring: Promise<Keyring>; failedAt?: number } | null = null
|
||||
/** How long a failed KMS unwrap is remembered, so an outage is not one KMS round trip per request. */
|
||||
export const KMS_RETRY_AFTER_MS = 10_000
|
||||
|
||||
/** The Worker's keyring, or null when SECRETS_KEK is not configured. */
|
||||
export function keyringFor(env: Env): Promise<Keyring> | null {
|
||||
function parseKeyMap(json: string | undefined): Record<string, string> {
|
||||
return json ? (JSON.parse(json) as Record<string, string>) : {}
|
||||
}
|
||||
|
||||
/**
|
||||
* SECRETS_KEK_SOURCE=kms: every KEK comes out of Cloud KMS (src/secrets-kms.ts), once per isolate.
|
||||
* SECRETS_KEK is never read on this path, so a KMS failure cannot fall back to a plaintext key.
|
||||
*/
|
||||
function kmsKeyring(env: Env, sealFormat: SealFormat, fetcher: typeof fetch | undefined): Promise<Keyring> {
|
||||
const activeId = env.SECRETS_KEK_ID ?? 'k1'
|
||||
const source = `kms\n${activeId}\n${env.SECRETS_KMS_KEY ?? ''}\n${env.SECRETS_KEK_WRAPPED ?? ''}\n${env.SECRETS_KEK_RETIRED_WRAPPED ?? ''}\n${sealFormat}`
|
||||
const cached = cachedKeyring
|
||||
if (cached?.source === source && (cached.failedAt === undefined || Date.now() - cached.failedAt < KMS_RETRY_AFTER_MS)) {
|
||||
return cached.keyring
|
||||
}
|
||||
const load = async (): Promise<Keyring> => {
|
||||
if (!env.SECRETS_KMS_KEY || !env.SECRETS_KMS_SERVICE_ACCOUNT || !env.SECRETS_KEK_WRAPPED) {
|
||||
throw new SecretsKmsError('config')
|
||||
}
|
||||
let retiredWrapped: Record<string, string>
|
||||
try {
|
||||
retiredWrapped = parseKeyMap(env.SECRETS_KEK_RETIRED_WRAPPED)
|
||||
} catch {
|
||||
throw new SecretsKmsError('config')
|
||||
}
|
||||
const unwrap = createKekUnwrapper({ keyName: env.SECRETS_KMS_KEY, serviceAccountJson: env.SECRETS_KMS_SERVICE_ACCOUNT, fetch: fetcher })
|
||||
const active = await unwrap(env.SECRETS_KEK_WRAPPED, activeId)
|
||||
const retired: Record<string, string> = {}
|
||||
for (const [id, wrapped] of Object.entries(retiredWrapped)) {
|
||||
if (typeof wrapped !== 'string') {
|
||||
throw new SecretsKmsError('config')
|
||||
}
|
||||
retired[id] = await unwrap(wrapped, id)
|
||||
}
|
||||
try {
|
||||
return await createKeyring({ id: activeId, key: active }, retired, { sealFormat })
|
||||
} catch {
|
||||
// KMS returned something that is not a 32-byte key, or an id is malformed.
|
||||
throw new SecretsKmsError('invalid')
|
||||
}
|
||||
}
|
||||
const entry: NonNullable<typeof cachedKeyring> = { source, keyring: load() }
|
||||
entry.keyring.catch((error: unknown) => {
|
||||
entry.failedAt = Date.now()
|
||||
const kms = error instanceof SecretsKmsError ? error : null
|
||||
// Reason and HTTP status only: never a response body, a token or a key.
|
||||
secretLog('secrets_kms_unavailable', { reason: kms?.reason ?? 'error', ...(kms?.status ? { status: kms.status } : {}) })
|
||||
})
|
||||
cachedKeyring = entry
|
||||
return entry.keyring
|
||||
}
|
||||
|
||||
/**
|
||||
* The Worker's keyring, or null when the secret store is not configured. With SECRETS_KEK_SOURCE=kms
|
||||
* the promise rejects with SecretsKmsError while KMS cannot hand over the keys.
|
||||
*/
|
||||
export function keyringFor(env: Env, fetcher?: typeof fetch): Promise<Keyring> | null {
|
||||
// Anything but the exact opt-in stays v1, the format every deployed version reads.
|
||||
const sealFormat = env.SECRETS_SEAL_FORMAT === 'v2' ? 'v2' : 'v1'
|
||||
if (env.SECRETS_KEK_SOURCE === 'kms') {
|
||||
return kmsKeyring(env, sealFormat, fetcher)
|
||||
}
|
||||
if (!env.SECRETS_KEK) {
|
||||
return null
|
||||
}
|
||||
// Anything but the exact opt-in stays v1, the format every deployed version reads.
|
||||
const sealFormat = env.SECRETS_SEAL_FORMAT === 'v2' ? 'v2' : 'v1'
|
||||
const source = `${env.SECRETS_KEK_ID ?? 'k1'}\n${env.SECRETS_KEK}\n${env.SECRETS_KEK_RETIRED ?? ''}\n${sealFormat}`
|
||||
if (cachedKeyring?.source !== source) {
|
||||
const retired = env.SECRETS_KEK_RETIRED ? (JSON.parse(env.SECRETS_KEK_RETIRED) as Record<string, string>) : {}
|
||||
cachedKeyring = {
|
||||
source,
|
||||
keyring: createKeyring({ id: env.SECRETS_KEK_ID ?? 'k1', key: env.SECRETS_KEK }, retired, { sealFormat })
|
||||
keyring: createKeyring({ id: env.SECRETS_KEK_ID ?? 'k1', key: env.SECRETS_KEK }, parseKeyMap(env.SECRETS_KEK_RETIRED), { sealFormat })
|
||||
}
|
||||
}
|
||||
return cachedKeyring.keyring
|
||||
|
||||
@@ -9,6 +9,7 @@ import { deriveProviderEnv, deriveProviderScopes, providerHosts } from './provid
|
||||
import { applySecretPlaceholders, encodeAccountRoute, encodeEgressSecretHosts } from './secret-egress'
|
||||
import { resolveSandboxSecrets } from './secrets'
|
||||
import type { Keyring } from './secrets-crypto'
|
||||
import { SecretsKmsError } from './secrets-kms'
|
||||
import type { SandboxRow } from './store'
|
||||
import { secretLog } from './secret-log'
|
||||
|
||||
@@ -80,9 +81,12 @@ function egressSwapOn(deps: Pick<LifecycleDeps, 'secrets' | 'config'>, row: Pick
|
||||
export type { AgentMode }
|
||||
|
||||
export async function sessionSecretEnv(
|
||||
deps: Pick<LifecycleDeps, 'db' | 'secrets' | 'config'>,
|
||||
deps: Pick<LifecycleDeps, 'db' | 'secrets' | 'secretsUnavailable' | 'config'>,
|
||||
row: SandboxRow
|
||||
): Promise<SessionSecrets> {
|
||||
if (deps.secretsUnavailable) {
|
||||
throw new SecretsKmsError(deps.secretsUnavailable)
|
||||
}
|
||||
if (!deps.secrets) {
|
||||
return EMPTY
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ describe('the git shim never lets a github.com push prompt for credentials', ()
|
||||
expect(err).not.toContain("Username for 'https://github.com'")
|
||||
expect(err).not.toContain('could not read Username')
|
||||
expect(err).toContain(
|
||||
"orca: Orca Cloud can't push to octocat/Hello-World. Install the Orca GitHub App on octocat, or connect your GitHub in Settings › Account."
|
||||
"orca: Orca Cloud can't push to octocat/Hello-World. Install the Orca GitHub App on octocat, or connect your GitHub in Settings → Account."
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// #503 follow-up (design-squad): a commit that goes out under the workspace identity (Orca Cloud's
|
||||
// name) says once per session how to use your own: connect GitHub in Settings › Account.
|
||||
// name) says once per session how to use your own: connect GitHub in Settings → Account.
|
||||
// Pushes and read-only git never say it; orca-git-as's own fallback line is replaced by it.
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
@@ -9,7 +9,7 @@ import { fileURLToPath } from 'node:url'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
|
||||
const SHIM = fileURLToPath(new URL('../image/vm/git', import.meta.url).href)
|
||||
const NUDGE = "orca: This commit uses Orca Cloud's name. Connect your GitHub in Settings › Account to use yours."
|
||||
const NUDGE = "orca: This commit uses Orca Cloud's name. Connect your GitHub in Settings → Account to use yours."
|
||||
|
||||
let home = ''
|
||||
let cwd = ''
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
import { createCipheriv, createDecipheriv, generateKeyPairSync, randomBytes, type KeyObject } from 'node:crypto'
|
||||
import { jwtVerify } from 'jose'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { START_COMMAND } from '../src/sandbox-vm-commands'
|
||||
import { KMS_RETRY_AFTER_MS } from '../src/secrets'
|
||||
import { createKeyring } from '../src/secrets-crypto'
|
||||
import { createKekUnwrapper, kekWrapAad, SecretsKmsError } from '../src/secrets-kms'
|
||||
import { createHarness } from './harness'
|
||||
|
||||
// Fake keys and values only; the log check looks for every one of them.
|
||||
const K1 = Buffer.alloc(32, 7).toString('base64')
|
||||
const K2 = Buffer.alloc(32, 9).toString('base64')
|
||||
const PLAIN = Buffer.alloc(32, 5).toString('base64')
|
||||
const OP = 'o'.repeat(40)
|
||||
const KEY_NAME = 'projects/onorca-cloud/locations/us/keyRings/orca-secrets/cryptoKeys/secrets-kek'
|
||||
const VALUE = 'kms-secret-value-aaaa-1111'
|
||||
const VALUE_2 = 'kms-secret-value-bbbb-2222'
|
||||
|
||||
type FakeKms = ReturnType<typeof createFakeKms>
|
||||
|
||||
/**
|
||||
* Google's token endpoint and Cloud KMS, in memory. The service-account assertion is verified against the
|
||||
* account's public key, and encrypt/decrypt are real AES-256-GCM under a root key that never leaves this object.
|
||||
*/
|
||||
function createFakeKms() {
|
||||
const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 })
|
||||
const root = randomBytes(32)
|
||||
const email = 'orca-secrets@onorca-cloud.iam.gserviceaccount.com'
|
||||
const state = {
|
||||
tokens: 0,
|
||||
decrypts: 0,
|
||||
issued: [] as string[],
|
||||
/** `down`: 503 from KMS. `denied`: 403 from KMS. `no-account`: token endpoint refuses. `offline`: fetch throws. */
|
||||
mode: 'up' as 'up' | 'down' | 'denied' | 'no-account' | 'offline'
|
||||
}
|
||||
const fetcher = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(input)
|
||||
if (state.mode === 'offline') {
|
||||
throw new TypeError('fetch failed')
|
||||
}
|
||||
if (url === 'https://oauth2.googleapis.com/token') {
|
||||
state.tokens++
|
||||
if (state.mode === 'no-account') {
|
||||
return Response.json({ error: 'invalid_grant', error_description: 'account disabled' }, { status: 400 })
|
||||
}
|
||||
const form = new URLSearchParams(String(init?.body))
|
||||
expect(form.get('grant_type')).toBe('urn:ietf:params:oauth:grant-type:jwt-bearer')
|
||||
const { payload } = await jwtVerify(form.get('assertion') ?? '', publicKey as unknown as KeyObject, {
|
||||
issuer: email,
|
||||
audience: 'https://oauth2.googleapis.com/token'
|
||||
})
|
||||
expect(payload.scope).toBe('https://www.googleapis.com/auth/cloudkms')
|
||||
const token = `ya29.fake-${randomBytes(8).toString('hex')}`
|
||||
state.issued.push(token)
|
||||
return Response.json({ access_token: token, expires_in: 3600, token_type: 'Bearer' })
|
||||
}
|
||||
if (url === `https://cloudkms.googleapis.com/v1/${KEY_NAME}:decrypt`) {
|
||||
state.decrypts++
|
||||
if (state.mode === 'down') {
|
||||
return Response.json({ error: { code: 503, message: 'backend unavailable' } }, { status: 503 })
|
||||
}
|
||||
const bearer = new Headers(init?.headers).get('authorization')?.slice('Bearer '.length) ?? ''
|
||||
if (state.mode === 'denied' || !state.issued.includes(bearer)) {
|
||||
return Response.json({ error: { code: 403, message: 'Permission cloudkms.cryptoKeyVersions.useToDecrypt denied' } }, { status: 403 })
|
||||
}
|
||||
const body = JSON.parse(String(init?.body)) as { ciphertext: string; additionalAuthenticatedData?: string }
|
||||
try {
|
||||
const bytes = Buffer.from(body.ciphertext, 'base64')
|
||||
const decipher = createDecipheriv('aes-256-gcm', root, bytes.subarray(0, 12))
|
||||
decipher.setAAD(Buffer.from(body.additionalAuthenticatedData ?? '', 'base64'))
|
||||
decipher.setAuthTag(bytes.subarray(bytes.length - 16))
|
||||
const plaintext = Buffer.concat([decipher.update(bytes.subarray(12, bytes.length - 16)), decipher.final()])
|
||||
return Response.json({ plaintext: plaintext.toString('base64') })
|
||||
} catch {
|
||||
return Response.json({ error: { code: 400, message: 'Decryption failed: the ciphertext is invalid.' } }, { status: 400 })
|
||||
}
|
||||
}
|
||||
throw new Error(`unexpected fetch ${url}`)
|
||||
}) as typeof fetch
|
||||
return {
|
||||
state,
|
||||
fetch: fetcher,
|
||||
serviceAccount: JSON.stringify({
|
||||
type: 'service_account',
|
||||
client_email: email,
|
||||
private_key: privateKey.export({ type: 'pkcs8', format: 'pem' }) as string,
|
||||
// Not trusted by the client: the real endpoint is pinned.
|
||||
token_uri: 'https://attacker.example/token'
|
||||
}),
|
||||
/** What `gcloud kms encrypt` does in the runbook: wrap a KEK's 32 bytes, bound to its id. */
|
||||
wrap(kekB64: string, kekId: string): string {
|
||||
const iv = randomBytes(12)
|
||||
const cipher = createCipheriv('aes-256-gcm', root, iv)
|
||||
cipher.setAAD(Buffer.from(kekWrapAad(kekId)))
|
||||
return Buffer.concat([iv, cipher.update(Buffer.from(kekB64, 'base64')), cipher.final(), cipher.getAuthTag()]).toString('base64')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let logs: string[] = []
|
||||
let kms: FakeKms
|
||||
let clock = 1_800_000_000_000
|
||||
beforeEach(() => {
|
||||
logs = []
|
||||
kms = createFakeKms()
|
||||
// The keyring cache is per isolate (module state); a fresh fake means fresh wrapped blobs, so no test sees another's entry.
|
||||
vi.stubGlobal('fetch', kms.fetch)
|
||||
// Past any earlier test's remembered failure.
|
||||
clock += 10 * KMS_RETRY_AFTER_MS
|
||||
vi.spyOn(Date, 'now').mockImplementation(() => clock)
|
||||
for (const method of ['log', 'info', 'warn', 'error', 'debug'] as const) {
|
||||
vi.spyOn(console, method).mockImplementation((...args: unknown[]) => {
|
||||
logs.push(args.map((arg) => (typeof arg === 'string' ? arg : JSON.stringify(arg))).join(' '))
|
||||
})
|
||||
}
|
||||
})
|
||||
afterEach(() => {
|
||||
// No value, key, credential or access token reached a log line.
|
||||
const privateKey = (JSON.parse(kms.serviceAccount) as { private_key: string }).private_key
|
||||
for (const secret of [VALUE, VALUE_2, K1, K2, PLAIN, privateKey.split('\n')[1]!, ...kms.state.issued]) {
|
||||
expect(logs.join('\n')).not.toContain(secret)
|
||||
}
|
||||
vi.unstubAllGlobals()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function kmsEnv(extra: Record<string, string> = {}): Record<string, string> {
|
||||
return {
|
||||
OPERATOR_TOKEN: OP,
|
||||
SECRETS_KEK_SOURCE: 'kms',
|
||||
SECRETS_KMS_KEY: KEY_NAME,
|
||||
SECRETS_KMS_SERVICE_ACCOUNT: kms.serviceAccount,
|
||||
SECRETS_KEK_WRAPPED: kms.wrap(K1, 'k1'),
|
||||
...extra
|
||||
}
|
||||
}
|
||||
|
||||
const put = (h: Awaited<ReturnType<typeof createHarness>>, bearer: string, name: string, value: string) =>
|
||||
h.call('PUT', `/v1/secrets/personal/${name}`, { bearer, body: { value } })
|
||||
|
||||
describe('KMS client', () => {
|
||||
it('unwraps a KEK wrapped for its id, with a pinned token endpoint and one token for many calls', async () => {
|
||||
const unwrap = createKekUnwrapper({ keyName: KEY_NAME, serviceAccountJson: kms.serviceAccount, fetch: kms.fetch })
|
||||
expect(await unwrap(kms.wrap(K1, 'k1'), 'k1')).toBe(K1)
|
||||
expect(await unwrap(kms.wrap(K2, 'k2'), 'k2')).toBe(K2)
|
||||
expect(kms.state).toMatchObject({ tokens: 1, decrypts: 2 })
|
||||
// A blob wrapped for another id, or a corrupted one, does not unwrap.
|
||||
await expect(unwrap(kms.wrap(K1, 'k1'), 'k2')).rejects.toMatchObject({ reason: 'invalid', status: 400 })
|
||||
await expect(unwrap('AAAA', 'k1')).rejects.toMatchObject({ reason: 'invalid' })
|
||||
})
|
||||
|
||||
it('classifies failures and retries only the retryable ones', async () => {
|
||||
const unwrap = createKekUnwrapper({ keyName: KEY_NAME, serviceAccountJson: kms.serviceAccount, fetch: kms.fetch })
|
||||
const wrapped = kms.wrap(K1, 'k1')
|
||||
kms.state.mode = 'down'
|
||||
await expect(unwrap(wrapped, 'k1')).rejects.toMatchObject({ name: 'SecretsKmsError', reason: 'unavailable', status: 503 })
|
||||
expect(kms.state.decrypts).toBe(2)
|
||||
kms.state.mode = 'denied'
|
||||
await expect(unwrap(wrapped, 'k1')).rejects.toMatchObject({ reason: 'denied', status: 403 })
|
||||
expect(kms.state.decrypts).toBe(3)
|
||||
kms.state.mode = 'offline'
|
||||
await expect(unwrap(wrapped, 'k1')).rejects.toMatchObject({ reason: 'unavailable' })
|
||||
const refused = createKekUnwrapper({ keyName: KEY_NAME, serviceAccountJson: kms.serviceAccount, fetch: kms.fetch })
|
||||
kms.state.mode = 'no-account'
|
||||
await expect(refused(wrapped, 'k1')).rejects.toMatchObject({ reason: 'denied' })
|
||||
// Error text is a fixed code: nothing Google said is carried along.
|
||||
const error = await refused(wrapped, 'k1').catch((caught: unknown) => caught)
|
||||
expect(error).toBeInstanceOf(SecretsKmsError)
|
||||
expect(String(error)).toBe('SecretsKmsError: secrets_kms_denied')
|
||||
})
|
||||
|
||||
it('refuses a malformed key name or credential without echoing it', () => {
|
||||
for (const keyName of ['', 'projects/x', `${KEY_NAME}/../../other`, `${KEY_NAME}:encrypt`, 'https://evil.example/projects/a/locations/b/keyRings/c/cryptoKeys/d']) {
|
||||
expect(() => createKekUnwrapper({ keyName, serviceAccountJson: kms.serviceAccount })).toThrow('secrets_kms_config')
|
||||
}
|
||||
for (const serviceAccountJson of ['', '{', '{"client_email":"a@b.c"}', 'not-json-PRIVATE']) {
|
||||
expect(() => createKekUnwrapper({ keyName: KEY_NAME, serviceAccountJson })).toThrow('secrets_kms_config')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('secret store with SECRETS_KEK_SOURCE=kms', () => {
|
||||
it('is off unless the flag is exactly `kms`: the plaintext SECRETS_KEK path is untouched and KMS is never called', async () => {
|
||||
for (const source of [undefined, '', 'KMS', 'env']) {
|
||||
const h = await createHarness({ ...kmsEnv(), SECRETS_KEK: PLAIN, ...(source === undefined ? {} : { SECRETS_KEK_SOURCE: source }) })
|
||||
if (source === undefined) {
|
||||
delete h.env.SECRETS_KEK_SOURCE
|
||||
}
|
||||
const alice = await h.token('alice')
|
||||
expect((await put(h, alice, 'PLAIN_VAR', VALUE)).status).toBe(200)
|
||||
const row = h.raw.prepare('SELECT kek_id, wrapped_dek, ciphertext FROM secrets').get() as { kek_id: string; wrapped_dek: string; ciphertext: string }
|
||||
const plain = await createKeyring({ id: 'k1', key: PLAIN })
|
||||
expect(await plain.open({ scope: 'personal', ownerId: 'user:alice', name: 'PLAIN_VAR' }, { kekId: row.kek_id, wrappedDek: row.wrapped_dek, ciphertext: row.ciphertext })).toBe(VALUE)
|
||||
}
|
||||
expect(kms.state).toMatchObject({ tokens: 0, decrypts: 0 })
|
||||
})
|
||||
|
||||
it('unwraps the KEK once per isolate and seals with it, ignoring any plaintext SECRETS_KEK', async () => {
|
||||
const h = await createHarness(kmsEnv({ SECRETS_KEK: PLAIN }))
|
||||
const alice = await h.token('alice')
|
||||
expect((await put(h, alice, 'FIRST_VAR', VALUE)).status).toBe(200)
|
||||
expect((await put(h, alice, 'SECOND_VAR', VALUE_2)).status).toBe(200)
|
||||
expect((await h.call('GET', '/v1/secrets?scope=personal', { bearer: alice })).body.secrets).toHaveLength(2)
|
||||
expect((await h.call('GET', '/v1/internal/secrets/kek', { bearer: OP })).body).toMatchObject({ activeKekId: 'k1', pending: 0, unknownKekIds: [] })
|
||||
// A session start decrypts them too.
|
||||
expect((await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' }, bearer: alice })).status).toBe(200)
|
||||
expect(h.vercel.commands.find((c) => c.command === START_COMMAND)!.env.ORCA_SECRET_ENV).toBeDefined()
|
||||
// One token and one decrypt for all of it; an outage afterwards does not matter to a warm isolate.
|
||||
expect(kms.state).toMatchObject({ tokens: 1, decrypts: 1 })
|
||||
kms.state.mode = 'down'
|
||||
expect((await put(h, alice, 'THIRD_VAR', VALUE)).status).toBe(200)
|
||||
expect(kms.state.decrypts).toBe(1)
|
||||
|
||||
// The rows are under the KMS-held key, not the plaintext one that was also configured.
|
||||
const row = h.raw.prepare(`SELECT kek_id, wrapped_dek, ciphertext FROM secrets WHERE name = 'FIRST_VAR'`).get() as { kek_id: string; wrapped_dek: string; ciphertext: string }
|
||||
const sealed = { kekId: row.kek_id, wrappedDek: row.wrapped_dek, ciphertext: row.ciphertext }
|
||||
const binding = { scope: 'personal', ownerId: 'user:alice', name: 'FIRST_VAR' }
|
||||
expect(await (await createKeyring({ id: 'k1', key: K1 })).open(binding, sealed)).toBe(VALUE)
|
||||
await expect((await createKeyring({ id: 'k1', key: PLAIN })).open(binding, sealed)).rejects.toThrow()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['down', 'unavailable'],
|
||||
['denied', 'denied'],
|
||||
['no-account', 'denied'],
|
||||
['offline', 'unavailable']
|
||||
] as const)('answers a clear 503 when KMS is %s, without falling back to the plaintext key', async (mode, reason) => {
|
||||
kms.state.mode = mode
|
||||
const h = await createHarness(kmsEnv({ SECRETS_KEK: PLAIN }))
|
||||
const alice = await h.token('alice')
|
||||
const refused = await put(h, alice, 'ANY_VAR', VALUE)
|
||||
expect(refused).toEqual({ status: 503, body: { error: 'secrets_unavailable' } })
|
||||
expect((await h.send(new Request('https://sandbox.test/v1/secrets?scope=personal', { headers: { authorization: `Bearer ${alice}` } }))).headers.get('retry-after')).toBe('30')
|
||||
expect(await h.call('GET', '/v1/internal/secrets/kek', { bearer: OP })).toEqual({ status: 503, body: { error: 'secrets_unavailable', reason } })
|
||||
expect(await h.call('POST', '/v1/internal/secrets/rewrap', { bearer: OP, body: {} })).toEqual({ status: 503, body: { error: 'secrets_unavailable', reason } })
|
||||
// Nothing was stored under any key.
|
||||
expect(h.raw.prepare('SELECT COUNT(*) AS n FROM secrets').get()).toEqual({ n: 0 })
|
||||
// A session does not start without its secrets, and no VM is left behind.
|
||||
const created = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' }, bearer: alice })
|
||||
expect(created).toEqual({ status: 503, body: { error: 'secrets_unavailable' } })
|
||||
expect(h.vercel.commands.filter((c) => c.command === START_COMMAND)).toHaveLength(0)
|
||||
// Routes that need no secrets still answer.
|
||||
expect((await h.call('GET', '/v1/internal/status', { bearer: OP })).status).toBe(200)
|
||||
expect(logs.some((line) => line.includes('"secrets_kms_unavailable"') && line.includes(`"reason":"${reason}"`))).toBe(true)
|
||||
})
|
||||
|
||||
it('remembers a failure briefly instead of calling KMS per request, then recovers', async () => {
|
||||
kms.state.mode = 'down'
|
||||
const h = await createHarness(kmsEnv())
|
||||
const alice = await h.token('alice')
|
||||
expect((await put(h, alice, 'ANY_VAR', VALUE)).status).toBe(503)
|
||||
const attempts = kms.state.decrypts
|
||||
expect((await put(h, alice, 'ANY_VAR', VALUE)).status).toBe(503)
|
||||
expect((await h.call('GET', '/v1/secrets?scope=personal', { bearer: alice })).status).toBe(503)
|
||||
expect(kms.state.decrypts).toBe(attempts)
|
||||
|
||||
kms.state.mode = 'up'
|
||||
clock += KMS_RETRY_AFTER_MS + 1
|
||||
expect((await put(h, alice, 'ANY_VAR', VALUE)).status).toBe(200)
|
||||
expect((await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' }, bearer: alice })).status).toBe(200)
|
||||
})
|
||||
|
||||
it('answers 503 for an incomplete or mislabelled KMS config, never the plaintext key', async () => {
|
||||
const cases: Record<string, string>[] = [
|
||||
{ SECRETS_KMS_KEY: '' },
|
||||
{ SECRETS_KMS_SERVICE_ACCOUNT: '' },
|
||||
{ SECRETS_KEK_WRAPPED: '' },
|
||||
{ SECRETS_KMS_KEY: 'projects/onorca-cloud' },
|
||||
{ SECRETS_KEK_RETIRED_WRAPPED: '{' },
|
||||
// The active blob was wrapped for k1 but is deployed as k2.
|
||||
{ SECRETS_KEK_ID: 'k2' },
|
||||
// KMS hands back something that is not a 32-byte key.
|
||||
{ SECRETS_KEK_WRAPPED: kms.wrap(Buffer.alloc(16, 1).toString('base64'), 'k1') }
|
||||
]
|
||||
for (const broken of cases) {
|
||||
const h = await createHarness(kmsEnv({ SECRETS_KEK: PLAIN, ...broken }))
|
||||
expect(await put(h, await h.token('alice'), 'ANY_VAR', VALUE)).toEqual({ status: 503, body: { error: 'secrets_unavailable' } })
|
||||
expect(h.raw.prepare('SELECT COUNT(*) AS n FROM secrets').get()).toEqual({ n: 0 })
|
||||
}
|
||||
})
|
||||
|
||||
it('rotates under KMS: new wrapped KEK active, old one retired, sweep, then the retired blob is dropped', async () => {
|
||||
const h = await createHarness(kmsEnv())
|
||||
const alice = await h.token('alice')
|
||||
await put(h, alice, 'FIRST_VAR', VALUE)
|
||||
await put(h, alice, 'SECOND_VAR', VALUE_2)
|
||||
|
||||
Object.assign(h.env, {
|
||||
SECRETS_KEK_WRAPPED: kms.wrap(K2, 'k2'),
|
||||
SECRETS_KEK_ID: 'k2',
|
||||
SECRETS_KEK_RETIRED_WRAPPED: JSON.stringify({ k1: h.env.SECRETS_KEK_WRAPPED })
|
||||
})
|
||||
expect((await h.call('GET', '/v1/internal/secrets/kek', { bearer: OP })).body).toMatchObject({ activeKekId: 'k2', retiredKekIds: ['k1'], pending: 2, retiredInUse: ['k1'], unknownKekIds: [] })
|
||||
expect((await h.call('POST', '/v1/internal/secrets/rewrap', { bearer: OP, body: { dryRun: true } })).body).toMatchObject({ scanned: 2, failed: 0 })
|
||||
expect((await h.call('POST', '/v1/internal/secrets/rewrap', { bearer: OP, body: {} })).body).toMatchObject({ resealed: 2, pending: 0, done: true })
|
||||
expect((await h.call('GET', '/v1/internal/secrets/kek', { bearer: OP })).body).toMatchObject({ pending: 0, retiredDroppable: ['k1'] })
|
||||
|
||||
delete h.env.SECRETS_KEK_RETIRED_WRAPPED
|
||||
expect((await h.call('GET', '/v1/internal/secrets/kek', { bearer: OP })).body).toMatchObject({ retiredKekIds: [], pending: 0, unknownKekIds: [] })
|
||||
const onlyNew = await createKeyring({ id: 'k2', key: K2 })
|
||||
const rows = h.raw.prepare('SELECT name, kek_id, wrapped_dek, ciphertext FROM secrets ORDER BY name').all() as { name: string; kek_id: string; wrapped_dek: string; ciphertext: string }[]
|
||||
const opened = await Promise.all(
|
||||
rows.map((row) => onlyNew.open({ scope: 'personal', ownerId: 'user:alice', name: row.name }, { kekId: row.kek_id, wrappedDek: row.wrapped_dek, ciphertext: row.ciphertext }))
|
||||
)
|
||||
expect(opened).toEqual([VALUE, VALUE_2])
|
||||
})
|
||||
|
||||
it('moves an existing plaintext-KEK store behind KMS without touching a row', async () => {
|
||||
const h = await createHarness({ OPERATOR_TOKEN: OP, SECRETS_KEK: K1 })
|
||||
const alice = await h.token('alice')
|
||||
await put(h, alice, 'FIRST_VAR', VALUE)
|
||||
const before = h.raw.prepare('SELECT * FROM secrets').all()
|
||||
// Same KEK, same id, now held by KMS; the Worker secret is removed.
|
||||
Object.assign(h.env, kmsEnv())
|
||||
delete h.env.SECRETS_KEK
|
||||
expect((await h.call('GET', '/v1/internal/secrets/kek', { bearer: OP })).body).toMatchObject({ activeKekId: 'k1', pending: 0, unknownKekIds: [] })
|
||||
expect((await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' }, bearer: alice })).status).toBe(200)
|
||||
expect(h.vercel.commands.find((c) => c.command === START_COMMAND)!.env.ORCA_SECRET_ENV).toBeDefined()
|
||||
expect(h.raw.prepare('SELECT * FROM secrets').all()).toEqual(before)
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
# SEC-3: moving the secrets-store KEK behind a KMS (design, not implemented)
|
||||
|
||||
Status: design and recommendation, 2026-11-12. Nothing here has been built or provisioned. No prod, no Terraform.
|
||||
Status: phase 1 Worker code is implemented behind `SECRETS_KEK_SOURCE=kms` (off by default; `src/secrets-kms.ts`, tested against a fake KMS only, never against Google). No KMS resources exist: provisioning and turn-on are in the launch runbook, for Neil. Phase 2 is design only.
|
||||
Differences from the plan below: the wrapped KEK is bound to its KEK id with KMS additional authenticated data; there is no cache window or stale-on-error (keys stay in memory for the isolate's life, so revocation needs a redeploy); a failed unwrap is retried at most every 10 seconds; with the flag on, `SECRETS_KEK` is never read (no fallback), and create/wake answer 503 `secrets_unavailable`.
|
||||
Prices, latencies and vendor feature claims are from memory of public docs and are **unmeasured**; check each before committing.
|
||||
|
||||
## Where we are after the SEC-3 PR
|
||||
|
||||
Reference in New Issue
Block a user