Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions acceptance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,8 @@ secrets as environment secrets.
| `ACCEPTANCE_ADMIN_RETURN_TENANT_SENSITIVE_DATA` | Whether the admin API returns sensitive tenant fields (keys, database URL). Defaults to `true`. |
| `ACCEPTANCE_ADMIN_DATABASE_URL_OVERRIDE` | Database URL to provision tenants with when sensitive tenant data isn't returned (see above). |
| `ACCEPTANCE_ENABLE_CDN` | Enables CDN purge tests. Managed local runs provide a purge stub by default. |
| `ACCEPTANCE_CDN_VERSION` | Smart CDN version of the target, `1` (default) or `2`. Selects V2-specific expectations and timing. |
| `ACCEPTANCE_CDN_NEEDS_PURGE` | Set to `true` when the target storage service does not yet actively purge the CDN on writes, so tests purge manually. Defaults to `false`. |
| `ACCEPTANCE_ENABLE_USAGE_CHECKSUM` | Set to `false` to disable the managed-local usage ledger stub and its checksum checks. |
| `ACCEPTANCE_ENABLE_RENDER` | Enables image transformation tests. |
| `ACCEPTANCE_IMGPROXY_DEVELOPMENT_ERRORS_MODE` | Whether target imgproxy runs with `IMGPROXY_DEVELOPMENT_ERRORS_MODE=true`. Defaults to `true`; set to `false` when imgproxy v4 runs without dev errors so invalid HEIF probes expect `500` instead of `400`. |
Expand Down
499 changes: 499 additions & 0 deletions acceptance/specs/cdn-object-versioning.test.ts

Large diffs are not rendered by default.

370 changes: 370 additions & 0 deletions acceptance/specs/cdn-signed-url-key-rotation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,370 @@
import { setTimeout as delay } from 'node:timers/promises'
import {
AdminJwksClient,
URL_SIGNING_KEY_TYPES,
type UrlSigningKey,
type UrlSigningKeyType,
} from '../support/admin-jwks'
import {
getObjectUrl,
pauseForWebhookIfNeeded,
SIGNED_EXPIRES_IN_S,
warmCacheEndpoint,
} from '../support/cdn'
import { describeAcceptance, getAcceptanceConfig } from '../support/config'
import { createRestClient, type HttpResponse } from '../support/http'
import {
cleanupRestResources,
createRestBucket,
uniqueBucketName,
uniqueObjectKey,
uploadRestObject,
} from '../support/resources'

// customer-router caches a project's /.well-known/jwks.json for 10 minutes
// (JWKS_CACHE_TTL_SECONDS in customer-router/src/storage/lib/jwks.ts). After a key rotation, the
// edge keeps verifying against the old document until that cache entry expires, so a new
// asymmetric key can take this long to become edge-verified. Keep in sync.
const EDGE_JWKS_CACHE_TTL_MS = 600_000
const EDGE_JWKS_WAIT_MS = EDGE_JWKS_CACHE_TTL_MS + 90_000
const EDGE_POLL_INTERVAL_MS = 10_000
const ORIGIN_WAIT_MS = 60_000
const ORIGIN_POLL_INTERVAL_MS = 2_000
// One rotation can wait out a full edge JWKS cache window, and a run has several rotations
const TEST_TIMEOUT_MS = 45 * 60_000

type SmartCdnAccess = 'signed-verified' | 'signed-unverified'

interface WellKnownJwksResponse {
keys: Array<Record<string, unknown>>
}

interface CarriedToken {
route: string
payload: string
}

function log(message: string) {
console.log(`[signed-url-key-rotation] ${message}`)
}

function getToken(route: string): string {
const token = new URL(route, 'http://localhost').searchParams.get('token')
if (!token) {
throw new Error(`Signed route has no token: ${route}`)
}
return token
}

function decodeTokenHeader(token: string): { alg?: string; kid?: string } {
return JSON.parse(Buffer.from(token.split('.')[0], 'base64url').toString('utf8'))
}

// A token's kid header is the key's bare uuid, but older tokens embedded the kind as a prefix
// ("<kind>_<uuid>"), which storage still normalizes when verifying
function headerKidMatches(headerKid: string | undefined, kid: string): boolean {
return headerKid === kid || Boolean(headerKid?.endsWith(`_${kid}`))
}

async function pollUntil<T>(
description: string,
timeoutMs: number,
intervalMs: number,
attempt: () => Promise<{ value: T } | { detail: string }>
): Promise<T> {
const started = Date.now()
let lastDetail = ''
let lastLoggedMinute = 0

for (;;) {
try {
const result = await attempt()
if ('value' in result) {
return result.value
}
lastDetail = result.detail
} catch (error) {
lastDetail = (error as Error).message
}

const elapsedMs = Date.now() - started
if (elapsedMs + intervalMs > timeoutMs) {
throw new Error(
`Timed out after ${Math.round(elapsedMs / 1000)}s waiting for ${description}. Last result: ${lastDetail}`
)
}

const elapsedMinutes = Math.floor(elapsedMs / 60_000)
if (elapsedMinutes > lastLoggedMinute) {
lastLoggedMinute = elapsedMinutes
log(`still waiting for ${description} (${elapsedMinutes}m): ${lastDetail}`)
}
await delay(intervalMs)
}
}

/**
* Rotates the tenant's url-signing key through every key type the admin API can generate and
* verifies signed urls at each step:
*
* - origin: new tokens are signed with the active key's algorithm and kid, tokens minted before
* the swap keep working, and /.well-known/jwks.json publishes only the PUBLIC half of an
* asymmetric key (never a symmetric key or any private field).
* - edge (remote targets with the CDN enabled only), per Smart CDN version:
* V1 never verifies at the edge, so the token is part of the cache key and
* every token for the same object is its own cache entry.
* V2 + HS512 symmetric keys are never published, so the edge cannot verify them: the
* token is part of the cache key (signed-unverified) and isolates entries.
* V2 + ES256 the edge verifies against the published JWKS (signed-verified), so the
* cache key excludes the token and every valid token shares one entry.
*
* It starts from whatever key type is active, visits each of the other types, then swaps the
* original key back in so the tenant is left as it was found. Needs the admin API.
*/
describeAcceptance(
'CDN signed url key rotation',
{
destructive: true,
profiles: ['full'],
requires: ['admin'],
},
() => {
const config = getAcceptanceConfig()
const isCdnV2 = config.cdnVersion === '2'
const hasEdge = config.capabilities.cdnEdge

it(
'signs, publishes, and (at the edge) verifies and caches signed urls across every key type',
async () => {
const admin = await AdminJwksClient.create()
const client = createRestClient()
const bucketName = uniqueBucketName('cdn-key-rotation')
const probeKey = uniqueObjectKey('key-rotation-probe')
const probePayload = `key-rotation-probe-${config.runId}`
const objectKeys = [probeKey]
const generatedKids: string[] = []

const originalKey = await admin.getActiveUrlSigningKey()
if (!originalKey) {
throw new Error(
`Tenant ${admin.tenantId} has no active url-signing key to rotate away from`
)
}

// Every token needs a distinct expiry so two tokens for the same object never end up
// byte-identical (HS512 signatures are deterministic)
let tokenSeq = 0
async function signRoute(objectKey: string, expiresIn = SIGNED_EXPIRES_IN_S) {
const { route } = await getObjectUrl(bucketName, objectKey, 'private', 'signed', {
expiresIn: expiresIn + tokenSeq++,
})
return route
}

// Rotation is propagated to every storage instance asynchronously, so poll until new
// tokens are signed by the expected key
async function waitForSigningKey(key: UrlSigningKey): Promise<string> {
return pollUntil<string>(
`${key.type} key ${key.kid} to start signing`,
ORIGIN_WAIT_MS,
ORIGIN_POLL_INTERVAL_MS,
async () => {
const route = await signRoute(probeKey)
const header = decodeTokenHeader(getToken(route))
if (header.alg === key.type && headerKidMatches(header.kid, key.kid)) {
return { value: route }
}
return { detail: `token header was ${JSON.stringify(header)}` }
}
)
}

async function verifyPublishedJwks(key: UrlSigningKey) {
// Through the edge, a newly rotated key can be published only after its JWKS cache expires
const timeoutMs = hasEdge ? EDGE_JWKS_WAIT_MS : ORIGIN_WAIT_MS
const keys = await pollUntil<Array<Record<string, unknown>>>(
`/.well-known/jwks.json to publish ${key.type} key ${key.kid}`,
timeoutMs,
hasEdge ? EDGE_POLL_INTERVAL_MS : ORIGIN_POLL_INTERVAL_MS,
async () => {
const response = await client.request<WellKnownJwksResponse>(
'GET',
'/.well-known/jwks.json',
{ expectedStatus: 200 }
)
const published = response.json?.keys ?? []
if (key.type === 'HS512' || published.some((jwk) => jwk.kid === key.kid)) {
return { value: published }
}
return { detail: `published kids: ${published.map((jwk) => jwk.kid).join(', ')}` }
}
)

// Nothing published may ever carry private or symmetric key material
for (const jwk of keys) {
expect(jwk).not.toHaveProperty('d')
expect(jwk).not.toHaveProperty('k')
}

const published = keys.find((jwk) => jwk.kid === key.kid)
if (key.type === 'ES256') {
expect(published).toEqual({
kty: 'EC',
crv: 'P-256',
x: expect.any(String),
y: expect.any(String),
kid: key.kid,
alg: 'ES256',
})
} else {
// Symmetric keys have no public form, so they are never published
expect(published).toBeUndefined()
}
}

// Expected edge behaviour for a token signed by `key`
function expectedAccess(key: UrlSigningKey): SmartCdnAccess {
return isCdnV2 && key.type === 'ES256' ? 'signed-verified' : 'signed-unverified'
}

function expectSmartCdnHeaders(response: HttpResponse, key: UrlSigningKey, route: string) {
const version = response.headers.get('x-smart-cdn-version')
const access = response.headers.get('x-smart-cdn-access')
const kid = response.headers.get('x-smart-cdn-kid')

if (isCdnV2) {
expect(version).toBe('v2')
expect(access).toBe(expectedAccess(key))
expect(kid).toBe(decodeTokenHeader(getToken(route)).kid)
} else {
// V1 never edge-verifies. Older deployments do not send these headers at all.
if (version !== null) expect(version).toBe('v1')
if (access !== null) expect(access).toBe('signed-unverified')
}
}

async function verifyOrigin(key: UrlSigningKey, carried: CarriedToken | undefined) {
const probeRoute = await waitForSigningKey(key)
await verifyPublishedJwks(key)

const served = await client.request('GET', probeRoute, { expectedStatus: 200 })
expect(served.body).toBe(probePayload)

// A token minted before the swap keeps working: the demoted key stays active for
// verification, so rotation never breaks urls that were already handed out
if (carried) {
const stillValid = await client.request('GET', carried.route, { expectedStatus: 200 })
expect(stillValid.body).toBe(carried.payload)
}
return probeRoute
}

async function verifyEdge(label: string, key: UrlSigningKey, probeRoute: string) {
const access = expectedAccess(key)

// V2 edge verification of a new asymmetric key waits on the edge's JWKS cache.
// Everything else is decided per request, so it is immediate.
const waitMs = isCdnV2 && key.type === 'ES256' ? EDGE_JWKS_WAIT_MS : ORIGIN_WAIT_MS
await pollUntil<unknown>(
`edge to report x-smart-cdn-access: ${access} for ${key.type} key ${key.kid}` +
(waitMs === EDGE_JWKS_WAIT_MS ? ' (waiting out the edge JWKS cache)' : ''),
waitMs,
EDGE_POLL_INTERVAL_MS,
async () => {
const response = await client.request('GET', probeRoute, { expectedStatus: 200 })
const reported = response.headers.get('x-smart-cdn-access')
if (!isCdnV2 || reported === access) {
return { value: response }
}
return { detail: `x-smart-cdn-access was ${reported}` }
}
)

// A fresh object per key state, so no cache entry can already exist for it
const objectKey = uniqueObjectKey(`key-rotation-${label}`)
const payload = `key-rotation-${label}-${config.runId}`
await uploadRestObject(bucketName, objectKey, payload)
objectKeys.push(objectKey)
await pauseForWebhookIfNeeded('signed')

const routeA = await signRoute(objectKey)
const routeB = await signRoute(objectKey)
expect(getToken(routeA)).not.toEqual(getToken(routeB))

const { hit: hitA, miss: missA } = await warmCacheEndpoint(client, routeA)
expect(missA.body).toBe(payload)
expect(hitA.body).toBe(payload)
expectSmartCdnHeaders(missA, key, routeA)
expectSmartCdnHeaders(hitA, key, routeA)

if (isCdnV2 && key.type === 'ES256') {
// Edge verified: the cache key excludes the token, so B shares the entry A warmed.
// No retries: a retry would re-warm an entry that was not actually shared.
const shared = await client.request('GET', routeB, {
expectedCacheStatus: 'HIT',
expectedStatus: 200,
})
expect(shared.body).toBe(payload)
expectSmartCdnHeaders(shared, key, routeB)
} else {
// Not edge verified: the token is in the cache key, so B is its own entry
const { hit: hitB, miss: missB } = await warmCacheEndpoint(client, routeB)
expect(missB.body).toBe(payload)
expect(hitB.body).toBe(payload)
expectSmartCdnHeaders(missB, key, routeB)
expectSmartCdnHeaders(hitB, key, routeB)
}
}

let carried: CarriedToken | undefined
async function verifyKeyState(label: string, key: UrlSigningKey) {
log(`${label}: verifying ${key.type} key ${key.kid} (Smart CDN V${isCdnV2 ? 2 : 1})`)
const probeRoute = await verifyOrigin(key, carried)
if (hasEdge) {
await verifyEdge(label, key, probeRoute)
}

// Hand a long-lived token to the next key state to prove it survives the rotation
carried = { route: await signRoute(probeKey, 3600), payload: probePayload }
log(`${label}: ok`)
}

try {
await createRestBucket(bucketName, { isPublic: false })
await uploadRestObject(bucketName, probeKey, probePayload)
await pauseForWebhookIfNeeded('signed')

// The starting key can be any type. Visit it first, then every other type.
const otherTypes: UrlSigningKeyType[] = URL_SIGNING_KEY_TYPES.filter(
(type) => type !== originalKey.type
)
await verifyKeyState(`start-${originalKey.type}`, originalKey)

for (const type of otherTypes) {
const standby = await admin.createStandby(type)
generatedKids.push(standby.kid)
await admin.swapToStandby(standby.kid)
await verifyKeyState(`rotate-${type}`, standby)
}

// Swapping the demoted original back in covers rotating *to* an already-published key
// (for ES256, one the edge may already have cached) and restores the tenant
await admin.swapToStandby(originalKey.kid)
await verifyKeyState(`restore-${originalKey.type}`, originalKey)
} finally {
const active = await admin.getActiveUrlSigningKey().catch(() => undefined)
if (active?.kid !== originalKey.kid) {
await admin
.swapToStandby(originalKey.kid, { tolerateMissing: true })
.catch((error) => log(`could not restore original key: ${(error as Error).message}`))
}
for (const kid of generatedKids) {
await admin.deactivate(kid)
}
await cleanupRestResources(bucketName, objectKeys, client)
}
},
TEST_TIMEOUT_MS
)
}
)
Loading