// AWS Signature Version 4, VERIFIED: what an AWS-shaped twin (S3, Secrets Manager, R2's S3 endpoint) checks before it // answers a signed request. The published algorithm (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html, // "Create a signed AWS API request"), the same one executor.ts signs with, run from the other side: the request names // its access key, its credential scope and the headers it signed; the twin finds the key's secret, builds the canonical // request from what arrived, and compares signatures. A presigned URL carries the same parts in its query // (X-Amz-Credential, X-Amz-SignedHeaders, X-Amz-Signature; its payload `UNSIGNED-PAYLOAD`). // // Where the request reached the twin rather than the vendor, the host it signed is the vendor's: the World's injector // names it (`x-volter-twin-original-host`), else the Host the request carries, else its URL's. S3 signs its path as // sent and every other service encodes it a second time (the specification's own clause, as in executor.ts). A // streaming upload (`STREAMING-AWS4-HMAC-SHA256-PAYLOAD`) is checked by its seed signature; its chunk signatures are // not (the twin's reading: the seed binds the request, and the chunks are the body the twin keeps). import * as nodeCrypto from 'node:crypto'; import { receiverNow } from './world-clock.ts'; export type SigV4Verdict = | { ok: true; keyId: string; region: string; service: string } | { ok: false; reason: 'unsigned' | 'malformed' | 'unknown_key' | 'bad_signature' | 'expired'; keyId?: string }; /** The path a request arrived with, where the kernel routed it by another (a virtual-hosted bucket put in front of the * path: pack-fetch's `routed`); a client signed the path it sent. */ export const ORIGINAL_PATH_HEADER = 'x-volter-original-path'; const rfc3986 = (v: string): string => encodeURIComponent(v).replace(/[!\x27()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); const sha256Hex = (data: string | Uint8Array): string => nodeCrypto.createHash('sha256').update(data).digest('hex'); const hmac = (key: Uint8Array | string, data: string): Buffer => nodeCrypto.createHmac('sha256', key).update(data).digest(); /** The time a SigV4 date names (`20260105T093000Z`), in epoch milliseconds. */ const dateOf = (amz: string): number => Date.parse(`${amz.slice(0, 4)}-${amz.slice(4, 6)}-${amz.slice(6, 8)}T${amz.slice(9, 11)}:${amz.slice(11, 13)}:${amz.slice(13, 15)}Z`); /** * Whether `request` is signed with SigV4 by a key `secretOf` knows (its secret, or undefined for a key the twin never * issued). `body` is the bytes it carries (the payload hash of * a service that sends no `x-amz-content-sha256`); `now` is the instant a presigned URL's expiry is checked at, in epoch * milliseconds, on the clock its signer signed by: the app's (`receiverNow()`, the default; ADR 0036 ยง4). The caller * decides what an unsigned request is (a public read, or a refusal). */ export async function verifySigV4(request: Request, body: Uint8Array | string | undefined, secretOf: (keyId: string) => string | undefined | Promise, now: number = receiverNow()): Promise { const url = new URL(request.url); const header = request.headers.get('authorization') ?? ''; const presigned = url.searchParams.get('X-Amz-Algorithm') === 'AWS4-HMAC-SHA256'; let credential: string; let signedHeaders: string; let signature: string; let amzDate: string; let payloadHash: string; if (/^AWS4-HMAC-SHA256\s/i.test(header)) { const parts = Object.fromEntries(header.replace(/^AWS4-HMAC-SHA256\s+/i, '').split(/,\s*/).map((p) => { const at = p.indexOf('='); return [p.slice(0, at).trim(), p.slice(at + 1).trim()]; })); if (!parts.Credential || !parts.SignedHeaders || !parts.Signature) return { ok: false, reason: 'malformed' }; credential = parts.Credential; signedHeaders = parts.SignedHeaders; signature = parts.Signature; amzDate = request.headers.get('x-amz-date') ?? ''; const declared = request.headers.get('x-amz-content-sha256'); payloadHash = declared ?? sha256Hex(body ?? ''); } else if (presigned) { credential = url.searchParams.get('X-Amz-Credential') ?? ''; signedHeaders = url.searchParams.get('X-Amz-SignedHeaders') ?? ''; signature = url.searchParams.get('X-Amz-Signature') ?? ''; amzDate = url.searchParams.get('X-Amz-Date') ?? ''; payloadHash = 'UNSIGNED-PAYLOAD'; const expires = Number(url.searchParams.get('X-Amz-Expires') ?? ''); if (!Number.isFinite(expires) || !/^\d{8}T\d{6}Z$/.test(amzDate)) return { ok: false, reason: 'malformed' }; if (now > dateOf(amzDate) + expires * 1000) return { ok: false, reason: 'expired' }; } else { return { ok: false, reason: 'unsigned' }; } const [keyId = '', dateStamp = '', region = '', service = '', terminal = ''] = credential.split('/'); if (!keyId || terminal !== 'aws4_request' || !/^\d{8}$/.test(dateStamp) || !/^\d{8}T\d{6}Z$/.test(amzDate)) return { ok: false, reason: 'malformed', ...(keyId ? { keyId } : {}) }; const secret = await secretOf(keyId); if (secret === undefined) return { ok: false, reason: 'unknown_key', keyId }; // A canonical request binds the declared hash; the declaration must also describe the bytes received. // S3's UNSIGNED-PAYLOAD and streaming markers are separate wire modes, not ordinary payload digests. // https://docs.aws.amazon.com/AmazonS3/latest/developerguide/sig-v4-header-based-auth.html const declaredPayload = request.headers.get('x-amz-content-sha256'); if (declaredPayload !== null && /^[0-9a-f]{64}$/i.test(declaredPayload) && declaredPayload.toLowerCase() !== sha256Hex(body ?? '')) { return { ok: false, reason: 'bad_signature', keyId }; } const host = request.headers.get('x-volter-twin-original-host') ?? request.headers.get('host') ?? url.host; const sentPath = request.headers.get(ORIGINAL_PATH_HEADER) ?? url.pathname; const raw = sentPath === '' ? '/' : sentPath; const canonicalUri = service === 's3' ? raw : raw.split('/').map((segment) => rfc3986(decodeURIComponent(segment))).map(rfc3986).join('/'); const canonicalQuery = [...url.searchParams.entries()] .filter(([k]) => !(presigned && k === 'X-Amz-Signature')) .map(([k, v]) => [rfc3986(k), rfc3986(v)] as const) .sort((left, right) => (left[0] === right[0] ? (left[1] < right[1] ? -1 : 1) : left[0] < right[0] ? -1 : 1)) .map(([k, v]) => `${k}=${v}`) .join('&'); const names = signedHeaders.toLowerCase().split(';').filter(Boolean); const value = (name: string): string => (name === 'host' ? host : (request.headers.get(name) ?? '')).trim().replace(/\s+/g, ' '); const canonicalHeaders = names.map((n) => `${n}:${value(n)}\n`).join(''); const canonicalRequest = [request.method.toUpperCase(), canonicalUri, canonicalQuery, canonicalHeaders, names.join(';'), payloadHash].join('\n'); const scope = `${dateStamp}/${region}/${service}/aws4_request`; const stringToSign = ['AWS4-HMAC-SHA256', amzDate, scope, sha256Hex(canonicalRequest)].join('\n'); let key: Buffer = hmac(`AWS4${secret}`, dateStamp); for (const part of [region, service, 'aws4_request']) key = hmac(key, part); const expected = hmac(key, stringToSign).toString('hex'); const given = Buffer.from(signature.toLowerCase(), 'utf8'); const want = Buffer.from(expected, 'utf8'); if (given.length !== want.length || !nodeCrypto.timingSafeEqual(given, want)) return { ok: false, reason: 'bad_signature', keyId }; return { ok: true, keyId, region, service }; } /** * The SigV4 headers a client adds (`authorization`, `x-amz-date`, and for S3 `x-amz-content-sha256`), signed over the * request as it will be sent: its method, URL, the headers it carries (host, `x-amz-*` and the content type are signed) * and its body, at `at`. What a walk sends as an AWS SDK sends it; the verifier above is its other side. */ export function signSigV4(input: { method: string; url: string; headers?: Record; body?: string | Uint8Array; keyId: string; secret: string; region: string; service: string; at: Date }): Record { const url = new URL(input.url); const amzDate = `${input.at.toISOString().slice(0, 19).replace(/[:-]/g, '')}Z`; const dateStamp = amzDate.slice(0, 8); const payloadHash = input.body === undefined ? new Headers(input.headers).get('x-amz-content-sha256') ?? sha256Hex('') : sha256Hex(input.body); const raw = url.pathname === '' ? '/' : url.pathname; const canonicalUri = input.service === 's3' ? raw : raw.split('/').map((segment) => rfc3986(decodeURIComponent(segment))).map(rfc3986).join('/'); const canonicalQuery = [...url.searchParams.entries()] .map(([k, v]) => [rfc3986(k), rfc3986(v)] as const) .sort((left, right) => (left[0] === right[0] ? (left[1] < right[1] ? -1 : 1) : left[0] < right[0] ? -1 : 1)) .map(([k, v]) => `${k}=${v}`) .join('&'); const added: Record = { 'x-amz-date': amzDate, ...(input.service === 's3' ? { 'x-amz-content-sha256': payloadHash } : {}) }; const signable = new Map([['host', url.host]]); for (const [name, value] of Object.entries({ ...(input.headers ?? {}), ...added })) { const n = name.toLowerCase(); if (n.startsWith('x-amz-') || n === 'content-type') signable.set(n, value.trim().replace(/\s+/g, ' ')); } const names = [...signable.keys()].sort(); const canonicalRequest = [input.method.toUpperCase(), canonicalUri, canonicalQuery, names.map((n) => `${n}:${signable.get(n)!}\n`).join(''), names.join(';'), payloadHash].join('\n'); const scope = `${dateStamp}/${input.region}/${input.service}/aws4_request`; const stringToSign = ['AWS4-HMAC-SHA256', amzDate, scope, sha256Hex(canonicalRequest)].join('\n'); let key: Buffer = hmac(`AWS4${input.secret}`, dateStamp); for (const part of [input.region, input.service, 'aws4_request']) key = hmac(key, part); return { ...added, authorization: `AWS4-HMAC-SHA256 Credential=${input.keyId}/${scope}, SignedHeaders=${names.join(';')}, Signature=${hmac(key, stringToSign).toString('hex')}` }; } /** * A presigned URL signed again with a key: its date, expiry, region, service and signed headers are the URL's own * (X-Amz-Date, X-Amz-Expires, X-Amz-Credential's scope, X-Amz-SignedHeaders, `host` when it names none), its key and * signature this key's. What an SDK's getSignedUrl makes, for a walk that wrote the URL as its client printed it. A * signed header other than `host` (a Content-Type the URL binds) is signed with the value the request sends (`headers`). */ export function presignSigV4(input: { method: string; url: string; keyId: string; secret: string; host?: string; headers?: Record }): string { const url = new URL(input.url); const q = url.searchParams; const [, dateStamp = '', region = '', service = ''] = (q.get('X-Amz-Credential') ?? '').split('/'); const amzDate = q.get('X-Amz-Date') ?? ''; q.set('X-Amz-Algorithm', 'AWS4-HMAC-SHA256'); q.set('X-Amz-Credential', `${input.keyId}/${dateStamp}/${region}/${service}/aws4_request`); if (!q.has('X-Amz-SignedHeaders')) q.set('X-Amz-SignedHeaders', 'host'); q.delete('X-Amz-Signature'); const raw = url.pathname === '' ? '/' : url.pathname; const canonicalUri = service === 's3' ? raw : raw.split('/').map((segment) => rfc3986(decodeURIComponent(segment))).map(rfc3986).join('/'); const canonicalQuery = [...q.entries()] .map(([k, v]) => [rfc3986(k), rfc3986(v)] as const) .sort((left, right) => (left[0] === right[0] ? (left[1] < right[1] ? -1 : 1) : left[0] < right[0] ? -1 : 1)) .map(([k, v]) => `${k}=${v}`) .join('&'); const names = (q.get('X-Amz-SignedHeaders') ?? 'host').toLowerCase().split(';').filter(Boolean); const sent = new Headers(input.headers ?? {}); const canonicalHeaders = names.map((n) => `${n}:${(n === 'host' ? (input.host ?? url.host) : sent.get(n) ?? '').trim().replace(/\s+/g, ' ')}\n`).join(''); const canonicalRequest = [input.method.toUpperCase(), canonicalUri, canonicalQuery, canonicalHeaders, names.join(';'), 'UNSIGNED-PAYLOAD'].join('\n'); const stringToSign = ['AWS4-HMAC-SHA256', amzDate, `${dateStamp}/${region}/${service}/aws4_request`, sha256Hex(canonicalRequest)].join('\n'); let key: Buffer = hmac(`AWS4${input.secret}`, dateStamp); for (const part of [region, service, 'aws4_request']) key = hmac(key, part); q.set('X-Amz-Signature', hmac(key, stringToSign).toString('hex')); return url.toString(); }