import { generateKeyPairSync, randomUUID } from 'node:crypto' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { openOtaPrivateKey, sealOtaPrivateKey } from '../cli/src/key/vault-envelope.ts' import { BASE_URL, createDirectApiKeyWithBindings, getAuthHeaders, getAuthHeadersForCredentials, getSupabaseClient, resetAndSeedAppData, resetAppData, USER_ID_2, USER_PASSWORD } from './test-utils.ts' // Dedicated app/org per run: these tests only touch the vault row of their own app. describe('/app/:id/ota-key-vault customer-encrypted OTA private key', () => { const id = randomUUID() const appId = `com.test.otavault.${id}` const orgId = randomUUID() const userId = USER_ID_2 const stripeCustomerId = `cus_otavault_${id.replaceAll('-', '').slice(0, 16)}` const secret = `vault-secret-${id}` const keys = generateKeyPairSync('rsa', { modulusLength: 2048 }) const privateKeyPem = keys.privateKey.export({ type: 'pkcs1', format: 'pem' }) as string const otherKeys = generateKeyPairSync('rsa', { modulusLength: 2048 }) const otherPrivateKeyPem = otherKeys.privateKey.export({ type: 'pkcs1', format: 'pem' }) as string let adminKey = '' let developerKey = '' let readerKey = '' let apikeyIds: number[] = [] const path = `${BASE_URL}/app/${encodeURIComponent(appId)}/ota-key-vault` function headers(key: string) { return { 'Authorization': key, 'Content-Type': 'application/json' } } const put = (auth: HeadersInit, body: unknown) => fetch(path, { method: 'PUT', headers: auth, body: JSON.stringify(body) }) const get = (auth: HeadersInit, query = '') => fetch(`${path}${query}`, { headers: auth }) beforeAll(async () => { await resetAndSeedAppData(appId, { orgId, userId, stripeCustomerId }) const created = await Promise.all(['app_admin', 'app_developer', 'app_reader'].map(appRoleName => createDirectApiKeyWithBindings({ userId, key: randomUUID(), name: `test-ota-key-vault-${appRoleName}-${id}`, orgId, roleName: 'org_member', appId, appRoleName, }))) if (created.some(key => !key?.key)) throw new Error('Seeded API keys missing generated key values') ;[adminKey, developerKey, readerKey] = created.map(key => key!.key!) apikeyIds = created.map(key => key!.id) }) afterAll(async () => { const supabase = getSupabaseClient() await (supabase as any).from('app_ota_key_vault').delete().eq('app_id', appId) if (apikeyIds.length) await supabase.from('apikeys').delete().in('id', apikeyIds) await resetAppData(appId) }) it('stores ciphertext only, enforces permissions and revisions, and lets a CI key decrypt locally', async () => { let response = await get(headers(developerKey)) expect(response.status).toBe(200) expect(await response.json()).toMatchObject({ app_id: appId, configured: false }) const sealed = await sealOtaPrivateKey({ appId, privateKeyPem, secret }) const body = { envelope: sealed.envelope, public_key: sealed.publicKeyPem, expected_revision: 0 } // Writing needs app.update_settings: app_developer is denied. response = await put(headers(developerKey), body) expect(response.status).toBe(403) expect(await response.json()).toHaveProperty('error', 'permission_denied') // The public key must hash to the fingerprint bound inside the envelope. const other = await sealOtaPrivateKey({ appId, privateKeyPem: otherPrivateKeyPem, secret }) response = await put(headers(adminKey), { ...body, public_key: other.publicKeyPem }) expect(response.status).toBe(400) expect(await response.json()).toHaveProperty('error', 'invalid_ota_key_vault') response = await put(headers(adminKey), { ...body, envelope: { ...sealed.envelope, kdf: { ...sealed.envelope.kdf, iterations: 1000 } } }) expect(response.status).toBe(400) response = await put(headers(adminKey), body) expect(response.status).toBe(200) const created = await response.json() as { revision: number } expect(created).toMatchObject({ configured: true, public_key_sha256: sealed.publicKeySha256 }) expect(created.revision).toBeGreaterThan(0) // No silent overwrite: a write must name the revision it replaces. response = await put(headers(adminKey), { envelope: other.envelope, public_key: other.publicKeyPem }) expect(response.status).toBe(409) expect(await response.json()).toMatchObject({ error: 'ota_key_vault_conflict', moreInfo: { revision: created.revision, current: { configured: true, revision: created.revision, public_key_sha256: sealed.publicKeySha256 } } }) // Capgo holds ciphertext only: neither the row nor the audit trail contains the key. const supabase = getSupabaseClient() as any const { data: row } = await supabase.from('app_ota_key_vault').select('*').eq('app_id', appId).single() expect(JSON.stringify(row)).not.toContain('PRIVATE KEY') expect(JSON.stringify(row)).not.toContain(secret) const { data: audit } = await supabase.from('audit_logs').select('old_record,new_record').eq('table_name', 'app_ota_key_vault').eq('record_id', appId) expect(audit.length).toBeGreaterThan(0) expect(JSON.stringify(audit)).not.toContain(sealed.envelope.ciphertext) // An upload-capable key gets the envelope and decrypts it locally with the vault secret. response = await get(headers(developerKey)) const status = await response.json() as { envelope?: unknown, envelope_access: boolean } expect(status.envelope_access).toBe(true) expect((await openOtaPrivateKey({ appId, envelope: status.envelope, secret })).trim()).toBe(privateKeyPem.trim()) await expect(openOtaPrivateKey({ appId, envelope: status.envelope, secret: `${secret}-wrong` })).rejects.toThrow() // A read-only key sees the status, never the envelope; include_envelope=false hides it too. response = await get(headers(readerKey)) expect(response.status).toBe(200) const readerStatus = await response.json() as Record expect(readerStatus).toMatchObject({ configured: true, envelope_access: false }) expect(readerStatus).not.toHaveProperty('envelope') expect(await (await get(headers(developerKey), '?include_envelope=false')).json()).not.toHaveProperty('envelope') // Rotation with the current revision. response = await put(headers(adminKey), { envelope: other.envelope, public_key: other.publicKeyPem, expected_revision: created.revision }) expect(response.status).toBe(200) const rotated = await response.json() as { revision: number } expect(rotated).toMatchObject({ public_key_sha256: other.publicKeySha256 }) expect(rotated.revision).toBeGreaterThan(created.revision) // A stale revision is refused. expect((await put(headers(adminKey), { ...body, expected_revision: created.revision })).status).toBe(409) // Another app's vault is out of reach for this app-scoped key. response = await fetch(`${BASE_URL}/app/${encodeURIComponent(`${appId}.other`)}/ota-key-vault`, { headers: headers(adminKey) }) expect(response.ok).toBe(false) // A stale revision gets a 409 with the current key, not a silent delete. response = await fetch(`${path}?expected_revision=${created.revision}`, { method: 'DELETE', headers: headers(adminKey) }) expect(response.status).toBe(409) expect(await response.json()).toMatchObject({ error: 'ota_key_vault_conflict', moreInfo: { current: { configured: true, revision: rotated.revision } } }) response = await fetch(path, { method: 'DELETE', headers: headers(developerKey) }) expect(response.status).toBe(403) response = await fetch(path, { method: 'DELETE', headers: headers(adminKey) }) expect(response.status).toBe(200) expect(await (await get(headers(adminKey))).json()).toMatchObject({ configured: false }) }) it('accepts an authorized console session and rejects another organization', async () => { const sealed = await sealOtaPrivateKey({ appId, privateKeyPem, secret }) const body = { envelope: sealed.envelope, public_key: sealed.publicKeyPem, expected_revision: 0 } const outsider = await getAuthHeaders() expect((await put(outsider, body)).status).toBe(403) const owner = await getAuthHeadersForCredentials('test2@capgo.app', USER_PASSWORD) const response = await put(owner, body) expect(response.status).toBe(200) const stored = await response.json() as { revision: number } expect(stored).toMatchObject({ configured: true }) expect((await fetch(path, { method: 'DELETE', headers: owner })).status).toBe(200) // Recreating the key never reuses a revision, so the old one cannot overwrite it. const recreated = await (await put(owner, body)).json() as { revision: number } expect(recreated.revision).toBeGreaterThan(stored.revision) expect((await put(owner, { ...body, expected_revision: stored.revision })).status).toBe(409) expect((await fetch(path, { method: 'DELETE', headers: owner })).status).toBe(200) }) })