diff --git a/apps/api-edge/component.yaml b/apps/api-edge/component.yaml new file mode 100644 index 0000000..5202f55 --- /dev/null +++ b/apps/api-edge/component.yaml @@ -0,0 +1,88 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: api-edge + description: Cloudflare Worker for the API edge Runtime +spec: + type: cloudflare-worker-turbo + lifecycle: production + owner: platform + domain: starter-runtime + path: apps/api-edge + dependsOn: + - component: cloudflare-d1 + - component: cloudflare-kv + - component: projects-worker + - component: events-worker + - component: config-worker + - component: webhooks-worker + - component: billing-worker + - component: integrations-worker + - component: identity-worker + - component: membership-worker + - component: metering-worker + - component: notifications-worker + # BF6 wiring documents from orun secrets (SEC-JOB): lease-published by + # the infra components; wire-live renders the wrangler template from + # these instead of Secrets Manager documents. + secretEnv: + WIRING_CLOUDFLARE_D1_STAGE: "secret://org_c126e518fd9b4cae9706f760c9f8551b/new-test/stage/WIRING_CLOUDFLARE_D1" + WIRING_CLOUDFLARE_D1_PROD: "secret://org_c126e518fd9b4cae9706f760c9f8551b/new-test/prod/WIRING_CLOUDFLARE_D1" + WIRING_CLOUDFLARE_KV_STAGE: "secret://org_c126e518fd9b4cae9706f760c9f8551b/new-test/stage/WIRING_CLOUDFLARE_KV" + WIRING_CLOUDFLARE_KV_PROD: "secret://org_c126e518fd9b4cae9706f760c9f8551b/new-test/prod/WIRING_CLOUDFLARE_KV" + + subscribe: + environments: + - name: dev + profile: verify + - name: stage + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + - name: prod + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + + workspaceDir: ../.. + appDir: . + + turboFilter: "@saas/api-edge" + wranglerConfig: wrangler.jsonc + + # BF6 deploy-time wiring (pilot): wrangler.jsonc is rendered, never + # committed. Verify lanes render from wiring.fixture.json (offline); + # deploy lanes resolve real IDs from the Secrets Manager wiring manifest + # published by the named infra components (BF5). + wranglerTemplate: wrangler.template.jsonc + wiringComponents: "cloudflare-d1,cloudflare-kv" + wiringEnvs: "stage,prod" + wiringFixture: wiring.fixture.json + orgName: sourceplane + owner: sourceplane + repo: new-test + + installCommand: pnpm install --frozen-lockfile + buildCommand: pnpm exec turbo run build --filter=@saas/api-edge + typecheckCommand: pnpm exec turbo run typecheck --filter=@saas/api-edge + + dryRunCommand: pnpm exec wrangler deploy --dry-run --config wrangler.jsonc --env prod + deployCommand: pnpm exec wrangler deploy --config wrangler.jsonc --env prod + + preDeployCommand: "echo 'No pre-deploy step configured.'" + migrationCommand: "echo 'No migrations configured.'" + smokeCommand: "echo 'No smoke test configured.'" + labels: + team: platform + layer: runtime + surface: api + runtime: cloudflare +# ci: re-trigger deploy (batch C — integrations + api-edge gateway, 20260622T141448Z) +# ci: re-trigger deploy (batch C — integrations + api-edge gateway, 20260622T141448Z) diff --git a/apps/api-edge/docs/architecture.md b/apps/api-edge/docs/architecture.md new file mode 100644 index 0000000..4b5cb37 --- /dev/null +++ b/apps/api-edge/docs/architecture.md @@ -0,0 +1,21 @@ +# api-edge — architecture + +A `cloudflare-worker-turbo` component: TypeScript built by the turbo pipeline +from `apps/api-edge`, deployed per environment by its CI lane. + +## Bindings and wiring + +- **Service bindings** → `projects-worker`, `events-worker`, `config-worker`, `webhooks-worker`, `billing-worker`, `integrations-worker`, `identity-worker`, `membership-worker`, `metering-worker`, `notifications-worker` — + in-process RPC to sibling Workers; no public hops between contexts. +- **Wired configuration** (resolved at deploy time from job-output + secrets published by the infrastructure terraform; names only): + `WIRING_CLOUDFLARE_D1_STAGE`, `WIRING_CLOUDFLARE_D1_PROD`, `WIRING_CLOUDFLARE_KV_STAGE`, `WIRING_CLOUDFLARE_KV_PROD`. +- **`PLATFORM_DB`** is a D1 binding. SQLite types apply: timestamps are + ISO-8601 text, JSON is text, booleans are 0/1, and there is no + interactive transaction (see `packages/db/src/d1`). + +## Boundaries + +This Worker owns its bounded context: its data, its invariants, its +API surface (exposed to the fleet through the edge). Cross-context calls +go over service bindings; nothing else may reach into its storage. diff --git a/apps/api-edge/docs/overview.md b/apps/api-edge/docs/overview.md new file mode 100644 index 0000000..505cc93 --- /dev/null +++ b/apps/api-edge/docs/overview.md @@ -0,0 +1,24 @@ +# api-edge + +Cloudflare Worker for the API edge Runtime + +Part of the new-test runtime: a Cloudflare Worker deployed per environment (`stage`, `prod`; `dev` is verify-only). Not publicly routable — reached only through `api-edge` service bindings. + +## Depends on + +- **cloudflare-d1** — Provisions the Cloudflare D1 platform database for stage and prod +- **cloudflare-kv** — Provisions Cloudflare KV namespaces backing the api-edge idempotency replay store (stage and prod) +- **projects-worker** — Cloudflare Worker for the Projects runtime +- **events-worker** — Cloudflare Worker for the Events and Audit runtime +- **config-worker** — Cloudflare Worker for the Config read-only API surface +- **webhooks-worker** — Cloudflare Worker for webhook endpoint, subscription, and delivery-attempt management +- **billing-worker** — Cloudflare Worker for the Billing API surface (private, service-binding only) +- **integrations-worker** — Cloudflare Worker for the integrations bounded context — provider connections (GitHub App first), inbound delivery inbox, repo links, and the installation-token broker +- **identity-worker** — Cloudflare Worker for the Identity auth runtime +- **membership-worker** — Cloudflare Worker for the Membership org runtime +- **metering-worker** — Cloudflare Worker for the Metering API surface (usage recording, quota checks) +- **notifications-worker** — Cloudflare Worker for the Notifications bounded context + +## Depended on by + +- **web-console-next** — Next.js 15 + opennextjs/cloudflare delivery of the new-test web console (per-environment, Workers + Static Assets) diff --git a/apps/api-edge/docs/runbook.md b/apps/api-edge/docs/runbook.md new file mode 100644 index 0000000..c15ecb3 --- /dev/null +++ b/apps/api-edge/docs/runbook.md @@ -0,0 +1,32 @@ +# api-edge — runbook + +## How it deploys + +Merges to `main` converge automatically: CI plans changed components +(`orun plan --changed`) and runs this component's lane via +`orun run --remote-state` with credential-free OIDC auth. The convergence +run is the deployment; the DAG orders this component after everything it +depends on. Failed lanes resume with `gh run rerun --failed`. + +## Rollback + +Revert the offending commit on `main`; the next convergence applies the +previous desired state. There is no out-of-band mutation to undo — the +repo is the source of truth. + +## Verify + +The deploy lane's own verify/smoke is the gate. End-to-end behavior is +exercised through `api-edge` (this Worker has no public URL). + +## Common failures + +- **Missing `WIRING_*` secret at deploy**: the infrastructure terraform + upstream has not applied — check that lane first; within one + convergence run the DAG guarantees order. +- **Service-binding target missing (Cloudflare 10143)**: the target + Worker does not exist yet on this account — converge the fleet before + this lane (the bootstrap's two-pass landing handles first boot). +- **Smoke fails right after a first deploy**: a brand-new workers.dev + route can 4xx for a few seconds; the lane already retries — persistent + failure means a real regression. diff --git a/apps/api-edge/eslint.config.js b/apps/api-edge/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/apps/api-edge/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/apps/api-edge/package.json b/apps/api-edge/package.json new file mode 100644 index 0000000..a2dcefb --- /dev/null +++ b/apps/api-edge/package.json @@ -0,0 +1,26 @@ +{ + "name": "@saas/api-edge", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "wrangler dev", + "build": "wrangler deploy --dry-run --outdir dist", + "deploy": "wrangler deploy", + "typecheck": "tsc --noEmit", + "lint": "eslint src", + "verify-bindings": "node scripts/verify-bindings.mjs", + "wire:fixture": "node ../../tooling/wire/render.mjs --template wrangler.template.jsonc --out wrangler.jsonc --map wiring.fixture.json" + }, + "devDependencies": { + "@cloudflare/workers-types": "^4.20250508.0", + "@saas/eslint-config": "workspace:*", + "@saas/tsconfig": "workspace:*", + "typescript": "^5.8.3", + "wrangler": "^4.14.4" + }, + "dependencies": { + "@saas/contracts": "workspace:*", + "@saas/db": "workspace:*" + } +} diff --git a/apps/api-edge/scripts/verify-bindings.mjs b/apps/api-edge/scripts/verify-bindings.mjs new file mode 100644 index 0000000..bd61708 --- /dev/null +++ b/apps/api-edge/scripts/verify-bindings.mjs @@ -0,0 +1,177 @@ +import { readFileSync } from "node:fs"; +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +function stripJsoncComments(text) { + return text.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, ""); +} + +// BF6: resource IDs are never committed — wrangler.jsonc is rendered from +// wrangler.template.jsonc, so this checks the rendered shape (valid 32-hex, +// stage and prod distinct), not literal account IDs. +const EXPECTED_D1 = { + stage: { binding: "PLATFORM_DB" }, + prod: { binding: "PLATFORM_DB" }, +}; + +// A D1 database id is a UUID; the offline wiring fixture uses the 32-hex form. +const D1_ID_PATTERN = + /^[0-9a-f]{32}$|^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +const seenD1Ids = new Map(); + +const EXPECTED_KV = { + stage: { + binding: "IDEMPOTENCY_KV", + }, + prod: { + binding: "IDEMPOTENCY_KV", + }, +}; + +const KV_ID_PATTERN = /^[0-9a-f]{32}$/; +const KV_ID_SENTINELS = new Set([ + "0000000000000000000000000000000a", + "0000000000000000000000000000000b", +]); + +// Service-binding targets carry the worker prefix the whole fleet ships with +// (`--`). The brand is NOT hardcoded: it is read from this +// worker's own `name`, so a rebranded fork verifies its own names instead of +// the baseline's. (Hardcoding it here is exactly what made this check pass in +// the baseline and fail in every fork.) +const EXPECTED_SERVICE_BINDINGS = [ + { binding: "IDENTITY_WORKER", worker: "identity-worker" }, + { binding: "MEMBERSHIP_WORKER", worker: "membership-worker" }, + { binding: "PROJECTS_WORKER", worker: "projects-worker" }, +]; + +const configPath = resolve(__dirname, "../wrangler.jsonc"); +const raw = readFileSync(configPath, "utf-8"); +const config = JSON.parse(stripJsoncComments(raw)); + +let failures = 0; + +for (const [envName, expected] of Object.entries(EXPECTED_D1)) { + const envBlock = config.env?.[envName]; + if (!envBlock) { + console.error(`FAIL: environment "${envName}" not found in wrangler.jsonc`); + failures++; + continue; + } + + const db = envBlock.d1_databases?.find((d) => d.binding === expected.binding); + if (!db) { + console.error( + `FAIL: [${envName}] missing d1_databases binding "${expected.binding}"` + ); + failures++; + continue; + } + + if (typeof db.database_id !== "string" || !D1_ID_PATTERN.test(db.database_id)) { + console.error( + `FAIL: [${envName}] binding "${expected.binding}" database_id "${db.database_id}" is not a D1 id` + ); + failures++; + continue; + } + + seenD1Ids.set(envName, db.database_id); + + const envVar = envBlock.vars?.ENVIRONMENT; + if (envVar !== envName) { + console.error( + `FAIL: [${envName}] ENVIRONMENT var mismatch: got "${envVar}", want "${envName}"` + ); + failures++; + continue; + } + + console.log(`OK: [${envName}] PLATFORM_DB → ${db.database_id}`); +} + +if (seenD1Ids.has("stage") && seenD1Ids.get("stage") === seenD1Ids.get("prod")) { + console.error( + `FAIL: stage and prod share the same D1 database id "${seenD1Ids.get("stage")}" — ` + + `one environment is bound to the other's data` + ); + failures++; +} + +for (const [envName, expected] of Object.entries(EXPECTED_KV)) { + const envBlock = config.env?.[envName]; + if (!envBlock) { + console.error(`FAIL: environment "${envName}" not found in wrangler.jsonc`); + failures++; + continue; + } + + const kv = envBlock.kv_namespaces?.find((k) => k.binding === expected.binding); + if (!kv) { + console.error( + `FAIL: [${envName}] missing kv_namespaces binding "${expected.binding}"` + ); + failures++; + continue; + } + + if (typeof kv.id !== "string" || !KV_ID_PATTERN.test(kv.id)) { + console.error( + `FAIL: [${envName}] kv binding "${expected.binding}" id "${kv.id}" does not match /^[0-9a-f]{32}$/` + ); + failures++; + continue; + } + + if (KV_ID_SENTINELS.has(kv.id)) { + console.error( + `FAIL: [${envName}] kv binding "${expected.binding}" still uses sentinel id "${kv.id}" — replace with the real Cloudflare KV namespace id` + ); + failures++; + continue; + } + + console.log(`OK: [${envName}] ${expected.binding} → ${kv.id}`); +} + +// `name` is `-api-edge`; everything before the last "-api-edge" is the +// brand prefix the fleet shares. +const brandPrefix = String(config.name ?? "").replace(/api-edge$/, ""); + +for (const envName of ["stage", "prod"]) { + const envBlock = config.env?.[envName]; + if (!envBlock) { + console.error(`FAIL: environment "${envName}" not found in wrangler.jsonc`); + failures++; + continue; + } + + for (const expected of EXPECTED_SERVICE_BINDINGS) { + const want = `${brandPrefix}${expected.worker}-${envName}`; + const svc = envBlock.services?.find((s) => s.binding === expected.binding); + if (!svc) { + console.error( + `FAIL: [${envName}] missing service binding "${expected.binding}"` + ); + failures++; + continue; + } + if (svc.service !== want) { + console.error( + `FAIL: [${envName}] service binding "${expected.binding}" target mismatch: got "${svc.service}", want "${want}"` + ); + failures++; + continue; + } + console.log(`OK: [${envName}] ${expected.binding} → ${svc.service}`); + } +} + +if (failures > 0) { + console.error(`\n${failures} binding verification failure(s)`); + process.exit(1); +} else { + console.log("\nAll binding verifications passed."); +} diff --git a/apps/api-edge/src/actor-cache.ts b/apps/api-edge/src/actor-cache.ts new file mode 100644 index 0000000..a22fd5c --- /dev/null +++ b/apps/api-edge/src/actor-cache.ts @@ -0,0 +1,113 @@ +import type { ActorInfo } from "./resolve-actor"; + +/** + * Edge bearer→actor resolution cache (Task 0131 / PERF2). + * + * Bearer resolution runs on every authenticated request (api-edge → + * identity-worker → 2 DB queries, ~0.45s measured). For a stable session/key + * that result is identical request-to-request, so we cache it for a short TTL + * and skip the identity hop on the hot path. + * + * Security invariants: + * - keyed on a SHA-256 hash of the token (the raw token is never stored or + * logged; the cached value is the minimal non-secret `ActorInfo` only); + * - short TTL (revocation latency is bounded by it); + * - only successful resolutions are cached — never a denial, so the cache can + * never turn a 401 into an allow; + * - best-effort: any cache error falls through to a live resolve (fail-closed + * is preserved by the resolver, not the cache). + * + * Backed by the Workers Cache API (`caches.default`) — colo-local, no new + * infra/resource. A `noopStore` is used when the Cache API is unavailable + * (e.g. unit tests) so resolution always still works. + */ + +export interface ActorCacheStore { + get(token: string): Promise; + set(token: string, actor: ActorInfo): Promise; + evict(token: string): Promise; +} + +export const ACTOR_CACHE_TTL_SECONDS = 30; + +/** SHA-256 hex of the token — the cache key material (never the raw token). */ +export async function hashToken(token: string): Promise { + const data = new TextEncoder().encode(token); + const digest = await crypto.subtle.digest("SHA-256", data); + return Array.from(new Uint8Array(digest)) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); +} + +function keyUrl(hash: string): string { + return `https://actor-cache.internal/v1/${hash}`; +} + +/** No-op store: every get misses, set/evict do nothing. */ +export function noopStore(): ActorCacheStore { + return { + async get() { + return null; + }, + async set() { + /* no-op */ + }, + async evict() { + /* no-op */ + }, + }; +} + +type CacheLike = { + match(key: string): Promise; + put(key: string, res: Response): Promise; + delete(key: string): Promise; +}; + +/** Cache-API-backed store. Falls back to a no-op store when unavailable. */ +export function cacheApiStore(): ActorCacheStore { + const c = + typeof caches !== "undefined" && (caches as unknown as { default?: CacheLike }).default + ? ((caches as unknown as { default: CacheLike }).default) + : null; + if (!c) return noopStore(); + return { + async get(token) { + try { + const res = await c.match(keyUrl(await hashToken(token))); + if (!res) return null; + return (await res.json()) as ActorInfo; + } catch { + return null; + } + }, + async set(token, actor) { + try { + const res = new Response(JSON.stringify(actor), { + status: 200, + headers: { + "content-type": "application/json", + "cache-control": `max-age=${ACTOR_CACHE_TTL_SECONDS}`, + }, + }); + await c.put(keyUrl(await hashToken(token)), res); + } catch { + /* best-effort */ + } + }, + async evict(token) { + try { + await c.delete(keyUrl(await hashToken(token))); + } catch { + /* best-effort */ + } + }, + }; +} + +/** Extract the bearer token from an Authorization header value, or null. */ +export function bearerToken(authorization: string | null): string | null { + if (!authorization || !authorization.startsWith("Bearer ")) return null; + const token = authorization.slice("Bearer ".length).trim(); + return token.length > 0 ? token : null; +} diff --git a/apps/api-edge/src/app-config.ts b/apps/api-edge/src/app-config.ts new file mode 100644 index 0000000..e6c915e --- /dev/null +++ b/apps/api-edge/src/app-config.ts @@ -0,0 +1,17 @@ +// Instance identity for api-edge (saas-bootstrap-factory BF3 seam). +// +// Every deployment-identity literal this Worker needs lives here, so a new +// instance of the starter retargets one file (or, later, one generated +// config) instead of hunting through handler code. Do not add behavior — +// values and trivial derivations only. + +/** The Cloudflare account's workers.dev subdomain serving this instance. */ +export const WORKERS_DEV_SUBDOMAIN = "nexo-7be"; + +/** Worker name prefix of the console delivery (per-env: `${prefix}-${env}`). */ +export const CONSOLE_WORKER_PREFIX = "new-test-web-console-next"; + +/** workers.dev origin of the console for a given environment name. */ +export function consoleWorkersDevOrigin(environment: string): string { + return `https://${CONSOLE_WORKER_PREFIX}-${environment}.${WORKERS_DEV_SUBDOMAIN}.workers.dev`; +} diff --git a/apps/api-edge/src/audit-facade.ts b/apps/api-edge/src/audit-facade.ts new file mode 100644 index 0000000..57c5239 --- /dev/null +++ b/apps/api-edge/src/audit-facade.ts @@ -0,0 +1,97 @@ +import type { Env } from "./env.js"; +import { errorResponse, withEdgeTimings } from "./http.js"; +import { enforceRateLimit, mergeRateLimitHeaders } from "./rate-limit.js"; +import { resolveActor } from "./resolve-actor.js"; +import { createTimings } from "@saas/contracts/timing"; + +const ORG_AUDIT_RE = /^\/v1\/organizations\/[^/]+\/audit$/; + +const FORWARDED_HEADERS = [ + "content-type", + "x-request-id", + "traceparent", + "idempotency-key", +]; + +export function isAuditRoute(pathname: string): boolean { + return ORG_AUDIT_RE.test(pathname); +} + +export async function handleAuditRoute( + request: Request, + env: Env, + requestId: string, + pathname: string, +): Promise { + if (request.method !== "GET") { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + const rateDecision = await enforceRateLimit(request, requestId, env, "audit"); + if (rateDecision.kind === "denied") { + return rateDecision.response; + } + const rateHeaders = rateDecision.headers; + + if (!env.IDENTITY_WORKER) { + return mergeRateLimitHeaders( + errorResponse("internal_error", "Authentication service unavailable", 503, requestId), + rateHeaders, + ); + } + + if (!env.EVENTS_WORKER) { + return mergeRateLimitHeaders( + errorResponse("internal_error", "Events service unavailable", 503, requestId), + rateHeaders, + ); + } + + const timings = createTimings(); + const endTotal = timings.start("edge_total"); + const sessionResult = await timings.measure("edge_auth", () => resolveActor(request, env, requestId)); + if ("error" in sessionResult) { + return mergeRateLimitHeaders(sessionResult.error, rateHeaders); + } + + const headers = new Headers(); + headers.set("x-request-id", requestId); + headers.set("x-actor-subject-id", sessionResult.subjectId); + headers.set("x-actor-subject-type", sessionResult.subjectType); + headers.set("x-actor-email", sessionResult.email); + if (sessionResult.orgId) { + } + for (const name of FORWARDED_HEADERS) { + if (name === "x-request-id") continue; + const value = request.headers.get(name); + if (value) headers.set(name, value); + } + + const url = new URL(request.url); + const target = new URL(pathname + url.search, "https://events.internal"); + + try { + const downstream = await timings.measure("edge_downstream", () => env.EVENTS_WORKER!.fetch(target.toString(), { + method: "GET", + headers, + })); + endTotal(); + return mergeRateLimitHeaders( + withEdgeTimings( + new Response(downstream.body, { + status: downstream.status, + headers: downstream.headers, + }), + requestId, + "edge.audit", + timings, + ), + rateHeaders, + ); + } catch { + return mergeRateLimitHeaders( + errorResponse("internal_error", "Events service unavailable", 503, requestId), + rateHeaders, + ); + } +} diff --git a/apps/api-edge/src/auth-facade.ts b/apps/api-edge/src/auth-facade.ts new file mode 100644 index 0000000..654359c --- /dev/null +++ b/apps/api-edge/src/auth-facade.ts @@ -0,0 +1,131 @@ +import type { Env } from "./env"; +import { errorResponse } from "./http"; +import { replayOrExecute } from "./idempotency"; +import { cacheApiStore, bearerToken } from "./actor-cache"; + +const LOGOUT_PATH = "/v1/auth/logout"; + +const AUTH_ROUTES: Record = { + "/v1/auth/login/start": "POST", + "/v1/auth/login/complete": "POST", + "/v1/auth/session": "GET", + "/v1/auth/resolve": "GET", + "/v1/auth/logout": "POST", + "/v1/auth/security-events": "GET", +}; + +const AUTH_MULTI_METHOD_ROUTES: Record> = { + "/v1/auth/profile": new Set(["GET", "PATCH"]), +}; + +// OAuth sign-in routes (all GET). `start` and `callback` are browser-redirect +// navigations; `providers` is a JSON read. The `:provider` segment is dynamic, +// so these are matched by pattern rather than the static route map. +const OAUTH_PROVIDERS_PATH = "/v1/auth/oauth/providers"; +const OAUTH_START_RE = /^\/v1\/auth\/oauth\/[^/]+\/start$/; +const OAUTH_CALLBACK_RE = /^\/v1\/auth\/oauth\/[^/]+\/callback$/; + +function isOAuthRoute(pathname: string): boolean { + return ( + pathname === OAUTH_PROVIDERS_PATH || + OAUTH_START_RE.test(pathname) || + OAUTH_CALLBACK_RE.test(pathname) + ); +} + +const FORWARDED_HEADERS = [ + "authorization", + "content-type", + "x-request-id", + "traceparent", + "idempotency-key", + // Forwarded so the OAuth callback can read the state cookie set by `start` + // (double-submit CSRF defense). Cookies are first-party to api-edge. + "cookie", +]; + +export function isAuthRoute(pathname: string): boolean { + return pathname in AUTH_ROUTES || pathname in AUTH_MULTI_METHOD_ROUTES || isOAuthRoute(pathname); +} + +export async function handleAuthRoute( + request: Request, + env: Env, + requestId: string, + pathname: string, +): Promise { + const expectedMethod = AUTH_ROUTES[pathname]; + const allowedMethods = AUTH_MULTI_METHOD_ROUTES[pathname]; + const oauth = isOAuthRoute(pathname); + + if (!expectedMethod && !allowedMethods && !oauth) { + return errorResponse("not_found", `Route not found: ${pathname}`, 404, requestId); + } + + if (oauth) { + if (request.method !== "GET") { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + } else if (expectedMethod && request.method !== expectedMethod) { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } else if (allowedMethods && !allowedMethods.has(request.method)) { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + return replayOrExecute(request, requestId, env, "auth", async () => { + if (!env.IDENTITY_WORKER) { + return errorResponse( + "internal_error", + "Authentication service unavailable", + 503, + requestId, + ); + } + + const headers = new Headers(); + headers.set("x-request-id", requestId); + for (const name of FORWARDED_HEADERS) { + if (name === "x-request-id") continue; + const value = request.headers.get(name); + if (value) headers.set(name, value); + } + + const url = new URL(request.url); + const target = new URL(pathname + url.search, "https://identity.internal"); + + const init: RequestInit = { + method: request.method, + headers, + // OAuth `start`/`callback` return 302s (to the provider, then back to the + // console). Without manual mode the service-binding fetch would FOLLOW + // them server-side instead of handing the redirect to the browser. + // Other auth routes never redirect, so this is inert for them. + redirect: "manual", + }; + + if (request.method === "POST" || request.method === "PATCH") { + init.body = request.body; + } + + try { + const downstream = await env.IDENTITY_WORKER.fetch(target.toString(), init); + // On a successful logout, evict the cached actor so the (now-revoked) + // session can't be served from the edge cache for the rest of its TTL. + if (pathname === LOGOUT_PATH && downstream.ok) { + const token = bearerToken(request.headers.get("authorization")); + if (token) await cacheApiStore().evict(token); + } + return new Response(downstream.body, { + status: downstream.status, + headers: downstream.headers, + }); + } catch { + return errorResponse( + "internal_error", + "Authentication service unavailable", + 503, + requestId, + ); + } + }); +} diff --git a/apps/api-edge/src/billing-facade.ts b/apps/api-edge/src/billing-facade.ts new file mode 100644 index 0000000..f527a1a --- /dev/null +++ b/apps/api-edge/src/billing-facade.ts @@ -0,0 +1,108 @@ +import type { Env } from "./env.js"; +import { errorResponse, withEdgeTimings } from "./http.js"; +import { replayOrExecute } from "./idempotency.js"; +import { resolveActor } from "./resolve-actor.js"; +import { createTimings } from "@saas/contracts/timing"; + +const ORG_BILLING_PLANS_RE = /^\/v1\/organizations\/[^/]+\/billing\/plans$/; +const ORG_BILLING_CUSTOMER_RE = /^\/v1\/organizations\/[^/]+\/billing\/customer$/; +const ORG_BILLING_SUMMARY_RE = /^\/v1\/organizations\/[^/]+\/billing\/summary$/; +const ORG_BILLING_INVOICES_RE = /^\/v1\/organizations\/[^/]+\/billing\/invoices$/; +const ORG_BILLING_ENTITLEMENTS_RE = /^\/v1\/organizations\/[^/]+\/billing\/entitlements$/; +const ORG_BILLING_PAYMENT_METHODS_RE = /^\/v1\/organizations\/[^/]+\/billing\/payment-methods$/; +const ORG_BILLING_CHECKOUT_RE = /^\/v1\/organizations\/[^/]+\/billing\/checkout$/; +const ORG_BILLING_PORTAL_RE = /^\/v1\/organizations\/[^/]+\/billing\/portal$/; +const ORG_BILLING_CANCEL_RE = /^\/v1\/organizations\/[^/]+\/billing\/subscription\/cancel$/; +const ORG_BILLING_CHANGE_RE = /^\/v1\/organizations\/[^/]+\/billing\/subscription\/change$/; +const ORG_BILLING_RECONCILE_RE = /^\/v1\/organizations\/[^/]+\/billing\/reconcile$/; + +const FORWARDED_HEADERS = [ + "content-type", + "x-request-id", + "traceparent", + "idempotency-key", +]; + +// checkout/portal/cancel/change are POST (billing.manage); the rest are GET reads. +const WRITE_BILLING_RES = [ORG_BILLING_CHECKOUT_RE, ORG_BILLING_PORTAL_RE, ORG_BILLING_CANCEL_RE, ORG_BILLING_CHANGE_RE, ORG_BILLING_RECONCILE_RE]; + +export function isBillingRoute(pathname: string): boolean { + return ( + ORG_BILLING_PLANS_RE.test(pathname) || + ORG_BILLING_CUSTOMER_RE.test(pathname) || + ORG_BILLING_SUMMARY_RE.test(pathname) || + ORG_BILLING_INVOICES_RE.test(pathname) || + ORG_BILLING_ENTITLEMENTS_RE.test(pathname) || + ORG_BILLING_PAYMENT_METHODS_RE.test(pathname) || + ORG_BILLING_CHECKOUT_RE.test(pathname) || + ORG_BILLING_PORTAL_RE.test(pathname) || + ORG_BILLING_CANCEL_RE.test(pathname) || + ORG_BILLING_CHANGE_RE.test(pathname) || + ORG_BILLING_RECONCILE_RE.test(pathname) + ); +} + +function isWriteBillingRoute(pathname: string): boolean { + return WRITE_BILLING_RES.some((re) => re.test(pathname)); +} + +export async function handleBillingRoute( + request: Request, + env: Env, + requestId: string, + pathname: string, +): Promise { + const isWrite = isWriteBillingRoute(pathname); + const expectedMethod = isWrite ? "POST" : "GET"; + if (request.method !== expectedMethod) { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + return replayOrExecute(request, requestId, env, "billing", async () => { + + if (!env.IDENTITY_WORKER) { + return errorResponse("internal_error", "Authentication service unavailable", 503, requestId); + } + + if (!env.BILLING_WORKER) { + return errorResponse("internal_error", "Billing service unavailable", 503, requestId); + } + + const timings = createTimings(); + const endTotal = timings.start("edge_total"); + const sessionResult = await timings.measure("edge_auth", () => resolveActor(request, env, requestId)); + if ("error" in sessionResult) { + return sessionResult.error; + } + + const headers = new Headers(); + headers.set("x-request-id", requestId); + headers.set("x-actor-subject-id", sessionResult.subjectId); + headers.set("x-actor-subject-type", sessionResult.subjectType); + headers.set("x-actor-email", sessionResult.email); + if (sessionResult.orgId) { + } + for (const name of FORWARDED_HEADERS) { + if (name === "x-request-id") continue; + const value = request.headers.get(name); + if (value) headers.set(name, value); + } + + const url = new URL(request.url); + const target = new URL(pathname + url.search, "https://billing.internal"); + + try { + const init: RequestInit = { method: request.method, headers }; + if (isWrite) init.body = request.body; + const downstream = await timings.measure("edge_downstream", () => env.BILLING_WORKER!.fetch(target.toString(), init)); + const res = new Response(downstream.body, { + status: downstream.status, + headers: downstream.headers, + }); + endTotal(); + return withEdgeTimings(res, requestId, "edge.billing", timings); + } catch { + return errorResponse("internal_error", "Billing service unavailable", 503, requestId); + } + }); +} \ No newline at end of file diff --git a/apps/api-edge/src/billing-webhooks-facade.ts b/apps/api-edge/src/billing-webhooks-facade.ts new file mode 100644 index 0000000..6744f35 --- /dev/null +++ b/apps/api-edge/src/billing-webhooks-facade.ts @@ -0,0 +1,61 @@ +import type { Env } from "./env"; +import { errorResponse } from "./http"; + +/** + * Public, unauthenticated inbound billing-provider webhook receiver (BP2). + * + * This is the one billing route with no session: the provider (Polar) calls it + * directly. api-edge does NOT verify or parse — it streams the RAW body and the + * Standard-Webhooks signature headers to billing-worker, which holds the signing + * secret and verifies (fails closed). Keeping verification at the billing-worker + * means the provider secret never lives at the edge. + */ + +const POLAR_WEBHOOK_RE = /^\/v1\/billing\/webhooks\/polar$/; + +// Signature + content headers the downstream verifier needs. Standard-Webhooks +// uses `webhook-*`; `svix-*` aliases are forwarded for compatibility. +const FORWARDED_WEBHOOK_HEADERS = [ + "content-type", + "webhook-id", + "webhook-timestamp", + "webhook-signature", + "svix-id", + "svix-timestamp", + "svix-signature", +]; + +export function isBillingWebhookRoute(pathname: string): boolean { + return POLAR_WEBHOOK_RE.test(pathname); +} + +export async function handleBillingWebhookRoute( + request: Request, + env: Env, + requestId: string, + _pathname: string, +): Promise { + if (request.method !== "POST") { + return errorResponse("method_not_allowed", "Method not allowed", 405, requestId); + } + if (!env.BILLING_WORKER) { + return errorResponse("service_unavailable", "Billing service unavailable", 503, requestId); + } + + const headers = new Headers(); + headers.set("x-request-id", requestId); + headers.set("x-internal-caller", "api-edge"); + for (const name of FORWARDED_WEBHOOK_HEADERS) { + const value = request.headers.get(name); + if (value) headers.set(name, value); + } + + // Stream the raw body through unread so the bytes the provider signed reach + // the verifier intact. + const target = new URL("/v1/internal/billing/webhooks/polar", "https://billing.internal"); + return env.BILLING_WORKER.fetch(target.toString(), { + method: "POST", + headers, + body: request.body, + }); +} diff --git a/apps/api-edge/src/config-facade.ts b/apps/api-edge/src/config-facade.ts new file mode 100644 index 0000000..943c277 --- /dev/null +++ b/apps/api-edge/src/config-facade.ts @@ -0,0 +1,102 @@ +import type { Env } from "./env.js"; +import { errorResponse } from "./http.js"; +import { replayOrExecute } from "./idempotency.js"; +import { resolveActor } from "./resolve-actor.js"; + +// Organization-scoped config +const ORG_CONFIG_SETTINGS_RE = /^\/v1\/organizations\/[^/]+\/config\/settings(\/[^/]+)?$/; +const ORG_CONFIG_FLAGS_RE = /^\/v1\/organizations\/[^/]+\/config\/feature-flags(\/[^/]+)?$/; +const ORG_CONFIG_SECRETS_RE = /^\/v1\/organizations\/[^/]+\/config\/secrets(\/[^/]+(\/rotate)?)?$/; + +// Project-scoped config +const PRJ_CONFIG_SETTINGS_RE = /^\/v1\/organizations\/[^/]+\/projects\/[^/]+\/config\/settings(\/[^/]+)?$/; +const PRJ_CONFIG_FLAGS_RE = /^\/v1\/organizations\/[^/]+\/projects\/[^/]+\/config\/feature-flags(\/[^/]+)?$/; +const PRJ_CONFIG_SECRETS_RE = /^\/v1\/organizations\/[^/]+\/projects\/[^/]+\/config\/secrets(\/[^/]+(\/rotate)?)?$/; + +// Environment-scoped config +const ENV_CONFIG_SETTINGS_RE = /^\/v1\/organizations\/[^/]+\/projects\/[^/]+\/environments\/[^/]+\/config\/settings(\/[^/]+)?$/; +const ENV_CONFIG_FLAGS_RE = /^\/v1\/organizations\/[^/]+\/projects\/[^/]+\/environments\/[^/]+\/config\/feature-flags(\/[^/]+)?$/; +const ENV_CONFIG_SECRETS_RE = /^\/v1\/organizations\/[^/]+\/projects\/[^/]+\/environments\/[^/]+\/config\/secrets(\/[^/]+(\/rotate)?)?$/; + +const FORWARDED_HEADERS = [ + "content-type", + "x-request-id", + "traceparent", + "idempotency-key", +]; + +export function isConfigRoute(pathname: string): boolean { + return ( + ORG_CONFIG_SETTINGS_RE.test(pathname) || + ORG_CONFIG_FLAGS_RE.test(pathname) || + ORG_CONFIG_SECRETS_RE.test(pathname) || + PRJ_CONFIG_SETTINGS_RE.test(pathname) || + PRJ_CONFIG_FLAGS_RE.test(pathname) || + PRJ_CONFIG_SECRETS_RE.test(pathname) || + ENV_CONFIG_SETTINGS_RE.test(pathname) || + ENV_CONFIG_FLAGS_RE.test(pathname) || + ENV_CONFIG_SECRETS_RE.test(pathname) + ); +} + +export async function handleConfigRoute( + request: Request, + env: Env, + requestId: string, + pathname: string, +): Promise { + // Config routes: GET (list), POST (create/rotate), PATCH (update), DELETE (revoke) + const allowedMethods = ["GET", "POST", "PATCH", "DELETE"]; + if (!allowedMethods.includes(request.method)) { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + return replayOrExecute(request, requestId, env, "config", async () => { + + if (!env.IDENTITY_WORKER) { + return errorResponse("internal_error", "Authentication service unavailable", 503, requestId); + } + + if (!env.CONFIG_WORKER) { + return errorResponse("internal_error", "Config service unavailable", 503, requestId); + } + + const sessionResult = await resolveActor(request, env, requestId); + if ("error" in sessionResult) { + return sessionResult.error; + } + + const headers = new Headers(); + headers.set("x-request-id", requestId); + headers.set("x-actor-subject-id", sessionResult.subjectId); + headers.set("x-actor-subject-type", sessionResult.subjectType); + headers.set("x-actor-email", sessionResult.email); + if (sessionResult.orgId) { + } + for (const name of FORWARDED_HEADERS) { + if (name === "x-request-id") continue; + const value = request.headers.get(name); + if (value) headers.set(name, value); + } + + const url = new URL(request.url); + const target = new URL(pathname + url.search, "https://config.internal"); + + try { + const fetchInit: RequestInit = { + method: request.method, + headers, + }; + if (request.method === "POST" || request.method === "PATCH") { + fetchInit.body = request.body; + } + const downstream = await env.CONFIG_WORKER.fetch(target.toString(), fetchInit); + return new Response(downstream.body, { + status: downstream.status, + headers: downstream.headers, + }); + } catch { + return errorResponse("internal_error", "Config service unavailable", 503, requestId); + } + }); +} diff --git a/apps/api-edge/src/cors.ts b/apps/api-edge/src/cors.ts new file mode 100644 index 0000000..00f915f --- /dev/null +++ b/apps/api-edge/src/cors.ts @@ -0,0 +1,97 @@ +import type { Env } from "./env"; +import { consoleWorkersDevOrigin } from "./app-config"; + +// Deploy hostnames for `apps/web-console-next` (Next.js + opennextjs/cloudflare) +// under the cloudflare-workers-assets-turbo composition. Per-env naming via +// `${prefix}-${env}` so the cutover keeps a stable shape across environments. +// Identity values (subdomain, worker prefix) come from `./app-config`. +// +// Legacy `apps/web-console` (vanilla Vite, Pages) was decommissioned in Task 0083 +// (custom-domain swing to web-console-next Workers). No CORS allowlist entry is +// needed for the now-orphaned Pages hostnames — they are not served by any +// current frontend. +const WORKERS_ORIGINS: Record = { + dev: consoleWorkersDevOrigin("dev"), + stage: consoleWorkersDevOrigin("stage"), + prod: consoleWorkersDevOrigin("prod"), +}; + +const LOCALHOST_RE = /^https?:\/\/localhost(:\d+)?$/; +const VITE_DEV_RE = /^https?:\/\/127\.0\.0\.1(:\d+)?$/; + +const ALLOWED_HEADERS = [ + "authorization", + "content-type", + "x-request-id", + "traceparent", + "idempotency-key", +].join(", "); + +const EXPOSED_HEADERS = [ + "x-request-id", +].join(", "); + +const ALLOWED_METHODS = "GET, POST, PUT, PATCH, DELETE, OPTIONS"; +const MAX_AGE = "86400"; + +export function isAllowedOrigin(origin: string | null, env: Env): boolean { + if (!origin) return false; + + if (LOCALHOST_RE.test(origin)) return true; + if (VITE_DEV_RE.test(origin)) return true; + + const environment = env.ENVIRONMENT; + const customDomain = env.CONSOLE_CUSTOM_DOMAIN; + + if (environment === "stage" || environment === "prod") { + if (customDomain && origin === `https://${customDomain}`) return true; + if (origin === WORKERS_ORIGINS[environment]) return true; + return false; + } + + if (customDomain && origin === `https://${customDomain}`) return true; + for (const workerOrigin of Object.values(WORKERS_ORIGINS)) { + if (origin === workerOrigin) return true; + } + + return false; +} + +export function handlePreflight(request: Request, env: Env): Response | null { + if (request.method !== "OPTIONS") return null; + + const origin = request.headers.get("origin"); + if (!isAllowedOrigin(origin, env)) { + return new Response(null, { status: 204 }); + } + + return new Response(null, { + status: 204, + headers: { + "access-control-allow-origin": origin!, + "access-control-allow-methods": ALLOWED_METHODS, + "access-control-allow-headers": ALLOWED_HEADERS, + "access-control-expose-headers": EXPOSED_HEADERS, + "access-control-max-age": MAX_AGE, + "access-control-allow-credentials": "true", + vary: "Origin", + }, + }); +} + +export function applyCorsHeaders(response: Response, request: Request, env: Env): Response { + const origin = request.headers.get("origin"); + if (!isAllowedOrigin(origin, env)) return response; + + const headers = new Headers(response.headers); + headers.set("access-control-allow-origin", origin!); + headers.set("access-control-allow-credentials", "true"); + headers.set("access-control-expose-headers", EXPOSED_HEADERS); + headers.set("vary", "Origin"); + + return new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers, + }); +} diff --git a/apps/api-edge/src/env.ts b/apps/api-edge/src/env.ts new file mode 100644 index 0000000..b929a3d --- /dev/null +++ b/apps/api-edge/src/env.ts @@ -0,0 +1,29 @@ +export interface Env { + PLATFORM_DB?: D1Database; + IDENTITY_WORKER?: Fetcher; + MEMBERSHIP_WORKER?: Fetcher; + PROJECTS_WORKER?: Fetcher; + EVENTS_WORKER?: Fetcher; + CONFIG_WORKER?: Fetcher; + WEBHOOKS_WORKER?: Fetcher; + METERING_WORKER?: Fetcher; + BILLING_WORKER?: Fetcher; + NOTIFICATIONS_WORKER?: Fetcher; + INTEGRATIONS_WORKER?: Fetcher; + // Optional KV binding backing the Stripe-style idempotency replay store + // (Task 0095). Absent on `dev` (no live worker) and absent on the older + // verify-only stages. When unbound, `replayOrExecute` degrades to a + // direct downstream forward — never 5xx. + IDEMPOTENCY_KV?: KVNamespace; + // Durable Object namespace backing the per-(scope,key) rate-limit counters + // (PERF5 Stage B). Each bucket key maps to one DO instance for an atomic, + // race-free token bucket without a KV write on the hot path. Absent on + // dev/local, where the limiter falls back to the KV path (then fail-open). + RATE_LIMITER_DO?: DurableObjectNamespace; + ENVIRONMENT: string; + CONSOLE_CUSTOM_DOMAIN?: string; + // M0 / Solo profile switch. "true" runs the single-user B2C profile (see + // ./solo-mode.ts); absent or any other value keeps the full multi-tenant + // baseline. Deploy-time wrangler var, not a secret. + SOLO_MODE?: string; +} diff --git a/apps/api-edge/src/http.ts b/apps/api-edge/src/http.ts new file mode 100644 index 0000000..46941b1 --- /dev/null +++ b/apps/api-edge/src/http.ts @@ -0,0 +1,58 @@ +import type { ErrorCode } from "@saas/contracts/errors"; +import type { Timings } from "@saas/contracts/timing"; +import { appendServerTiming, shouldEmitTimingLog } from "@saas/contracts/timing"; + +const REQUEST_ID_RE = /^[\w-]{1,128}$/; + +/** Append the edge's own phases to the downstream worker's `Server-Timing` + * header so a single response carries the end-to-end breakdown, and emit a + * (sampled) structured timing log line. The header is always set; the log line + * is sampled (PERF14) to bound Workers Logs ingestion cost. Returns the same + * response for chaining. */ +export function withEdgeTimings(response: Response, requestId: string, route: string, timings: Timings): Response { + const addition = timings.header(); + if (addition) { + response.headers.set("Server-Timing", appendServerTiming(response.headers.get("Server-Timing"), addition)); + } + const phases = timings.toJSON(); + if (shouldEmitTimingLog(phases)) { + // eslint-disable-next-line no-console -- structured timing line for prod observability + console.log(JSON.stringify({ level: "info", msg: "timing", route, requestId, phases })); + } + return response; +} + +export function resolveRequestId(request: Request): string { + const header = request.headers.get("x-request-id"); + if (header && REQUEST_ID_RE.test(header)) return header; + return generateRequestId(); +} + +function generateRequestId(): string { + const buf = new Uint8Array(12); + crypto.getRandomValues(buf); + let hex = ""; + for (let i = 0; i < buf.length; i++) { + hex += buf[i]!.toString(16).padStart(2, "0"); + } + return `req_${hex}`; +} + +export function errorResponse( + code: ErrorCode | string, + message: string, + status: number, + requestId: string, + details?: Record, +): Response { + return Response.json( + { + error: { code, message, details: details ?? {}, requestId }, + }, + { status, headers: { "content-type": "application/json" } }, + ); +} + +export function notFound(requestId: string, path: string): Response { + return errorResponse("not_found", `Route not found: ${path}`, 404, requestId); +} diff --git a/apps/api-edge/src/idempotency.ts b/apps/api-edge/src/idempotency.ts new file mode 100644 index 0000000..f60d8b9 --- /dev/null +++ b/apps/api-edge/src/idempotency.ts @@ -0,0 +1,533 @@ +// Edge-side idempotency seam. +// +// Two responsibilities, both anchored on the shared parser from +// `@saas/contracts/idempotency` so the wire contract (Task 0094) and the +// durable replay store (Task 0095) can never drift: +// +// 1. `validateIdempotencyKey(request, requestId)` — the original Task 0094 +// validation gate, retained as a thin wrapper for callers that don't +// need replay (none in production today, but kept for tests and for +// any future facade that handles its own forwarding). +// +// 2. `replayOrExecute(request, requestId, env, downstream)` — the +// Stripe-style replay chokepoint introduced in Task 0095. Every unsafe +// method (POST/PATCH/PUT/DELETE) carrying a valid `Idempotency-Key` is +// first looked up in `env.IDEMPOTENCY_KV`. On hit, the stored response +// envelope is reconstructed and returned without invoking the +// downstream worker. On miss, the downstream is called once, its +// response is stored under a 24h TTL, and the original response is +// returned to the caller. +// +// Failure semantics: +// - Header absent on an unsafe method → no cache lookup, no cache write, +// downstream is invoked exactly once. +// - Header malformed on an unsafe method → 400 `validation_failed` +// (Task 0094 wire behavior preserved verbatim) BEFORE any KV touch. +// - Header malformed on a safe method (GET/HEAD) → ignored; reads have +// no idempotency semantics. Downstream is invoked normally. +// - KV binding missing OR KV `get` throws OR KV `put` throws → log via +// console.warn (caught by the standard observability hook) and degrade +// to "execute downstream once, no replay." A KV outage MUST NOT 5xx the +// request — Stripe-quality systems fail open on the cache. +// +// Key/envelope shape (latitude exercised under the Task 0095 architect +// brief): +// +// - Key: `idem:v1:{orgScope}:{routeKey}:{idempotencyKey}` where +// `orgScope` is the path-derived org id (`/v1/organizations/{orgId}/...`) +// or the literal `"anon"` when the route has no org segment; +// `routeKey` is the URL path with concrete IDs collapsed to `:id` +// placeholders (so `/v1/organizations/org_abc/projects/proj_xyz/foo` +// → `/v1/organizations/:id/projects/:id/foo`); both segments are +// length-bounded and the whole key is fingerprinted with SHA-256 + +// re-encoded as `idem:v1:{orgScope}:{hash40}` if the literal form +// would exceed the 512-byte cap. +// +// Rationale: org-scope by URL path keeps the lookup work synchronous +// and avoids dragging `resolveActor` ahead of the KV touch (Stripe's +// replay is identity-agnostic — the key itself is the principal). +// Anon scope handles `/v1/auth/login/start` which has no org. Route +// canonicalisation prevents `org_a/.../foo` and `org_b/.../foo` +// colliding when callers reuse keys but lets `/foo` and `/bar` +// coexist. SHA-256 fallback guarantees we stay under the 512-byte +// cap regardless of caller-supplied key length. +// +// - Envelope: JSON `{ status, headers, contentType, body, bodyEncoding, +// storedAt, requestId }`. Headers are a strict allow-list (see +// `STORED_HEADER_ALLOWLIST`) — caller-controlled or session-bearing +// headers like `set-cookie` / `authorization` are NEVER persisted. +// `bodyEncoding` is `"utf8"` for text/JSON bodies and `"base64"` for +// anything else, preserving binary safety. + +import { + IDEMPOTENCY_KEY_HEADER, + describeIdempotencyKeyParseError, + parseIdempotencyKey, +} from "@saas/contracts/idempotency"; +import { createTimings, appendServerTiming, shouldEmitTimingLog, type Timings } from "@saas/contracts/timing"; + +import type { Env } from "./env.js"; +import { errorResponse } from "./http.js"; +import { + enforceRateLimit, + mergeRateLimitHeaders, + type RouteFamily, +} from "./rate-limit.js"; + +const UNSAFE_METHODS: ReadonlySet = new Set(["POST", "PATCH", "PUT", "DELETE"]); + +const KV_KEY_PREFIX = "idem:v1"; +const KV_KEY_BYTE_CAP = 512; +const KV_TTL_SECONDS = 86_400; // 24h, matches Stripe's documented replay window. +const KV_ENVELOPE_VERSION = 1 as const; + +/** + * Headers that are SAFE to store and replay. Any header outside this list is + * dropped on store. This protects callers from accidental leakage of + * `set-cookie`, `authorization`, or other principal-bearing values that the + * downstream worker would have set on the original response. + */ +const STORED_HEADER_ALLOWLIST: ReadonlySet = new Set([ + "content-type", + "content-language", + "cache-control", + "etag", + "x-request-id", + "x-saas-replay-source", +]); + +interface StoredEnvelopeV1 { + v: typeof KV_ENVELOPE_VERSION; + status: number; + headers: Record; + contentType: string; + body: string; + bodyEncoding: "utf8" | "base64"; + storedAt: string; + requestId: string; +} + +/** + * Returns `null` when the request can proceed (header absent, valid, or + * method is safe), and a 400 `Response` when the header is present-but- + * malformed on an unsafe method. + * + * Retained for symmetry with Task 0094 callers / tests. New code should + * prefer `replayOrExecute`, which performs the same validation gate AND + * the durable replay lookup behind a single chokepoint. + */ +export function validateIdempotencyKey( + request: Request, + requestId: string, +): Response | null { + if (!UNSAFE_METHODS.has(request.method)) { + return null; + } + + const raw = request.headers.get("idempotency-key"); + const result = parseIdempotencyKey(raw); + if (result.ok) { + return null; + } + + return errorResponse( + "validation_failed", + describeIdempotencyKeyParseError(result.reason), + 400, + requestId, + { header: IDEMPOTENCY_KEY_HEADER, reason: result.reason }, + ); +} + +/** + * Single chokepoint for unsafe-method requests: validate the header, replay + * a stored response on cache hit, otherwise invoke `downstream` once, store + * the response, and return it. + * + * Callers pass `downstream` as a thunk because the facade has already + * decided WHICH worker to forward to (auth → identity, org → membership, + * etc.) and how to shape the request — this helper has no business + * deciding that. + * + * On safe methods or absent keys, this function is effectively a pass- + * through that just calls `downstream()`. + */ +export async function replayOrExecute( + request: Request, + requestId: string, + env: Env, + routeFamily: RouteFamily, + downstream: () => Promise, +): Promise { + // PERF6: time the edge gate (rate-limit + idempotency) so a single response + // carries the full breakdown. The gate runs BEFORE the facade's own + // `createTimings` block, so without this its cost is invisible to + // Server-Timing — the exact blind spot that hid the rate limiter's ~264ms. + const gate = createTimings(); + + // Rate-limit gate runs FIRST — before any KV cache lookup, before any + // cross-binding fetch. Failure-open is handled inside `enforceRateLimit`. + const endRateLimit = gate.start("edge_ratelimit"); + const rateDecision = await enforceRateLimit(request, requestId, env, routeFamily); + endRateLimit(); + + if (rateDecision.kind === "denied") { + return finishGate(rateDecision.response, requestId, routeFamily, gate); + } + const rateHeaders = rateDecision.headers; + + let response: Response; + + // Safe methods: never cache, never validate; pass through (still decorated). + if (!UNSAFE_METHODS.has(request.method)) { + response = mergeRateLimitHeaders(await downstream(), rateHeaders); + } else { + const parsed = parseIdempotencyKey(request.headers.get("idempotency-key")); + + if (!parsed.ok) { + response = mergeRateLimitHeaders( + errorResponse( + "validation_failed", + describeIdempotencyKeyParseError(parsed.reason), + 400, + requestId, + { header: IDEMPOTENCY_KEY_HEADER, reason: parsed.reason }, + ), + rateHeaders, + ); + } else if (parsed.key === null) { + // Header absent on an unsafe method is allowed (Task 0094 contract). + response = mergeRateLimitHeaders(await downstream(), rateHeaders); + } else if (!env.IDEMPOTENCY_KV) { + // KV binding missing → degrade open. + response = mergeRateLimitHeaders(await downstream(), rateHeaders); + } else { + const kv = env.IDEMPOTENCY_KV; + const url = new URL(request.url); + const cacheKey = await buildCacheKey(parsed.key, url.pathname); + + // --- Lookup (timed as edge_idem): colo-local Cache API L1, then KV. --- + // KV stays the GLOBAL source of truth (a cross-colo retry must still find + // the stored response). The Cache API layer is colo-local and serves + // same-colo replays without the ~40-90ms KV `get`. An idempotency envelope + // is write-once per key, so L1 can never diverge from KV for a given key. + let stored: StoredEnvelopeV1 | null = null; + let backfillL1 = false; + const endIdem = gate.start("edge_idem"); + stored = await idemCacheGet(cacheKey); + if (!stored) { + try { + const rawStored = await kv.get(cacheKey, "text"); + if (rawStored) { + stored = parseEnvelope(rawStored); + backfillL1 = stored !== null; + } + } catch (err) { + // KV read failure is not fatal — log and proceed as if cache-miss. + logKvFailure("get", err, requestId); + } + } + endIdem(); + + // Backfill L1 from a KV hit so the next same-colo replay skips KV. Off the + // timed path — it's a side effect, not part of the lookup the caller waits on. + if (backfillL1 && stored) { + await idemCachePut(cacheKey, stored); + } + + if (stored) { + response = mergeRateLimitHeaders(reconstructResponse(stored), rateHeaders); + } else { + // --- Cache miss: execute downstream, then store to KV (global) + L1. --- + const fresh = await downstream(); + + // Only cache "successful" final responses (skip 5xx — transient). + if (fresh.status < 500) { + try { + const envelope = await buildEnvelope(fresh, requestId); + // `buildEnvelope` operates on a clone, so `fresh` is still streamable. + await kv.put(cacheKey, JSON.stringify(envelope), { + expirationTtl: KV_TTL_SECONDS, + }); + // Populate the colo-local L1 for fast same-colo replays. + await idemCachePut(cacheKey, envelope); + } catch (err) { + // KV write failure is not fatal — caller still gets the real response. + logKvFailure("put", err, requestId); + } + } + response = mergeRateLimitHeaders(fresh, rateHeaders); + } + } + } + + return finishGate(response, requestId, routeFamily, gate); +} + +/** + * Append the gate's `edge_ratelimit` / `edge_idem` phases to the response's + * `Server-Timing` header (without clobbering the facade/worker phases already + * there) and emit a structured timing line for the prod observability sink. + */ +function finishGate( + response: Response, + requestId: string, + routeFamily: RouteFamily, + gate: Timings, +): Response { + const addition = gate.header(); + if (addition) { + response.headers.set( + "Server-Timing", + appendServerTiming(response.headers.get("Server-Timing"), addition), + ); + } + // PERF14: header is always set; the log line is sampled to bound Workers Logs + // ingestion cost (always emitted when a phase is slow). + const phases = gate.toJSON(); + if (shouldEmitTimingLog(phases)) { + // eslint-disable-next-line no-console -- structured timing line for prod observability + console.log( + JSON.stringify({ + level: "info", + msg: "timing", + route: `edge.gate.${routeFamily}`, + requestId, + phases, + }), + ); + } + return response; +} + +async function buildCacheKey( + idempotencyKey: string, + pathname: string, +): Promise { + const orgScope = extractOrgScope(pathname); + const routeKey = canonicaliseRoute(pathname); + const literal = `${KV_KEY_PREFIX}:${orgScope}:${routeKey}:${idempotencyKey}`; + + // Cheap path: literal fits the cap. Useful for debug / forensic lookups. + // (UTF-8 encoding length, since KV measures bytes.) + const bytes = new TextEncoder().encode(literal); + if (bytes.byteLength <= KV_KEY_BYTE_CAP) { + return literal; + } + + // Fallback: collapse the variable tail into a stable SHA-256 hash so the + // total length is bounded regardless of caller-supplied key size. + const hash = await sha256Hex(`${routeKey}:${idempotencyKey}`); + return `${KV_KEY_PREFIX}:${orgScope}:${hash}`; +} + +const ORG_SEGMENT_RE = /^\/v1\/organizations\/([^/]+)(?:\/|$)/; + +function extractOrgScope(pathname: string): string { + const m = ORG_SEGMENT_RE.exec(pathname); + if (!m || !m[1]) return "anon"; + return m[1]; +} + +/** + * Collapse concrete IDs in the path into the literal `:id`. Heuristic: any + * path segment that looks like an opaque identifier (containing a `_`, a + * `-`, or being purely alphanumeric and >= 8 chars) is replaced. This is + * good enough for our route surface — all current IDs are either ULIDs, + * UUIDs, or `prefix_…` opaque tokens. + */ +function canonicaliseRoute(pathname: string): string { + return pathname + .split("/") + .map((segment) => { + if (segment === "") return segment; + if (/^[a-z]+$/.test(segment)) return segment; + if (/^v\d+$/.test(segment)) return segment; + // Looks like an opaque ID. + if (segment.length >= 8 || segment.includes("_") || segment.includes("-")) { + return ":id"; + } + return segment; + }) + .join("/"); +} + +async function sha256Hex(input: string): Promise { + const data = new TextEncoder().encode(input); + const digest = await crypto.subtle.digest("SHA-256", data); + const bytes = new Uint8Array(digest); + let hex = ""; + for (let i = 0; i < bytes.length; i++) { + hex += bytes[i]!.toString(16).padStart(2, "0"); + } + return hex; +} + +// --- Idempotency replay L1 (colo-local Cache API, in front of the KV store) --- +// +// The Cache API (`caches.default`) is colo-local and free — a fast accelerator +// for same-colo replays. KV remains the global source of truth, so cross-colo +// retries and L1 evictions fall through to KV (correctness preserved). An +// envelope is write-once per key, so the L1 copy can never diverge from KV. +// Best-effort throughout: any error degrades to a miss / no-op, never a 5xx. + +type CacheLike = { + match(key: string): Promise; + put(key: string, res: Response): Promise; +}; + +function idemCache(): CacheLike | null { + return typeof caches !== "undefined" && + (caches as unknown as { default?: CacheLike }).default + ? (caches as unknown as { default: CacheLike }).default + : null; +} + +/** Cache-API key URL for an idempotency `cacheKey` (hashed to stay URL-safe). */ +async function idemCacheKeyUrl(cacheKey: string): Promise { + return `https://idem-cache.internal/v1/${await sha256Hex(cacheKey)}`; +} + +async function idemCacheGet(cacheKey: string): Promise { + const c = idemCache(); + if (!c) return null; + try { + const res = await c.match(await idemCacheKeyUrl(cacheKey)); + if (!res) return null; + return parseEnvelope(await res.text()); + } catch { + return null; + } +} + +async function idemCachePut(cacheKey: string, envelope: StoredEnvelopeV1): Promise { + const c = idemCache(); + if (!c) return; + try { + const res = new Response(JSON.stringify(envelope), { + status: 200, + headers: { + "content-type": "application/json", + // Cache API honours max-age for TTL; match the KV replay window. + "cache-control": `max-age=${KV_TTL_SECONDS}`, + }, + }); + await c.put(await idemCacheKeyUrl(cacheKey), res); + } catch { + /* best-effort */ + } +} + +async function buildEnvelope( + response: Response, + requestId: string, +): Promise { + // Clone before reading so the original body is still streamable to the + // caller of `replayOrExecute`. + const clone = response.clone(); + + const headers: Record = {}; + clone.headers.forEach((value, name) => { + if (STORED_HEADER_ALLOWLIST.has(name.toLowerCase())) { + headers[name.toLowerCase()] = value; + } + }); + + const contentType = clone.headers.get("content-type") ?? ""; + const isText = + contentType.startsWith("text/") || + contentType.includes("json") || + contentType.includes("xml") || + contentType.includes("javascript") || + contentType === ""; + + let body: string; + let bodyEncoding: "utf8" | "base64"; + if (isText) { + body = await clone.text(); + bodyEncoding = "utf8"; + } else { + const buffer = await clone.arrayBuffer(); + body = arrayBufferToBase64(buffer); + bodyEncoding = "base64"; + } + + return { + v: KV_ENVELOPE_VERSION, + status: response.status, + headers, + contentType, + body, + bodyEncoding, + storedAt: new Date().toISOString(), + requestId, + }; +} + +function reconstructResponse(envelope: StoredEnvelopeV1): Response { + const headers = new Headers(); + for (const [name, value] of Object.entries(envelope.headers)) { + headers.set(name, value); + } + // Always tag the replayed response so downstream observability can + // distinguish a cache hit from a real downstream call. Caller-side + // logs / dashboards key off this header. + headers.set("x-saas-replay-source", "edge-idempotency"); + + let body: BodyInit; + if (envelope.bodyEncoding === "base64") { + body = base64ToArrayBuffer(envelope.body); + } else { + body = envelope.body; + } + return new Response(body, { status: envelope.status, headers }); +} + +function parseEnvelope(raw: string): StoredEnvelopeV1 | null { + try { + const parsed: unknown = JSON.parse(raw); + if ( + parsed && + typeof parsed === "object" && + (parsed as { v?: unknown }).v === KV_ENVELOPE_VERSION + ) { + return parsed as StoredEnvelopeV1; + } + } catch { + // fall through + } + return null; +} + +function arrayBufferToBase64(buffer: ArrayBuffer): string { + const bytes = new Uint8Array(buffer); + let binary = ""; + for (let i = 0; i < bytes.byteLength; i++) { + binary += String.fromCharCode(bytes[i]!); + } + return btoa(binary); +} + +function base64ToArrayBuffer(b64: string): ArrayBuffer { + const binary = atob(b64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + return bytes.buffer; +} + +function logKvFailure(op: "get" | "put", err: unknown, requestId: string): void { + // We deliberately use console.warn (Workers Logs ingest hook) rather than + // throw — KV is a best-effort cache and the request must still succeed. + const message = err instanceof Error ? err.message : String(err); + console.warn( + JSON.stringify({ + level: "warn", + msg: "idempotency.kv_failure", + op, + requestId, + error: message, + }), + ); +} diff --git a/apps/api-edge/src/index.ts b/apps/api-edge/src/index.ts new file mode 100644 index 0000000..cbcb60f --- /dev/null +++ b/apps/api-edge/src/index.ts @@ -0,0 +1,129 @@ +import { createD1Adapter } from "@saas/db/d1"; +import type { HealthStatus } from "@saas/contracts/health"; +import type { Env } from "./env"; +import { resolveRequestId, notFound } from "./http"; +import { handlePreflight, applyCorsHeaders } from "./cors"; +import { isAuthRoute, handleAuthRoute } from "./auth-facade"; +import { isOrgRoute, handleOrgRoute } from "./org-facade"; +import { isProjectRoute, handleProjectRoute } from "./project-facade"; +import { isAuditRoute, handleAuditRoute } from "./audit-facade"; +import { isConfigRoute, handleConfigRoute } from "./config-facade"; +import { isWebhooksRoute, handleWebhooksRoute } from "./webhooks-facade"; +import { isMeteringRoute, handleMeteringRoute } from "./metering-facade"; +import { isBillingRoute, handleBillingRoute } from "./billing-facade"; +import { isBillingWebhookRoute, handleBillingWebhookRoute } from "./billing-webhooks-facade"; +import { isNotificationsRoute, handleNotificationsRoute } from "./notifications-facade"; +import { + isIntegrationsRoute, + isIntegrationsIngressRoute, + handleIntegrationsRoute, + handleIntegrationsIngressRoute, +} from "./integrations-facade"; +import { isSoloMode, isSoloSuppressed } from "./solo-mode"; + +// Durable Object class backing the PERF5 Stage B rate-limit counters. Must be +// exported from the Worker entry so the runtime can instantiate it for the +// `RATE_LIMITER_DO` binding. +export { RateLimiterDO } from "./rate-limit-do"; + +export default { + async fetch(request: Request, env: Env): Promise { + const preflight = handlePreflight(request, env); + if (preflight) return preflight; + + const url = new URL(request.url); + const requestId = resolveRequestId(request); + + let response: Response; + + if (url.pathname === "/health") { + response = await handleHealth(env); + } else if (isSoloMode(env) && isSoloSuppressed(url.pathname, request.method)) { + // M0 / Solo profile: org/team/project and platform-plumbing surfaces are + // hidden. Suppress at the edge before any facade dispatch — the route + // reads as "not found" to the single-user surface. Flip SOLO_MODE off and + // this branch is dead, restoring the full baseline. (See ./solo-mode.ts.) + response = notFound(requestId, url.pathname); + } else if (isAuthRoute(url.pathname)) { + response = await handleAuthRoute(request, env, requestId, url.pathname); + } else if (isAuditRoute(url.pathname)) { + response = await handleAuditRoute(request, env, requestId, url.pathname); + } else if (isConfigRoute(url.pathname)) { + response = await handleConfigRoute(request, env, requestId, url.pathname); + } else if (isIntegrationsIngressRoute(url.pathname)) { + // Public install-callback ingress (no session) — authenticated by the + // signed single-use state verified in integrations-worker. + response = await handleIntegrationsIngressRoute(request, env, requestId, url.pathname); + } else if (isIntegrationsRoute(url.pathname)) { + response = await handleIntegrationsRoute(request, env, requestId, url.pathname); + } else if (isBillingWebhookRoute(url.pathname)) { + // Public inbound provider webhook (no session) — matched before the + // authenticated webhooks/billing facades. + response = await handleBillingWebhookRoute(request, env, requestId, url.pathname); + } else if (isWebhooksRoute(url.pathname)) { + response = await handleWebhooksRoute(request, env, requestId, url.pathname); + } else if (isNotificationsRoute(url.pathname)) { + response = await handleNotificationsRoute(request, env, requestId, url.pathname); + } else if (isMeteringRoute(url.pathname)) { + response = await handleMeteringRoute(request, env, requestId, url.pathname); + } else if (isBillingRoute(url.pathname)) { + response = await handleBillingRoute(request, env, requestId, url.pathname); + } else if (isProjectRoute(url.pathname)) { + response = await handleProjectRoute(request, env, requestId, url.pathname); + } else if (isOrgRoute(url.pathname)) { + response = await handleOrgRoute(request, env, requestId, url.pathname); + } else { + response = notFound(requestId, url.pathname); + } + + return applyCorsHeaders(response, request, env); + }, +} satisfies ExportedHandler; + +async function handleHealth(env: Env): Promise { + const db = await checkDatabase(env); + const identity = checkIdentityBinding(env); + const membership = checkMembershipBinding(env); + + const status: HealthStatus = !db.configured + ? "ok" + : db.reachable + ? "ok" + : "degraded"; + + const code = status === "ok" ? 200 : 503; + + return Response.json( + { + status, + service: "api-edge", + environment: env.ENVIRONMENT ?? "local", + timestamp: new Date().toISOString(), + checks: { database: db, identity, membership }, + }, + { status: code }, + ); +} + +function checkIdentityBinding(env: Env): { configured: boolean } { + return { configured: !!env.IDENTITY_WORKER }; +} + +function checkMembershipBinding(env: Env): { configured: boolean } { + return { configured: !!env.MEMBERSHIP_WORKER }; +} + +async function checkDatabase( + env: Env, +): Promise<{ configured: boolean; reachable: boolean }> { + if (!env.PLATFORM_DB) { + return { configured: false, reachable: false }; + } + + const adapter = createD1Adapter(env.PLATFORM_DB); + try { + return await adapter.ping(); + } finally { + await adapter.dispose(); + } +} diff --git a/apps/api-edge/src/integrations-facade.ts b/apps/api-edge/src/integrations-facade.ts new file mode 100644 index 0000000..e49be7c --- /dev/null +++ b/apps/api-edge/src/integrations-facade.ts @@ -0,0 +1,201 @@ +import type { Env } from "./env.js"; +import { errorResponse } from "./http.js"; +import { replayOrExecute } from "./idempotency.js"; +import { enforceRateLimit, mergeRateLimitHeaders } from "./rate-limit.js"; +import { resolveActor } from "./resolve-actor.js"; + +// Authenticated org-scoped integration routes → integrations-worker. +const ORG_INTEGRATIONS_RE = /^\/v1\/organizations\/[^/]+\/integrations(\/.*)?$/; +// Project-scoped repo links (IG3) live in the integrations bounded context. +const PROJECT_REPO_LINKS_RE = /^\/v1\/organizations\/[^/]+\/projects\/[^/]+\/repo-links(\/.*)?$/; + +// Public install-callback ingress (design §5): GitHub redirects the installing +// user's BROWSER here after an App install. There is no bearer token — the +// request authenticates via the signed single-use state inside the query +// string, which integrations-worker (owner of the state secret) verifies. +// Allowlist-routed: exactly this one path, GET only, rate-limited. +const GITHUB_SETUP_PATH = "/ingress/github/setup"; + +// Public inbound webhook ingress (design §5): GitHub POSTs signed deliveries +// here. The edge does NOT verify or parse — it streams the RAW body plus the +// signature headers to integrations-worker, which owns the webhook secret +// and verifies over raw bytes before any parse (same posture as the Polar +// billing webhook). Allowlist-routed; rate-limited per source. +const GITHUB_WEBHOOK_PATH = "/ingress/github/webhook"; + +const FORWARDED_WEBHOOK_HEADERS = [ + "content-type", + "x-github-delivery", + "x-github-event", + "x-hub-signature-256", +]; + +const FORWARDED_HEADERS = [ + "content-type", + "x-request-id", + "traceparent", + "idempotency-key", +]; + +export function isIntegrationsRoute(pathname: string): boolean { + return ORG_INTEGRATIONS_RE.test(pathname) || PROJECT_REPO_LINKS_RE.test(pathname); +} + +export function isIntegrationsIngressRoute(pathname: string): boolean { + return pathname === GITHUB_SETUP_PATH || pathname === GITHUB_WEBHOOK_PATH; +} + +export async function handleIntegrationsIngressRoute( + request: Request, + env: Env, + requestId: string, + pathname: string, +): Promise { + if (!env.INTEGRATIONS_WORKER) { + return errorResponse("internal_error", "Integrations service unavailable", 503, requestId); + } + + if (pathname === GITHUB_WEBHOOK_PATH) { + if (request.method !== "POST") { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + const rateDecision = await enforceRateLimit(request, requestId, env, "integrations"); + if (rateDecision.kind === "denied") { + return rateDecision.response; + } + const headers = new Headers(); + headers.set("x-request-id", requestId); + headers.set("x-internal-caller", "api-edge"); + for (const name of FORWARDED_WEBHOOK_HEADERS) { + const value = request.headers.get(name); + if (value) headers.set(name, value); + } + const target = new URL(pathname, "https://integrations.internal"); + try { + // Stream the raw body through unread so the bytes GitHub signed reach + // the verifier intact. + const downstream = await env.INTEGRATIONS_WORKER.fetch(target.toString(), { + method: "POST", + headers, + body: request.body, + }); + return mergeRateLimitHeaders( + new Response(downstream.body, { + status: downstream.status, + headers: downstream.headers, + }), + rateDecision.headers, + ); + } catch { + return errorResponse("internal_error", "Integrations service unavailable", 503, requestId); + } + } + + if (request.method !== "GET") { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + // Per-source rate limit on the bearer-less surface (keyed by IP for + // anonymous callers). No resolveActor, no tenant lookup at the edge. + const rateDecision = await enforceRateLimit(request, requestId, env, "integrations"); + if (rateDecision.kind === "denied") { + return rateDecision.response; + } + + const headers = new Headers(); + headers.set("x-request-id", requestId); + headers.set("x-internal-caller", "api-edge"); + + const url = new URL(request.url); + const target = new URL(pathname + url.search, "https://integrations.internal"); + try { + const downstream = await env.INTEGRATIONS_WORKER.fetch(target.toString(), { + method: "GET", + headers, + }); + return mergeRateLimitHeaders( + new Response(downstream.body, { + status: downstream.status, + headers: downstream.headers, + }), + rateDecision.headers, + ); + } catch { + return errorResponse("internal_error", "Integrations service unavailable", 503, requestId); + } +} + +export async function handleIntegrationsRoute( + request: Request, + env: Env, + requestId: string, + pathname: string, +): Promise { + const allowedMethods = ["GET", "POST", "PATCH", "DELETE"]; + if (!allowedMethods.includes(request.method)) { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + const rateDecision = await enforceRateLimit(request, requestId, env, "integrations"); + if (rateDecision.kind === "denied") { + return rateDecision.response; + } + const rateHeaders = rateDecision.headers; + + return replayOrExecute(request, requestId, env, "integrations", async () => { + if (!env.IDENTITY_WORKER) { + return mergeRateLimitHeaders( + errorResponse("internal_error", "Authentication service unavailable", 503, requestId), + rateHeaders, + ); + } + if (!env.INTEGRATIONS_WORKER) { + return mergeRateLimitHeaders( + errorResponse("internal_error", "Integrations service unavailable", 503, requestId), + rateHeaders, + ); + } + + const sessionResult = await resolveActor(request, env, requestId); + if ("error" in sessionResult) { + return mergeRateLimitHeaders(sessionResult.error, rateHeaders); + } + + const headers = new Headers(); + headers.set("x-request-id", requestId); + headers.set("x-actor-subject-id", sessionResult.subjectId); + headers.set("x-actor-subject-type", sessionResult.subjectType); + headers.set("x-actor-email", sessionResult.email); + for (const name of FORWARDED_HEADERS) { + if (name === "x-request-id") continue; + const value = request.headers.get(name); + if (value) headers.set(name, value); + } + + const url = new URL(request.url); + const target = new URL(pathname + url.search, "https://integrations.internal"); + + try { + const fetchInit: RequestInit = { + method: request.method, + headers, + }; + if (request.method === "POST" || request.method === "PATCH") { + fetchInit.body = request.body; + } + const downstream = await env.INTEGRATIONS_WORKER.fetch(target.toString(), fetchInit); + return mergeRateLimitHeaders( + new Response(downstream.body, { + status: downstream.status, + headers: downstream.headers, + }), + rateHeaders, + ); + } catch { + return mergeRateLimitHeaders( + errorResponse("internal_error", "Integrations service unavailable", 503, requestId), + rateHeaders, + ); + } + }); +} diff --git a/apps/api-edge/src/metering-facade.ts b/apps/api-edge/src/metering-facade.ts new file mode 100644 index 0000000..73cfa13 --- /dev/null +++ b/apps/api-edge/src/metering-facade.ts @@ -0,0 +1,88 @@ +import type { Env } from "./env.js"; +import { errorResponse } from "./http.js"; +import { replayOrExecute } from "./idempotency.js"; +import { resolveActor } from "./resolve-actor.js"; + +const ORG_USAGE_RE = /^\/v1\/organizations\/[^/]+\/usage$/; +const ORG_USAGE_BATCH_RE = /^\/v1\/organizations\/[^/]+\/usage\/batch$/; +const ORG_USAGE_SUMMARY_RE = /^\/v1\/organizations\/[^/]+\/usage\/summary$/; +const ORG_QUOTA_CHECK_RE = /^\/v1\/organizations\/[^/]+\/quotas\/check$/; +const ORG_QUOTA_VIOLATIONS_RE = /^\/v1\/organizations\/[^/]+\/quotas\/violations$/; + +const FORWARDED_HEADERS = [ + "content-type", + "x-request-id", + "traceparent", + "idempotency-key", +]; + +export function isMeteringRoute(pathname: string): boolean { + return ( + ORG_USAGE_RE.test(pathname) || + ORG_USAGE_BATCH_RE.test(pathname) || + ORG_USAGE_SUMMARY_RE.test(pathname) || + ORG_QUOTA_CHECK_RE.test(pathname) || + ORG_QUOTA_VIOLATIONS_RE.test(pathname) + ); +} + +export async function handleMeteringRoute( + request: Request, + env: Env, + requestId: string, + pathname: string, +): Promise { + const allowedMethods = ["GET", "POST"]; + if (!allowedMethods.includes(request.method)) { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + return replayOrExecute(request, requestId, env, "metering", async () => { + + if (!env.IDENTITY_WORKER) { + return errorResponse("internal_error", "Authentication service unavailable", 503, requestId); + } + + if (!env.METERING_WORKER) { + return errorResponse("internal_error", "Metering service unavailable", 503, requestId); + } + + const sessionResult = await resolveActor(request, env, requestId); + if ("error" in sessionResult) { + return sessionResult.error; + } + + const headers = new Headers(); + headers.set("x-request-id", requestId); + headers.set("x-actor-subject-id", sessionResult.subjectId); + headers.set("x-actor-subject-type", sessionResult.subjectType); + headers.set("x-actor-email", sessionResult.email); + if (sessionResult.orgId) { + } + for (const name of FORWARDED_HEADERS) { + if (name === "x-request-id") continue; + const value = request.headers.get(name); + if (value) headers.set(name, value); + } + + const url = new URL(request.url); + const target = new URL(pathname + url.search, "https://metering.internal"); + + try { + const fetchInit: RequestInit = { + method: request.method, + headers, + }; + if (request.method === "POST") { + fetchInit.body = request.body; + } + const downstream = await env.METERING_WORKER.fetch(target.toString(), fetchInit); + return new Response(downstream.body, { + status: downstream.status, + headers: downstream.headers, + }); + } catch { + return errorResponse("internal_error", "Metering service unavailable", 503, requestId); + } + }); +} \ No newline at end of file diff --git a/apps/api-edge/src/notifications-facade.ts b/apps/api-edge/src/notifications-facade.ts new file mode 100644 index 0000000..a371b96 --- /dev/null +++ b/apps/api-edge/src/notifications-facade.ts @@ -0,0 +1,136 @@ +import type { Env } from "./env.js"; +import { errorResponse, withEdgeTimings } from "./http.js"; +import { enforceRateLimit, mergeRateLimitHeaders } from "./rate-limit.js"; +import { resolveActor } from "./resolve-actor.js"; +import { createTimings } from "@saas/contracts/timing"; + +/** + * Public facade for end-user notification preferences (PX3). + * + * `GET` / `PUT /v1/notifications/preferences` forward to notifications-worker + * over the service binding. The subject is **pinned to the resolved session + * actor**: whatever `subjectKind` / `subjectId` the caller supplies is + * replaced with `user` / the actor's own id, so a user can only ever read or + * update their own preferences. Org-level (subjectKind=organization) defaults + * remain internal-only — no public route exposes them. + */ + +const PREFERENCES_PATH = "/v1/notifications/preferences"; + +export function isNotificationsRoute(pathname: string): boolean { + return pathname === PREFERENCES_PATH; +} + +export async function handleNotificationsRoute( + request: Request, + env: Env, + requestId: string, + pathname: string, +): Promise { + if (request.method !== "GET" && request.method !== "PUT") { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + const rateDecision = await enforceRateLimit(request, requestId, env, "notifications"); + if (rateDecision.kind === "denied") { + return rateDecision.response; + } + const rateHeaders = rateDecision.headers; + + if (!env.IDENTITY_WORKER) { + return mergeRateLimitHeaders( + errorResponse("internal_error", "Authentication service unavailable", 503, requestId), + rateHeaders, + ); + } + if (!env.NOTIFICATIONS_WORKER) { + return mergeRateLimitHeaders( + errorResponse("internal_error", "Notifications service unavailable", 503, requestId), + rateHeaders, + ); + } + + const timings = createTimings(); + const endTotal = timings.start("edge_total"); + const sessionResult = await timings.measure("edge_auth", () => + resolveActor(request, env, requestId), + ); + if ("error" in sessionResult) { + return mergeRateLimitHeaders(sessionResult.error, rateHeaders); + } + + const headers = new Headers(); + headers.set("x-request-id", requestId); + // notifications-worker's internal-actor gate: the edge is an allowed caller + // and the actor headers carry the pinned subject. + headers.set("x-internal-actor", "api-edge"); + headers.set("x-actor-subject-id", sessionResult.subjectId); + headers.set("x-actor-subject-type", sessionResult.subjectType); + const traceparent = request.headers.get("traceparent"); + if (traceparent) headers.set("traceparent", traceparent); + + const url = new URL(request.url); + let init: RequestInit; + let target: URL; + + if (request.method === "GET") { + // Rebuild the query with the subject pinned to the actor; pass through + // only orgId and the optional channel filter. + target = new URL(pathname, "https://notifications.internal"); + const orgId = url.searchParams.get("orgId"); + if (orgId) target.searchParams.set("orgId", orgId); + const channel = url.searchParams.get("channel"); + if (channel) target.searchParams.set("channel", channel); + target.searchParams.set("subjectKind", "user"); + target.searchParams.set("subjectId", sessionResult.subjectId); + init = { method: "GET", headers }; + } else { + let body: unknown; + try { + body = await request.json(); + } catch { + return mergeRateLimitHeaders( + errorResponse("bad_request", "Invalid JSON body", 400, requestId), + rateHeaders, + ); + } + if (!body || typeof body !== "object" || Array.isArray(body)) { + return mergeRateLimitHeaders( + errorResponse("bad_request", "Body must be a JSON object", 400, requestId), + rateHeaders, + ); + } + const pinned = { + ...(body as Record), + subjectKind: "user", + subjectId: sessionResult.subjectId, + }; + headers.set("content-type", "application/json"); + target = new URL(pathname, "https://notifications.internal"); + init = { method: "PUT", headers, body: JSON.stringify(pinned) }; + } + + try { + const downstream = await timings.measure("edge_downstream", () => + env.NOTIFICATIONS_WORKER!.fetch(target.toString(), init), + ); + endTotal(); + return mergeRateLimitHeaders( + withEdgeTimings( + new Response(downstream.body, { + status: downstream.status, + headers: downstream.headers, + }), + requestId, + "edge.notifications", + timings, + ), + rateHeaders, + ); + } catch { + return mergeRateLimitHeaders( + errorResponse("internal_error", "Notifications service unavailable", 503, requestId), + rateHeaders, + ); + } +} diff --git a/apps/api-edge/src/org-facade.ts b/apps/api-edge/src/org-facade.ts new file mode 100644 index 0000000..098b78d --- /dev/null +++ b/apps/api-edge/src/org-facade.ts @@ -0,0 +1,146 @@ +import type { Env } from "./env.js"; +import { errorResponse, withEdgeTimings } from "./http.js"; +import { replayOrExecute } from "./idempotency.js"; +import { resolveActor } from "./resolve-actor.js"; +import { createTimings } from "@saas/contracts/timing"; + +const ORG_ROUTES: Record = { + "/v1/organizations": "POST|GET", +}; + +const ORG_ID_RE = /^\/v1\/organizations\/[^/]+$/; +const ORG_MEMBERS_RE = /^\/v1\/organizations\/[^/]+\/members$/; +const ORG_MEMBER_ID_RE = /^\/v1\/organizations\/[^/]+\/members\/[^/]+$/; +const ORG_INVITATIONS_ACCEPT_RE = /^\/v1\/organizations\/[^/]+\/invitations\/accept$/; +const ORG_INVITATIONS_RE = /^\/v1\/organizations\/[^/]+\/invitations$/; +const ORG_INVITATION_ID_RE = /^\/v1\/organizations\/[^/]+\/invitations\/[^/]+$/; +const ORG_API_KEYS_RE = /^\/v1\/organizations\/[^/]+\/api-keys$/; +const ORG_API_KEY_ID_RE = /^\/v1\/organizations\/[^/]+\/api-keys\/[^/]+$/; + +const FORWARDED_HEADERS = [ + "content-type", + "x-request-id", + "traceparent", + "idempotency-key", +]; + +export function isOrgRoute(pathname: string): boolean { + return pathname in ORG_ROUTES || ORG_ID_RE.test(pathname) || ORG_MEMBERS_RE.test(pathname) || ORG_MEMBER_ID_RE.test(pathname) || ORG_INVITATIONS_ACCEPT_RE.test(pathname) || ORG_INVITATIONS_RE.test(pathname) || ORG_INVITATION_ID_RE.test(pathname) || ORG_API_KEYS_RE.test(pathname) || ORG_API_KEY_ID_RE.test(pathname); +} + +export async function handleOrgRoute( + request: Request, + env: Env, + requestId: string, + pathname: string, +): Promise { + const allowedMethods = ORG_ROUTES[pathname]; + if (allowedMethods && !allowedMethods.includes(request.method)) { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + if (ORG_INVITATIONS_ACCEPT_RE.test(pathname) && request.method !== "POST") { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + if (ORG_MEMBERS_RE.test(pathname) && request.method !== "GET") { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + if (ORG_MEMBER_ID_RE.test(pathname) && request.method !== "PATCH" && request.method !== "DELETE") { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + if (ORG_INVITATIONS_RE.test(pathname) && request.method !== "POST" && request.method !== "GET") { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + if (ORG_INVITATION_ID_RE.test(pathname) && !ORG_INVITATIONS_ACCEPT_RE.test(pathname) && request.method !== "DELETE") { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + if (ORG_API_KEYS_RE.test(pathname) && request.method !== "POST" && request.method !== "GET") { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + if (ORG_API_KEY_ID_RE.test(pathname) && request.method !== "DELETE") { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + if (ORG_ID_RE.test(pathname) && !ORG_API_KEYS_RE.test(pathname) && !ORG_API_KEY_ID_RE.test(pathname) && request.method !== "GET") { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + return replayOrExecute(request, requestId, env, "org", async () => { + + if (!env.IDENTITY_WORKER) { + return errorResponse( + "internal_error", + "Authentication service unavailable", + 503, + requestId, + ); + } + + if (!env.MEMBERSHIP_WORKER) { + return errorResponse( + "internal_error", + "Membership service unavailable", + 503, + requestId, + ); + } + + const timings = createTimings(); + const endTotal = timings.start("edge_total"); + const sessionResult = await timings.measure("edge_auth", () => resolveActor(request, env, requestId)); + if ("error" in sessionResult) { + return sessionResult.error; + } + + const headers = new Headers(); + headers.set("x-request-id", requestId); + headers.set("x-actor-subject-id", sessionResult.subjectId); + headers.set("x-actor-subject-type", sessionResult.subjectType); + headers.set("x-actor-email", sessionResult.email); + if (sessionResult.orgId) { + } + for (const name of FORWARDED_HEADERS) { + if (name === "x-request-id") continue; + const value = request.headers.get(name); + if (value) headers.set(name, value); + } + + const url = new URL(request.url); + const isApiKeyRoute = ORG_API_KEYS_RE.test(pathname) || ORG_API_KEY_ID_RE.test(pathname); + const targetWorker = isApiKeyRoute ? env.IDENTITY_WORKER! : env.MEMBERSHIP_WORKER!; + const targetHost = isApiKeyRoute ? "https://identity.internal" : "https://membership.internal"; + const target = new URL(pathname + url.search, targetHost); + + const init: RequestInit = { + method: request.method, + headers, + }; + + if (request.method === "POST" || request.method === "PATCH") { + init.body = request.body; + } + + try { + const downstream = await timings.measure("edge_downstream", () => targetWorker.fetch(target.toString(), init)); + const res = new Response(downstream.body, { + status: downstream.status, + headers: downstream.headers, + }); + endTotal(); + return withEdgeTimings(res, requestId, "edge.org", timings); + } catch { + return errorResponse( + "internal_error", + "Membership service unavailable", + 503, + requestId, + ); + } + }); +} diff --git a/apps/api-edge/src/project-facade.ts b/apps/api-edge/src/project-facade.ts new file mode 100644 index 0000000..1ff9246 --- /dev/null +++ b/apps/api-edge/src/project-facade.ts @@ -0,0 +1,104 @@ +import type { Env } from "./env.js"; +import { errorResponse, withEdgeTimings } from "./http.js"; +import { replayOrExecute } from "./idempotency.js"; +import { resolveActor } from "./resolve-actor.js"; +import { createTimings } from "@saas/contracts/timing"; + +const ORG_PROJECTS_RE = /^\/v1\/organizations\/[^/]+\/projects$/; +const ORG_PROJECT_ID_RE = /^\/v1\/organizations\/[^/]+\/projects\/[^/]+$/; +const ORG_PROJECT_ENVIRONMENTS_RE = /^\/v1\/organizations\/[^/]+\/projects\/[^/]+\/environments$/; +const ORG_PROJECT_ENVIRONMENT_ID_RE = /^\/v1\/organizations\/[^/]+\/projects\/[^/]+\/environments\/[^/]+$/; + +const FORWARDED_HEADERS = [ + "content-type", + "x-request-id", + "traceparent", + "idempotency-key", +]; + +export function isProjectRoute(pathname: string): boolean { + return ( + ORG_PROJECTS_RE.test(pathname) || + ORG_PROJECT_ID_RE.test(pathname) || + ORG_PROJECT_ENVIRONMENTS_RE.test(pathname) || + ORG_PROJECT_ENVIRONMENT_ID_RE.test(pathname) + ); +} + +export async function handleProjectRoute( + request: Request, + env: Env, + requestId: string, + pathname: string, +): Promise { + if (ORG_PROJECTS_RE.test(pathname) && request.method !== "POST" && request.method !== "GET") { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + if (ORG_PROJECT_ID_RE.test(pathname) && request.method !== "GET" && request.method !== "DELETE") { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + if (ORG_PROJECT_ENVIRONMENTS_RE.test(pathname) && request.method !== "POST" && request.method !== "GET") { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + if (ORG_PROJECT_ENVIRONMENT_ID_RE.test(pathname) && request.method !== "GET" && request.method !== "DELETE") { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + return replayOrExecute(request, requestId, env, "project", async () => { + + if (!env.IDENTITY_WORKER) { + return errorResponse("internal_error", "Authentication service unavailable", 503, requestId); + } + + if (!env.PROJECTS_WORKER) { + return errorResponse("internal_error", "Projects service unavailable", 503, requestId); + } + + const timings = createTimings(); + const endTotal = timings.start("edge_total"); + const sessionResult = await timings.measure("edge_auth", () => resolveActor(request, env, requestId)); + if ("error" in sessionResult) { + return sessionResult.error; + } + + const headers = new Headers(); + headers.set("x-request-id", requestId); + headers.set("x-actor-subject-id", sessionResult.subjectId); + headers.set("x-actor-subject-type", sessionResult.subjectType); + headers.set("x-actor-email", sessionResult.email); + if (sessionResult.orgId) { + } + for (const name of FORWARDED_HEADERS) { + if (name === "x-request-id") continue; + const value = request.headers.get(name); + if (value) headers.set(name, value); + } + + const url = new URL(request.url); + const target = new URL(pathname + url.search, "https://projects.internal"); + + const init: RequestInit = { + method: request.method, + headers, + }; + + if (request.method === "POST") { + init.body = request.body; + } + + try { + const downstream = await timings.measure("edge_downstream", () => env.PROJECTS_WORKER!.fetch(target.toString(), init)); + const res = new Response(downstream.body, { + status: downstream.status, + headers: downstream.headers, + }); + endTotal(); + return withEdgeTimings(res, requestId, "edge.project", timings); + } catch { + return errorResponse("internal_error", "Projects service unavailable", 503, requestId); + } + }); +} \ No newline at end of file diff --git a/apps/api-edge/src/rate-limit-do.ts b/apps/api-edge/src/rate-limit-do.ts new file mode 100644 index 0000000..af187c1 --- /dev/null +++ b/apps/api-edge/src/rate-limit-do.ts @@ -0,0 +1,70 @@ +// Rate-limiter Durable Object (PERF5 Stage B). +// +// One DO instance per (scope,key) rate-limit bucket — the edge addresses it via +// `idFromName(bucketKey)`. The Workers runtime serializes all requests to a +// single DO instance, so the token-bucket read-modify-write here is ATOMIC. +// That is the whole point of Stage B: the KV limiter it replaces did a +// non-atomic get-then-put and documented "last-writer-wins under concurrent +// retry", i.e. it was both slow (a central KV write per request) and inaccurate +// under the exact burst load it exists to bound. The DO is correct and needs no +// KV write on the hot path. +// +// State is held in memory. A DO that hibernates or is evicted loses its bucket +// and the next request starts from a full bucket — for a token bucket that just +// means it refilled, which is acceptable (and a hot bucket under active load +// stays resident for the duration of the burst that matters). We therefore keep +// NO durable storage, which also keeps the consume path I/O-free. + +import { tokenBucketStep, type BucketState } from "./rate-limit.js"; + +interface ConsumeRequest { + limit: number; + windowSec: number; + scope: "org" | "identity"; +} + +function isConsumeRequest(value: unknown): value is ConsumeRequest { + return ( + typeof value === "object" && + value !== null && + typeof (value as ConsumeRequest).limit === "number" && + typeof (value as ConsumeRequest).windowSec === "number" && + ((value as ConsumeRequest).scope === "org" || + (value as ConsumeRequest).scope === "identity") + ); +} + +export class RateLimiterDO { + /** In-memory token bucket for this single (scope,key). See the file header. */ + private bucket: BucketState | null = null; + + // Workers constructs a DO with (state, env). We keep neither — the bucket is + // in-memory and the limits arrive on each request — but the signature is part + // of the Durable Object contract. + constructor(_state: DurableObjectState, _env: unknown) {} + + async fetch(request: Request): Promise { + let body: unknown; + try { + body = await request.json(); + } catch { + return new Response("invalid body", { status: 400 }); + } + if (!isConsumeRequest(body)) { + return new Response("invalid body", { status: 400 }); + } + + const now = Date.now() / 1000; + const step = tokenBucketStep(this.bucket, body.limit, body.windowSec, now); + this.bucket = step.next; + + return Response.json({ + scope: body.scope, + limit: body.limit, + remaining: step.remaining, + resetEpoch: step.resetEpoch, + retryAfterSec: step.retryAfterSec, + allowed: step.allowed, + }); + } +} diff --git a/apps/api-edge/src/rate-limit.ts b/apps/api-edge/src/rate-limit.ts new file mode 100644 index 0000000..d6fc39e --- /dev/null +++ b/apps/api-edge/src/rate-limit.ts @@ -0,0 +1,601 @@ +// Edge-side per-org / per-identity rate limiter (Task 0097). +// +// Sits in front of `replayOrExecute` so every facade picks it up uniformly. +// Independent buckets: +// +// - `org`: keyed on `orgId` extracted from `/v1/organizations/{orgId}/…`. +// Skipped when the URL has no org segment. +// - `identity`: keyed on a SHA-256 fingerprint of the bearer token when one +// is present (same token ⇒ same bucket, regardless of which +// actor type `resolveActor` will eventually classify it as); +// otherwise falls back to `anon::` +// so abuse from a single IP cannot bypass the limit. +// +// Algorithm: token bucket with refill per second. State persisted in KV as +// compact JSON `{t, r}` (`t` = tokens float, `r` = refilledAt epoch seconds). +// Last-writer-wins under concurrent retry — acceptable for V1; documented in +// the implementer report. +// +// Backend: reuses `IDEMPOTENCY_KV` with a mandatory `rl:v1:` key prefix to +// avoid keyspace collision with the existing `idem:v1:` replay store. This +// ships the limiter without the chicken-and-egg of provisioning a new KV +// namespace + wiring its ID in the same PR. +// +// Failure-open: if the KV binding is missing, or `get`/`put` throws, the +// request is admitted without rate-limit headers (we have no real counters +// to publish under failure). Logged via `console.warn`. +// +// PERF5 (latency): the KV token bucket did a `get`+`put` per bucket on EVERY +// request, before auth — measured at ~130ms/bucket, ~264ms for an org-scoped +// read (org + identity buckets, serialized). The fix has two stages: +// +// Stage A — take it off the read hot path without losing protection: +// 1. Unsafe (mutating) methods keep a durable cross-isolate limiter, but the +// buckets are evaluated CONCURRENTLY (`Promise.all`) instead of serially. +// 2. Safe (read) methods use a colo-local, in-isolate token bucket with ZERO +// network I/O. Approximate (per-isolate state ⇒ the effective global limit +// scales with isolate count) — acceptable for reads: caps are generous and +// reads are not the abuse vector writes are. +// +// Stage B — make the durable (write) limiter both faster and CORRECT: +// the durable counters move from KV to Durable Objects. Each (scope,key) +// bucket maps to one DO instance whose single-threaded execution makes the +// read-modify-write atomic (fixing the KV limiter's documented +// last-writer-wins race) with no central KV write on the hot path. When the +// DO binding is absent (dev/local), the limiter falls back to the Stage A KV +// path, then to fail-open — so the change is safe to roll out incrementally. + +import type { Env } from "./env.js"; + +export type RouteFamily = + | "auth" + | "org" + | "project" + | "config" + | "webhooks" + | "metering" + | "billing" + | "audit" + | "notifications" + | "integrations"; + +interface BucketLimits { + /** Bucket capacity (max tokens). */ + limit: number; + /** Window length in seconds; refill rate = limit / windowSec tokens/sec. */ + windowSec: number; +} + +interface FamilyConfig { + identity: BucketLimits; + org: BucketLimits; +} + +/** + * Per-route-family caps. Picked to absorb legitimate burstiness while still + * blunting abuse. Tunable; no per-tenant overrides yet (B5 territory). + * + * - `auth`: tighter — login/logout flows are the brute-force target. + * - everything else (writes/reads): 60/300 per minute identity/org. + * - `audit` is read-only and trusted further; raised to 120/600. + */ +const LIMITS: Record = { + auth: { + identity: { limit: 10, windowSec: 60 }, + org: { limit: 60, windowSec: 60 }, + }, + org: { + identity: { limit: 60, windowSec: 60 }, + org: { limit: 300, windowSec: 60 }, + }, + project: { + identity: { limit: 60, windowSec: 60 }, + org: { limit: 300, windowSec: 60 }, + }, + config: { + identity: { limit: 60, windowSec: 60 }, + org: { limit: 300, windowSec: 60 }, + }, + webhooks: { + identity: { limit: 60, windowSec: 60 }, + org: { limit: 300, windowSec: 60 }, + }, + metering: { + identity: { limit: 60, windowSec: 60 }, + org: { limit: 300, windowSec: 60 }, + }, + billing: { + identity: { limit: 60, windowSec: 60 }, + org: { limit: 300, windowSec: 60 }, + }, + audit: { + identity: { limit: 120, windowSec: 60 }, + org: { limit: 600, windowSec: 60 }, + }, + notifications: { + identity: { limit: 60, windowSec: 60 }, + org: { limit: 300, windowSec: 60 }, + }, + integrations: { + identity: { limit: 60, windowSec: 60 }, + org: { limit: 300, windowSec: 60 }, + }, +}; + +const KV_PREFIX = "rl:v1"; +const KV_TTL_SECONDS = 600; +const ORG_PATH_RE = /^\/v1\/organizations\/([^/]+)/; + +// PERF5 Stage A: only mutating methods pay the durable cross-isolate KV +// limiter. Safe reads use the in-isolate limiter below. Mirrors the +// `UNSAFE_METHODS` set in idempotency.ts (kept local to avoid an import cycle). +const DURABLE_LIMIT_METHODS: ReadonlySet = new Set([ + "POST", + "PATCH", + "PUT", + "DELETE", +]); + +// In-isolate token-bucket state for safe (read) methods. Colo-local and +// per-isolate by design (see `enforceRateLimit`). Bounded so a long-lived +// isolate seeing many distinct orgs/identities cannot grow it without limit. +interface MemBucketState { + t: number; + r: number; +} +const MEM_BUCKET_CAP = 10_000; +const memBuckets = new Map(); + +/** Public result. `headers` is merged into the final response by the caller. */ +export type RateLimitResult = + | { kind: "allowed"; headers: Record } + | { kind: "denied"; response: Response }; + +/** Token-bucket persistence shape: `t` = tokens (float), `r` = refilledAt (epoch s). */ +export interface BucketState { + t: number; + r: number; +} + +interface BucketDecision { + scope: "org" | "identity"; + limit: number; + remaining: number; + resetEpoch: number; + retryAfterSec: number; + allowed: boolean; +} + +export interface TokenBucketStep { + next: BucketState; + allowed: boolean; + remaining: number; + resetEpoch: number; + retryAfterSec: number; +} + +/** + * Pure token-bucket step — the single source of truth for the refill/consume + * math, shared by the KV limiter, the in-isolate read limiter, and the Durable + * Object write limiter (PERF5). Given the previous state (or `null` for a fresh + * bucket) and the current time, returns the new state and the decision. + */ +export function tokenBucketStep( + prev: BucketState | null, + limit: number, + windowSec: number, + now: number, +): TokenBucketStep { + const refillRate = limit / windowSec; + const base = prev ?? { t: limit, r: now }; + const elapsed = Math.max(0, now - base.r); + const refilled = Math.min(limit, base.t + elapsed * refillRate); + + if (refilled >= 1) { + const tokens = refilled - 1; + return { + next: { t: tokens, r: now }, + allowed: true, + remaining: Math.floor(tokens), + resetEpoch: Math.ceil(now + (limit - tokens) / refillRate), + retryAfterSec: 0, + }; + } + return { + next: { t: refilled, r: now }, + allowed: false, + remaining: 0, + resetEpoch: Math.ceil(now + (limit - refilled) / refillRate), + retryAfterSec: Math.max(1, Math.ceil((1 - refilled) / refillRate)), + }; +} + +/** + * Returns `allowed` (with headers to merge) or `denied` (with a complete + * 429 response carrying the standard envelope and `Retry-After`). + * + * Never throws; KV failures degrade to admit-with-no-headers per the + * fail-open contract. + */ +export async function enforceRateLimit( + request: Request, + requestId: string, + env: Env, + routeFamily: RouteFamily, +): Promise { + const config = LIMITS[routeFamily]; + + const url = new URL(request.url); + const orgId = extractOrgId(url.pathname); + const identityKey = await deriveIdentityKey(request, routeFamily); + + const buckets: Array<{ + scope: "org" | "identity"; + key: string; + limits: BucketLimits; + }> = []; + if (orgId) { + buckets.push({ + scope: "org", + key: `${KV_PREFIX}:org:${routeFamily}:${orgId}`, + limits: config.org, + }); + } + buckets.push({ + scope: "identity", + key: `${KV_PREFIX}:identity:${routeFamily}:${identityKey}`, + limits: config.identity, + }); + + let decisions: BucketDecision[]; + let failureOpen = false; + + if (DURABLE_LIMIT_METHODS.has(request.method)) { + // Unsafe (mutating) methods → durable, cross-isolate limiter. + const ns = env.RATE_LIMITER_DO; + if (ns) { + // PERF5 Stage B: precise per-(scope,key) counters in Durable Objects. + // Each bucket key maps to one DO instance whose single-threaded execution + // makes the read-modify-write ATOMIC (no last-writer-wins race, the KV + // limiter's documented V1 flaw) and needs no central KV write on the hot + // path. Buckets are independent → evaluated concurrently. + decisions = await Promise.all( + buckets.map(async (b) => { + try { + return await consumeViaDurableObject(ns, b.key, b.limits, b.scope); + } catch (err) { + logLimiterFailure("durable_object", err, requestId); + failureOpen = true; + return fullBucketDecision(b.scope, b.limits); + } + }), + ); + } else { + // Fallback: the durable KV limiter (Stage A) when the DO binding is not + // wired (e.g. dev / local). Backend missing entirely → fail open. + const kv = env.IDEMPOTENCY_KV; + if (!kv) { + return { kind: "allowed", headers: {} }; + } + // PERF5 Stage A: buckets are independent keys → evaluate CONCURRENTLY + // rather than in a serial await-loop (halves the KV cost on org routes). + decisions = await Promise.all( + buckets.map(async (b) => { + try { + return await consumeToken(kv, b.key, b.limits, b.scope); + } catch (err) { + logLimiterFailure("kv", err, requestId); + failureOpen = true; + return fullBucketDecision(b.scope, b.limits); + } + }), + ); + } + } else { + // PERF5 Stage A: safe (read) methods use a colo-local, in-isolate token + // bucket — ZERO network I/O — so the KV read-modify-write is OFF the read + // hot path. Approximate (per-isolate) by design; see the module header. + decisions = buckets.map((b) => + consumeTokenInMemory(b.key, b.limits, b.scope), + ); + } + + const headers = buildHeaders(decisions); + + // Under failure-open we do NOT deny even if a partial decision said no — + // the fail-open contract supersedes the partial counter. + if (failureOpen) { + return { kind: "allowed", headers }; + } + + const denied = decisions.find((d) => !d.allowed); + if (denied) { + const retry = Math.max(1, denied.retryAfterSec); + const responseHeaders: Record = { + ...headers, + "content-type": "application/json", + "Retry-After": String(retry), + }; + const body = JSON.stringify({ + error: { + code: "rate_limited", + message: `Rate limit exceeded for ${denied.scope} scope. Retry after ${retry} seconds.`, + details: { scope: denied.scope, retryAfterSeconds: retry }, + requestId, + }, + }); + return { + kind: "denied", + response: new Response(body, { status: 429, headers: responseHeaders }), + }; + } + + return { kind: "allowed", headers }; +} + +/** + * Merge rate-limit headers into an existing response without reading its body. + * Used by `replayOrExecute` to decorate every allowed response. + */ +export function mergeRateLimitHeaders( + response: Response, + headers: Record, +): Response { + if (Object.keys(headers).length === 0) return response; + const merged = new Headers(response.headers); + for (const [name, value] of Object.entries(headers)) { + merged.set(name, value); + } + return new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers: merged, + }); +} + +// --- Internals --- + +async function consumeToken( + kv: KVNamespace, + key: string, + limits: BucketLimits, + scope: "org" | "identity", +): Promise { + const now = Date.now() / 1000; + const refillRate = limits.limit / limits.windowSec; + + const raw = await kv.get(key, "text"); + let state: BucketState; + if (raw) { + const parsed = parseState(raw); + state = parsed ?? { t: limits.limit, r: now }; + } else { + state = { t: limits.limit, r: now }; + } + + // Refill since last touch, capped at limit. + const elapsed = Math.max(0, now - state.r); + const refilled = Math.min(limits.limit, state.t + elapsed * refillRate); + + if (refilled >= 1) { + const newState: BucketState = { t: refilled - 1, r: now }; + await kv.put(key, JSON.stringify(newState), { + expirationTtl: KV_TTL_SECONDS, + }); + const remaining = Math.floor(newState.t); + const tokensToFull = limits.limit - newState.t; + const resetEpoch = Math.ceil(now + tokensToFull / refillRate); + return { + scope, + limit: limits.limit, + remaining, + resetEpoch, + retryAfterSec: 0, + allowed: true, + }; + } + + // Deny. Persist refilled state (refilledAt update only) so subsequent + // requests see the same wall-clock origin. + const denyState: BucketState = { t: refilled, r: now }; + try { + await kv.put(key, JSON.stringify(denyState), { + expirationTtl: KV_TTL_SECONDS, + }); + } catch { + // Non-fatal: the deny is still correct, we just won't update the touch. + } + const needed = 1 - refilled; + const waitSec = needed / refillRate; + const retryAfterSec = Math.max(1, Math.ceil(waitSec)); + const tokensToFull = limits.limit - refilled; + const resetEpoch = Math.ceil(now + tokensToFull / refillRate); + return { + scope, + limit: limits.limit, + remaining: 0, + resetEpoch, + retryAfterSec, + allowed: false, + }; +} + +/** Synthetic full-bucket decision (failure-open: admit, no real counter). */ +function fullBucketDecision( + scope: "org" | "identity", + limits: BucketLimits, +): BucketDecision { + const now = Math.ceil(Date.now() / 1000); + return { + scope, + limit: limits.limit, + remaining: limits.limit, + resetEpoch: now + limits.windowSec, + retryAfterSec: 0, + allowed: true, + }; +} + +/** + * Synchronous, in-isolate token bucket for safe-method (read) rate limiting + * (PERF5 Stage A). Same refill math as `consumeToken`, but state lives in a + * module-scoped Map instead of KV — no network I/O on the read hot path. + * + * Approximate by design: state is per-isolate, so the effective global limit + * scales with the number of live isolates. Acceptable for reads (generous caps; + * not the abuse vector writes are). Mutating methods keep the precise durable + * KV limiter. + */ +function consumeTokenInMemory( + key: string, + limits: BucketLimits, + scope: "org" | "identity", +): BucketDecision { + const now = Date.now() / 1000; + const existing = memBuckets.get(key); + + // Bound memory: when the map is full and this is a new key, drop all state. + // A reset just refills everyone to capacity — harmless for an approximate + // read limiter, and isolates are recycled frequently anyway. + if (!existing && memBuckets.size >= MEM_BUCKET_CAP) { + memBuckets.clear(); + } + + const step = tokenBucketStep(existing ?? null, limits.limit, limits.windowSec, now); + memBuckets.set(key, step.next); + return { + scope, + limit: limits.limit, + remaining: step.remaining, + resetEpoch: step.resetEpoch, + retryAfterSec: step.retryAfterSec, + allowed: step.allowed, + }; +} + +/** + * Consume one token from the per-(scope,key) Durable Object (PERF5 Stage B). + * The bucket key maps to a single DO instance via `idFromName`; its + * single-threaded execution makes the consume atomic. Throws on a non-OK DO + * response so the caller can fail open. + */ +async function consumeViaDurableObject( + ns: DurableObjectNamespace, + key: string, + limits: BucketLimits, + scope: "org" | "identity", +): Promise { + const stub = ns.get(ns.idFromName(key)); + const res = await stub.fetch("https://rate-limiter.internal/consume", { + method: "POST", + body: JSON.stringify({ + limit: limits.limit, + windowSec: limits.windowSec, + scope, + }), + }); + if (!res.ok) { + throw new Error(`rate-limiter DO responded ${res.status}`); + } + const d = (await res.json()) as { + limit: number; + remaining: number; + resetEpoch: number; + retryAfterSec: number; + allowed: boolean; + }; + return { + scope, + limit: d.limit, + remaining: d.remaining, + resetEpoch: d.resetEpoch, + retryAfterSec: d.retryAfterSec, + allowed: d.allowed, + }; +} + +/** Test-only: clear the in-isolate read buckets between cases. */ +export function __resetRateLimitMemoryForTest(): void { + memBuckets.clear(); +} + +function parseState(raw: string): BucketState | null { + try { + const parsed: unknown = JSON.parse(raw); + if ( + parsed && + typeof parsed === "object" && + typeof (parsed as { t?: unknown }).t === "number" && + typeof (parsed as { r?: unknown }).r === "number" + ) { + return { t: (parsed as BucketState).t, r: (parsed as BucketState).r }; + } + } catch { + // fall through + } + return null; +} + +function buildHeaders(decisions: BucketDecision[]): Record { + const headers: Record = {}; + for (const d of decisions) { + headers[`X-RateLimit-Limit-${d.scope}`] = String(d.limit); + headers[`X-RateLimit-Remaining-${d.scope}`] = String(d.remaining); + headers[`X-RateLimit-Reset-${d.scope}`] = String(d.resetEpoch); + } + return headers; +} + +function extractOrgId(pathname: string): string | null { + const m = ORG_PATH_RE.exec(pathname); + if (!m || !m[1]) return null; + return m[1]; +} + +async function deriveIdentityKey( + request: Request, + routeFamily: RouteFamily, +): Promise { + const auth = request.headers.get("authorization"); + if (auth && auth.startsWith("Bearer ")) { + const token = auth.slice("Bearer ".length).trim(); + if (token.length > 0) { + const hash = await sha256Hex(token); + return `bearer:${hash.slice(0, 32)}`; + } + } + const ip = request.headers.get("CF-Connecting-IP") ?? "unknown"; + return `anon:${routeFamily}:${ip}`; +} + +async function sha256Hex(input: string): Promise { + const data = new TextEncoder().encode(input); + const digest = await crypto.subtle.digest("SHA-256", data); + const bytes = new Uint8Array(digest); + let hex = ""; + for (let i = 0; i < bytes.length; i++) { + hex += bytes[i]!.toString(16).padStart(2, "0"); + } + return hex; +} + +function logLimiterFailure( + backend: "kv" | "durable_object", + err: unknown, + requestId: string, +): void { + const message = err instanceof Error ? err.message : String(err); + console.warn( + JSON.stringify({ + level: "warn", + msg: "rate_limit.backend_failure", + backend, + requestId, + error: message, + }), + ); +} + +// Test-only export: allows unit tests to introspect the configured limits +// without needing to mirror the table. +export const __rateLimitConfigForTest: Record = LIMITS; diff --git a/apps/api-edge/src/resolve-actor.ts b/apps/api-edge/src/resolve-actor.ts new file mode 100644 index 0000000..e146fc1 --- /dev/null +++ b/apps/api-edge/src/resolve-actor.ts @@ -0,0 +1,107 @@ +import type { Env } from "./env"; +import { errorResponse } from "./http"; +import { cacheApiStore, bearerToken, type ActorCacheStore } from "./actor-cache"; + +export interface ActorInfo { + subjectId: string; + subjectType: string; + email: string; + orgId?: string; +} + +export interface ActorFailure { + error: Response; +} + +export interface ResolveActorDeps { + /** Injectable cache store (tests). Defaults to the Cache-API store. */ + cache?: ActorCacheStore; +} + +/** + * Resolves bearer token to actor context via IDENTITY_WORKER /v1/auth/resolve. + * Supports both user sessions (sps_ses_ tokens) and API keys (service_principal). + * + * Hot-path cache (Task 0131 / PERF2): a successful resolution is cached by a + * hash of the token for a short TTL, so repeat requests skip the identity-worker + * hop + its DB queries. Misses and failures fall through to a live resolve. + */ +export async function resolveActor( + request: Request, + env: Env, + requestId: string, + deps?: ResolveActorDeps, +): Promise { + const authorization = request.headers.get("authorization"); + const token = bearerToken(authorization); + if (!authorization || !token) { + return { + error: errorResponse("unauthenticated", "Missing or invalid Authorization header", 401, requestId), + }; + } + + if (!env.IDENTITY_WORKER) { + return { + error: errorResponse("internal_error", "Authentication service unavailable", 503, requestId), + }; + } + + const cache = deps?.cache ?? cacheApiStore(); + const cached = await cache.get(token); + if (cached) return cached; + + const headers = new Headers(); + headers.set("authorization", authorization); + headers.set("x-request-id", requestId); + + const target = new URL("/v1/auth/resolve", "https://identity.internal"); + + try { + const response = await env.IDENTITY_WORKER.fetch(target.toString(), { + method: "GET", + headers, + }); + + if (!response.ok) { + return { + error: errorResponse("unauthenticated", "Authentication failed", 401, requestId), + }; + } + + const json = (await response.json()) as { + data?: { + actor?: { + actorType?: string; + actorId?: string; + email?: string; + orgId?: string; + }; + user?: { id?: string; email?: string }; + }; + }; + + const actor = json?.data?.actor; + if (!actor?.actorType || !actor?.actorId) { + return { + error: errorResponse("unauthenticated", "Authentication failed", 401, requestId), + }; + } + + // For user actors, prefer user-level email; for service_principal, use actor email or empty + const email = json?.data?.user?.email ?? actor.email ?? ""; + + const info: ActorInfo = { + subjectId: actor.actorId, + subjectType: actor.actorType, + email, + ...(actor.orgId && { orgId: actor.orgId }), + }; + // Cache only successful resolutions (best-effort; never cache a denial). + await cache.set(token, info); + return info; + } catch { + return { + error: errorResponse("internal_error", "Authentication service unavailable", 503, requestId), + }; + } +} diff --git a/apps/api-edge/src/solo-mode.ts b/apps/api-edge/src/solo-mode.ts new file mode 100644 index 0000000..ff03b1e --- /dev/null +++ b/apps/api-edge/src/solo-mode.ts @@ -0,0 +1,88 @@ +// M0 / Solo profile — the single instance-wide switch (SOLO_MODE). +// +// When SOLO_MODE is on, the product behaves as a single-user B2C app: the user +// IS the tenant (one auto-provisioned, invisible personal organization) and +// never sees orgs, teams, projects, or platform plumbing. This module is the +// api-edge ENFORCEMENT seam — the one place that decides, for a single request, +// whether a route is suppressed under the Solo profile. `index.ts` consults it +// once, before dispatching to any facade, and 404s a suppressed route. +// +// Design contract (specs/profiles/solo-m0.md): +// - Suppress, don't remove. No facade is deleted; matchers are reused. +// - Everything keys off this one flag. Flip SOLO_MODE off (unset the wrangler +// var) and `isSoloMode` returns false, this predicate is never consulted, +// and the full multi-tenant baseline is restored unchanged. +// - RBAC/billing/audit keep running on their existing paths underneath. + +import type { Env } from "./env"; +import { isProjectRoute } from "./project-facade"; +import { isMeteringRoute } from "./metering-facade"; +import { isWebhooksRoute } from "./webhooks-facade"; +import { isIntegrationsRoute, isIntegrationsIngressRoute } from "./integrations-facade"; + +/** + * Is this instance running the M0/Solo profile? Deploy-time wrangler var; an + * absent or non-"true" value means the full multi-tenant baseline (the safe + * default — Solo is strictly opt-in). + */ +export function isSoloMode(env: Env): boolean { + return env.SOLO_MODE === "true"; +} + +// Org sub-resources hidden under Solo. The personal org itself stays usable +// (GET list + GET by id); only the collaboration and credential surfaces are +// suppressed. Patterns mirror org-facade's own matchers (members/invitations/ +// api-keys, with or without a trailing id segment). +const ORG_MEMBERS_RE = /^\/v1\/organizations\/[^/]+\/members(?:\/[^/]+)?$/; +const ORG_INVITATIONS_RE = /^\/v1\/organizations\/[^/]+\/invitations(?:\/[^/]+)?$/; +const ORG_API_KEYS_RE = /^\/v1\/organizations\/[^/]+\/api-keys(?:\/[^/]+)?$/; + +/** + * Is this (path, method) suppressed under the Solo profile? + * + * Suppressed (404 at the edge when SOLO_MODE is on): + * - projects & environments — entire bounded context + * - metering / quotas — entire bounded context + * - outbound webhooks — entire bounded context + * - integrations + install ingress — entire bounded context + * - org members & invitations — collaboration surface + * - org-scoped API keys — credentials (M0-hidden; flag re-enables) + * + * Kept (NOT suppressed — the single-user surfaces): + * - auth (magic-link + OAuth), account/profile + * - per-user billing (checkout/portal) and the provider billing webhook + * - config: settings & feature flags + * - notifications, silent audit logging + * - reading and using the one personal org (GET /v1/organizations[/:id]) + * - BOOTSTRAPPING that one personal org (POST /v1/organizations) — see below + * + * `POST /v1/organizations` is deliberately NOT suppressed here. The Solo rule is + * "no *second* org", and the edge cannot tell a bootstrap from a second one — it + * would have to count the actor's orgs, which membership-worker already does for + * the MO2 gate. Suppressing the whole verb here also broke the profile's own + * recovery path: `ensurePersonalOrg` (identity-worker) is best-effort by design, + * so an account can legitimately reach the console with zero orgs, and the + * console's onboarding fallback then had no way to create the first one + * ("Route not found: /v1/organizations"). The one-org guarantee is enforced in + * `membership-worker`'s create-organization gate instead, where the account's + * org count is known. See specs/profiles/solo-m0.md. + * + * `isSoloMode` is checked separately by the caller, so this is a pure routing + * predicate (no env) and trivially unit-testable for both profile states. The + * `method` argument is kept in the signature as the seam for method-specific + * suppression rules; no current rule needs it. + */ +export function isSoloSuppressed(pathname: string, _method: string): boolean { + // Whole bounded contexts the B2C user never sees. + if (isProjectRoute(pathname)) return true; + if (isMeteringRoute(pathname)) return true; + if (isWebhooksRoute(pathname)) return true; + if (isIntegrationsRoute(pathname) || isIntegrationsIngressRoute(pathname)) return true; + + // Org collaboration + credential sub-resources. + if (ORG_MEMBERS_RE.test(pathname)) return true; + if (ORG_INVITATIONS_RE.test(pathname)) return true; + if (ORG_API_KEYS_RE.test(pathname)) return true; + + return false; +} diff --git a/apps/api-edge/src/webhooks-facade.ts b/apps/api-edge/src/webhooks-facade.ts new file mode 100644 index 0000000..37a9c99 --- /dev/null +++ b/apps/api-edge/src/webhooks-facade.ts @@ -0,0 +1,82 @@ +import type { Env } from "./env.js"; +import { errorResponse } from "./http.js"; +import { replayOrExecute } from "./idempotency.js"; +import { resolveActor } from "./resolve-actor.js"; + +// Organization-scoped webhook routes +const ORG_WEBHOOKS_RE = /^\/v1\/organizations\/[^/]+\/webhooks\//; + +// Project-scoped webhook routes +const PRJ_WEBHOOKS_RE = /^\/v1\/organizations\/[^/]+\/projects\/[^/]+\/webhooks\//; + +const FORWARDED_HEADERS = [ + "content-type", + "x-request-id", + "traceparent", + "idempotency-key", +]; + +export function isWebhooksRoute(pathname: string): boolean { + return ORG_WEBHOOKS_RE.test(pathname) || PRJ_WEBHOOKS_RE.test(pathname); +} + +export async function handleWebhooksRoute( + request: Request, + env: Env, + requestId: string, + pathname: string, +): Promise { + const allowedMethods = ["GET", "POST", "PATCH", "DELETE"]; + if (!allowedMethods.includes(request.method)) { + return errorResponse("unsupported", "Method not allowed", 405, requestId); + } + + return replayOrExecute(request, requestId, env, "webhooks", async () => { + + if (!env.IDENTITY_WORKER) { + return errorResponse("internal_error", "Authentication service unavailable", 503, requestId); + } + + if (!env.WEBHOOKS_WORKER) { + return errorResponse("internal_error", "Webhooks service unavailable", 503, requestId); + } + + const sessionResult = await resolveActor(request, env, requestId); + if ("error" in sessionResult) { + return sessionResult.error; + } + + const headers = new Headers(); + headers.set("x-request-id", requestId); + headers.set("x-actor-subject-id", sessionResult.subjectId); + headers.set("x-actor-subject-type", sessionResult.subjectType); + headers.set("x-actor-email", sessionResult.email); + if (sessionResult.orgId) { + } + for (const name of FORWARDED_HEADERS) { + if (name === "x-request-id") continue; + const value = request.headers.get(name); + if (value) headers.set(name, value); + } + + const url = new URL(request.url); + const target = new URL(pathname + url.search, "https://webhooks.internal"); + + try { + const fetchInit: RequestInit = { + method: request.method, + headers, + }; + if (request.method === "POST" || request.method === "PATCH") { + fetchInit.body = request.body; + } + const downstream = await env.WEBHOOKS_WORKER.fetch(target.toString(), fetchInit); + return new Response(downstream.body, { + status: downstream.status, + headers: downstream.headers, + }); + } catch { + return errorResponse("internal_error", "Webhooks service unavailable", 503, requestId); + } + }); +} \ No newline at end of file diff --git a/apps/api-edge/tsconfig.json b/apps/api-edge/tsconfig.json new file mode 100644 index 0000000..276fd08 --- /dev/null +++ b/apps/api-edge/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tooling/tsconfig/worker.json", + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/apps/api-edge/wiring.fixture.json b/apps/api-edge/wiring.fixture.json new file mode 100644 index 0000000..3740ed8 --- /dev/null +++ b/apps/api-edge/wiring.fixture.json @@ -0,0 +1,14 @@ +{ + "cloudflare-d1/stage": { + "d1_database_id": "00000000000000000000000000000001" + }, + "cloudflare-kv/stage": { + "api_edge_idempotency_kv_id": "00000000000000000000000000000002" + }, + "cloudflare-d1/prod": { + "d1_database_id": "00000000000000000000000000000003" + }, + "cloudflare-kv/prod": { + "api_edge_idempotency_kv_id": "00000000000000000000000000000004" + } +} diff --git a/apps/api-edge/wrangler.template.jsonc b/apps/api-edge/wrangler.template.jsonc new file mode 100644 index 0000000..5505ab2 --- /dev/null +++ b/apps/api-edge/wrangler.template.jsonc @@ -0,0 +1,183 @@ +// Rendered to wrangler.jsonc by tooling/wire/render.mjs (BF6 deploy-time wiring). +// Resource IDs are NEVER committed: @@wiring(/:)@@ tokens are +// resolved from the workspace's orun secrets at deploy time (wire-live) or from the +// committed wiring.fixture.json for offline dry-runs (wire-fixture). +{ + "name": "new-test-api-edge", + "compatibility_date": "2025-05-01", + "compatibility_flags": ["nodejs_compat"], + "main": "src/index.ts", + "minify": false, + "vars": { + "ENVIRONMENT": "local", + "CONSOLE_CUSTOM_DOMAIN": "", + // M0 / Solo profile (new-test ships single-user). Set "false" to restore the + // full multi-tenant baseline. See specs/profiles/solo-m0.md. + "SOLO_MODE": "true" + }, + "durable_objects": { + "bindings": [ + { "name": "RATE_LIMITER_DO", "class_name": "RateLimiterDO" } + ] + }, + "migrations": [ + { "tag": "v1", "new_sqlite_classes": ["RateLimiterDO"] } + ], + "env": { + "dev": { + "vars": { + "ENVIRONMENT": "dev", + "CONSOLE_CUSTOM_DOMAIN": "", + "SOLO_MODE": "true" + }, + "durable_objects": { + "bindings": [ + { "name": "RATE_LIMITER_DO", "class_name": "RateLimiterDO" } + ] + }, + "migrations": [ + { "tag": "v1", "new_sqlite_classes": ["RateLimiterDO"] } + ] + }, + "stage": { + "vars": { + "ENVIRONMENT": "stage", + "CONSOLE_CUSTOM_DOMAIN": "stage.new-test.dev", + "SOLO_MODE": "true" + }, + "d1_databases": [ + { + "binding": "PLATFORM_DB", + "database_name": "new-test-stage", + "database_id": "@@wiring(cloudflare-d1/stage:d1_database_id)@@" + } + ], + "kv_namespaces": [ + { + "binding": "IDEMPOTENCY_KV", + "id": "@@wiring(cloudflare-kv/stage:api_edge_idempotency_kv_id)@@" + } + ], + "services": [ + { + "binding": "IDENTITY_WORKER", + "service": "new-test-identity-worker-stage" + }, + { + "binding": "MEMBERSHIP_WORKER", + "service": "new-test-membership-worker-stage" + }, + { + "binding": "PROJECTS_WORKER", + "service": "new-test-projects-worker-stage" + }, + { + "binding": "EVENTS_WORKER", + "service": "new-test-events-worker-stage" + }, + { + "binding": "CONFIG_WORKER", + "service": "new-test-config-worker-stage" + }, + { + "binding": "WEBHOOKS_WORKER", + "service": "new-test-webhooks-worker-stage" + }, + { + "binding": "METERING_WORKER", + "service": "new-test-metering-worker-stage" + }, + { + "binding": "BILLING_WORKER", + "service": "new-test-billing-worker-stage" + }, + { + "binding": "NOTIFICATIONS_WORKER", + "service": "new-test-notifications-worker-stage" + }, + { + "binding": "INTEGRATIONS_WORKER", + "service": "new-test-integrations-worker-stage" + } + ], + "durable_objects": { + "bindings": [ + { "name": "RATE_LIMITER_DO", "class_name": "RateLimiterDO" } + ] + }, + "migrations": [ + { "tag": "v1", "new_sqlite_classes": ["RateLimiterDO"] } + ] + }, + "prod": { + "vars": { + "ENVIRONMENT": "prod", + "CONSOLE_CUSTOM_DOMAIN": "prod.new-test.dev", + "SOLO_MODE": "true" + }, + "d1_databases": [ + { + "binding": "PLATFORM_DB", + "database_name": "new-test-prod", + "database_id": "@@wiring(cloudflare-d1/prod:d1_database_id)@@" + } + ], + "kv_namespaces": [ + { + "binding": "IDEMPOTENCY_KV", + "id": "@@wiring(cloudflare-kv/prod:api_edge_idempotency_kv_id)@@" + } + ], + "services": [ + { + "binding": "IDENTITY_WORKER", + "service": "new-test-identity-worker-prod" + }, + { + "binding": "MEMBERSHIP_WORKER", + "service": "new-test-membership-worker-prod" + }, + { + "binding": "PROJECTS_WORKER", + "service": "new-test-projects-worker-prod" + }, + { + "binding": "EVENTS_WORKER", + "service": "new-test-events-worker-prod" + }, + { + "binding": "CONFIG_WORKER", + "service": "new-test-config-worker-prod" + }, + { + "binding": "WEBHOOKS_WORKER", + "service": "new-test-webhooks-worker-prod" + }, + { + "binding": "METERING_WORKER", + "service": "new-test-metering-worker-prod" + }, + { + "binding": "BILLING_WORKER", + "service": "new-test-billing-worker-prod" + }, + { + "binding": "NOTIFICATIONS_WORKER", + "service": "new-test-notifications-worker-prod" + }, + { + "binding": "INTEGRATIONS_WORKER", + "service": "new-test-integrations-worker-prod" + } + ], + "durable_objects": { + "bindings": [ + { "name": "RATE_LIMITER_DO", "class_name": "RateLimiterDO" } + ] + }, + "migrations": [ + { "tag": "v1", "new_sqlite_classes": ["RateLimiterDO"] } + ] + } + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5a11a3b..696b735 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -49,6 +49,31 @@ importers: specifier: ^4.14.4 version: 4.135.0(@cloudflare/workers-types@4.20260702.1) + apps/api-edge: + dependencies: + '@saas/contracts': + specifier: workspace:* + version: link:../../packages/contracts + '@saas/db': + specifier: workspace:* + version: link:../../packages/db + devDependencies: + '@cloudflare/workers-types': + specifier: ^4.20250508.0 + version: 4.20260702.1 + '@saas/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@saas/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + typescript: + specifier: ^5.8.3 + version: 5.9.3 + wrangler: + specifier: ^4.14.4 + version: 4.135.0(@cloudflare/workers-types@4.20260702.1) + apps/billing-worker: dependencies: '@polar-sh/sdk': @@ -526,6 +551,37 @@ importers: specifier: ^5.8.3 version: 5.9.3 + tests/api-edge: + dependencies: + '@saas/contracts': + specifier: workspace:* + version: link:../../packages/contracts + devDependencies: + '@cloudflare/workers-types': + specifier: ^4.20250508.0 + version: 4.20260702.1 + '@saas/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@saas/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + '@types/jest': + specifier: ^29.5.14 + version: 29.5.14 + '@types/node': + specifier: ^20.17.0 + version: 20.19.43 + jest: + specifier: ^29.7.0 + version: 29.7.0(@types/node@20.19.43) + ts-jest: + specifier: ^29.3.4 + version: 29.4.12(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@20.19.43))(typescript@5.9.3) + typescript: + specifier: ^5.8.3 + version: 5.9.3 + tests/billing-worker: dependencies: '@saas/contracts': diff --git a/tests/api-edge/component.yaml b/tests/api-edge/component.yaml new file mode 100644 index 0000000..8967756 --- /dev/null +++ b/tests/api-edge/component.yaml @@ -0,0 +1,23 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: api-edge-tests +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: starter-tests + subscribe: + environments: + - name: dev + profile: quick-check + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + preBuildCommand: pnpm exec turbo run test --filter=./ + labels: + team: platform + layer: test +# ci: trigger full-component verification (orun v2.12.0 upgrade — PR #183) diff --git a/tests/api-edge/docs/architecture.md b/tests/api-edge/docs/architecture.md new file mode 100644 index 0000000..943afaf --- /dev/null +++ b/tests/api-edge/docs/architecture.md @@ -0,0 +1,9 @@ +# api-edge-tests — architecture + +A `turbo-package` component: TypeScript built by the turbo pipeline +from `tests/api-edge`. + +## Boundaries + +A library, not a runtime: it holds no credentials, opens no connections, +and is consumed at build time by the components that depend on it. diff --git a/tests/api-edge/docs/overview.md b/tests/api-edge/docs/overview.md new file mode 100644 index 0000000..69a18b0 --- /dev/null +++ b/tests/api-edge/docs/overview.md @@ -0,0 +1,13 @@ +# api-edge-tests + + + +A workspace package built by the turbo pipeline. It deploys nothing on its own — its lane type-checks, lints, tests, and builds it for the components that depend on it. + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/tests/api-edge/docs/runbook.md b/tests/api-edge/docs/runbook.md new file mode 100644 index 0000000..c8d516b --- /dev/null +++ b/tests/api-edge/docs/runbook.md @@ -0,0 +1,26 @@ +# api-edge-tests — runbook + +## How it deploys + +Merges to `main` converge automatically: CI plans changed components +(`orun plan --changed`) and runs this component's lane via +`orun run --remote-state` with credential-free OIDC auth. The convergence +run is the deployment; the DAG orders this component after everything it +depends on. Failed lanes resume with `gh run rerun --failed`. + +## Rollback + +Revert the offending commit on `main`; the next convergence applies the +previous desired state. There is no out-of-band mutation to undo — the +repo is the source of truth. + +## Verify + +The lane itself is the gate: typecheck, lint, test, build. This package +has no deployed surface. + +## Common failures + +- **A dependent's lane fails to build after a change here**: the change + was source-compatible but not type-compatible — run + `pnpm typecheck` across the workspace before landing. diff --git a/tests/api-edge/eslint.config.js b/tests/api-edge/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/tests/api-edge/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/tests/api-edge/package.json b/tests/api-edge/package.json new file mode 100644 index 0000000..8de1c66 --- /dev/null +++ b/tests/api-edge/package.json @@ -0,0 +1,52 @@ +{ + "name": "@saas/api-edge-tests", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "build": "tsc --noEmit", + "typecheck": "tsc --noEmit", + "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js", + "lint": "eslint src" + }, + "devDependencies": { + "@cloudflare/workers-types": "^4.20250508.0", + "@saas/eslint-config": "workspace:*", + "@saas/tsconfig": "workspace:*", + "@types/jest": "^29.5.14", + "@types/node": "^20.17.0", + "jest": "^29.7.0", + "ts-jest": "^29.3.4", + "typescript": "^5.8.3" + }, + "dependencies": { + "@saas/contracts": "workspace:*" + }, + "jest": { + "preset": "ts-jest/presets/default-esm", + "extensionsToTreatAsEsm": [ + ".ts" + ], + "moduleNameMapper": { + "^(\\.{1,2}/.*)\\.js$": "$1", + "^@saas/contracts$": "/../../packages/contracts/src/index.ts", + "^@saas/contracts/(.*)$": "/../../packages/contracts/src/$1.ts", + "^@api-edge/(.*)$": "/../../apps/api-edge/src/$1.ts", + "^@saas/db$": "/../../packages/db/src/index.ts", + "^@saas/db/manifest$": "/../../packages/db/src/manifest.ts", + "^@saas/db/types$": "/../../packages/db/src/types.ts", + "^@saas/db/(.*)$": "/../../packages/db/src/$1/index.ts" + }, + "transform": { + "^.+\\.ts$": [ + "ts-jest", + { + "useESM": true + } + ] + }, + "testMatch": [ + "/src/**/*.test.ts" + ] + } +} diff --git a/tests/api-edge/src/api-key-routes.test.ts b/tests/api-edge/src/api-key-routes.test.ts new file mode 100644 index 0000000..7961d6b --- /dev/null +++ b/tests/api-edge/src/api-key-routes.test.ts @@ -0,0 +1,176 @@ +import { isOrgRoute, handleOrgRoute } from "@api-edge/org-facade"; + +interface FetchCall { + url: string; + init: RequestInit; +} + +function createFakeFetcher( + response: Response = Response.json({ data: {}, meta: { requestId: "req_test", cursor: null } }), +): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init: init ?? {} }); + return Promise.resolve(response.clone()); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +function createSessionFetcher(userId: string): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init: init ?? {} }); + if (url.includes("/v1/auth/resolve")) { + return Promise.resolve( + Response.json({ + data: { + actor: { actorType: "user", actorId: userId, email: "user@test.com" }, + session: { id: "ses_abc", expiresAt: "2026-12-01T00:00:00Z", createdAt: "2026-01-01T00:00:00Z" }, + user: { id: userId, email: "user@test.com", displayName: "Test" }, + }, + meta: { requestId: "req_inner", cursor: null }, + }), + ); + } + return Promise.resolve(Response.json({ data: {}, meta: { requestId: "req_test", cursor: null } })); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +describe("api-edge api-key routes", () => { + describe("isOrgRoute", () => { + it("matches /v1/organizations/{id}/api-keys", () => { + expect(isOrgRoute("/v1/organizations/org_abc123/api-keys")).toBe(true); + }); + + it("matches /v1/organizations/{id}/api-keys/{keyId}", () => { + expect(isOrgRoute("/v1/organizations/org_abc123/api-keys/key_xyz")).toBe(true); + }); + }); + + describe("routing api-key requests to IDENTITY_WORKER", () => { + it("forwards POST /v1/organizations/{id}/api-keys to IDENTITY_WORKER", async () => { + const { fetcher: identityFetcher, calls: identityCalls } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/api-keys", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ label: "test", role: "admin" }), + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/api-keys", + ); + + // Session resolve + forwarded request = 2 calls to IDENTITY_WORKER + expect(identityCalls).toHaveLength(2); + expect(identityCalls[0]!.url).toContain("/v1/auth/resolve"); + expect(identityCalls[1]!.url).toContain("/v1/organizations/org_abc/api-keys"); + + // MEMBERSHIP_WORKER should NOT be called + expect(membershipCalls).toHaveLength(0); + }); + + it("forwards GET /v1/organizations/{id}/api-keys to IDENTITY_WORKER", async () => { + const { fetcher: identityFetcher, calls: identityCalls } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/api-keys", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/api-keys", + ); + + expect(identityCalls).toHaveLength(2); + expect(identityCalls[1]!.url).toContain("/v1/organizations/org_abc/api-keys"); + expect(membershipCalls).toHaveLength(0); + }); + + it("forwards DELETE /v1/organizations/{id}/api-keys/{keyId} to IDENTITY_WORKER", async () => { + const { fetcher: identityFetcher, calls: identityCalls } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/api-keys/key_xyz", { + method: "DELETE", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/api-keys/key_xyz", + ); + + expect(identityCalls).toHaveLength(2); + expect(identityCalls[1]!.url).toContain("/v1/organizations/org_abc/api-keys/key_xyz"); + expect(membershipCalls).toHaveLength(0); + }); + }); + + describe("method validation", () => { + it("returns 405 for PUT on /v1/organizations/{id}/api-keys", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/api-keys", { + method: "PUT", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/api-keys", + ); + + expect(response.status).toBe(405); + const json = await response.json() as any; + expect(json.error.code).toBe("unsupported"); + }); + + it("returns 405 for PATCH on /v1/organizations/{id}/api-keys/{keyId}", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/api-keys/key_xyz", { + method: "PATCH", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/api-keys/key_xyz", + ); + + expect(response.status).toBe(405); + const json = await response.json() as any; + expect(json.error.code).toBe("unsupported"); + }); + }); +}); diff --git a/tests/api-edge/src/audit-facade.test.ts b/tests/api-edge/src/audit-facade.test.ts new file mode 100644 index 0000000..fe1d82d --- /dev/null +++ b/tests/api-edge/src/audit-facade.test.ts @@ -0,0 +1,220 @@ +import { isAuditRoute, handleAuditRoute } from "@api-edge/audit-facade"; + +interface FetchCall { + url: string; + init: RequestInit; +} + +function createFakeFetcher( + response: Response = Response.json({ data: { auditEntries: [] }, meta: { requestId: "req_test", cursor: null } }), +): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init: init ?? {} }); + return Promise.resolve(response.clone()); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +function createThrowingFetcher(): Fetcher { + return { + fetch(): Promise { + return Promise.reject(new Error("connection refused")); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; +} + +function createSessionFetcher(userId: string): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init: init ?? {} }); + if (url.includes("/v1/auth/resolve")) { + return Promise.resolve( + Response.json({ + data: { actor: { actorType: "user", actorId: userId, email: "user@test.com" }, session: { id: "ses_abc" }, user: { id: userId, email: "user@test.com", displayName: "Test" } }, + meta: { requestId: "req_inner", cursor: null }, + }), + ); + } + return Promise.resolve(Response.json({ data: { auditEntries: [] }, meta: { requestId: "req_test", cursor: null } })); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +function createEnv(overrides?: Record) { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: eventsFetcher } = createFakeFetcher(); + return { + IDENTITY_WORKER: identityFetcher, + EVENTS_WORKER: eventsFetcher, + MEMBERSHIP_WORKER: createFakeFetcher().fetcher, + PROJECTS_WORKER: createFakeFetcher().fetcher, + ENVIRONMENT: "test", + ...overrides, + }; +} + +describe("api-edge audit facade", () => { + describe("isAuditRoute", () => { + it("matches /v1/organizations/{orgId}/audit", () => { + expect(isAuditRoute("/v1/organizations/org_abc123def456/audit")).toBe(true); + }); + + it("does not match /v1/organizations/{orgId}/audit/extra", () => { + expect(isAuditRoute("/v1/organizations/org_abc/audit/extra")).toBe(false); + }); + + it("does not match /v1/organizations/{orgId}/members", () => { + expect(isAuditRoute("/v1/organizations/org_abc/members")).toBe(false); + }); + + it("does not match /v1/organizations/{orgId}/projects", () => { + expect(isAuditRoute("/v1/organizations/org_abc/projects")).toBe(false); + }); + }); + + describe("handleAuditRoute", () => { + it("returns 405 for non-GET methods", async () => { + const env = createEnv(); + const req = new Request("https://api.test/v1/organizations/org_abc/audit", { + method: "POST", + headers: { authorization: "Bearer token123" }, + }); + const res = await handleAuditRoute(req, env as any, "req_test", "/v1/organizations/org_abc/audit"); + expect(res.status).toBe(405); + }); + + it("returns 503 when IDENTITY_WORKER is missing", async () => { + const env = createEnv({ IDENTITY_WORKER: undefined }); + const req = new Request("https://api.test/v1/organizations/org_abc/audit", { + method: "GET", + headers: { authorization: "Bearer token123" }, + }); + const res = await handleAuditRoute(req, env as any, "req_test", "/v1/organizations/org_abc/audit"); + expect(res.status).toBe(503); + }); + + it("returns 503 when EVENTS_WORKER is missing", async () => { + const env = createEnv({ EVENTS_WORKER: undefined }); + const req = new Request("https://api.test/v1/organizations/org_abc/audit", { + method: "GET", + headers: { authorization: "Bearer token123" }, + }); + const res = await handleAuditRoute(req, env as any, "req_test", "/v1/organizations/org_abc/audit"); + expect(res.status).toBe(503); + }); + + it("returns 401 when no authorization header", async () => { + const env = createEnv(); + const req = new Request("https://api.test/v1/organizations/org_abc/audit", { + method: "GET", + }); + const res = await handleAuditRoute(req, env as any, "req_test", "/v1/organizations/org_abc/audit"); + expect(res.status).toBe(401); + }); + + it("forwards to EVENTS_WORKER with actor headers after session resolution", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: eventsFetcher, calls: eventsCalls } = createFakeFetcher(); + const env = { + IDENTITY_WORKER: identityFetcher, + EVENTS_WORKER: eventsFetcher, + ENVIRONMENT: "test", + }; + + const req = new Request("https://api.test/v1/organizations/org_abc/audit?limit=10&category=membership", { + method: "GET", + headers: { + authorization: "Bearer token123", + traceparent: "00-trace-span-01", + "idempotency-key": "idem-123", + }, + }); + + const res = await handleAuditRoute(req, env as any, "req_test", "/v1/organizations/org_abc/audit"); + expect(res.status).toBe(200); + + expect(eventsCalls).toHaveLength(1); + const call = eventsCalls[0]!; + expect(call.url).toContain("/v1/organizations/org_abc/audit?limit=10&category=membership"); + const h = call.init.headers as Headers; + expect(h.get("x-actor-subject-id")).toBe("usr_abc123"); + expect(h.get("x-actor-subject-type")).toBe("user"); + expect(h.get("x-actor-email")).toBe("user@test.com"); + expect(h.get("x-request-id")).toBe("req_test"); + expect(h.get("traceparent")).toBe("00-trace-span-01"); + expect(h.get("idempotency-key")).toBe("idem-123"); + }); + + it("does not forward bearer token to EVENTS_WORKER", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: eventsFetcher, calls: eventsCalls } = createFakeFetcher(); + const env = { + IDENTITY_WORKER: identityFetcher, + EVENTS_WORKER: eventsFetcher, + ENVIRONMENT: "test", + }; + + const req = new Request("https://api.test/v1/organizations/org_abc/audit", { + method: "GET", + headers: { authorization: "Bearer secret-token" }, + }); + + await handleAuditRoute(req, env as any, "req_test", "/v1/organizations/org_abc/audit"); + + const h = eventsCalls[0]!.init.headers as Headers; + expect(h.get("authorization")).toBeNull(); + }); + + it("does not forward body for GET", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: eventsFetcher, calls: eventsCalls } = createFakeFetcher(); + const env = { + IDENTITY_WORKER: identityFetcher, + EVENTS_WORKER: eventsFetcher, + ENVIRONMENT: "test", + }; + + const req = new Request("https://api.test/v1/organizations/org_abc/audit", { + method: "GET", + headers: { authorization: "Bearer token123" }, + }); + + await handleAuditRoute(req, env as any, "req_test", "/v1/organizations/org_abc/audit"); + + expect(eventsCalls[0]!.init.body).toBeUndefined(); + }); + + it("returns 503 when EVENTS_WORKER fetch throws", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const env = { + IDENTITY_WORKER: identityFetcher, + EVENTS_WORKER: createThrowingFetcher(), + ENVIRONMENT: "test", + }; + + const req = new Request("https://api.test/v1/organizations/org_abc/audit", { + method: "GET", + headers: { authorization: "Bearer token123" }, + }); + + const res = await handleAuditRoute(req, env as any, "req_test", "/v1/organizations/org_abc/audit"); + expect(res.status).toBe(503); + }); + }); +}); diff --git a/tests/api-edge/src/auth-facade.test.ts b/tests/api-edge/src/auth-facade.test.ts new file mode 100644 index 0000000..c7f2a21 --- /dev/null +++ b/tests/api-edge/src/auth-facade.test.ts @@ -0,0 +1,709 @@ +import { readFileSync } from "node:fs"; +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { isAuthRoute, handleAuthRoute } from "@api-edge/auth-facade"; +import { resolveRequestId, notFound } from "@api-edge/http"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +function stripJsoncComments(text: string): string { + return text.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, ""); +} + +interface FetchCall { + url: string; + init: RequestInit; +} + +function createFakeFetcher( + response: Response = Response.json({ data: {}, meta: { requestId: "req_test", cursor: null } }), +): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init: init ?? {} }); + return Promise.resolve(response.clone()); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +function createThrowingFetcher(error: Error): Fetcher { + return { + fetch(): Promise { + return Promise.reject(error); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; +} + +describe("api-edge auth facade", () => { + describe("isAuthRoute", () => { + it("matches /v1/auth/login/start", () => { + expect(isAuthRoute("/v1/auth/login/start")).toBe(true); + }); + + it("matches /v1/auth/login/complete", () => { + expect(isAuthRoute("/v1/auth/login/complete")).toBe(true); + }); + + it("matches /v1/auth/session", () => { + expect(isAuthRoute("/v1/auth/session")).toBe(true); + }); + + it("matches /v1/auth/logout", () => { + expect(isAuthRoute("/v1/auth/logout")).toBe(true); + }); + + it("matches /v1/auth/security-events", () => { + expect(isAuthRoute("/v1/auth/security-events")).toBe(true); + }); + + it("matches /v1/auth/profile", () => { + expect(isAuthRoute("/v1/auth/profile")).toBe(true); + }); + + it("does not match unknown auth routes", () => { + expect(isAuthRoute("/v1/auth/unknown")).toBe(false); + }); + + it("does not match non-auth routes", () => { + expect(isAuthRoute("/v1/organizations")).toBe(false); + }); + }); + + describe("route forwarding", () => { + it("forwards POST /v1/auth/login/start to IDENTITY_WORKER", async () => { + const { fetcher, calls } = createFakeFetcher(); + const body = JSON.stringify({ email: "test@example.com" }); + const request = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { + "content-type": "application/json", + "x-request-id": "req_test123", + }, + body, + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_test123", + "/v1/auth/login/start", + ); + + expect(response.status).toBe(200); + expect(calls).toHaveLength(1); + expect(calls[0]!.url).toContain("/v1/auth/login/start"); + expect(calls[0]!.init.method).toBe("POST"); + }); + + it("forwards POST /v1/auth/login/complete to IDENTITY_WORKER", async () => { + const { fetcher, calls } = createFakeFetcher(); + const body = JSON.stringify({ challengeId: "chl_abc", code: "123456" }); + const request = new Request("https://api.example.com/v1/auth/login/complete", { + method: "POST", + headers: { "content-type": "application/json" }, + body, + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_abc", + "/v1/auth/login/complete", + ); + + expect(response.status).toBe(200); + expect(calls).toHaveLength(1); + expect(calls[0]!.url).toContain("/v1/auth/login/complete"); + }); + + it("forwards GET /v1/auth/session to IDENTITY_WORKER", async () => { + const { fetcher, calls } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/session", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc123.secret" }, + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_abc", + "/v1/auth/session", + ); + + expect(response.status).toBe(200); + expect(calls).toHaveLength(1); + expect(calls[0]!.url).toContain("/v1/auth/session"); + }); + + it("forwards POST /v1/auth/logout to IDENTITY_WORKER", async () => { + const { fetcher, calls } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/logout", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc123.secret" }, + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_abc", + "/v1/auth/logout", + ); + + expect(response.status).toBe(200); + expect(calls).toHaveLength(1); + expect(calls[0]!.url).toContain("/v1/auth/logout"); + }); + + it("forwards GET /v1/auth/security-events to IDENTITY_WORKER", async () => { + const { fetcher, calls } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/security-events", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc123.secret" }, + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_sec1", + "/v1/auth/security-events", + ); + + expect(response.status).toBe(200); + expect(calls).toHaveLength(1); + expect(calls[0]!.url).toContain("/v1/auth/security-events"); + }); + + it("forwards GET /v1/auth/security-events with query string", async () => { + const { fetcher, calls } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/security-events?limit=10&cursor=abc", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc123.secret" }, + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_sec2", + "/v1/auth/security-events", + ); + + expect(response.status).toBe(200); + expect(calls).toHaveLength(1); + expect(calls[0]!.url).toContain("?limit=10&cursor=abc"); + }); + + it("returns 405 for POST /v1/auth/security-events", async () => { + const { fetcher } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/security-events", { + method: "POST", + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_sec3", + "/v1/auth/security-events", + ); + + expect(response.status).toBe(405); + const json = (await response.json()) as any; + expect(json.error.code).toBe("unsupported"); + }); + + it("forwards GET /v1/auth/profile to IDENTITY_WORKER", async () => { + const { fetcher, calls } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/profile", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc123.secret" }, + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_prof1", + "/v1/auth/profile", + ); + + expect(response.status).toBe(200); + expect(calls).toHaveLength(1); + expect(calls[0]!.url).toContain("/v1/auth/profile"); + expect(calls[0]!.init.method).toBe("GET"); + }); + + it("forwards PATCH /v1/auth/profile to IDENTITY_WORKER with body", async () => { + const { fetcher, calls } = createFakeFetcher(); + const body = JSON.stringify({ displayName: "Alice" }); + const request = new Request("https://api.example.com/v1/auth/profile", { + method: "PATCH", + headers: { + authorization: "Bearer sps_ses_abc123.secret", + "content-type": "application/json", + }, + body, + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_prof2", + "/v1/auth/profile", + ); + + expect(response.status).toBe(200); + expect(calls).toHaveLength(1); + expect(calls[0]!.url).toContain("/v1/auth/profile"); + expect(calls[0]!.init.method).toBe("PATCH"); + expect(calls[0]!.init.body).toBeDefined(); + }); + + it("returns 405 for POST /v1/auth/profile", async () => { + const { fetcher } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/profile", { + method: "POST", + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_prof3", + "/v1/auth/profile", + ); + + expect(response.status).toBe(405); + const json = (await response.json()) as any; + expect(json.error.code).toBe("unsupported"); + }); + }); + + describe("header preservation", () => { + it("preserves authorization header", async () => { + const { fetcher, calls } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/session", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc123.secret" }, + }); + + await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_abc", + "/v1/auth/session", + ); + + const forwarded = new Headers(calls[0]!.init.headers as HeadersInit); + expect(forwarded.get("authorization")).toBe("Bearer sps_ses_abc123.secret"); + }); + + it("preserves x-request-id header", async () => { + const { fetcher, calls } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/session", { + method: "GET", + headers: { "x-request-id": "req_custom123" }, + }); + + await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_custom123", + "/v1/auth/session", + ); + + const forwarded = new Headers(calls[0]!.init.headers as HeadersInit); + expect(forwarded.get("x-request-id")).toBe("req_custom123"); + }); + + it("preserves traceparent header", async () => { + const { fetcher, calls } = createFakeFetcher(); + const traceparent = "00-abcdef1234567890-1234567890abcdef-01"; + const request = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { + "content-type": "application/json", + traceparent, + }, + body: JSON.stringify({ email: "a@b.com" }), + }); + + await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_abc", + "/v1/auth/login/start", + ); + + const forwarded = new Headers(calls[0]!.init.headers as HeadersInit); + expect(forwarded.get("traceparent")).toBe(traceparent); + }); + + it("preserves idempotency-key header", async () => { + const { fetcher, calls } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { + "content-type": "application/json", + "idempotency-key": "idem_123", + }, + body: JSON.stringify({ email: "a@b.com" }), + }); + + await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_abc", + "/v1/auth/login/start", + ); + + const forwarded = new Headers(calls[0]!.init.headers as HeadersInit); + expect(forwarded.get("idempotency-key")).toBe("idem_123"); + }); + + it("preserves query string", async () => { + const { fetcher, calls } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/session?foo=bar", { + method: "GET", + }); + + await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_abc", + "/v1/auth/session", + ); + + expect(calls[0]!.url).toContain("?foo=bar"); + }); + + it("forwards request body for POST routes", async () => { + const { fetcher, calls } = createFakeFetcher(); + const body = JSON.stringify({ email: "test@example.com" }); + const request = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { "content-type": "application/json" }, + body, + }); + + await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_abc", + "/v1/auth/login/start", + ); + + expect(calls[0]!.init.body).toBeDefined(); + }); + }); + + describe("downstream response passthrough", () => { + it("passes through success envelope unchanged", async () => { + const envelope = { data: { challengeId: "chl_abc" }, meta: { requestId: "req_123", cursor: null } }; + const downstream = Response.json(envelope, { status: 200 }); + const { fetcher } = createFakeFetcher(downstream); + const request = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ email: "a@b.com" }), + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_123", + "/v1/auth/login/start", + ); + + expect(response.status).toBe(200); + const json = await response.json(); + expect(json).toEqual(envelope); + }); + + it("passes through error envelope from downstream", async () => { + const envelope = { + error: { + code: "validation_failed", + message: "Validation failed", + details: { fields: { email: ["required"] } }, + requestId: "req_456", + }, + }; + const downstream = Response.json(envelope, { status: 422 }); + const { fetcher } = createFakeFetcher(downstream); + const request = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({}), + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_456", + "/v1/auth/login/start", + ); + + expect(response.status).toBe(422); + const json = await response.json(); + expect(json).toEqual(envelope); + }); + }); + + describe("error handling", () => { + it("returns 503 with safe envelope when IDENTITY_WORKER is not configured", async () => { + const request = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ email: "a@b.com" }), + }); + + const response = await handleAuthRoute( + request, + { ENVIRONMENT: "test" }, + "req_abc123", + "/v1/auth/login/start", + ); + + expect(response.status).toBe(503); + const json = await response.json() as any; + expect(json.error.code).toBe("internal_error"); + expect(json.error.message).toBe("Authentication service unavailable"); + expect(json.error.requestId).toBe("req_abc123"); + expect(JSON.stringify(json)).not.toContain("identity-worker"); + expect(JSON.stringify(json)).not.toContain("stack"); + }); + + it("returns 503 with safe envelope when service binding throws", async () => { + const fetcher = createThrowingFetcher( + new Error("Connection refused to new-test-identity-worker-stage.internal"), + ); + const request = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ email: "a@b.com" }), + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_abc123", + "/v1/auth/login/start", + ); + + expect(response.status).toBe(503); + const json = await response.json() as any; + expect(json.error.code).toBe("internal_error"); + expect(json.error.message).toBe("Authentication service unavailable"); + expect(JSON.stringify(json)).not.toContain("Connection refused"); + expect(JSON.stringify(json)).not.toContain("new-test-identity-worker-stage"); + }); + + it("returns 405 for wrong method on auth routes", async () => { + const { fetcher } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/login/start", { + method: "GET", + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_abc", + "/v1/auth/login/start", + ); + + expect(response.status).toBe(405); + const json = await response.json() as any; + expect(json.error.code).toBe("unsupported"); + }); + + it("returns 404 for unknown auth routes", async () => { + const { fetcher } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/unknown", { + method: "POST", + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_abc", + "/v1/auth/unknown", + ); + + expect(response.status).toBe(404); + const json = await response.json() as any; + expect(json.error.code).toBe("not_found"); + }); + }); + + describe("request ID resolution", () => { + it("preserves valid incoming x-request-id", () => { + const request = new Request("https://api.example.com/v1/auth/session", { + headers: { "x-request-id": "req_custom123" }, + }); + expect(resolveRequestId(request)).toBe("req_custom123"); + }); + + it("generates a new request ID when header is missing", () => { + const request = new Request("https://api.example.com/v1/auth/session"); + const id = resolveRequestId(request); + expect(id).toMatch(/^req_[0-9a-f]{24}$/); + }); + + it("generates a new request ID when header is invalid", () => { + const request = new Request("https://api.example.com/v1/auth/session", { + headers: { "x-request-id": "invalid header with spaces!!!" }, + }); + const id = resolveRequestId(request); + expect(id).toMatch(/^req_[0-9a-f]{24}$/); + }); + }); + + describe("notFound helper", () => { + it("returns standard error envelope", async () => { + const response = notFound("req_test", "/v1/some/unknown"); + expect(response.status).toBe(404); + const json = await response.json() as any; + expect(json.error.code).toBe("not_found"); + expect(json.error.requestId).toBe("req_test"); + expect(json.error.message).toContain("/v1/some/unknown"); + }); + }); + + describe("config verification", () => { + it("wrangler.jsonc has stage service binding to new-test-identity-worker-stage", () => { + const configPath = resolve(__dirname, "../../../apps/api-edge/wrangler.jsonc"); + const raw = readFileSync(configPath, "utf-8"); + const config = JSON.parse(stripJsoncComments(raw)); + + const stageServices = config.env?.stage?.services; + expect(stageServices).toBeDefined(); + const identity = stageServices.find((s: any) => s.binding === "IDENTITY_WORKER"); + expect(identity).toBeDefined(); + expect(identity.service).toBe("new-test-identity-worker-stage"); + }); + + it("wrangler.jsonc has prod service binding to new-test-identity-worker-prod", () => { + const configPath = resolve(__dirname, "../../../apps/api-edge/wrangler.jsonc"); + const raw = readFileSync(configPath, "utf-8"); + const config = JSON.parse(stripJsoncComments(raw)); + + const prodServices = config.env?.prod?.services; + expect(prodServices).toBeDefined(); + const identity = prodServices.find((s: any) => s.binding === "IDENTITY_WORKER"); + expect(identity).toBeDefined(); + expect(identity.service).toBe("new-test-identity-worker-prod"); + }); + + it("stage does not bind to prod identity worker", () => { + const configPath = resolve(__dirname, "../../../apps/api-edge/wrangler.jsonc"); + const raw = readFileSync(configPath, "utf-8"); + const config = JSON.parse(stripJsoncComments(raw)); + + const stageServices = config.env?.stage?.services ?? []; + for (const svc of stageServices) { + expect(svc.service).not.toContain("prod"); + } + }); + + it("prod does not bind to stage identity worker", () => { + const configPath = resolve(__dirname, "../../../apps/api-edge/wrangler.jsonc"); + const raw = readFileSync(configPath, "utf-8"); + const config = JSON.parse(stripJsoncComments(raw)); + + const prodServices = config.env?.prod?.services ?? []; + for (const svc of prodServices) { + expect(svc.service).not.toContain("stage"); + } + }); + }); + + describe("oauth routes", () => { + it("recognises the oauth routes via isAuthRoute", () => { + expect(isAuthRoute("/v1/auth/oauth/providers")).toBe(true); + expect(isAuthRoute("/v1/auth/oauth/github/start")).toBe(true); + expect(isAuthRoute("/v1/auth/oauth/github/callback")).toBe(true); + expect(isAuthRoute("/v1/auth/oauth/github")).toBe(false); + }); + + it("forwards GET /v1/auth/oauth/providers to IDENTITY_WORKER", async () => { + const { fetcher, calls } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/oauth/providers", { method: "GET" }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_p", + "/v1/auth/oauth/providers", + ); + + expect(response.status).toBe(200); + expect(calls[0]!.url).toContain("/v1/auth/oauth/providers"); + expect(calls[0]!.init.method).toBe("GET"); + }); + + it("returns 405 for POST to an oauth route", async () => { + const { fetcher } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/oauth/github/start", { method: "POST" }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_p", + "/v1/auth/oauth/github/start", + ); + + expect(response.status).toBe(405); + }); + + it("forwards the cookie header and uses manual redirect on callback", async () => { + const { fetcher, calls } = createFakeFetcher(); + const request = new Request( + "https://api.example.com/v1/auth/oauth/github/callback?code=abc&state=xyz", + { method: "GET", headers: { cookie: "sp_oauth_state=nonce123" } }, + ); + + await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_cb", + "/v1/auth/oauth/github/callback", + ); + + const forwarded = new Headers(calls[0]!.init.headers as HeadersInit); + expect(forwarded.get("cookie")).toBe("sp_oauth_state=nonce123"); + expect(calls[0]!.init.redirect).toBe("manual"); + expect(calls[0]!.url).toContain("?code=abc&state=xyz"); + }); + + it("passes a 302 redirect (Location + Set-Cookie) back to the caller", async () => { + const downstream = new Response(null, { + status: 302, + headers: { + location: "https://github.com/login/oauth/authorize?x=1", + "set-cookie": "sp_oauth_state=abc; Path=/v1/auth/oauth; HttpOnly", + }, + }); + const { fetcher } = createFakeFetcher(downstream); + const request = new Request("https://api.example.com/v1/auth/oauth/github/start?return_to=x", { + method: "GET", + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_s", + "/v1/auth/oauth/github/start", + ); + + expect(response.status).toBe(302); + expect(response.headers.get("location")).toContain("github.com/login/oauth/authorize"); + expect(response.headers.get("set-cookie")).toContain("sp_oauth_state=abc"); + }); + }); +}); diff --git a/tests/api-edge/src/billing-facade.test.ts b/tests/api-edge/src/billing-facade.test.ts new file mode 100644 index 0000000..48e20b5 --- /dev/null +++ b/tests/api-edge/src/billing-facade.test.ts @@ -0,0 +1,322 @@ +import { isBillingRoute, handleBillingRoute } from "@api-edge/billing-facade"; + +interface FetchCall { + url: string; + init: RequestInit; +} + +function createFakeFetcher( + response: Response = Response.json({ + data: { plans: [] }, + meta: { requestId: "req_test", cursor: null }, + }), +): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = + typeof input === "string" + ? input + : input instanceof URL + ? input.toString() + : input.url; + calls.push({ url, init: init ?? {} }); + return Promise.resolve(response.clone()); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +function createThrowingFetcher(): Fetcher { + return { + fetch(): Promise { + return Promise.reject(new Error("connection refused")); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; +} + +function createSessionFetcher(userId: string): { fetcher: Fetcher } { + const fetcher = { + fetch(input: string | Request | URL): Promise { + const url = + typeof input === "string" + ? input + : input instanceof URL + ? input.toString() + : input.url; + if (url.includes("/v1/auth/resolve")) { + return Promise.resolve( + Response.json({ + data: { + actor: { actorType: "user", actorId: userId, email: "user@test.com" }, + session: { id: "ses_abc" }, + user: { id: userId, email: "user@test.com", displayName: "Test" }, + }, + meta: { requestId: "req_inner", cursor: null }, + }), + ); + } + return Promise.resolve( + Response.json({ + data: { plans: [] }, + meta: { requestId: "req_test", cursor: null }, + }), + ); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher }; +} + +function createEnv(overrides?: Record) { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: billingFetcher } = createFakeFetcher(); + return { + IDENTITY_WORKER: identityFetcher, + BILLING_WORKER: billingFetcher, + ENVIRONMENT: "test", + ...overrides, + }; +} + +describe("api-edge billing facade", () => { + describe("isBillingRoute", () => { + it("matches plans", () => { + expect( + isBillingRoute("/v1/organizations/org_abc123def456/billing/plans"), + ).toBe(true); + }); + it("matches customer", () => { + expect( + isBillingRoute("/v1/organizations/org_abc/billing/customer"), + ).toBe(true); + }); + it("matches summary", () => { + expect( + isBillingRoute("/v1/organizations/org_abc/billing/summary"), + ).toBe(true); + }); + it("matches invoices", () => { + expect( + isBillingRoute("/v1/organizations/org_abc/billing/invoices"), + ).toBe(true); + }); + it("matches entitlements", () => { + expect( + isBillingRoute("/v1/organizations/org_abc/billing/entitlements"), + ).toBe(true); + }); + it("does not match unknown billing subpath", () => { + expect( + isBillingRoute("/v1/organizations/org_abc/billing/unknown"), + ).toBe(false); + }); + it("does not match mutation-style routes", () => { + expect( + isBillingRoute("/v1/organizations/org_abc/billing/invoices/inv_abc"), + ).toBe(false); + }); + it("does not match metering routes", () => { + expect( + isBillingRoute("/v1/organizations/org_abc/usage"), + ).toBe(false); + }); + it("does not expose the private internal entitlement-check route", () => { + // Task 0078 introduced POST /v1/internal/billing/entitlements/check on + // billing-worker as a private service-binding route. api-edge MUST NOT + // route this — public traffic must never reach it. + expect( + isBillingRoute("/v1/internal/billing/entitlements/check"), + ).toBe(false); + expect( + isBillingRoute("/v1/organizations/org_abc/billing/entitlements/check"), + ).toBe(false); + expect( + isBillingRoute("/v1/internal/billing/entitlements"), + ).toBe(false); + }); + it("public billing facade matches the read routes plus checkout/portal (BP2)", () => { + // Documents the exact public surface — guards against accidental + // expansion of the facade. Any new public billing route should require + // a deliberate change to this list. checkout/portal are the deliberate + // BP2 additions (POST, provider hand-off). + const allowed = [ + "/v1/organizations/org_abc/billing/plans", + "/v1/organizations/org_abc/billing/customer", + "/v1/organizations/org_abc/billing/summary", + "/v1/organizations/org_abc/billing/invoices", + "/v1/organizations/org_abc/billing/entitlements", + "/v1/organizations/org_abc/billing/checkout", + "/v1/organizations/org_abc/billing/portal", + ]; + for (const p of allowed) { + expect(isBillingRoute(p)).toBe(true); + } + const denied = [ + "/v1/organizations/org_abc/billing", + "/v1/organizations/org_abc/billing/subscriptions", + "/v1/internal/billing/entitlements/check", + "/v1/internal/billing", + "/v1/billing/entitlements/check", + ]; + for (const p of denied) { + expect(isBillingRoute(p)).toBe(false); + } + }); + }); + + describe("handleBillingRoute", () => { + it("returns 405 for GET on a write route (checkout)", async () => { + const env = createEnv(); + const req = new Request( + "https://api-edge/v1/organizations/org_abc/billing/checkout", + { method: "GET", headers: { authorization: "Bearer tok_test" } }, + ); + const res = await handleBillingRoute( + req, + env as never, + "req_test", + "/v1/organizations/org_abc/billing/checkout", + ); + expect(res.status).toBe(405); + }); + + it("returns 405 for POST", async () => { + const env = createEnv(); + const req = new Request( + "https://api-edge/v1/organizations/org_abc/billing/plans", + { + method: "POST", + headers: { authorization: "Bearer tok_test" }, + }, + ); + const res = await handleBillingRoute( + req, + env as never, + "req_test", + "/v1/organizations/org_abc/billing/plans", + ); + expect(res.status).toBe(405); + }); + + it("returns 503 when IDENTITY_WORKER missing", async () => { + const env = createEnv({ IDENTITY_WORKER: undefined }); + const req = new Request( + "https://api-edge/v1/organizations/org_abc/billing/plans", + { + method: "GET", + headers: { authorization: "Bearer tok_test" }, + }, + ); + const res = await handleBillingRoute( + req, + env as never, + "req_test", + "/v1/organizations/org_abc/billing/plans", + ); + expect(res.status).toBe(503); + }); + + it("returns 503 when BILLING_WORKER missing", async () => { + const env = createEnv({ BILLING_WORKER: undefined }); + const req = new Request( + "https://api-edge/v1/organizations/org_abc/billing/plans", + { + method: "GET", + headers: { authorization: "Bearer tok_test" }, + }, + ); + const res = await handleBillingRoute( + req, + env as never, + "req_test", + "/v1/organizations/org_abc/billing/plans", + ); + expect(res.status).toBe(503); + }); + + it("returns 401 when authorization header is missing", async () => { + const env = createEnv(); + const req = new Request( + "https://api-edge/v1/organizations/org_abc/billing/plans", + { method: "GET" }, + ); + const res = await handleBillingRoute( + req, + env as never, + "req_test", + "/v1/organizations/org_abc/billing/plans", + ); + expect(res.status).toBe(401); + }); + + it("forwards GET to BILLING_WORKER with actor headers and search", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_test"); + const billingResponse = Response.json({ + data: { plans: [] }, + meta: { requestId: "req_test", cursor: null }, + }); + const { fetcher: billingFetcher, calls: billingCalls } = + createFakeFetcher(billingResponse); + const env = createEnv({ + IDENTITY_WORKER: identityFetcher, + BILLING_WORKER: billingFetcher, + }); + const req = new Request( + "https://api-edge/v1/organizations/org_abc/billing/invoices?limit=10", + { + method: "GET", + headers: { + authorization: "Bearer tok_test", + "x-request-id": "req_fwd", + }, + }, + ); + const res = await handleBillingRoute( + req, + env as never, + "req_fwd", + "/v1/organizations/org_abc/billing/invoices", + ); + expect(res.status).toBe(200); + expect(billingCalls.length).toBe(1); + expect(billingCalls[0]!.url).toContain( + "/v1/organizations/org_abc/billing/invoices?limit=10", + ); + const fwdHeaders = billingCalls[0]!.init.headers as Headers; + expect(fwdHeaders.get("x-actor-subject-id")).toBe("usr_test"); + expect(fwdHeaders.get("x-actor-subject-type")).toBe("user"); + expect(fwdHeaders.get("x-request-id")).toBe("req_fwd"); + }); + + it("returns 503 when BILLING_WORKER fetch throws", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_test"); + const env = createEnv({ + IDENTITY_WORKER: identityFetcher, + BILLING_WORKER: createThrowingFetcher(), + }); + const req = new Request( + "https://api-edge/v1/organizations/org_abc/billing/plans", + { + method: "GET", + headers: { authorization: "Bearer tok_test" }, + }, + ); + const res = await handleBillingRoute( + req, + env as never, + "req_test", + "/v1/organizations/org_abc/billing/plans", + ); + expect(res.status).toBe(503); + }); + }); +}); diff --git a/tests/api-edge/src/billing-webhooks-facade.test.ts b/tests/api-edge/src/billing-webhooks-facade.test.ts new file mode 100644 index 0000000..ffc5183 --- /dev/null +++ b/tests/api-edge/src/billing-webhooks-facade.test.ts @@ -0,0 +1,78 @@ +import { + isBillingWebhookRoute, + handleBillingWebhookRoute, +} from "@api-edge/billing-webhooks-facade"; + +interface FetchCall { + url: string; + init: RequestInit; +} + +function createFakeFetcher(): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init: init ?? {} }); + return Promise.resolve(Response.json({ data: { received: true }, meta: { requestId: "req_inner" } })); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +function webhookReq(method = "POST"): Request { + const init: RequestInit = { + method, + headers: { + "content-type": "application/json", + "webhook-id": "msg_1", + "webhook-timestamp": "1700000000", + "webhook-signature": "v1,abc", + }, + }; + if (method === "POST") init.body = '{"type":"subscription.active"}'; + return new Request("https://api.example/v1/billing/webhooks/polar", init); +} + +describe("isBillingWebhookRoute", () => { + it("matches the polar webhook path only", () => { + expect(isBillingWebhookRoute("/v1/billing/webhooks/polar")).toBe(true); + expect(isBillingWebhookRoute("/v1/billing/webhooks/stripe")).toBe(false); + expect(isBillingWebhookRoute("/v1/organizations/org_x/billing/summary")).toBe(false); + }); +}); + +describe("handleBillingWebhookRoute", () => { + it("forwards to billing-worker with the internal-caller + signature headers", async () => { + const { fetcher, calls } = createFakeFetcher(); + const env = { ENVIRONMENT: "test", BILLING_WORKER: fetcher } as unknown as Parameters< + typeof handleBillingWebhookRoute + >[1]; + const res = await handleBillingWebhookRoute(webhookReq(), env, "req_t", "/v1/billing/webhooks/polar"); + expect(res.status).toBe(200); + expect(calls).toHaveLength(1); + expect(calls[0]!.url).toContain("/v1/internal/billing/webhooks/polar"); + const headers = calls[0]!.init.headers as Headers; + expect(headers.get("x-internal-caller")).toBe("api-edge"); + expect(headers.get("webhook-signature")).toBe("v1,abc"); + expect(headers.get("webhook-id")).toBe("msg_1"); + }); + + it("rejects non-POST with 405", async () => { + const { fetcher } = createFakeFetcher(); + const env = { ENVIRONMENT: "test", BILLING_WORKER: fetcher } as unknown as Parameters< + typeof handleBillingWebhookRoute + >[1]; + const res = await handleBillingWebhookRoute(webhookReq("GET"), env, "req_t", "/v1/billing/webhooks/polar"); + expect(res.status).toBe(405); + }); + + it("returns 503 when the billing-worker binding is missing", async () => { + const env = { ENVIRONMENT: "test" } as unknown as Parameters[1]; + const res = await handleBillingWebhookRoute(webhookReq(), env, "req_t", "/v1/billing/webhooks/polar"); + expect(res.status).toBe(503); + }); +}); diff --git a/tests/api-edge/src/config-facade.test.ts b/tests/api-edge/src/config-facade.test.ts new file mode 100644 index 0000000..2da49f9 --- /dev/null +++ b/tests/api-edge/src/config-facade.test.ts @@ -0,0 +1,265 @@ +import { isConfigRoute, handleConfigRoute } from "@api-edge/config-facade"; + +interface FetchCall { + url: string; + init: RequestInit; +} + +function createFakeFetcher( + response: Response = Response.json({ data: { settings: [] }, meta: { requestId: "req_test", cursor: null } }), +): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init: init ?? {} }); + return Promise.resolve(response.clone()); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +function createThrowingFetcher(): Fetcher { + return { + fetch(): Promise { + return Promise.reject(new Error("connection refused")); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; +} + +function createSessionFetcher(userId: string): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init: init ?? {} }); + if (url.includes("/v1/auth/resolve")) { + return Promise.resolve( + Response.json({ + data: { actor: { actorType: "user", actorId: userId, email: "user@test.com" }, session: { id: "ses_abc" }, user: { id: userId, email: "user@test.com", displayName: "Test" } }, + meta: { requestId: "req_inner", cursor: null }, + }), + ); + } + return Promise.resolve(Response.json({ data: { settings: [] }, meta: { requestId: "req_test", cursor: null } })); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +function createEnv(overrides?: Record) { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: configFetcher } = createFakeFetcher(); + return { + IDENTITY_WORKER: identityFetcher, + CONFIG_WORKER: configFetcher, + MEMBERSHIP_WORKER: createFakeFetcher().fetcher, + PROJECTS_WORKER: createFakeFetcher().fetcher, + EVENTS_WORKER: createFakeFetcher().fetcher, + ENVIRONMENT: "test", + ...overrides, + }; +} + +describe("api-edge config facade", () => { + describe("isConfigRoute", () => { + // Organization scope + it("matches /v1/organizations/{orgId}/config/settings", () => { + expect(isConfigRoute("/v1/organizations/org_abc123def456/config/settings")).toBe(true); + }); + + it("matches /v1/organizations/{orgId}/config/feature-flags", () => { + expect(isConfigRoute("/v1/organizations/org_abc123def456/config/feature-flags")).toBe(true); + }); + + it("matches /v1/organizations/{orgId}/config/secrets", () => { + expect(isConfigRoute("/v1/organizations/org_abc123def456/config/secrets")).toBe(true); + }); + + // Project scope + it("matches /v1/organizations/{orgId}/projects/{prjId}/config/settings", () => { + expect(isConfigRoute("/v1/organizations/org_abc/projects/prj_def/config/settings")).toBe(true); + }); + + it("matches /v1/organizations/{orgId}/projects/{prjId}/config/feature-flags", () => { + expect(isConfigRoute("/v1/organizations/org_abc/projects/prj_def/config/feature-flags")).toBe(true); + }); + + it("matches /v1/organizations/{orgId}/projects/{prjId}/config/secrets", () => { + expect(isConfigRoute("/v1/organizations/org_abc/projects/prj_def/config/secrets")).toBe(true); + }); + + // Environment scope + it("matches environment-scoped config settings", () => { + expect(isConfigRoute("/v1/organizations/org_a/projects/prj_b/environments/env_c/config/settings")).toBe(true); + }); + + it("matches environment-scoped config feature-flags", () => { + expect(isConfigRoute("/v1/organizations/org_a/projects/prj_b/environments/env_c/config/feature-flags")).toBe(true); + }); + + it("matches environment-scoped config secrets", () => { + expect(isConfigRoute("/v1/organizations/org_a/projects/prj_b/environments/env_c/config/secrets")).toBe(true); + }); + + // Non-matches + it("does not match /v1/organizations/{orgId}/projects", () => { + expect(isConfigRoute("/v1/organizations/org_abc/projects")).toBe(false); + }); + + it("does not match /v1/organizations/{orgId}/config/unknown", () => { + expect(isConfigRoute("/v1/organizations/org_abc/config/unknown")).toBe(false); + }); + + it("matches config item routes (settings/feature-flags with ID segment)", () => { + expect(isConfigRoute("/v1/organizations/org_abc/config/settings/stg_abc")).toBe(true); + expect(isConfigRoute("/v1/organizations/org_abc/config/feature-flags/flg_abc")).toBe(true); + }); + + // Secret item routes + it("matches secret item route (org scope)", () => { + expect(isConfigRoute("/v1/organizations/org_abc/config/secrets/sec_abc")).toBe(true); + }); + + it("matches secret item route (project scope)", () => { + expect(isConfigRoute("/v1/organizations/org_abc/projects/prj_def/config/secrets/sec_abc")).toBe(true); + }); + + it("matches secret item route (environment scope)", () => { + expect(isConfigRoute("/v1/organizations/org_a/projects/prj_b/environments/env_c/config/secrets/sec_abc")).toBe(true); + }); + + it("matches secret rotate route", () => { + expect(isConfigRoute("/v1/organizations/org_abc/config/secrets/sec_abc/rotate")).toBe(true); + }); + + it("matches project-scoped secret rotate route", () => { + expect(isConfigRoute("/v1/organizations/org_abc/projects/prj_def/config/secrets/sec_abc/rotate")).toBe(true); + }); + + it("matches environment-scoped secret rotate route", () => { + expect(isConfigRoute("/v1/organizations/org_a/projects/prj_b/environments/env_c/config/secrets/sec_abc/rotate")).toBe(true); + }); + }); + + describe("handleConfigRoute", () => { + it("forwards POST to config-worker (create)", async () => { + const env = createEnv(); + const req = new Request("https://api-edge/v1/organizations/org_abc/config/settings", { + method: "POST", + headers: { "content-type": "application/json", authorization: "Bearer tok_test" }, + body: JSON.stringify({ key: "app.name", value: "test" }), + }); + const res = await handleConfigRoute(req, env as never, "req_test", "/v1/organizations/org_abc/config/settings"); + // Resolves actor then forwards; exact status depends on env stubs + expect([200, 503]).toContain(res.status); + }); + + it("forwards DELETE to config-worker for secret revoke", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_test"); + const { fetcher: configFetcher, calls: configCalls } = createFakeFetcher(); + const env = createEnv({ + IDENTITY_WORKER: identityFetcher, + CONFIG_WORKER: configFetcher, + }); + const req = new Request("https://api-edge/v1/organizations/org_abc/config/secrets/sec_abc", { + method: "DELETE", + headers: { authorization: "Bearer tok_test" }, + }); + const res = await handleConfigRoute(req, env as never, "req_test", "/v1/organizations/org_abc/config/secrets/sec_abc"); + expect(res.status).toBe(200); + expect(configCalls.length).toBe(1); + expect(configCalls[0]!.init.method).toBe("DELETE"); + }); + + it("returns 405 for PUT (unsupported method)", async () => { + const env = createEnv(); + const req = new Request("https://api-edge/v1/organizations/org_abc/config/settings", { + method: "PUT", + headers: { authorization: "Bearer tok_test" }, + }); + const res = await handleConfigRoute(req, env as never, "req_test", "/v1/organizations/org_abc/config/settings"); + expect(res.status).toBe(405); + }); + + it("returns 503 when IDENTITY_WORKER is missing", async () => { + const env = createEnv({ IDENTITY_WORKER: undefined }); + const req = new Request("https://api-edge/v1/organizations/org_abc/config/settings", { + method: "GET", + headers: { authorization: "Bearer tok_test" }, + }); + const res = await handleConfigRoute(req, env as never, "req_test", "/v1/organizations/org_abc/config/settings"); + expect(res.status).toBe(503); + }); + + it("returns 503 when CONFIG_WORKER is missing", async () => { + const env = createEnv({ CONFIG_WORKER: undefined }); + const req = new Request("https://api-edge/v1/organizations/org_abc/config/settings", { + method: "GET", + headers: { authorization: "Bearer tok_test" }, + }); + const res = await handleConfigRoute(req, env as never, "req_test", "/v1/organizations/org_abc/config/settings"); + expect(res.status).toBe(503); + }); + + it("forwards GET to CONFIG_WORKER and returns response", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_test"); + const configResponse = Response.json({ data: { settings: [{ id: "stg_abc" }] }, meta: { requestId: "req_test", cursor: null } }); + const { fetcher: configFetcher, calls: configCalls } = createFakeFetcher(configResponse); + const env = createEnv({ + IDENTITY_WORKER: identityFetcher, + CONFIG_WORKER: configFetcher, + }); + const req = new Request("https://api-edge/v1/organizations/org_abc/config/settings?limit=10", { + method: "GET", + headers: { authorization: "Bearer tok_test", "x-request-id": "req_fwd" }, + }); + const res = await handleConfigRoute(req, env as never, "req_fwd", "/v1/organizations/org_abc/config/settings"); + expect(res.status).toBe(200); + expect(configCalls.length).toBe(1); + expect(configCalls[0]!.url).toContain("/v1/organizations/org_abc/config/settings?limit=10"); + }); + + it("returns 503 when CONFIG_WORKER fetch throws", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_test"); + const env = createEnv({ + IDENTITY_WORKER: identityFetcher, + CONFIG_WORKER: createThrowingFetcher(), + }); + const req = new Request("https://api-edge/v1/organizations/org_abc/config/settings", { + method: "GET", + headers: { authorization: "Bearer tok_test" }, + }); + const res = await handleConfigRoute(req, env as never, "req_test", "/v1/organizations/org_abc/config/settings"); + expect(res.status).toBe(503); + }); + + it("injects actor headers when forwarding to config-worker", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_test"); + const { fetcher: configFetcher, calls: configCalls } = createFakeFetcher(); + const env = createEnv({ + IDENTITY_WORKER: identityFetcher, + CONFIG_WORKER: configFetcher, + }); + const req = new Request("https://api-edge/v1/organizations/org_abc/config/feature-flags", { + method: "GET", + headers: { authorization: "Bearer tok_test", "x-request-id": "req_actor" }, + }); + await handleConfigRoute(req, env as never, "req_actor", "/v1/organizations/org_abc/config/feature-flags"); + expect(configCalls.length).toBe(1); + const fwdHeaders = configCalls[0]!.init.headers as Headers; + expect(fwdHeaders.get("x-actor-subject-id")).toBe("usr_test"); + expect(fwdHeaders.get("x-actor-subject-type")).toBe("user"); + expect(fwdHeaders.get("x-request-id")).toBe("req_actor"); + }); + }); +}); diff --git a/tests/api-edge/src/cors.test.ts b/tests/api-edge/src/cors.test.ts new file mode 100644 index 0000000..e325e06 --- /dev/null +++ b/tests/api-edge/src/cors.test.ts @@ -0,0 +1,313 @@ +import { handlePreflight, applyCorsHeaders, isAllowedOrigin } from "@api-edge/cors"; +import { consoleWorkersDevOrigin } from "@api-edge/app-config"; +import type { Env } from "@api-edge/env"; + +const stageEnv: Env = { ENVIRONMENT: "stage", CONSOLE_CUSTOM_DOMAIN: "stage.new-test.dev" }; +const prodEnv: Env = { ENVIRONMENT: "prod", CONSOLE_CUSTOM_DOMAIN: "prod.new-test.dev" }; +const testEnv: Env = { ENVIRONMENT: "test" }; + +// Post Task 0083: legacy `apps/web-console` (Pages) was decommissioned. The CORS +// allowlist now permits only the custom-domain hostnames + the web-console-next +// `*.workers.dev` shadow hostnames. Origins are built from the same BF3 +// identity seam the worker uses (`app-config`), so the assertions exercise the +// allowlist *logic*, not a copy of the literals. +const STAGE_WORKER_ORIGIN = consoleWorkersDevOrigin("stage"); +const PROD_WORKER_ORIGIN = consoleWorkersDevOrigin("prod"); +const DEV_WORKER_ORIGIN = consoleWorkersDevOrigin("dev"); + +describe("api-edge cors", () => { + describe("isAllowedOrigin — stage environment", () => { + it("allows the stage custom domain origin", () => { + expect(isAllowedOrigin("https://stage.new-test.dev", stageEnv)).toBe(true); + }); + + it("allows the stage workers.dev origin", () => { + expect(isAllowedOrigin(STAGE_WORKER_ORIGIN, stageEnv)).toBe(true); + }); + + it("rejects the prod custom domain origin", () => { + expect(isAllowedOrigin("https://prod.new-test.dev", stageEnv)).toBe(false); + }); + + it("rejects the prod workers.dev origin", () => { + expect(isAllowedOrigin(PROD_WORKER_ORIGIN, stageEnv)).toBe(false); + }); + + it("rejects the legacy Pages console origins", () => { + expect(isAllowedOrigin("https://new-test-web-console.pages.dev", stageEnv)).toBe(false); + expect(isAllowedOrigin("https://new-test-web-console-stage.pages.dev", stageEnv)).toBe(false); + expect(isAllowedOrigin("https://new-test-web-console-prod.pages.dev", stageEnv)).toBe(false); + expect(isAllowedOrigin("https://abc123.new-test-web-console-stage.pages.dev", stageEnv)).toBe(false); + }); + + it("allows localhost origins", () => { + expect(isAllowedOrigin("http://localhost:5173", stageEnv)).toBe(true); + expect(isAllowedOrigin("http://localhost:3000", stageEnv)).toBe(true); + expect(isAllowedOrigin("https://localhost", stageEnv)).toBe(true); + }); + + it("allows 127.0.0.1 origins", () => { + expect(isAllowedOrigin("http://127.0.0.1:5173", stageEnv)).toBe(true); + }); + }); + + describe("isAllowedOrigin — prod environment", () => { + it("allows the prod custom domain origin", () => { + expect(isAllowedOrigin("https://prod.new-test.dev", prodEnv)).toBe(true); + }); + + it("allows the prod workers.dev origin", () => { + expect(isAllowedOrigin(PROD_WORKER_ORIGIN, prodEnv)).toBe(true); + }); + + it("rejects the stage custom domain origin", () => { + expect(isAllowedOrigin("https://stage.new-test.dev", prodEnv)).toBe(false); + }); + + it("rejects the stage workers.dev origin", () => { + expect(isAllowedOrigin(STAGE_WORKER_ORIGIN, prodEnv)).toBe(false); + }); + + it("rejects the legacy Pages console origins", () => { + expect(isAllowedOrigin("https://new-test-web-console.pages.dev", prodEnv)).toBe(false); + expect(isAllowedOrigin("https://new-test-web-console-prod.pages.dev", prodEnv)).toBe(false); + expect(isAllowedOrigin("https://feat-branch-42.new-test-web-console-stage.pages.dev", prodEnv)).toBe(false); + }); + + it("allows localhost origins", () => { + expect(isAllowedOrigin("http://localhost:5173", prodEnv)).toBe(true); + }); + + it("allows 127.0.0.1 origins", () => { + expect(isAllowedOrigin("http://127.0.0.1:5173", prodEnv)).toBe(true); + }); + }); + + describe("isAllowedOrigin — fallback (test/unknown environment)", () => { + it("rejects custom domain origins when CONSOLE_CUSTOM_DOMAIN is not set", () => { + expect(isAllowedOrigin("https://stage.new-test.dev", testEnv)).toBe(false); + expect(isAllowedOrigin("https://prod.new-test.dev", testEnv)).toBe(false); + }); + + it("allows custom domain origin when CONSOLE_CUSTOM_DOMAIN is set", () => { + const envWithDomain: Env = { ENVIRONMENT: "test", CONSOLE_CUSTOM_DOMAIN: "custom.example.com" }; + expect(isAllowedOrigin("https://custom.example.com", envWithDomain)).toBe(true); + }); + + it("allows all workers.dev origins (dev, stage, prod) in fallback env", () => { + expect(isAllowedOrigin(DEV_WORKER_ORIGIN, testEnv)).toBe(true); + expect(isAllowedOrigin(STAGE_WORKER_ORIGIN, testEnv)).toBe(true); + expect(isAllowedOrigin(PROD_WORKER_ORIGIN, testEnv)).toBe(true); + }); + + it("rejects legacy Pages console origins in fallback env", () => { + expect(isAllowedOrigin("https://new-test-web-console-stage.pages.dev", testEnv)).toBe(false); + expect(isAllowedOrigin("https://new-test-web-console-prod.pages.dev", testEnv)).toBe(false); + }); + + it("allows localhost origins", () => { + expect(isAllowedOrigin("http://localhost:5173", testEnv)).toBe(true); + }); + }); + + describe("isAllowedOrigin — common rejections", () => { + it("rejects null origin", () => { + expect(isAllowedOrigin(null, stageEnv)).toBe(false); + expect(isAllowedOrigin(null, prodEnv)).toBe(false); + }); + + it("rejects arbitrary origins", () => { + expect(isAllowedOrigin("https://evil.com", stageEnv)).toBe(false); + expect(isAllowedOrigin("https://evil.com", prodEnv)).toBe(false); + expect( + // Suffix attack: the real stage origin with `.evil.com` appended must + // stay disallowed. Derived from the seam so the attack string tracks + // the real hostname. + isAllowedOrigin(`${consoleWorkersDevOrigin("stage")}.evil.com`, stageEnv), + ).toBe(false); + }); + + it("rejects similar but not matching origins", () => { + expect(isAllowedOrigin("https://other-project.workers.dev", stageEnv)).toBe(false); + expect(isAllowedOrigin(`${STAGE_WORKER_ORIGIN}:8080`, stageEnv)).toBe(false); + }); + }); + + describe("handlePreflight", () => { + it("returns null for non-OPTIONS requests", () => { + const req = new Request("https://api.test/v1/auth/session", { method: "GET" }); + expect(handlePreflight(req, stageEnv)).toBeNull(); + }); + + it("returns 204 with CORS headers for allowed stage custom domain", () => { + const req = new Request("https://api.test/v1/auth/session", { + method: "OPTIONS", + headers: { origin: "https://stage.new-test.dev" }, + }); + const res = handlePreflight(req, stageEnv); + expect(res).not.toBeNull(); + expect(res!.status).toBe(204); + expect(res!.headers.get("access-control-allow-origin")).toBe( + "https://stage.new-test.dev", + ); + expect(res!.headers.get("access-control-allow-credentials")).toBe("true"); + }); + + it("returns 204 with CORS headers for allowed stage workers.dev origin", () => { + const req = new Request("https://api.test/v1/auth/session", { + method: "OPTIONS", + headers: { origin: STAGE_WORKER_ORIGIN }, + }); + const res = handlePreflight(req, stageEnv); + expect(res).not.toBeNull(); + expect(res!.status).toBe(204); + expect(res!.headers.get("access-control-allow-origin")).toBe(STAGE_WORKER_ORIGIN); + expect(res!.headers.get("access-control-allow-methods")).toContain("GET"); + expect(res!.headers.get("access-control-allow-methods")).toContain("POST"); + expect(res!.headers.get("access-control-allow-headers")).toContain("authorization"); + expect(res!.headers.get("access-control-allow-headers")).toContain("content-type"); + expect(res!.headers.get("access-control-allow-headers")).toContain("x-request-id"); + expect(res!.headers.get("access-control-allow-headers")).toContain("traceparent"); + expect(res!.headers.get("access-control-allow-headers")).toContain("idempotency-key"); + expect(res!.headers.get("access-control-allow-credentials")).toBe("true"); + expect(res!.headers.get("vary")).toBe("Origin"); + }); + + it("returns 204 without CORS headers when prod custom domain hits stage API", () => { + const req = new Request("https://api.test/v1/auth/session", { + method: "OPTIONS", + headers: { origin: "https://prod.new-test.dev" }, + }); + const res = handlePreflight(req, stageEnv); + expect(res).not.toBeNull(); + expect(res!.status).toBe(204); + expect(res!.headers.get("access-control-allow-origin")).toBeNull(); + }); + + it("returns 204 without CORS headers when prod workers.dev hits stage API", () => { + const req = new Request("https://api.test/v1/auth/session", { + method: "OPTIONS", + headers: { origin: PROD_WORKER_ORIGIN }, + }); + const res = handlePreflight(req, stageEnv); + expect(res).not.toBeNull(); + expect(res!.status).toBe(204); + expect(res!.headers.get("access-control-allow-origin")).toBeNull(); + }); + + it("returns 204 without CORS headers for disallowed origin", () => { + const req = new Request("https://api.test/v1/auth/session", { + method: "OPTIONS", + headers: { origin: "https://evil.com" }, + }); + const res = handlePreflight(req, stageEnv); + expect(res).not.toBeNull(); + expect(res!.status).toBe(204); + expect(res!.headers.get("access-control-allow-origin")).toBeNull(); + }); + + it("returns 204 without CORS headers when no origin", () => { + const req = new Request("https://api.test/v1/auth/session", { + method: "OPTIONS", + }); + const res = handlePreflight(req, prodEnv); + expect(res).not.toBeNull(); + expect(res!.status).toBe(204); + expect(res!.headers.get("access-control-allow-origin")).toBeNull(); + }); + }); + + describe("applyCorsHeaders", () => { + it("adds CORS headers for stage custom domain on stage env", () => { + const req = new Request("https://api.test/v1/auth/session", { + headers: { origin: "https://stage.new-test.dev" }, + }); + const original = Response.json({ data: {} }, { status: 200 }); + const res = applyCorsHeaders(original, req, stageEnv); + + expect(res.status).toBe(200); + expect(res.headers.get("access-control-allow-origin")).toBe( + "https://stage.new-test.dev", + ); + expect(res.headers.get("access-control-allow-credentials")).toBe("true"); + expect(res.headers.get("vary")).toBe("Origin"); + }); + + it("adds CORS headers for allowed stage workers.dev origin on stage env", () => { + const req = new Request("https://api.test/v1/auth/session", { + headers: { origin: STAGE_WORKER_ORIGIN }, + }); + const original = Response.json({ data: {} }, { status: 200 }); + const res = applyCorsHeaders(original, req, stageEnv); + + expect(res.status).toBe(200); + expect(res.headers.get("access-control-allow-origin")).toBe(STAGE_WORKER_ORIGIN); + expect(res.headers.get("access-control-allow-credentials")).toBe("true"); + expect(res.headers.get("vary")).toBe("Origin"); + }); + + it("does not add CORS headers for prod custom domain on stage env", () => { + const req = new Request("https://api.test/v1/auth/session", { + headers: { origin: "https://prod.new-test.dev" }, + }); + const original = Response.json({ data: {} }, { status: 200 }); + const res = applyCorsHeaders(original, req, stageEnv); + + expect(res.headers.get("access-control-allow-origin")).toBeNull(); + }); + + it("does not add CORS headers for prod workers.dev origin on stage env", () => { + const req = new Request("https://api.test/v1/auth/session", { + headers: { origin: PROD_WORKER_ORIGIN }, + }); + const original = Response.json({ data: {} }, { status: 200 }); + const res = applyCorsHeaders(original, req, stageEnv); + + expect(res.headers.get("access-control-allow-origin")).toBeNull(); + }); + + it("does not add CORS headers for stage custom domain on prod env", () => { + const req = new Request("https://api.test/v1/auth/session", { + headers: { origin: "https://stage.new-test.dev" }, + }); + const original = Response.json({ data: {} }, { status: 200 }); + const res = applyCorsHeaders(original, req, prodEnv); + + expect(res.headers.get("access-control-allow-origin")).toBeNull(); + }); + + it("does not add CORS headers for stage workers.dev origin on prod env", () => { + const req = new Request("https://api.test/v1/auth/session", { + headers: { origin: STAGE_WORKER_ORIGIN }, + }); + const original = Response.json({ data: {} }, { status: 200 }); + const res = applyCorsHeaders(original, req, prodEnv); + + expect(res.headers.get("access-control-allow-origin")).toBeNull(); + }); + + it("does not add CORS headers for disallowed origin", () => { + const req = new Request("https://api.test/v1/auth/session", { + headers: { origin: "https://evil.com" }, + }); + const original = Response.json({ data: {} }, { status: 200 }); + const res = applyCorsHeaders(original, req, stageEnv); + + expect(res.headers.get("access-control-allow-origin")).toBeNull(); + }); + + it("preserves original response status and body", async () => { + const req = new Request("https://api.test/v1/auth/session", { + headers: { origin: "http://localhost:5173" }, + }); + const body = { error: { code: "unauthenticated", message: "No token" } }; + const original = Response.json(body, { status: 401 }); + const res = applyCorsHeaders(original, req, stageEnv); + + expect(res.status).toBe(401); + const json = await res.json(); + expect(json).toEqual(body); + expect(res.headers.get("access-control-allow-origin")).toBe("http://localhost:5173"); + }); + }); +}); diff --git a/tests/api-edge/src/edge-timing.test.ts b/tests/api-edge/src/edge-timing.test.ts new file mode 100644 index 0000000..51e21ab --- /dev/null +++ b/tests/api-edge/src/edge-timing.test.ts @@ -0,0 +1,94 @@ +// PERF6 — edge gate Server-Timing instrumentation. +// +// Asserts that `replayOrExecute` (the rate-limit + idempotency gate that runs +// BEFORE the facade's own timings) now contributes `edge_ratelimit` and, for an +// idempotent unsafe request, `edge_idem` phases to the response `Server-Timing` +// header — without clobbering phases the downstream worker already emitted. + +import { replayOrExecute } from "@api-edge/idempotency"; +import { __resetRateLimitMemoryForTest } from "@api-edge/rate-limit"; +import { parseServerTimingDuration } from "@saas/contracts/timing"; +import type { Env } from "@api-edge/env"; + +function createFakeKv(): { binding: KVNamespace; store: Map } { + const store = new Map(); + const binding = { + get: (k: string) => Promise.resolve(store.get(k) ?? null), + put: (k: string, v: string) => { + store.set(k, v); + return Promise.resolve(); + }, + delete: (k: string) => { + store.delete(k); + return Promise.resolve(); + }, + } as unknown as KVNamespace; + return { binding, store }; +} + +const VALID_KEY = "550e8400-e29b-41d4-a716-446655440000"; + +describe("PERF6 edge gate Server-Timing", () => { + beforeEach(() => __resetRateLimitMemoryForTest()); + + it("a safe GET carries edge_ratelimit and preserves the downstream phases", async () => { + const env = { ENVIRONMENT: "test" } as Env; // no KV/DO → in-isolate read limiter + const downstream = () => + Promise.resolve( + new Response("{}", { + status: 200, + headers: { "content-type": "application/json", "Server-Timing": "db;dur=5" }, + }), + ); + const req = new Request("https://api.example.com/v1/organizations/org_t/projects", { + method: "GET", + }); + + const res = await replayOrExecute(req, "req_get", env, "project", downstream); + const st = res.headers.get("Server-Timing"); + expect(st).not.toBeNull(); + // downstream phase preserved (appended, not clobbered)... + expect(parseServerTimingDuration(st, "db")).toBe(5); + // ...and the gate phase is now present. + expect(parseServerTimingDuration(st, "edge_ratelimit")).not.toBeNull(); + // reads do no idempotency lookup. + expect(parseServerTimingDuration(st, "edge_idem")).toBeNull(); + }); + + it("an idempotent unsafe POST carries both edge_ratelimit and edge_idem", async () => { + const kv = createFakeKv(); + const env = { IDEMPOTENCY_KV: kv.binding, ENVIRONMENT: "test" } as Env; + const downstream = () => Promise.resolve(Response.json({ ok: true })); + const req = new Request("https://api.example.com/v1/organizations/org_t/projects", { + method: "POST", + headers: { "content-type": "application/json", "idempotency-key": VALID_KEY }, + body: "{}", + }); + + const res = await replayOrExecute(req, "req_post", env, "project", downstream); + const st = res.headers.get("Server-Timing"); + expect(parseServerTimingDuration(st, "edge_ratelimit")).not.toBeNull(); + expect(parseServerTimingDuration(st, "edge_idem")).not.toBeNull(); + }); + + it("a rate-limit denial (429) still reports edge_ratelimit", async () => { + const kv = createFakeKv(); + const env = { IDEMPOTENCY_KV: kv.binding, ENVIRONMENT: "test" } as Env; + const downstream = () => Promise.resolve(Response.json({ ok: true })); + const mkReq = () => + new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { "content-type": "application/json", "CF-Connecting-IP": "9.9.9.9" }, + body: "{}", + }); + + // Drain the auth identity bucket (tight: 10/min) to force a 429. + let denied: Response | null = null; + for (let i = 0; i < 20 && !denied; i++) { + const r = await replayOrExecute(mkReq(), `req_${i}`, env, "auth", downstream); + if (r.status === 429) denied = r; + } + expect(denied).not.toBeNull(); + expect(parseServerTimingDuration(denied!.headers.get("Server-Timing"), "edge_ratelimit")).not.toBeNull(); + }); +}); diff --git a/tests/api-edge/src/idempotency-cache.test.ts b/tests/api-edge/src/idempotency-cache.test.ts new file mode 100644 index 0000000..b3bd633 --- /dev/null +++ b/tests/api-edge/src/idempotency-cache.test.ts @@ -0,0 +1,113 @@ +// Idempotency replay L1 (colo-local Cache API in front of the KV store). +// +// Asserts the tiered design: KV stays the global source of truth, while a +// same-colo replay is served from the Cache API without a KV `get`; and when +// there is no L1 (cross-colo / eviction), the lookup falls back to KV so +// idempotency correctness is preserved. + +import { replayOrExecute } from "@api-edge/idempotency"; +import { __resetRateLimitMemoryForTest } from "@api-edge/rate-limit"; +import type { Env } from "@api-edge/env"; + +function makeFakeCaches() { + const store = new Map(); + const def = { + async match(key: string): Promise { + const r = store.get(key); + return r ? r.clone() : undefined; + }, + async put(key: string, res: Response): Promise { + store.set(key, res.clone()); + }, + }; + return { caches: { default: def }, store }; +} + +// Counts only idempotency (`idem:`-prefixed) KV ops, so the rate limiter's own +// KV fallback (same binding, `rl:` prefix) does not pollute the assertions. +function countingKv() { + const store = new Map(); + const counts = { idemGet: 0, idemPut: 0 }; + const binding = { + get: (k: string) => { + if (k.startsWith("idem:")) counts.idemGet++; + return Promise.resolve(store.get(k) ?? null); + }, + put: (k: string, v: string) => { + if (k.startsWith("idem:")) counts.idemPut++; + store.set(k, v); + return Promise.resolve(); + }, + } as unknown as KVNamespace; + return { binding, store, counts }; +} + +const KEY = "550e8400-e29b-41d4-a716-446655440000"; +function postReq(): Request { + return new Request("https://api.example.com/v1/organizations/org_idem/projects", { + method: "POST", + headers: { "content-type": "application/json", "idempotency-key": KEY }, + body: "{}", + }); +} + +describe("idempotency Cache API L1 (tiered in front of KV)", () => { + let originalCaches: unknown; + beforeEach(() => { + __resetRateLimitMemoryForTest(); + originalCaches = (globalThis as unknown as { caches?: unknown }).caches; + }); + afterEach(() => { + (globalThis as unknown as { caches?: unknown }).caches = originalCaches; + }); + + it("serves a same-colo replay from L1 without a KV get, and survives KV loss", async () => { + const { caches } = makeFakeCaches(); + (globalThis as unknown as { caches: unknown }).caches = caches; + const kv = countingKv(); + const env = { IDEMPOTENCY_KV: kv.binding, ENVIRONMENT: "test" } as Env; + + let downstreamCalls = 0; + const downstream = () => { + downstreamCalls++; + return Promise.resolve(Response.json({ n: downstreamCalls }, { status: 201 })); + }; + + // 1st request: miss L1 + KV → execute downstream → store to KV + L1. + const r1 = await replayOrExecute(postReq(), "r1", env, "project", downstream); + expect(r1.status).toBe(201); + expect(downstreamCalls).toBe(1); + expect(kv.counts.idemPut).toBe(1); + const idemGetsAfter1 = kv.counts.idemGet; + + // 2nd request (same key): L1 hit → replay, no downstream, no extra KV get. + const r2 = await replayOrExecute(postReq(), "r2", env, "project", downstream); + expect(downstreamCalls).toBe(1); + expect(r2.headers.get("x-saas-replay-source")).toBe("edge-idempotency"); + expect(kv.counts.idemGet).toBe(idemGetsAfter1); // KV not touched on the L1 hit + + // 3rd: wipe KV but keep L1 → still replays (proves L1 served it). + kv.store.clear(); + const r3 = await replayOrExecute(postReq(), "r3", env, "project", downstream); + expect(downstreamCalls).toBe(1); + expect(r3.headers.get("x-saas-replay-source")).toBe("edge-idempotency"); + }); + + it("falls back to KV (global) when there is no L1 — cross-colo correctness", async () => { + (globalThis as unknown as { caches?: unknown }).caches = undefined; // no Cache API + const kv = countingKv(); + const env = { IDEMPOTENCY_KV: kv.binding, ENVIRONMENT: "test" } as Env; + + let calls = 0; + const downstream = () => { + calls++; + return Promise.resolve(Response.json({ n: calls }, { status: 201 })); + }; + + await replayOrExecute(postReq(), "r1", env, "project", downstream); + const r2 = await replayOrExecute(postReq(), "r2", env, "project", downstream); + expect(calls).toBe(1); // replayed from KV even with no L1 layer + expect(r2.headers.get("x-saas-replay-source")).toBe("edge-idempotency"); + expect(kv.counts.idemPut).toBe(1); + }); +}); diff --git a/tests/api-edge/src/idempotency-edge.test.ts b/tests/api-edge/src/idempotency-edge.test.ts new file mode 100644 index 0000000..2ec0a02 --- /dev/null +++ b/tests/api-edge/src/idempotency-edge.test.ts @@ -0,0 +1,346 @@ +// Edge-side idempotency-key validation tests (Task 0094). +// +// Asserts the validation gate added in `apps/api-edge/src/idempotency.ts`: +// - valid `Idempotency-Key` on POST → forwarded downstream (2xx flow) +// - missing `Idempotency-Key` on POST → forwarded (header is optional) +// - malformed `Idempotency-Key` on POST → 400 `validation_failed` at the edge, +// downstream worker NEVER called +// - safe GET with malformed header → not rejected for the malformed reason +// (the edge has no idempotency semantics on reads) +// +// Two facades are covered to satisfy the Task 0094 acceptance criterion: +// - auth-facade.handleAuthRoute (POST /v1/auth/login/start, GET /v1/auth/session) +// - org-facade.handleOrgRoute (POST /v1/organizations) + +import { handleAuthRoute } from "@api-edge/auth-facade"; +import { handleOrgRoute } from "@api-edge/org-facade"; + +interface FetchCall { + url: string; + init: RequestInit; +} + +function createFakeFetcher( + response: Response = Response.json({ + data: {}, + meta: { requestId: "req_test", cursor: null }, + }), +): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = + typeof input === "string" + ? input + : input instanceof URL + ? input.toString() + : input.url; + calls.push({ url, init: init ?? {} }); + return Promise.resolve(response.clone()); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +function createSessionFetcher(userId: string): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = + typeof input === "string" + ? input + : input instanceof URL + ? input.toString() + : input.url; + calls.push({ url, init: init ?? {} }); + if (url.includes("/v1/auth/resolve")) { + return Promise.resolve( + Response.json({ + data: { + actor: { actorType: "user", actorId: userId, email: "user@test.com" }, + session: { + id: "ses_abc", + expiresAt: "2026-12-01T00:00:00Z", + createdAt: "2026-01-01T00:00:00Z", + }, + user: { id: userId, email: "user@test.com", displayName: "Test" }, + }, + meta: { requestId: "req_inner", cursor: null }, + }), + ); + } + return Promise.resolve( + Response.json({ data: {}, meta: { requestId: "req_test", cursor: null } }), + ); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +const VALID_KEY = "550e8400-e29b-41d4-a716-446655440000"; +const MALFORMED_KEY_TOO_LONG = "a".repeat(256); +// Note: the `illegal_characters` reason is exercised by the contract-level unit test +// (`tests/contracts/src/idempotency.test.ts`). At the edge layer we can't construct a +// Request with a literal CR/LF in a header — the Web Headers constructor rejects it +// before it reaches our validator — so edge coverage here uses `too_long` and `empty`, +// which both round-trip cleanly through Request and Headers. + +describe("api-edge idempotency-key validation gate", () => { + describe("auth-facade (POST /v1/auth/login/start)", () => { + it("forwards request when Idempotency-Key is valid", async () => { + const { fetcher, calls } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { + "content-type": "application/json", + "idempotency-key": VALID_KEY, + }, + body: JSON.stringify({ email: "user@test.com" }), + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/auth/login/start", + ); + + expect(response.status).toBe(200); + expect(calls).toHaveLength(1); + const forwarded = new Headers(calls[0]!.init.headers as HeadersInit); + expect(forwarded.get("idempotency-key")).toBe(VALID_KEY); + }); + + it("forwards request when Idempotency-Key is absent (header is optional)", async () => { + const { fetcher, calls } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ email: "user@test.com" }), + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/auth/login/start", + ); + + expect(response.status).toBe(200); + expect(calls).toHaveLength(1); + }); + + it("rejects with 400 validation_failed when Idempotency-Key is too long", async () => { + const { fetcher, calls } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { + "content-type": "application/json", + "idempotency-key": MALFORMED_KEY_TOO_LONG, + }, + body: JSON.stringify({ email: "user@test.com" }), + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/auth/login/start", + ); + + expect(response.status).toBe(400); + const body = (await response.json()) as { + error: { code: string; message: string; details?: { reason?: string; header?: string } }; + }; + expect(body.error.code).toBe("validation_failed"); + expect(body.error.message).toContain("Idempotency-Key"); + expect(body.error.details?.header).toBe("Idempotency-Key"); + expect(body.error.details?.reason).toBe("too_long"); + // critically, downstream worker MUST NOT be invoked + expect(calls).toHaveLength(0); + }); + + it("rejects with 400 when Idempotency-Key is empty/whitespace", async () => { + const { fetcher, calls } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { + "content-type": "application/json", + "idempotency-key": " ", + }, + body: JSON.stringify({ email: "user@test.com" }), + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/auth/login/start", + ); + + expect(response.status).toBe(400); + const body = (await response.json()) as { + error: { code: string; details?: { reason?: string } }; + }; + expect(body.error.code).toBe("validation_failed"); + expect(body.error.details?.reason).toBe("empty"); + expect(calls).toHaveLength(0); + }); + + it("does NOT reject GET requests for a malformed Idempotency-Key (reads have no idempotency semantics)", async () => { + const { fetcher, calls } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/auth/session", { + method: "GET", + headers: { + authorization: "Bearer sps_ses_abc.secret", + "idempotency-key": MALFORMED_KEY_TOO_LONG, + }, + }); + + const response = await handleAuthRoute( + request, + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/auth/session", + ); + + // Forwarded — not rejected at the edge for the idempotency reason. + expect(response.status).toBe(200); + expect(calls).toHaveLength(1); + }); + }); + + describe("org-facade (POST /v1/organizations)", () => { + it("forwards request when Idempotency-Key is valid", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations", { + method: "POST", + headers: { + authorization: "Bearer sps_ses_abc.secret", + "content-type": "application/json", + "idempotency-key": VALID_KEY, + }, + body: JSON.stringify({ name: "Acme" }), + }); + + const response = await handleOrgRoute( + request, + { + IDENTITY_WORKER: identityFetcher, + MEMBERSHIP_WORKER: membershipFetcher, + ENVIRONMENT: "test", + }, + "req_test", + "/v1/organizations", + ); + + expect(response.status).toBe(200); + expect(membershipCalls).toHaveLength(1); + const forwarded = new Headers(membershipCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("idempotency-key")).toBe(VALID_KEY); + }); + + it("forwards request when Idempotency-Key is absent", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations", { + method: "POST", + headers: { + authorization: "Bearer sps_ses_abc.secret", + "content-type": "application/json", + }, + body: JSON.stringify({ name: "Acme" }), + }); + + const response = await handleOrgRoute( + request, + { + IDENTITY_WORKER: identityFetcher, + MEMBERSHIP_WORKER: membershipFetcher, + ENVIRONMENT: "test", + }, + "req_test", + "/v1/organizations", + ); + + expect(response.status).toBe(200); + expect(membershipCalls).toHaveLength(1); + }); + + it("rejects with 400 validation_failed when Idempotency-Key is malformed (too long)", async () => { + const { fetcher: identityFetcher, calls: identityCalls } = createSessionFetcher( + "usr_abc123", + ); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations", { + method: "POST", + headers: { + authorization: "Bearer sps_ses_abc.secret", + "content-type": "application/json", + "idempotency-key": MALFORMED_KEY_TOO_LONG, + }, + body: JSON.stringify({ name: "Acme" }), + }); + + const response = await handleOrgRoute( + request, + { + IDENTITY_WORKER: identityFetcher, + MEMBERSHIP_WORKER: membershipFetcher, + ENVIRONMENT: "test", + }, + "req_test", + "/v1/organizations", + ); + + expect(response.status).toBe(400); + const body = (await response.json()) as { + error: { code: string; details?: { reason?: string; header?: string } }; + }; + expect(body.error.code).toBe("validation_failed"); + expect(body.error.details?.header).toBe("Idempotency-Key"); + expect(body.error.details?.reason).toBe("too_long"); + // gate must run BEFORE both identity-resolve and the downstream membership fetch + expect(identityCalls).toHaveLength(0); + expect(membershipCalls).toHaveLength(0); + }); + + it("does NOT reject GET /v1/organizations with malformed Idempotency-Key", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations", { + method: "GET", + headers: { + authorization: "Bearer sps_ses_abc.secret", + "idempotency-key": MALFORMED_KEY_TOO_LONG, + }, + }); + + const response = await handleOrgRoute( + request, + { + IDENTITY_WORKER: identityFetcher, + MEMBERSHIP_WORKER: membershipFetcher, + ENVIRONMENT: "test", + }, + "req_test", + "/v1/organizations", + ); + + // GET passes through to membership worker; never 400 for the idempotency reason. + expect(response.status).toBe(200); + expect(membershipCalls).toHaveLength(1); + }); + }); +}); diff --git a/tests/api-edge/src/idempotency-replay.test.ts b/tests/api-edge/src/idempotency-replay.test.ts new file mode 100644 index 0000000..fae773c --- /dev/null +++ b/tests/api-edge/src/idempotency-replay.test.ts @@ -0,0 +1,368 @@ +// Edge-side idempotency replay store tests (Task 0095). +// +// Asserts the durable KV-backed replay behaviour added in +// `apps/api-edge/src/idempotency.ts::replayOrExecute`: +// - cache miss on POST → downstream invoked, response cached +// - cache hit on POST → downstream NOT invoked, cached envelope replayed +// - GET request → never cached, never validated, always passthrough +// - absent Idempotency-Key on POST → not cached (header is optional) +// - missing IDEMPOTENCY_KV binding → degrades open (downstream only) +// - non-text response body → base64-encoded round trip +// - replay marks response with x-saas-replay-source header +// - 5xx responses are NOT cached (transient errors) +// - TTL of 86400 seconds (24h) is set on KV.put +// +// Tests drive the full facade pipeline (handleAuthRoute) so the integration +// is verified end-to-end, not just the helper in isolation. + +import { handleAuthRoute } from "@api-edge/auth-facade"; +import { replayOrExecute } from "@api-edge/idempotency"; + +interface KvPutCall { + key: string; + value: string; + options: { expirationTtl?: number } | undefined; +} + +interface FakeKv { + binding: KVNamespace; + store: Map; + putCalls: KvPutCall[]; + getCalls: string[]; +} + +function createFakeKv(seed: Record = {}): FakeKv { + const store = new Map(Object.entries(seed)); + const putCalls: KvPutCall[] = []; + const getCalls: string[] = []; + const binding = { + get(key: string, _type?: string): Promise { + getCalls.push(key); + return Promise.resolve(store.get(key) ?? null); + }, + put(key: string, value: string, options?: { expirationTtl?: number }): Promise { + putCalls.push({ key, value, options }); + store.set(key, value); + return Promise.resolve(); + }, + delete(key: string): Promise { + store.delete(key); + return Promise.resolve(); + }, + list(): Promise<{ keys: { name: string }[]; list_complete: true; cacheStatus: null }> { + return Promise.resolve({ + keys: Array.from(store.keys()).map((name) => ({ name })), + list_complete: true, + cacheStatus: null, + }); + }, + } as unknown as KVNamespace; + return { binding, store, putCalls, getCalls }; +} + +interface FetchCall { + url: string; + init: RequestInit; +} + +function createFakeFetcher( + responseFactory: () => Response = () => + Response.json({ + data: { ok: true }, + meta: { requestId: "req_inner", cursor: null }, + }), +): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = + typeof input === "string" + ? input + : input instanceof URL + ? input.toString() + : input.url; + calls.push({ url, init: init ?? {} }); + return Promise.resolve(responseFactory()); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +const VALID_KEY_A = "550e8400-e29b-41d4-a716-446655440000"; +const VALID_KEY_B = "11111111-2222-3333-4444-555555555555"; + +function makePost(key?: string, body: string = '{"email":"u@test.com"}'): Request { + const headers: Record = { "content-type": "application/json" }; + if (key) headers["idempotency-key"] = key; + return new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers, + body, + }); +} + +describe("api-edge idempotency replay store (Task 0095)", () => { + describe("integration via handleAuthRoute", () => { + it("cache miss → downstream called, response stored with TTL=86400", async () => { + const kv = createFakeKv(); + const { fetcher, calls } = createFakeFetcher(); + + const response = await handleAuthRoute( + makePost(VALID_KEY_A), + { IDENTITY_WORKER: fetcher, IDEMPOTENCY_KV: kv.binding, ENVIRONMENT: "test" }, + "req_test", + "/v1/auth/login/start", + ); + + expect(response.status).toBe(200); + expect(calls).toHaveLength(1); + const idemPuts = kv.putCalls.filter(c => c.key.startsWith("idem:")); + expect(idemPuts).toHaveLength(1); + expect(idemPuts[0]!.options?.expirationTtl).toBe(86400); + expect([...kv.store.keys()].filter(k => k.startsWith("idem:")).length).toBe(1); + }); + + it("cache hit → downstream NOT called, replayed envelope returned with x-saas-replay-source", async () => { + const kv = createFakeKv(); + const { fetcher, calls } = createFakeFetcher(); + const env = { IDENTITY_WORKER: fetcher, IDEMPOTENCY_KV: kv.binding, ENVIRONMENT: "test" }; + + // First request populates cache. + const first = await handleAuthRoute(makePost(VALID_KEY_A), env, "req_a", "/v1/auth/login/start"); + expect(first.status).toBe(200); + expect(calls).toHaveLength(1); + + // Second request with SAME key → replay. + const second = await handleAuthRoute(makePost(VALID_KEY_A), env, "req_b", "/v1/auth/login/start"); + expect(second.status).toBe(200); + expect(calls).toHaveLength(1); // downstream NOT called again + expect(second.headers.get("x-saas-replay-source")).toBe("edge-idempotency"); + }); + + it("different idempotency keys → cache miss for each, downstream called for both", async () => { + const kv = createFakeKv(); + const { fetcher, calls } = createFakeFetcher(); + const env = { IDENTITY_WORKER: fetcher, IDEMPOTENCY_KV: kv.binding, ENVIRONMENT: "test" }; + + await handleAuthRoute(makePost(VALID_KEY_A), env, "req_a", "/v1/auth/login/start"); + await handleAuthRoute(makePost(VALID_KEY_B), env, "req_b", "/v1/auth/login/start"); + + expect(calls).toHaveLength(2); + expect([...kv.store.keys()].filter(k => k.startsWith("idem:")).length).toBe(2); + }); + + it("absent Idempotency-Key on POST → passthrough, NOT cached", async () => { + const kv = createFakeKv(); + const { fetcher, calls } = createFakeFetcher(); + + const response = await handleAuthRoute( + makePost(), + { IDENTITY_WORKER: fetcher, IDEMPOTENCY_KV: kv.binding, ENVIRONMENT: "test" }, + "req_test", + "/v1/auth/login/start", + ); + + expect(response.status).toBe(200); + expect(calls).toHaveLength(1); + expect(kv.putCalls.filter(c => c.key.startsWith("idem:"))).toHaveLength(0); + expect(kv.getCalls.filter(k => k.startsWith("idem:"))).toHaveLength(0); + }); + + it("IDEMPOTENCY_KV unbound → degrades open, downstream still called", async () => { + const { fetcher, calls } = createFakeFetcher(); + + const response = await handleAuthRoute( + makePost(VALID_KEY_A), + { IDENTITY_WORKER: fetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/auth/login/start", + ); + + expect(response.status).toBe(200); + expect(calls).toHaveLength(1); + }); + + it("5xx response is NOT cached (transient errors should be retryable)", async () => { + const kv = createFakeKv(); + const { fetcher } = createFakeFetcher(() => + Response.json( + { error: { code: "internal_error", message: "boom" }, meta: { requestId: "req_inner", cursor: null } }, + { status: 503 }, + ), + ); + + await handleAuthRoute( + makePost(VALID_KEY_A), + { IDENTITY_WORKER: fetcher, IDEMPOTENCY_KV: kv.binding, ENVIRONMENT: "test" }, + "req_test", + "/v1/auth/login/start", + ); + + expect(kv.putCalls.filter(c => c.key.startsWith("idem:"))).toHaveLength(0); + }); + + it("4xx response IS cached (stable client errors replay deterministically)", async () => { + const kv = createFakeKv(); + const { fetcher } = createFakeFetcher(() => + Response.json( + { error: { code: "validation_failed", message: "bad email" }, meta: { requestId: "req_inner", cursor: null } }, + { status: 400 }, + ), + ); + + await handleAuthRoute( + makePost(VALID_KEY_A), + { IDENTITY_WORKER: fetcher, IDEMPOTENCY_KV: kv.binding, ENVIRONMENT: "test" }, + "req_test", + "/v1/auth/login/start", + ); + + expect(kv.putCalls.filter(c => c.key.startsWith("idem:"))).toHaveLength(1); + }); + }); + + describe("replayOrExecute (helper, isolated)", () => { + function makeEnv(kvBinding: KVNamespace | undefined) { + return { IDEMPOTENCY_KV: kvBinding, ENVIRONMENT: "test" } as unknown as Parameters[2]; + } + + it("GET request → downstream invoked once, never touches KV", async () => { + const kv = createFakeKv(); + let downstreamCalls = 0; + const get = new Request("https://api.example.com/v1/auth/session", { method: "GET" }); + + const response = await replayOrExecute(get, "req_test", makeEnv(kv.binding), "auth", () => { + downstreamCalls += 1; + return Promise.resolve(new Response("ok", { status: 200 })); + }); + + expect(response.status).toBe(200); + expect(downstreamCalls).toBe(1); + expect(kv.getCalls.filter(k => k.startsWith("idem:"))).toHaveLength(0); + expect(kv.putCalls.filter(c => c.key.startsWith("idem:"))).toHaveLength(0); + }); + + it("malformed Idempotency-Key on POST → 400 validation_failed, downstream NOT called", async () => { + const kv = createFakeKv(); + let downstreamCalls = 0; + const req = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { "idempotency-key": "a".repeat(256) }, + body: "{}", + }); + + const response = await replayOrExecute(req, "req_test", makeEnv(kv.binding), "auth", () => { + downstreamCalls += 1; + return Promise.resolve(new Response("ok")); + }); + + expect(response.status).toBe(400); + expect(downstreamCalls).toBe(0); + expect(kv.getCalls.filter(k => k.startsWith("idem:"))).toHaveLength(0); + }); + + it("KV get failure → degrades to cache-miss, downstream still called once", async () => { + const failing = { + get(): Promise { + return Promise.reject(new Error("kv unavailable")); + }, + put(): Promise { + return Promise.resolve(); + }, + } as unknown as KVNamespace; + let downstreamCalls = 0; + const req = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { "idempotency-key": VALID_KEY_A }, + body: "{}", + }); + + const response = await replayOrExecute(req, "req_test", makeEnv(failing), "auth", () => { + downstreamCalls += 1; + return Promise.resolve(new Response("ok", { status: 200 })); + }); + + expect(response.status).toBe(200); + expect(downstreamCalls).toBe(1); + }); + + it("non-text response body → base64-encoded in envelope, replay round-trips bytes", async () => { + const kv = createFakeKv(); + const bytes = new Uint8Array([0xff, 0x00, 0x42, 0xab, 0xcd]); + let downstreamCalls = 0; + const downstream = () => { + downstreamCalls += 1; + return Promise.resolve( + new Response(bytes, { + status: 200, + headers: { "content-type": "application/octet-stream" }, + }), + ); + }; + const req1 = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { "idempotency-key": VALID_KEY_A }, + body: "{}", + }); + + const first = await replayOrExecute(req1, "req_a", makeEnv(kv.binding), "auth", downstream); + expect(first.status).toBe(200); + expect(downstreamCalls).toBe(1); + const stored = kv.putCalls.find(c => c.key.startsWith("idem:"))!.value; + const env = JSON.parse(stored) as { bodyEncoding: string; v: number }; + expect(env.bodyEncoding).toBe("base64"); + expect(env.v).toBe(1); + + // Replay + const req2 = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { "idempotency-key": VALID_KEY_A }, + body: "{}", + }); + const replay = await replayOrExecute(req2, "req_b", makeEnv(kv.binding), "auth", downstream); + expect(downstreamCalls).toBe(1); // not called again + const replayBytes = new Uint8Array(await replay.arrayBuffer()); + expect(Array.from(replayBytes)).toEqual(Array.from(bytes)); + }); + + it("identity-agnostic key → same path + same idempotency-key collides regardless of caller actor", async () => { + const kv = createFakeKv(); + let downstreamCalls = 0; + const downstream = () => { + downstreamCalls += 1; + return Promise.resolve(Response.json({ data: { n: downstreamCalls } })); + }; + + // Two requests, same path + same key, "different actors" (we don't pass actor — + // this asserts the cache key derivation does not depend on identity headers). + const r1 = new Request("https://api.example.com/v1/organizations/org_abc/invitations", { + method: "POST", + headers: { + "idempotency-key": VALID_KEY_A, + authorization: "Bearer caller-A", + }, + body: "{}", + }); + const r2 = new Request("https://api.example.com/v1/organizations/org_abc/invitations", { + method: "POST", + headers: { + "idempotency-key": VALID_KEY_A, + authorization: "Bearer caller-B", + }, + body: "{}", + }); + + const env = makeEnv(kv.binding); + const first = await replayOrExecute(r1, "req_a", env, "org", downstream); + const second = await replayOrExecute(r2, "req_b", env, "org", downstream); + + expect(first.status).toBe(200); + expect(second.status).toBe(200); + expect(downstreamCalls).toBe(1); + expect(second.headers.get("x-saas-replay-source")).toBe("edge-idempotency"); + }); + }); +}); diff --git a/tests/api-edge/src/integrations-facade.test.ts b/tests/api-edge/src/integrations-facade.test.ts new file mode 100644 index 0000000..1d40eef --- /dev/null +++ b/tests/api-edge/src/integrations-facade.test.ts @@ -0,0 +1,236 @@ +import { + isIntegrationsRoute, + isIntegrationsIngressRoute, + handleIntegrationsRoute, + handleIntegrationsIngressRoute, +} from "@api-edge/integrations-facade"; + +interface FetchCall { + url: string; + init: RequestInit; +} + +function createFakeFetcher( + response: Response = Response.json({ + data: { connections: [], nextCursor: null }, + meta: { requestId: "req_test", cursor: null }, + }), +): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = + typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init: init ?? {} }); + return Promise.resolve(response.clone()); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +function createSessionFetcher(userId: string): Fetcher { + return { + fetch(input: string | Request | URL): Promise { + const url = + typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + if (url.includes("/v1/auth/resolve")) { + return Promise.resolve( + Response.json({ + data: { + actor: { actorType: "user", actorId: userId, email: "user@test.com" }, + session: { id: "ses_abc" }, + user: { id: userId, email: "user@test.com", displayName: "Test" }, + }, + meta: { requestId: "req_inner", cursor: null }, + }), + ); + } + return Promise.resolve(Response.json({ data: {}, meta: { requestId: "req_x", cursor: null } })); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; +} + +const ORG_PATH = "/v1/organizations/org_11111111111111111111111111111111/integrations"; + +function createEnv(overrides?: Record) { + const { fetcher: integrationsFetcher, calls } = createFakeFetcher(); + return { + env: { + IDENTITY_WORKER: createSessionFetcher("usr_abc123"), + INTEGRATIONS_WORKER: integrationsFetcher, + ENVIRONMENT: "test", + ...overrides, + }, + calls, + }; +} + +describe("integrations facade — route matching", () => { + it("matches org integration routes", () => { + expect(isIntegrationsRoute(ORG_PATH)).toBe(true); + expect(isIntegrationsRoute(`${ORG_PATH}/github/connect`)).toBe(true); + expect(isIntegrationsRoute(`${ORG_PATH}/int_abc`)).toBe(true); + expect(isIntegrationsRoute("/v1/organizations/org_x/webhooks/endpoints")).toBe(false); + expect(isIntegrationsRoute("/v1/integrations")).toBe(false); + }); + + it("matches project repo-link routes (IG3) but not other project routes", () => { + expect(isIntegrationsRoute("/v1/organizations/org_x/projects/prj_y/repo-links")).toBe(true); + expect(isIntegrationsRoute("/v1/organizations/org_x/projects/prj_y/repo-links/repl_z")).toBe(true); + expect(isIntegrationsRoute("/v1/organizations/org_x/projects/prj_y/environments")).toBe(false); + expect(isIntegrationsRoute("/v1/organizations/org_x/projects/prj_y")).toBe(false); + }); + + it("matches exactly the two allowlisted ingress paths", () => { + expect(isIntegrationsIngressRoute("/ingress/github/setup")).toBe(true); + expect(isIntegrationsIngressRoute("/ingress/github/webhook")).toBe(true); + expect(isIntegrationsIngressRoute("/ingress/github/setup/extra")).toBe(false); + expect(isIntegrationsIngressRoute("/ingress/github/other")).toBe(false); + }); +}); + +describe("integrations facade — authenticated surface", () => { + it("rejects unsupported methods", async () => { + const { env } = createEnv(); + const res = await handleIntegrationsRoute( + new Request(`https://edge.test${ORG_PATH}`, { method: "PUT" }), + env as never, + "req_1", + ORG_PATH, + ); + expect(res.status).toBe(405); + }); + + it("401s without a bearer token", async () => { + const { env, calls } = createEnv(); + const res = await handleIntegrationsRoute( + new Request(`https://edge.test${ORG_PATH}`, { method: "GET" }), + env as never, + "req_1", + ORG_PATH, + ); + expect(res.status).toBe(401); + expect(calls).toHaveLength(0); + }); + + it("forwards with pinned x-actor headers and preserves path + query", async () => { + const { env, calls } = createEnv(); + const res = await handleIntegrationsRoute( + new Request(`https://edge.test${ORG_PATH}?limit=10`, { + method: "GET", + headers: { authorization: "Bearer tok_123" }, + }), + env as never, + "req_1", + ORG_PATH, + ); + expect(res.status).toBe(200); + expect(calls).toHaveLength(1); + const target = new URL(calls[0]!.url); + expect(target.pathname).toBe(ORG_PATH); + expect(target.searchParams.get("limit")).toBe("10"); + const headers = new Headers(calls[0]!.init.headers); + expect(headers.get("x-actor-subject-id")).toBe("usr_abc123"); + expect(headers.get("x-actor-subject-type")).toBe("user"); + expect(headers.get("x-request-id")).toBe("req_1"); + }); + + it("503s when the integrations binding is missing", async () => { + const { env } = createEnv({ INTEGRATIONS_WORKER: undefined }); + const res = await handleIntegrationsRoute( + new Request(`https://edge.test${ORG_PATH}`, { + method: "GET", + headers: { authorization: "Bearer tok_123" }, + }), + env as never, + "req_1", + ORG_PATH, + ); + expect(res.status).toBe(503); + }); +}); + +describe("integrations facade — public setup ingress", () => { + const INGRESS = "/ingress/github/setup?installation_id=99&state=abc.def"; + + it("forwards GET with the full query string and no session requirement", async () => { + const { env, calls } = createEnv(); + const res = await handleIntegrationsIngressRoute( + new Request(`https://edge.test${INGRESS}`, { method: "GET" }), + env as never, + "req_1", + "/ingress/github/setup", + ); + expect(res.status).toBe(200); + expect(calls).toHaveLength(1); + const target = new URL(calls[0]!.url); + expect(target.pathname).toBe("/ingress/github/setup"); + expect(target.searchParams.get("installation_id")).toBe("99"); + expect(target.searchParams.get("state")).toBe("abc.def"); + const headers = new Headers(calls[0]!.init.headers); + expect(headers.get("x-internal-caller")).toBe("api-edge"); + // Never any actor headers on the bearer-less surface. + expect(headers.get("x-actor-subject-id")).toBeNull(); + }); + + it("rejects non-GET methods", async () => { + const { env, calls } = createEnv(); + const res = await handleIntegrationsIngressRoute( + new Request("https://edge.test/ingress/github/setup", { method: "POST" }), + env as never, + "req_1", + "/ingress/github/setup", + ); + expect(res.status).toBe(405); + expect(calls).toHaveLength(0); + }); +}); + +describe("integrations facade — public webhook ingress", () => { + it("streams the raw body with the signature headers, no session required", async () => { + const { env, calls } = createEnv(); + const res = await handleIntegrationsIngressRoute( + new Request("https://edge.test/ingress/github/webhook", { + method: "POST", + headers: { + "content-type": "application/json", + "x-github-delivery": "gh-uuid-1", + "x-github-event": "push", + "x-hub-signature-256": "sha256=abc", + }, + body: JSON.stringify({ zen: "Keep it logically awesome." }), + }), + env as never, + "req_1", + "/ingress/github/webhook", + ); + expect(res.status).toBe(200); + expect(calls).toHaveLength(1); + const headers = new Headers(calls[0]!.init.headers); + expect(headers.get("x-github-delivery")).toBe("gh-uuid-1"); + expect(headers.get("x-github-event")).toBe("push"); + expect(headers.get("x-hub-signature-256")).toBe("sha256=abc"); + expect(headers.get("x-internal-caller")).toBe("api-edge"); + expect(headers.get("x-actor-subject-id")).toBeNull(); + // Raw body forwarded as a stream, not re-serialized. + expect(calls[0]!.init.body).toBeTruthy(); + }); + + it("rejects non-POST on the webhook path", async () => { + const { env, calls } = createEnv(); + const res = await handleIntegrationsIngressRoute( + new Request("https://edge.test/ingress/github/webhook", { method: "GET" }), + env as never, + "req_1", + "/ingress/github/webhook", + ); + expect(res.status).toBe(405); + expect(calls).toHaveLength(0); + }); +}); diff --git a/tests/api-edge/src/notifications-facade.test.ts b/tests/api-edge/src/notifications-facade.test.ts new file mode 100644 index 0000000..ac291e4 --- /dev/null +++ b/tests/api-edge/src/notifications-facade.test.ts @@ -0,0 +1,176 @@ +import { isNotificationsRoute, handleNotificationsRoute } from "@api-edge/notifications-facade"; + +interface FetchCall { + url: string; + init: RequestInit; +} + +function createFakeFetcher( + response: Response = Response.json({ + data: { preferences: [] }, + meta: { requestId: "req_test", cursor: null }, + }), +): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init: init ?? {} }); + return Promise.resolve(response.clone()); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +function createSessionFetcher(userId: string): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init: init ?? {} }); + if (url.includes("/v1/auth/resolve")) { + return Promise.resolve( + Response.json({ + data: { + actor: { actorType: "user", actorId: userId, email: "user@test.com" }, + session: { id: "ses_abc" }, + user: { id: userId, email: "user@test.com", displayName: "Test" }, + }, + meta: { requestId: "req_inner", cursor: null }, + }), + ); + } + return Promise.resolve( + Response.json({ data: { preferences: [] }, meta: { requestId: "req_test", cursor: null } }), + ); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +function createEnv(overrides?: Record) { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: notificationsFetcher } = createFakeFetcher(); + return { + IDENTITY_WORKER: identityFetcher, + NOTIFICATIONS_WORKER: notificationsFetcher, + ENVIRONMENT: "test", + ...overrides, + }; +} + +const PATH = "/v1/notifications/preferences"; + +describe("api-edge notifications facade", () => { + describe("isNotificationsRoute", () => { + it("matches the preferences path exactly", () => { + expect(isNotificationsRoute(PATH)).toBe(true); + }); + it("does not match other notifications paths", () => { + expect(isNotificationsRoute("/v1/notifications")).toBe(false); + expect(isNotificationsRoute("/v1/notifications/ntf_123")).toBe(false); + expect(isNotificationsRoute(`${PATH}/extra`)).toBe(false); + }); + }); + + describe("handleNotificationsRoute", () => { + it("returns 405 for POST", async () => { + const req = new Request(`https://api.test${PATH}`, { + method: "POST", + headers: { authorization: "Bearer token123" }, + }); + const res = await handleNotificationsRoute(req, createEnv() as never, "req_test", PATH); + expect(res.status).toBe(405); + }); + + it("returns 503 when NOTIFICATIONS_WORKER is missing", async () => { + const env = createEnv({ NOTIFICATIONS_WORKER: undefined }); + const req = new Request(`https://api.test${PATH}`, { + method: "GET", + headers: { authorization: "Bearer token123" }, + }); + const res = await handleNotificationsRoute(req, env as never, "req_test", PATH); + expect(res.status).toBe(503); + }); + + it("returns 401 when no authorization header", async () => { + const req = new Request(`https://api.test${PATH}`, { method: "GET" }); + const res = await handleNotificationsRoute(req, createEnv() as never, "req_test", PATH); + expect(res.status).toBe(401); + }); + + it("pins the GET subject to the resolved actor, ignoring caller-supplied subject params", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_me"); + const { fetcher: notificationsFetcher, calls } = createFakeFetcher(); + const env = { + IDENTITY_WORKER: identityFetcher, + NOTIFICATIONS_WORKER: notificationsFetcher, + ENVIRONMENT: "test", + }; + const req = new Request( + `https://api.test${PATH}?orgId=org_abc&subjectKind=organization&subjectId=usr_victim`, + { method: "GET", headers: { authorization: "Bearer token123" } }, + ); + const res = await handleNotificationsRoute(req, env as never, "req_test", PATH); + expect(res.status).toBe(200); + expect(calls).toHaveLength(1); + const url = new URL(calls[0]!.url); + expect(url.searchParams.get("orgId")).toBe("org_abc"); + expect(url.searchParams.get("subjectKind")).toBe("user"); + expect(url.searchParams.get("subjectId")).toBe("usr_me"); + const headers = new Headers(calls[0]!.init.headers); + expect(headers.get("x-internal-actor")).toBe("api-edge"); + expect(headers.get("x-actor-subject-id")).toBe("usr_me"); + }); + + it("pins the PUT body subject to the resolved actor", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_me"); + const { fetcher: notificationsFetcher, calls } = createFakeFetcher( + Response.json({ + data: { preference: {} }, + meta: { requestId: "req_test", cursor: null }, + }), + ); + const env = { + IDENTITY_WORKER: identityFetcher, + NOTIFICATIONS_WORKER: notificationsFetcher, + ENVIRONMENT: "test", + }; + const req = new Request(`https://api.test${PATH}`, { + method: "PUT", + headers: { authorization: "Bearer token123", "content-type": "application/json" }, + body: JSON.stringify({ + orgId: "org_abc", + subjectKind: "organization", + subjectId: "usr_victim", + channel: "email", + categories: { billing: false }, + }), + }); + const res = await handleNotificationsRoute(req, env as never, "req_test", PATH); + expect(res.status).toBe(200); + expect(calls).toHaveLength(1); + const body = JSON.parse(String(calls[0]!.init.body)) as Record; + expect(body.subjectKind).toBe("user"); + expect(body.subjectId).toBe("usr_me"); + expect(body.orgId).toBe("org_abc"); + expect(body.categories).toEqual({ billing: false }); + }); + + it("rejects a non-JSON PUT body with 400", async () => { + const req = new Request(`https://api.test${PATH}`, { + method: "PUT", + headers: { authorization: "Bearer token123" }, + body: "not-json", + }); + const res = await handleNotificationsRoute(req, createEnv() as never, "req_test", PATH); + expect(res.status).toBe(400); + }); + }); +}); diff --git a/tests/api-edge/src/org-facade.test.ts b/tests/api-edge/src/org-facade.test.ts new file mode 100644 index 0000000..5a9a3da --- /dev/null +++ b/tests/api-edge/src/org-facade.test.ts @@ -0,0 +1,1329 @@ +import { readFileSync } from "node:fs"; +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { isOrgRoute, handleOrgRoute } from "@api-edge/org-facade"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +function stripJsoncComments(text: string): string { + return text.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, ""); +} + +interface FetchCall { + url: string; + init: RequestInit; +} + +function createFakeFetcher( + response: Response = Response.json({ data: {}, meta: { requestId: "req_test", cursor: null } }), +): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init: init ?? {} }); + return Promise.resolve(response.clone()); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +function createThrowingFetcher(error: Error): Fetcher { + return { + fetch(): Promise { + return Promise.reject(error); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; +} + +function createSessionFetcher(userId: string): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init: init ?? {} }); + if (url.includes("/v1/auth/resolve")) { + return Promise.resolve( + Response.json({ + data: { + actor: { actorType: "user", actorId: userId, email: "user@test.com" }, + session: { id: "ses_abc", expiresAt: "2026-12-01T00:00:00Z", createdAt: "2026-01-01T00:00:00Z" }, + user: { id: userId, email: "user@test.com", displayName: "Test" }, + }, + meta: { requestId: "req_inner", cursor: null }, + }), + ); + } + return Promise.resolve(Response.json({ data: {}, meta: { requestId: "req_test", cursor: null } })); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +describe("api-edge org facade", () => { + describe("isOrgRoute", () => { + it("matches /v1/organizations", () => { + expect(isOrgRoute("/v1/organizations")).toBe(true); + }); + + it("matches /v1/organizations/{orgId}", () => { + expect(isOrgRoute("/v1/organizations/org_abc123def456")).toBe(true); + }); + + it("matches /v1/organizations/{orgId}/members", () => { + expect(isOrgRoute("/v1/organizations/org_abc/members")).toBe(true); + }); + + it("matches /v1/organizations/{orgId}/members/{memberId}", () => { + expect(isOrgRoute("/v1/organizations/org_abc/members/mem_abc123")).toBe(true); + }); + + it("does not match deeper nested org routes", () => { + expect(isOrgRoute("/v1/organizations/org_abc/members/mem_abc123/extra")).toBe(false); + }); + + it("does not match /v1/auth routes", () => { + expect(isOrgRoute("/v1/auth/resolve")).toBe(false); + }); + }); + + describe("session resolution through IDENTITY_WORKER", () => { + it("resolves session and forwards actor context to MEMBERSHIP_WORKER", async () => { + const { fetcher: identityFetcher, calls: identityCalls } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations", + ); + + expect(identityCalls).toHaveLength(1); + expect(identityCalls[0]!.url).toContain("/v1/auth/resolve"); + + expect(membershipCalls).toHaveLength(1); + const forwardedHeaders = new Headers(membershipCalls[0]!.init.headers as HeadersInit); + expect(forwardedHeaders.get("x-actor-subject-id")).toBe("usr_abc123"); + expect(forwardedHeaders.get("x-actor-subject-type")).toBe("user"); + }); + + it("does not forward raw bearer token to MEMBERSHIP_WORKER", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations", + ); + + const forwardedHeaders = new Headers(membershipCalls[0]!.init.headers as HeadersInit); + expect(forwardedHeaders.get("authorization")).toBeNull(); + const rawCall = JSON.stringify(membershipCalls[0]); + expect(rawCall).not.toContain("sps_ses_"); + expect(rawCall).not.toContain("Bearer"); + }); + + it("returns unauthenticated when bearer token is missing", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations", { + method: "GET", + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations", + ); + + expect(response.status).toBe(401); + const json = await response.json() as any; + expect(json.error.code).toBe("unauthenticated"); + }); + + it("returns unauthenticated when identity service returns error", async () => { + const identityFetcher = { + fetch(): Promise { + return Promise.resolve( + Response.json({ error: { code: "unauthenticated", message: "Invalid token", requestId: "req_x" } }, { status: 401 }), + ); + }, + connect() { throw new Error("not implemented"); }, + } as unknown as Fetcher; + const { fetcher: membershipFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.bad" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations", + ); + + expect(response.status).toBe(401); + }); + }); + + describe("error handling", () => { + it("returns 503 when IDENTITY_WORKER is not configured", async () => { + const { fetcher: membershipFetcher } = createFakeFetcher(); + const request = new Request("https://api.example.com/v1/organizations", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations", + ); + + expect(response.status).toBe(503); + const json = await response.json() as any; + expect(json.error.code).toBe("internal_error"); + expect(json.error.message).toBe("Authentication service unavailable"); + expect(JSON.stringify(json)).not.toContain("identity-worker"); + }); + + it("returns 503 when MEMBERSHIP_WORKER is not configured", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const request = new Request("https://api.example.com/v1/organizations", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations", + ); + + expect(response.status).toBe(503); + const json = await response.json() as any; + expect(json.error.code).toBe("internal_error"); + expect(json.error.message).toBe("Membership service unavailable"); + expect(JSON.stringify(json)).not.toContain("membership-worker"); + }); + + it("returns 503 with safe envelope when membership binding throws", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const membershipFetcher = createThrowingFetcher( + new Error("Connection refused to new-test-membership-worker-stage.internal"), + ); + + const request = new Request("https://api.example.com/v1/organizations", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations", + ); + + expect(response.status).toBe(503); + const json = await response.json() as any; + expect(json.error.message).toBe("Membership service unavailable"); + expect(JSON.stringify(json)).not.toContain("Connection refused"); + expect(JSON.stringify(json)).not.toContain("new-test-membership-worker-stage"); + }); + + it("returns 405 for unsupported method on /v1/organizations", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations", { + method: "DELETE", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations", + ); + + expect(response.status).toBe(405); + const json = await response.json() as any; + expect(json.error.code).toBe("unsupported"); + }); + + it("returns 405 for non-GET on /v1/organizations/:id", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc", { + method: "DELETE", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc", + ); + + expect(response.status).toBe(405); + }); + }); + + describe("downstream response passthrough", () => { + it("passes through membership success envelope", async () => { + const envelope = { data: { organizations: [] }, meta: { requestId: "req_123", cursor: null } }; + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(Response.json(envelope)); + + const request = new Request("https://api.example.com/v1/organizations", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations", + ); + + expect(response.status).toBe(200); + const json = await response.json(); + expect(json).toEqual(envelope); + }); + + it("passes through membership error envelope", async () => { + const envelope = { error: { code: "conflict", message: "Organization already exists", details: {}, requestId: "req_123" } }; + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(Response.json(envelope, { status: 409 })); + + const request = new Request("https://api.example.com/v1/organizations", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ name: "test" }), + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations", + ); + + expect(response.status).toBe(409); + const json = await response.json(); + expect(json).toEqual(envelope); + }); + }); + + describe("header forwarding", () => { + it("forwards x-request-id to membership", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret", "x-request-id": "req_custom" }, + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_custom", + "/v1/organizations", + ); + + const forwarded = new Headers(calls[0]!.init.headers as HeadersInit); + expect(forwarded.get("x-request-id")).toBe("req_custom"); + }); + + it("forwards traceparent to membership", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls } = createFakeFetcher(); + const traceparent = "00-abcdef1234567890-1234567890abcdef-01"; + + const request = new Request("https://api.example.com/v1/organizations", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret", traceparent }, + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations", + ); + + const forwarded = new Headers(calls[0]!.init.headers as HeadersInit); + expect(forwarded.get("traceparent")).toBe(traceparent); + }); + + it("forwards idempotency-key to membership", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json", "idempotency-key": "idem_xyz" }, + body: JSON.stringify({ name: "Test" }), + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations", + ); + + const forwarded = new Headers(calls[0]!.init.headers as HeadersInit); + expect(forwarded.get("idempotency-key")).toBe("idem_xyz"); + }); + + it("forwards POST body to membership", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ name: "My Org" }), + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations", + ); + + expect(calls[0]!.init.body).toBeDefined(); + }); + }); + + describe("binding verification config", () => { + it("wrangler.jsonc has stage MEMBERSHIP_WORKER binding to new-test-membership-worker-stage", () => { + const configPath = resolve(__dirname, "../../../apps/api-edge/wrangler.jsonc"); + const raw = readFileSync(configPath, "utf-8"); + const config = JSON.parse(stripJsoncComments(raw)); + + const stageServices = config.env?.stage?.services; + expect(stageServices).toBeDefined(); + const membership = stageServices.find((s: any) => s.binding === "MEMBERSHIP_WORKER"); + expect(membership).toBeDefined(); + expect(membership.service).toBe("new-test-membership-worker-stage"); + }); + + it("wrangler.jsonc has prod MEMBERSHIP_WORKER binding to new-test-membership-worker-prod", () => { + const configPath = resolve(__dirname, "../../../apps/api-edge/wrangler.jsonc"); + const raw = readFileSync(configPath, "utf-8"); + const config = JSON.parse(stripJsoncComments(raw)); + + const prodServices = config.env?.prod?.services; + expect(prodServices).toBeDefined(); + const membership = prodServices.find((s: any) => s.binding === "MEMBERSHIP_WORKER"); + expect(membership).toBeDefined(); + expect(membership.service).toBe("new-test-membership-worker-prod"); + }); + + it("stage does not bind to prod membership worker", () => { + const configPath = resolve(__dirname, "../../../apps/api-edge/wrangler.jsonc"); + const raw = readFileSync(configPath, "utf-8"); + const config = JSON.parse(stripJsoncComments(raw)); + + const stageServices = config.env?.stage?.services ?? []; + const membershipBindings = stageServices.filter((s: any) => s.binding === "MEMBERSHIP_WORKER"); + for (const svc of membershipBindings) { + expect(svc.service).not.toContain("prod"); + } + }); + + it("prod does not bind to stage membership worker", () => { + const configPath = resolve(__dirname, "../../../apps/api-edge/wrangler.jsonc"); + const raw = readFileSync(configPath, "utf-8"); + const config = JSON.parse(stripJsoncComments(raw)); + + const prodServices = config.env?.prod?.services ?? []; + const membershipBindings = prodServices.filter((s: any) => s.binding === "MEMBERSHIP_WORKER"); + for (const svc of membershipBindings) { + expect(svc.service).not.toContain("stage"); + } + }); + }); + + describe("members route /v1/organizations/{orgId}/members", () => { + it("forwards GET /v1/organizations/{orgId}/members to MEMBERSHIP_WORKER", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/members", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/members", + ); + + expect(response.status).toBe(200); + expect(membershipCalls).toHaveLength(1); + expect(membershipCalls[0]!.url).toContain("/v1/organizations/org_abc123/members"); + }); + + it("only allows GET method", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/members", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({}), + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/members", + ); + + expect(response.status).toBe(405); + const json = await response.json() as any; + expect(json.error.code).toBe("unsupported"); + }); + + it("resolves auth and forwards actor headers", async () => { + const { fetcher: identityFetcher, calls: identityCalls } = createSessionFetcher("usr_member_actor"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/members", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/members", + ); + + expect(identityCalls).toHaveLength(1); + expect(identityCalls[0]!.url).toContain("/v1/auth/resolve"); + + const forwarded = new Headers(membershipCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("x-actor-subject-id")).toBe("usr_member_actor"); + expect(forwarded.get("x-actor-subject-type")).toBe("user"); + }); + + it("does not forward raw bearer token to MEMBERSHIP_WORKER", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/members", { + method: "GET", + headers: { authorization: "Bearer sps_ses_secret_token.xyz" }, + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/members", + ); + + const forwarded = new Headers(membershipCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("authorization")).toBeNull(); + const rawCall = JSON.stringify(membershipCalls[0]); + expect(rawCall).not.toContain("sps_ses_secret_token"); + expect(rawCall).not.toContain("Bearer"); + }); + + it("passes through downstream success response", async () => { + const envelope = { data: { members: [] }, meta: { requestId: "req_123", cursor: null } }; + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(Response.json(envelope)); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/members", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/members", + ); + + expect(response.status).toBe(200); + const json = await response.json(); + expect(json).toEqual(envelope); + }); + + it("passes through downstream error response", async () => { + const envelope = { error: { code: "not_found", message: "Organization not found", details: {}, requestId: "req_123" } }; + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(Response.json(envelope, { status: 404 })); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/members", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/members", + ); + + expect(response.status).toBe(404); + const json = await response.json(); + expect(json).toEqual(envelope); + }); + }); + + describe("member item route /v1/organizations/{orgId}/members/{memberId}", () => { + it("forwards PATCH to MEMBERSHIP_WORKER", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/members/mem_xyz", { + method: "PATCH", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ role: "admin" }), + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/members/mem_xyz", + ); + + expect(response.status).toBe(200); + expect(membershipCalls).toHaveLength(1); + expect(membershipCalls[0]!.url).toContain("/v1/organizations/org_abc/members/mem_xyz"); + expect(membershipCalls[0]!.init.method).toBe("PATCH"); + }); + + it("forwards DELETE to MEMBERSHIP_WORKER", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/members/mem_xyz", { + method: "DELETE", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/members/mem_xyz", + ); + + expect(response.status).toBe(200); + expect(membershipCalls).toHaveLength(1); + expect(membershipCalls[0]!.url).toContain("/v1/organizations/org_abc/members/mem_xyz"); + expect(membershipCalls[0]!.init.method).toBe("DELETE"); + }); + + it("forwards PATCH body to MEMBERSHIP_WORKER", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/members/mem_xyz", { + method: "PATCH", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ role: "editor" }), + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/members/mem_xyz", + ); + + expect(membershipCalls[0]!.init.body).toBeDefined(); + }); + + it("returns 405 for GET on member item route", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/members/mem_xyz", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/members/mem_xyz", + ); + + expect(response.status).toBe(405); + const json = await response.json() as any; + expect(json.error.code).toBe("unsupported"); + }); + + it("returns 405 for POST on member item route", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/members/mem_xyz", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({}), + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/members/mem_xyz", + ); + + expect(response.status).toBe(405); + const json = await response.json() as any; + expect(json.error.code).toBe("unsupported"); + }); + + it("returns 405 for PUT on member item route", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/members/mem_xyz", { + method: "PUT", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ role: "admin" }), + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/members/mem_xyz", + ); + + expect(response.status).toBe(405); + const json = await response.json() as any; + expect(json.error.code).toBe("unsupported"); + }); + + it("resolves auth and forwards actor headers", async () => { + const { fetcher: identityFetcher, calls: identityCalls } = createSessionFetcher("usr_member_actor"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/members/mem_xyz", { + method: "PATCH", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ role: "admin" }), + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/members/mem_xyz", + ); + + expect(identityCalls).toHaveLength(1); + expect(identityCalls[0]!.url).toContain("/v1/auth/resolve"); + + const forwarded = new Headers(membershipCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("x-actor-subject-id")).toBe("usr_member_actor"); + expect(forwarded.get("x-actor-subject-type")).toBe("user"); + }); + + it("does not forward raw bearer token to MEMBERSHIP_WORKER", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/members/mem_xyz", { + method: "PATCH", + headers: { authorization: "Bearer sps_ses_secret_token.xyz", "content-type": "application/json" }, + body: JSON.stringify({ role: "admin" }), + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/members/mem_xyz", + ); + + const forwarded = new Headers(membershipCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("authorization")).toBeNull(); + const rawCall = JSON.stringify(membershipCalls[0]); + expect(rawCall).not.toContain("sps_ses_secret_token"); + expect(rawCall).not.toContain("Bearer"); + }); + }); + + describe("pagination query-string forwarding", () => { + it("forwards limit and cursor query params to membership-worker for /v1/organizations", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations?limit=10&cursor=abc123", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations", + ); + + const membershipCall = calls.find((c) => c.url.includes("/v1/organizations")); + expect(membershipCall).toBeDefined(); + expect(membershipCall!.url).toContain("limit=10"); + expect(membershipCall!.url).toContain("cursor=abc123"); + }); + + it("forwards limit and cursor query params to membership-worker for /v1/organizations/{orgId}/members", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/members?limit=25&cursor=xyz789", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/members", + ); + + const membershipCall = calls.find((c) => c.url.includes("/members")); + expect(membershipCall).toBeDefined(); + expect(membershipCall!.url).toContain("limit=25"); + expect(membershipCall!.url).toContain("cursor=xyz789"); + }); + + it("does not forward authorization header to membership-worker", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations?limit=5", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations", + ); + + const membershipCall = calls.find((c) => c.url.includes("/v1/organizations")); + expect(membershipCall).toBeDefined(); + const headers = membershipCall!.init.headers as Headers; + expect(headers.get("authorization")).toBeNull(); + }); + + it("preserves empty query string when no params provided", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations", + ); + + const membershipCall = calls.find((c) => c.url.includes("/v1/organizations")); + expect(membershipCall).toBeDefined(); + const url = new URL(membershipCall!.url); + expect(url.pathname).toBe("/v1/organizations"); + }); + }); + + describe("invitation routes", () => { + describe("isOrgRoute for invitation paths", () => { + it("matches /v1/organizations/{orgId}/invitations", () => { + expect(isOrgRoute("/v1/organizations/org_abc/invitations")).toBe(true); + }); + + it("matches /v1/organizations/{orgId}/invitations/{invitationId}", () => { + expect(isOrgRoute("/v1/organizations/org_abc/invitations/inv_def")).toBe(true); + }); + }); + + describe("POST /v1/organizations/{orgId}/invitations", () => { + it("forwards POST to MEMBERSHIP_WORKER with body", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ email: "test@example.com", role: "viewer" }), + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations", + ); + + expect(response.status).toBe(200); + expect(membershipCalls).toHaveLength(1); + expect(membershipCalls[0]!.url).toContain("/v1/organizations/org_abc/invitations"); + expect(membershipCalls[0]!.init.method).toBe("POST"); + expect(membershipCalls[0]!.init.body).toBeDefined(); + }); + + it("resolves auth before forwarding", async () => { + const { fetcher: identityFetcher, calls: identityCalls } = createSessionFetcher("usr_admin"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ email: "test@example.com", role: "viewer" }), + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations", + ); + + expect(identityCalls).toHaveLength(1); + const forwarded = new Headers(membershipCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("x-actor-subject-id")).toBe("usr_admin"); + expect(forwarded.get("x-actor-subject-type")).toBe("user"); + }); + + it("does not forward bearer token", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations", { + method: "POST", + headers: { authorization: "Bearer sps_ses_secret.token", "content-type": "application/json" }, + body: JSON.stringify({ email: "test@example.com", role: "viewer" }), + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations", + ); + + const forwarded = new Headers(membershipCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("authorization")).toBeNull(); + const rawCall = JSON.stringify(membershipCalls[0]); + expect(rawCall).not.toContain("sps_ses_secret"); + }); + }); + + describe("GET /v1/organizations/{orgId}/invitations", () => { + it("forwards GET with query string to MEMBERSHIP_WORKER", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations?limit=10&cursor=xyz", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations", + ); + + expect(response.status).toBe(200); + expect(membershipCalls[0]!.url).toContain("limit=10"); + expect(membershipCalls[0]!.url).toContain("cursor=xyz"); + }); + }); + + describe("method restrictions on invitation collection", () => { + it("returns 405 for DELETE on collection route", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations", { + method: "DELETE", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations", + ); + + expect(response.status).toBe(405); + const json = await response.json() as any; + expect(json.error.code).toBe("unsupported"); + }); + + it("returns 405 for PUT on collection route", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations", { + method: "PUT", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({}), + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations", + ); + + expect(response.status).toBe(405); + }); + }); + + describe("DELETE /v1/organizations/{orgId}/invitations/{invitationId}", () => { + it("forwards DELETE to MEMBERSHIP_WORKER", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations/inv_def", { + method: "DELETE", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations/inv_def", + ); + + expect(response.status).toBe(200); + expect(membershipCalls).toHaveLength(1); + expect(membershipCalls[0]!.url).toContain("/v1/organizations/org_abc/invitations/inv_def"); + expect(membershipCalls[0]!.init.method).toBe("DELETE"); + }); + + it("returns 405 for GET on item route", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations/inv_def", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations/inv_def", + ); + + expect(response.status).toBe(405); + const json = await response.json() as any; + expect(json.error.code).toBe("unsupported"); + }); + + it("returns 405 for POST on item route", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations/inv_def", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({}), + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations/inv_def", + ); + + expect(response.status).toBe(405); + }); + + it("does not forward bearer token for DELETE", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations/inv_def", { + method: "DELETE", + headers: { authorization: "Bearer sps_ses_secret.xyz" }, + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations/inv_def", + ); + + const forwarded = new Headers(membershipCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("authorization")).toBeNull(); + const rawCall = JSON.stringify(membershipCalls[0]); + expect(rawCall).not.toContain("sps_ses_secret"); + }); + }); + + describe("downstream passthrough for invitation routes", () => { + it("passes through success response from membership for create", async () => { + const envelope = { data: { invitation: { id: "inv_abc" } }, meta: { requestId: "req_123", cursor: null } }; + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(Response.json(envelope, { status: 201 })); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ email: "test@x.com", role: "viewer" }), + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations", + ); + + expect(response.status).toBe(201); + const json = await response.json(); + expect(json).toEqual(envelope); + }); + + it("passes through error response from membership for revoke", async () => { + const envelope = { error: { code: "not_found", message: "Invitation not found", details: {}, requestId: "req_123" } }; + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(Response.json(envelope, { status: 404 })); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations/inv_def", { + method: "DELETE", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations/inv_def", + ); + + expect(response.status).toBe(404); + const json = await response.json(); + expect(json).toEqual(envelope); + }); + }); + + describe("POST /v1/organizations/{orgId}/invitations/accept", () => { + it("matches isOrgRoute for accept path", () => { + expect(isOrgRoute("/v1/organizations/org_abc/invitations/accept")).toBe(true); + }); + + it("forwards POST with body to MEMBERSHIP_WORKER", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations/accept", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ token: "a".repeat(64) }), + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations/accept", + ); + + expect(response.status).toBe(200); + expect(membershipCalls).toHaveLength(1); + expect(membershipCalls[0]!.url).toContain("/v1/organizations/org_abc/invitations/accept"); + expect(membershipCalls[0]!.init.method).toBe("POST"); + expect(membershipCalls[0]!.init.body).toBeDefined(); + }); + + it("resolves auth before forwarding", async () => { + const { fetcher: identityFetcher, calls: identityCalls } = createSessionFetcher("usr_accept"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations/accept", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ token: "b".repeat(64) }), + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations/accept", + ); + + expect(identityCalls).toHaveLength(1); + const forwarded = new Headers(membershipCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("x-actor-subject-id")).toBe("usr_accept"); + expect(forwarded.get("x-actor-subject-type")).toBe("user"); + }); + + it("forwards x-actor-email from identity session response", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_accept"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations/accept", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ token: "c".repeat(64) }), + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations/accept", + ); + + const forwarded = new Headers(membershipCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("x-actor-email")).toBe("user@test.com"); + }); + + it("forwards request even when identity response has no email", async () => { + const noEmailFetcher = { + fetch(input: string | Request | URL): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + if (url.includes("/v1/auth/resolve")) { + return Promise.resolve( + Response.json({ + data: { actor: { actorType: "user", actorId: "usr_123" }, session: { id: "ses_abc" }, user: { id: "usr_123" } }, + meta: { requestId: "req_inner", cursor: null }, + }), + ); + } + return Promise.resolve(Response.json({ data: {}, meta: { requestId: "req_test", cursor: null } })); + }, + connect() { throw new Error("not implemented"); }, + } as unknown as Fetcher; + + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations/accept", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ token: "d".repeat(64) }), + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: noEmailFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations/accept", + ); + + expect(response.status).toBe(200); + expect(membershipCalls).toHaveLength(1); + const forwarded = new Headers(membershipCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("x-actor-email")).toBe(""); + }); + + it("returns 405 for non-POST methods", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations/accept", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations/accept", + ); + + expect(response.status).toBe(405); + }); + + it("does not forward bearer token to MEMBERSHIP_WORKER", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: membershipFetcher, calls: membershipCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc/invitations/accept", { + method: "POST", + headers: { authorization: "Bearer sps_ses_secret.bearer", "content-type": "application/json" }, + body: JSON.stringify({ token: "e".repeat(64) }), + }); + + await handleOrgRoute( + request, + { IDENTITY_WORKER: identityFetcher, MEMBERSHIP_WORKER: membershipFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc/invitations/accept", + ); + + const forwarded = new Headers(membershipCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("authorization")).toBeNull(); + const rawCall = JSON.stringify(membershipCalls[0]); + expect(rawCall).not.toContain("sps_ses_secret"); + }); + }); + }); +}); diff --git a/tests/api-edge/src/project-facade.test.ts b/tests/api-edge/src/project-facade.test.ts new file mode 100644 index 0000000..f8834c6 --- /dev/null +++ b/tests/api-edge/src/project-facade.test.ts @@ -0,0 +1,887 @@ +import { readFileSync } from "node:fs"; +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { isProjectRoute, handleProjectRoute } from "@api-edge/project-facade"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +function stripJsoncComments(text: string): string { + return text.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, ""); +} + +interface FetchCall { + url: string; + init: RequestInit; +} + +function createFakeFetcher( + response: Response = Response.json({ data: {}, meta: { requestId: "req_test", cursor: null } }), +): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init: init ?? {} }); + return Promise.resolve(response.clone()); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +function createThrowingFetcher(): Fetcher { + return { + fetch(): Promise { + return Promise.reject(new Error("network error")); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; +} + +function createSessionFetcher(userId: string): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init: init ?? {} }); + if (url.includes("/v1/auth/resolve")) { + return Promise.resolve( + Response.json({ + data: { actor: { actorType: "user", actorId: userId, email: "user@test.com" }, session: { id: "ses_abc", expiresAt: "2026-12-01T00:00:00Z", createdAt: "2026-01-01T00:00:00Z" }, user: { id: userId, email: "user@test.com", displayName: "Test" } }, + meta: { requestId: "req_inner", cursor: null }, + }), + ); + } + return Promise.resolve(Response.json({ data: {}, meta: { requestId: "req_test", cursor: null } })); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +describe("api-edge project facade", () => { + describe("isProjectRoute", () => { + it("matches POST /v1/organizations/{orgId}/projects", () => { + expect(isProjectRoute("/v1/organizations/org_abc123/projects")).toBe(true); + }); + + it("matches GET /v1/organizations/{orgId}/projects/{projectId}", () => { + expect(isProjectRoute("/v1/organizations/org_abc123/projects/prj_def456")).toBe(true); + }); + + it("does not match project list (same as POST collection)", () => { + expect(isProjectRoute("/v1/organizations/org_abc123/projects")).toBe(true); + }); + + it("matches nested environment routes under projects", () => { + expect(isProjectRoute("/v1/organizations/org_abc/projects/prj_def/environments")).toBe(true); + }); + + it("does not match org routes", () => { + expect(isProjectRoute("/v1/organizations/org_abc")).toBe(false); + }); + + it("does not match auth routes", () => { + expect(isProjectRoute("/v1/auth/resolve")).toBe(false); + }); + }); + + describe("POST /v1/organizations/{orgId}/projects forwarding", () => { + it("forwards POST to PROJECTS_WORKER after identity resolution", async () => { + const { fetcher: identityFetcher, calls: identityCalls } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher( + Response.json({ data: { project: { id: "prj_abc" } }, meta: { requestId: "req_test", cursor: null } }, { status: 201 }), + ); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ name: "My Project", slug: "my-project" }), + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects", + ); + + expect(response.status).toBe(201); + expect(identityCalls).toHaveLength(1); + expect(identityCalls[0]!.url).toContain("/v1/auth/resolve"); + expect(projectsCalls).toHaveLength(1); + expect(projectsCalls[0]!.url).toContain("/v1/organizations/org_abc123/projects"); + expect(projectsCalls[0]!.init.method).toBe("POST"); + }); + + it("forwards actor headers to PROJECTS_WORKER", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ name: "Test" }), + }); + + await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects", + ); + + const forwarded = new Headers(projectsCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("x-actor-subject-id")).toBe("usr_abc123"); + expect(forwarded.get("x-actor-subject-type")).toBe("user"); + expect(forwarded.get("x-actor-email")).toBe("user@test.com"); + }); + + it("does not forward bearer token to PROJECTS_WORKER", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects", { + method: "POST", + headers: { authorization: "Bearer sps_ses_secret.token", "content-type": "application/json" }, + body: JSON.stringify({ name: "Test" }), + }); + + await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects", + ); + + const forwarded = new Headers(projectsCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("authorization")).toBeNull(); + const rawCall = JSON.stringify(projectsCalls[0]); + expect(rawCall).not.toContain("sps_ses_secret"); + expect(rawCall).not.toContain("Bearer"); + }); + }); + + describe("GET /v1/organizations/{orgId}/projects/{projectId} forwarding", () => { + it("forwards GET to PROJECTS_WORKER with actor headers", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456", + ); + + expect(response.status).toBe(200); + expect(projectsCalls).toHaveLength(1); + expect(projectsCalls[0]!.url).toContain("/v1/organizations/org_abc123/projects/prj_def456"); + expect(projectsCalls[0]!.init.method).toBe("GET"); + + const forwarded = new Headers(projectsCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("x-actor-subject-id")).toBe("usr_abc123"); + expect(forwarded.get("x-actor-subject-type")).toBe("user"); + }); + + it("PERF4: appends edge phases to the downstream Server-Timing header", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + // Downstream worker already emits its own Server-Timing. + const downstream = Response.json( + { data: { projects: [] }, meta: { requestId: "req_test", cursor: null } }, + { headers: { "Server-Timing": "authctx;dur=12, db;dur=34, policy;dur=2, total;dur=40" } }, + ); + const { fetcher: projectsFetcher } = createFakeFetcher(downstream); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects", + ); + + expect(response.status).toBe(200); + const timing = response.headers.get("Server-Timing"); + expect(timing).toBeTruthy(); + // Preserves the worker phases AND adds the edge phases. + for (const phase of ["authctx", "db", "policy", "total", "edge_auth", "edge_downstream", "edge_total"]) { + expect(timing).toContain(phase); + } + }); + + it("does not forward bearer token to PROJECTS_WORKER for GET", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456", { + method: "GET", + headers: { authorization: "Bearer sps_ses_secret.bearer" }, + }); + + await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456", + ); + + const forwarded = new Headers(projectsCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("authorization")).toBeNull(); + const rawCall = JSON.stringify(projectsCalls[0]); + expect(rawCall).not.toContain("sps_ses_secret"); + }); + }); + + describe("DELETE /v1/organizations/{orgId}/projects/{projectId} forwarding", () => { + it("forwards DELETE to PROJECTS_WORKER after identity resolution", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher( + Response.json({ data: { project: { id: "prj_abc", status: "archived" } }, meta: { requestId: "req_test", cursor: null } }), + ); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456", { + method: "DELETE", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456", + ); + + expect(response.status).toBe(200); + expect(projectsCalls).toHaveLength(1); + expect(projectsCalls[0]!.url).toContain("/v1/organizations/org_abc123/projects/prj_def456"); + expect(projectsCalls[0]!.init.method).toBe("DELETE"); + + const forwarded = new Headers(projectsCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("x-actor-subject-id")).toBe("usr_abc123"); + expect(forwarded.get("x-actor-subject-type")).toBe("user"); + }); + + it("does not forward bearer token for DELETE", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456", { + method: "DELETE", + headers: { authorization: "Bearer sps_ses_secret.token" }, + }); + + await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456", + ); + + const forwarded = new Headers(projectsCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("authorization")).toBeNull(); + const rawCall = JSON.stringify(projectsCalls[0]); + expect(rawCall).not.toContain("sps_ses_secret"); + }); + + it("returns 503 when PROJECTS_WORKER is missing for DELETE", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456", { + method: "DELETE", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456", + ); + + expect(response.status).toBe(503); + const json = await response.json() as any; + expect(json.error.message).toBe("Projects service unavailable"); + }); + + it("returns 405 for PATCH on project item", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456", { + method: "PATCH", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ name: "Updated" }), + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456", + ); + + expect(response.status).toBe(405); + }); + }); + + describe("error handling", () => { + it("returns 503 when PROJECTS_WORKER is not configured", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ name: "Test" }), + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects", + ); + + expect(response.status).toBe(503); + const json = await response.json() as any; + expect(json.error.code).toBe("internal_error"); + expect(json.error.message).toBe("Projects service unavailable"); + }); + + it("returns 503 when IDENTITY_WORKER is not configured", async () => { + const { fetcher: projectsFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ name: "Test" }), + }); + + const response = await handleProjectRoute( + request, + { PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects", + ); + + expect(response.status).toBe(503); + const json = await response.json() as any; + expect(json.error.message).toBe("Authentication service unavailable"); + }); + + it("returns 503 with safe message when PROJECTS_WORKER throws", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const projectsFetcher = createThrowingFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ name: "Test" }), + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects", + ); + + expect(response.status).toBe(503); + const json = await response.json() as any; + expect(json.error.message).toBe("Projects service unavailable"); + expect(JSON.stringify(json)).not.toContain("network error"); + }); + + it("forwards GET on projects collection to PROJECTS_WORKER after identity resolution", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher( + Response.json({ data: { projects: [] }, meta: { requestId: "req_test", cursor: null } }), + ); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects?limit=10&cursor=abc", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects", + ); + + expect(response.status).toBe(200); + expect(projectsCalls).toHaveLength(1); + expect(projectsCalls[0]!.url).toContain("/v1/organizations/org_abc123/projects"); + expect(projectsCalls[0]!.url).toContain("limit=10"); + expect(projectsCalls[0]!.url).toContain("cursor=abc"); + expect(projectsCalls[0]!.init.method).toBe("GET"); + + const forwarded = new Headers(projectsCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("x-actor-subject-id")).toBe("usr_abc123"); + expect(forwarded.get("x-actor-subject-type")).toBe("user"); + expect(forwarded.get("authorization")).toBeNull(); + }); + + it("returns 503 when PROJECTS_WORKER is not configured for GET collection", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects", + ); + + expect(response.status).toBe(503); + const json = await response.json() as any; + expect(json.error.message).toBe("Projects service unavailable"); + }); + + it("returns 401 when bearer token is missing", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ name: "Test" }), + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects", + ); + + expect(response.status).toBe(401); + const json = await response.json() as any; + expect(json.error.code).toBe("unauthenticated"); + }); + }); + + describe("isProjectRoute environment routes", () => { + it("matches POST /v1/organizations/{orgId}/projects/{projectId}/environments", () => { + expect(isProjectRoute("/v1/organizations/org_abc/projects/prj_def/environments")).toBe(true); + }); + + it("matches GET /v1/organizations/{orgId}/projects/{projectId}/environments/{envId}", () => { + expect(isProjectRoute("/v1/organizations/org_abc/projects/prj_def/environments/env_ghi")).toBe(true); + }); + }); + + describe("POST /v1/organizations/{orgId}/projects/{projectId}/environments forwarding", () => { + it("forwards POST to PROJECTS_WORKER after identity resolution with body", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher( + Response.json({ data: { environment: { id: "env_abc" } }, meta: { requestId: "req_test", cursor: null } }, { status: 201 }), + ); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456/environments", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ name: "Production", slug: "production" }), + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456/environments", + ); + + expect(response.status).toBe(201); + expect(projectsCalls).toHaveLength(1); + expect(projectsCalls[0]!.url).toContain("/v1/organizations/org_abc123/projects/prj_def456/environments"); + expect(projectsCalls[0]!.init.method).toBe("POST"); + }); + + it("forwards actor headers and does not forward bearer token", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456/environments", { + method: "POST", + headers: { authorization: "Bearer sps_ses_secret.token", "content-type": "application/json" }, + body: JSON.stringify({ name: "Staging" }), + }); + + await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456/environments", + ); + + const forwarded = new Headers(projectsCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("x-actor-subject-id")).toBe("usr_abc123"); + expect(forwarded.get("x-actor-subject-type")).toBe("user"); + expect(forwarded.get("authorization")).toBeNull(); + const rawCall = JSON.stringify(projectsCalls[0]); + expect(rawCall).not.toContain("sps_ses_secret"); + }); + }); + + describe("GET /v1/organizations/{orgId}/projects/{projectId}/environments forwarding", () => { + it("forwards GET with query params to PROJECTS_WORKER", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher( + Response.json({ data: { environments: [] }, meta: { requestId: "req_test", cursor: null } }), + ); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456/environments?limit=10&cursor=abc", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456/environments", + ); + + expect(response.status).toBe(200); + expect(projectsCalls).toHaveLength(1); + expect(projectsCalls[0]!.url).toContain("/v1/organizations/org_abc123/projects/prj_def456/environments"); + expect(projectsCalls[0]!.url).toContain("limit=10"); + expect(projectsCalls[0]!.url).toContain("cursor=abc"); + expect(projectsCalls[0]!.init.method).toBe("GET"); + }); + }); + + describe("GET /v1/organizations/{orgId}/projects/{projectId}/environments/{envId} forwarding", () => { + it("forwards GET to PROJECTS_WORKER with actor headers", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456/environments/env_ghi789", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456/environments/env_ghi789", + ); + + expect(response.status).toBe(200); + expect(projectsCalls).toHaveLength(1); + expect(projectsCalls[0]!.url).toContain("/v1/organizations/org_abc123/projects/prj_def456/environments/env_ghi789"); + expect(projectsCalls[0]!.init.method).toBe("GET"); + + const forwarded = new Headers(projectsCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("x-actor-subject-id")).toBe("usr_abc123"); + expect(forwarded.get("authorization")).toBeNull(); + }); + }); + + describe("environment route method restrictions", () => { + it("returns 405 for DELETE on environments collection", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456/environments", { + method: "DELETE", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456/environments", + ); + + expect(response.status).toBe(405); + }); + + it("returns 405 for PATCH on environment item", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456/environments/env_ghi789", { + method: "PATCH", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456/environments/env_ghi789", + ); + + expect(response.status).toBe(405); + }); + + it("forwards DELETE on environment item to PROJECTS_WORKER", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456/environments/env_ghi789", { + method: "DELETE", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456/environments/env_ghi789", + ); + + expect(response.status).toBe(200); + expect(projectsCalls).toHaveLength(1); + expect(projectsCalls[0]!.init.method).toBe("DELETE"); + }); + + it("does not forward bearer token for DELETE on environment item", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456/environments/env_ghi789", { + method: "DELETE", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456/environments/env_ghi789", + ); + + const forwarded = new Headers(projectsCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("authorization")).toBeNull(); + const rawCall = JSON.stringify(projectsCalls[0]); + expect(rawCall).not.toContain("sps_ses_abc"); + }); + + it("does not forward body for DELETE on environment item", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456/environments/env_ghi789", { + method: "DELETE", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456/environments/env_ghi789", + ); + + expect(projectsCalls[0]!.init.body).toBeUndefined(); + }); + + it("forwards actor and request headers for DELETE on environment item", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456/environments/env_ghi789", { + method: "DELETE", + headers: { + authorization: "Bearer sps_ses_abc.secret", + traceparent: "00-trace-id", + "idempotency-key": "idem_123", + }, + }); + + await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456/environments/env_ghi789", + ); + + const forwarded = new Headers(projectsCalls[0]!.init.headers as HeadersInit); + expect(forwarded.get("x-actor-subject-id")).toBe("usr_abc123"); + expect(forwarded.get("x-actor-subject-type")).toBe("user"); + expect(forwarded.get("x-request-id")).toBe("req_test"); + expect(forwarded.get("traceparent")).toBe("00-trace-id"); + expect(forwarded.get("idempotency-key")).toBe("idem_123"); + }); + + it("returns 503 when PROJECTS_WORKER is missing for DELETE on environment item", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456/environments/env_ghi789", { + method: "DELETE", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456/environments/env_ghi789", + ); + + expect(response.status).toBe(503); + }); + + it("preserves existing GET behavior for environment item route", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456/environments/env_ghi789", { + method: "GET", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456/environments/env_ghi789", + ); + + expect(response.status).toBe(200); + expect(projectsCalls).toHaveLength(1); + expect(projectsCalls[0]!.init.method).toBe("GET"); + }); + + it("returns 503 when PROJECTS_WORKER is missing for environment route", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456/environments", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ name: "Test" }), + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456/environments", + ); + + expect(response.status).toBe(503); + const json = await response.json() as any; + expect(json.error.message).toBe("Projects service unavailable"); + }); + }); + + describe("existing project routes still work", () => { + it("POST projects collection still forwards correctly", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher( + Response.json({ data: { project: { id: "prj_abc" } }, meta: { requestId: "req_test", cursor: null } }, { status: 201 }), + ); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects", { + method: "POST", + headers: { authorization: "Bearer sps_ses_abc.secret", "content-type": "application/json" }, + body: JSON.stringify({ name: "My Project" }), + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects", + ); + + expect(response.status).toBe(201); + expect(projectsCalls).toHaveLength(1); + }); + + it("DELETE project item still forwards correctly", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: projectsFetcher, calls: projectsCalls } = createFakeFetcher(); + + const request = new Request("https://api.example.com/v1/organizations/org_abc123/projects/prj_def456", { + method: "DELETE", + headers: { authorization: "Bearer sps_ses_abc.secret" }, + }); + + const response = await handleProjectRoute( + request, + { IDENTITY_WORKER: identityFetcher, PROJECTS_WORKER: projectsFetcher, ENVIRONMENT: "test" }, + "req_test", + "/v1/organizations/org_abc123/projects/prj_def456", + ); + + expect(response.status).toBe(200); + expect(projectsCalls).toHaveLength(1); + expect(projectsCalls[0]!.init.method).toBe("DELETE"); + }); + }); + + describe("binding verification config", () => { + it("wrangler.jsonc has stage PROJECTS_WORKER binding to new-test-projects-worker-stage", () => { + const configPath = resolve(__dirname, "../../../apps/api-edge/wrangler.jsonc"); + const raw = readFileSync(configPath, "utf-8"); + const config = JSON.parse(stripJsoncComments(raw)); + + const stageServices = config.env?.stage?.services; + expect(stageServices).toBeDefined(); + const projects = stageServices.find((s: any) => s.binding === "PROJECTS_WORKER"); + expect(projects).toBeDefined(); + expect(projects.service).toBe("new-test-projects-worker-stage"); + }); + + it("wrangler.jsonc has prod PROJECTS_WORKER binding to new-test-projects-worker-prod", () => { + const configPath = resolve(__dirname, "../../../apps/api-edge/wrangler.jsonc"); + const raw = readFileSync(configPath, "utf-8"); + const config = JSON.parse(stripJsoncComments(raw)); + + const prodServices = config.env?.prod?.services; + expect(prodServices).toBeDefined(); + const projects = prodServices.find((s: any) => s.binding === "PROJECTS_WORKER"); + expect(projects).toBeDefined(); + expect(projects.service).toBe("new-test-projects-worker-prod"); + }); + + it("stage does not bind to prod projects worker", () => { + const configPath = resolve(__dirname, "../../../apps/api-edge/wrangler.jsonc"); + const raw = readFileSync(configPath, "utf-8"); + const config = JSON.parse(stripJsoncComments(raw)); + + const stageServices = config.env?.stage?.services ?? []; + const projectsBindings = stageServices.filter((s: any) => s.binding === "PROJECTS_WORKER"); + for (const svc of projectsBindings) { + expect(svc.service).not.toContain("prod"); + } + }); + + it("prod does not bind to stage projects worker", () => { + const configPath = resolve(__dirname, "../../../apps/api-edge/wrangler.jsonc"); + const raw = readFileSync(configPath, "utf-8"); + const config = JSON.parse(stripJsoncComments(raw)); + + const prodServices = config.env?.prod?.services ?? []; + const projectsBindings = prodServices.filter((s: any) => s.binding === "PROJECTS_WORKER"); + for (const svc of projectsBindings) { + expect(svc.service).not.toContain("stage"); + } + }); + }); +}); diff --git a/tests/api-edge/src/rate-limit-do.test.ts b/tests/api-edge/src/rate-limit-do.test.ts new file mode 100644 index 0000000..0a9c182 --- /dev/null +++ b/tests/api-edge/src/rate-limit-do.test.ts @@ -0,0 +1,241 @@ +// PERF5 Stage B — Durable Object rate-limiter tests. +// +// Asserts: +// - the DO token bucket allows up to the limit then denies (atomic, in-memory) +// - enforceRateLimit PREFERS the DO for unsafe methods and does NOT touch KV +// - a DO failure fails open (admit), same contract as the KV path +// - when no DO binding is present, the limiter falls back to the KV path +// - safe (read) methods never call the DO (in-isolate path, Stage A) + +import { RateLimiterDO } from "@api-edge/rate-limit-do"; +import { + enforceRateLimit, + __rateLimitConfigForTest, + __resetRateLimitMemoryForTest, +} from "@api-edge/rate-limit"; +import type { Env } from "@api-edge/env"; + +// --- Fakes --------------------------------------------------------------- + +interface FakeKv { + binding: KVNamespace; + store: Map; +} +function createFakeKv(): FakeKv { + const store = new Map(); + const binding = { + get: (k: string) => Promise.resolve(store.get(k) ?? null), + put: (k: string, v: string) => { + store.set(k, v); + return Promise.resolve(); + }, + delete: (k: string) => { + store.delete(k); + return Promise.resolve(); + }, + } as unknown as KVNamespace; + return { binding, store }; +} + +/** Routes idFromName→get→fetch to a per-key in-memory RateLimiterDO instance. */ +function createFakeRateLimiterNamespace(opts?: { throwOnFetch?: boolean }): { + ns: DurableObjectNamespace; + fetchedKeys: string[]; +} { + const instances = new Map(); + const fetchedKeys: string[] = []; + const ns = { + idFromName(name: string) { + return { __key: name } as unknown as DurableObjectId; + }, + get(id: unknown) { + const key = (id as { __key: string }).__key; + return { + async fetch(input: RequestInfo, init?: RequestInit) { + fetchedKeys.push(key); + if (opts?.throwOnFetch) throw new Error("DO unavailable"); + let inst = instances.get(key); + if (!inst) { + inst = new RateLimiterDO({} as DurableObjectState, {}); + instances.set(key, inst); + } + return inst.fetch(new Request(input as string, init)); + }, + } as unknown as DurableObjectStub; + }, + } as unknown as DurableObjectNamespace; + return { ns, fetchedKeys }; +} + +function makeEnv(opts: { kv?: KVNamespace; ratelimiterDo?: DurableObjectNamespace }): Env { + return { + IDEMPOTENCY_KV: opts.kv, + RATE_LIMITER_DO: opts.ratelimiterDo, + ENVIRONMENT: "test", + } as Env; +} + +function postOrgReq(org = "org_b"): Request { + return new Request(`https://api.example.com/v1/organizations/${org}/projects`, { + method: "POST", + headers: { "content-type": "application/json", "CF-Connecting-IP": "1.2.3.4" }, + body: "{}", + }); +} + +// --- DO unit ------------------------------------------------------------ + +describe("RateLimiterDO token bucket", () => { + it("allows up to the limit, then denies — atomically in memory", async () => { + const doInst = new RateLimiterDO({} as DurableObjectState, {}); + const limit = 5; + const call = () => + doInst.fetch( + new Request("https://rate-limiter.internal/consume", { + method: "POST", + body: JSON.stringify({ limit, windowSec: 60, scope: "org" }), + }), + ); + + for (let i = 0; i < limit; i++) { + const res = await call(); + const body = (await res.json()) as { allowed: boolean; remaining: number }; + expect(body.allowed).toBe(true); + expect(body.remaining).toBe(limit - 1 - i); + } + const denied = (await (await call()).json()) as { + allowed: boolean; + retryAfterSec: number; + scope: string; + }; + expect(denied.allowed).toBe(false); + expect(denied.retryAfterSec).toBeGreaterThanOrEqual(1); + expect(denied.scope).toBe("org"); + }); + + it("rejects a malformed body with 400", async () => { + const doInst = new RateLimiterDO({} as DurableObjectState, {}); + const res = await doInst.fetch( + new Request("https://rate-limiter.internal/consume", { method: "POST", body: "not-json" }), + ); + expect(res.status).toBe(400); + }); +}); + +// --- enforceRateLimit integration -------------------------------------- + +describe("enforceRateLimit with the Durable Object backend (Stage B)", () => { + beforeEach(() => __resetRateLimitMemoryForTest()); + + it("unsafe POST consumes via the DO and does NOT touch KV", async () => { + const kv = createFakeKv(); + const { ns, fetchedKeys } = createFakeRateLimiterNamespace(); + const result = await enforceRateLimit( + postOrgReq(), + "req_do", + makeEnv({ kv: kv.binding, ratelimiterDo: ns }), + "project", + ); + expect(result.kind).toBe("allowed"); + // Both buckets resolved through the DO... + expect(fetchedKeys.length).toBe(2); + expect(fetchedKeys.some((k) => k.includes(":org:"))).toBe(true); + expect(fetchedKeys.some((k) => k.includes(":identity:"))).toBe(true); + // ...and the KV store was never written (no rl:* keys). + expect([...kv.store.keys()].filter((k) => k.startsWith("rl:v1:"))).toHaveLength(0); + }); + + it("emits both org and identity headers from the DO decisions", async () => { + const { ns } = createFakeRateLimiterNamespace(); + const result = await enforceRateLimit( + postOrgReq(), + "req_h", + makeEnv({ ratelimiterDo: ns }), + "project", + ); + if (result.kind !== "allowed") throw new Error("expected allowed"); + expect(result.headers["X-RateLimit-Limit-org"]).toBe( + String(__rateLimitConfigForTest.project.org.limit), + ); + expect(result.headers["X-RateLimit-Limit-identity"]).toBe( + String(__rateLimitConfigForTest.project.identity.limit), + ); + }); + + it("overflows the org bucket via the DO → 429", async () => { + const { ns } = createFakeRateLimiterNamespace(); + const env = makeEnv({ ratelimiterDo: ns }); + const orgLimit = __rateLimitConfigForTest.project.org.limit; + const idLimit = __rateLimitConfigForTest.project.identity.limit; + const identitiesNeeded = Math.ceil(orgLimit / idLimit) + 1; + let denied: Awaited> | null = null; + for (let i = 0; i < identitiesNeeded && !denied; i++) { + for (let j = 0; j < idLimit; j++) { + const r = new Request("https://api.example.com/v1/organizations/org_OF/projects", { + method: "POST", + headers: { "content-type": "application/json", authorization: `Bearer tok_${i}` }, + body: "{}", + }); + const res = await enforceRateLimit(r, `r_${i}_${j}`, env, "project"); + if (res.kind === "denied") { + denied = res; + break; + } + } + } + expect(denied?.kind).toBe("denied"); + if (denied?.kind === "denied") { + const body = (await denied.response.json()) as { error: { details: { scope: string } } }; + expect(body.error.details.scope).toBe("org"); + } + }); + + it("a DO failure fails open (admit), like the KV path", async () => { + const { ns } = createFakeRateLimiterNamespace({ throwOnFetch: true }); + const original = console.warn; + let warned = false; + console.warn = () => { + warned = true; + }; + const result = await enforceRateLimit( + postOrgReq(), + "req_fail", + makeEnv({ ratelimiterDo: ns }), + "project", + ); + console.warn = original; + expect(result.kind).toBe("allowed"); + expect(warned).toBe(true); + }); + + it("falls back to the KV path when no DO binding is present", async () => { + const kv = createFakeKv(); + const result = await enforceRateLimit( + postOrgReq(), + "req_fallback", + makeEnv({ kv: kv.binding }), + "project", + ); + expect(result.kind).toBe("allowed"); + // KV path persisted both rl:* buckets. + expect([...kv.store.keys()].filter((k) => k.startsWith("rl:v1:"))).toHaveLength(2); + }); + + it("safe (read) GET never calls the DO and never touches KV", async () => { + const kv = createFakeKv(); + const { ns, fetchedKeys } = createFakeRateLimiterNamespace(); + const req = new Request("https://api.example.com/v1/organizations/org_r/projects", { + method: "GET", + headers: { authorization: "Bearer tok_read" }, + }); + const result = await enforceRateLimit( + req, + "req_read", + makeEnv({ kv: kv.binding, ratelimiterDo: ns }), + "project", + ); + expect(result.kind).toBe("allowed"); + expect(fetchedKeys).toHaveLength(0); + expect(kv.store.size).toBe(0); + }); +}); diff --git a/tests/api-edge/src/rate-limit.test.ts b/tests/api-edge/src/rate-limit.test.ts new file mode 100644 index 0000000..d541c26 --- /dev/null +++ b/tests/api-edge/src/rate-limit.test.ts @@ -0,0 +1,612 @@ +// Edge-side rate-limit tests (Task 0097). +// +// Asserts: +// - under-limit allows the request and emits X-RateLimit-* headers +// - identity bucket overflow returns 429 with envelope and Retry-After +// - org bucket overflow returns 429 with envelope and Retry-After +// - anon traffic limited by IP (CF-Connecting-IP) +// - separate IPs do NOT share the same bucket +// - missing IDEMPOTENCY_KV binding → fail open (admit, no headers) +// - KV get failure → fail open +// - KV put failure → fail open +// - refill correctness across simulated time +// - key isolation across orgs / identities / route families +// - rate-limit fires BEFORE replayOrExecute KV touch (denied request never +// reaches the idempotency cache) + +import { handleAuthRoute } from "@api-edge/auth-facade"; +import { + enforceRateLimit, + __rateLimitConfigForTest, + __resetRateLimitMemoryForTest, + type RouteFamily, +} from "@api-edge/rate-limit"; +import type { Env } from "@api-edge/env"; + +interface FakeKv { + binding: KVNamespace; + store: Map; + getThrows: { value: boolean }; + putThrows: { value: boolean }; +} + +function createFakeKv(): FakeKv { + const store = new Map(); + const getThrows = { value: false }; + const putThrows = { value: false }; + const binding = { + get(key: string): Promise { + if (getThrows.value) return Promise.reject(new Error("kv get fail")); + return Promise.resolve(store.get(key) ?? null); + }, + put(key: string, value: string): Promise { + if (putThrows.value) return Promise.reject(new Error("kv put fail")); + store.set(key, value); + return Promise.resolve(); + }, + delete(key: string): Promise { + store.delete(key); + return Promise.resolve(); + }, + list(): Promise<{ keys: { name: string }[]; list_complete: true; cacheStatus: null }> { + return Promise.resolve({ keys: [], list_complete: true, cacheStatus: null }); + }, + } as unknown as KVNamespace; + return { binding, store, getThrows, putThrows }; +} + +function makeEnv(kv?: KVNamespace): Env { + return { + IDEMPOTENCY_KV: kv, + ENVIRONMENT: "test", + } as Env; +} + +function makeRequest(opts: { + url?: string; + method?: string; + ip?: string; + bearer?: string; +}): Request { + const headers: Record = {}; + if (opts.ip) headers["CF-Connecting-IP"] = opts.ip; + if (opts.bearer) headers["authorization"] = `Bearer ${opts.bearer}`; + const method = opts.method ?? "POST"; + const url = opts.url ?? "https://api.example.com/v1/auth/login/start"; + if (method === "POST" || method === "PATCH" || method === "PUT") { + return new Request(url, { method, headers, body: "{}" }); + } + return new Request(url, { method, headers }); +} + +describe("api-edge rate limiter (Task 0097)", () => { + describe("config sanity", () => { + it("auth family is the tightest identity bucket", () => { + expect(__rateLimitConfigForTest.auth.identity.limit).toBeLessThan( + __rateLimitConfigForTest.org.identity.limit, + ); + }); + + it("every family has both org and identity limits > 0", () => { + const families: RouteFamily[] = [ + "auth", + "org", + "project", + "config", + "webhooks", + "metering", + "billing", + "audit", + ]; + for (const f of families) { + expect(__rateLimitConfigForTest[f].org.limit).toBeGreaterThan(0); + expect(__rateLimitConfigForTest[f].identity.limit).toBeGreaterThan(0); + } + }); + }); + + describe("under-limit allows + emits headers", () => { + it("allowed result carries X-RateLimit-Limit/Remaining/Reset for active scopes", async () => { + const kv = createFakeKv(); + const result = await enforceRateLimit( + makeRequest({ ip: "1.2.3.4" }), + "req_a", + makeEnv(kv.binding), + "auth", + ); + expect(result.kind).toBe("allowed"); + if (result.kind !== "allowed") return; + expect(result.headers["X-RateLimit-Limit-identity"]).toBe( + String(__rateLimitConfigForTest.auth.identity.limit), + ); + // remaining is limit-1 since one token was consumed + expect(Number(result.headers["X-RateLimit-Remaining-identity"])).toBe( + __rateLimitConfigForTest.auth.identity.limit - 1, + ); + expect(Number(result.headers["X-RateLimit-Reset-identity"])).toBeGreaterThan(0); + // No org segment in URL → no org headers. + expect(result.headers["X-RateLimit-Limit-org"]).toBeUndefined(); + }); + + it("org-scoped path emits both org and identity headers", async () => { + const kv = createFakeKv(); + const result = await enforceRateLimit( + makeRequest({ + url: "https://api.example.com/v1/organizations/org_abc/projects", + bearer: "tok_x", + }), + "req_a", + makeEnv(kv.binding), + "project", + ); + expect(result.kind).toBe("allowed"); + if (result.kind !== "allowed") return; + expect(result.headers["X-RateLimit-Limit-org"]).toBeDefined(); + expect(result.headers["X-RateLimit-Limit-identity"]).toBeDefined(); + }); + }); + + describe("identity overflow", () => { + it("returns 429 with rate_limited envelope and Retry-After once limit hit", async () => { + const kv = createFakeKv(); + const env = makeEnv(kv.binding); + const limit = __rateLimitConfigForTest.auth.identity.limit; + + // Exhaust the bucket. + for (let i = 0; i < limit; i++) { + const r = await enforceRateLimit( + makeRequest({ ip: "9.9.9.9" }), + `req_${i}`, + env, + "auth", + ); + expect(r.kind).toBe("allowed"); + } + + // (limit+1)th request → denied. + const denied = await enforceRateLimit( + makeRequest({ ip: "9.9.9.9" }), + "req_overflow", + env, + "auth", + ); + expect(denied.kind).toBe("denied"); + if (denied.kind !== "denied") return; + expect(denied.response.status).toBe(429); + const retryAfter = denied.response.headers.get("Retry-After"); + expect(retryAfter).not.toBeNull(); + expect(Number(retryAfter)).toBeGreaterThanOrEqual(1); + expect(denied.response.headers.get("X-RateLimit-Remaining-identity")).toBe("0"); + + const body = (await denied.response.json()) as { + error: { code: string; details: { scope: string; retryAfterSeconds: number } }; + }; + expect(body.error.code).toBe("rate_limited"); + expect(body.error.details.scope).toBe("identity"); + expect(body.error.details.retryAfterSeconds).toBeGreaterThanOrEqual(1); + }); + }); + + describe("org overflow", () => { + it("two different identities under the same org hit the org bucket", async () => { + const kv = createFakeKv(); + const env = makeEnv(kv.binding); + // Use the audit family — its identity cap (120) is well above the + // org cap we'll trigger if we keep alternating identities. Actually + // we want the OPPOSITE: identity cap high, org cap low. Use a + // synthetic family with mismatched caps via the project family — + // identity 60, org 300. We'd need to drive 300 reqs to exceed org. + // Instead drive via a single identity past org cap by interleaving + // identities so per-identity stays under 60. + const orgLimit = __rateLimitConfigForTest.project.org.limit; + // We'll alternate across many identities so identity bucket never + // overflows. Each identity does at most `identityLimit`. + const idLimit = __rateLimitConfigForTest.project.identity.limit; + const identitiesNeeded = Math.ceil(orgLimit / idLimit) + 1; + let consumed = 0; + let overflow: Awaited> | null = null; + for (let i = 0; i < identitiesNeeded && !overflow; i++) { + for (let j = 0; j < idLimit; j++) { + const r = await enforceRateLimit( + makeRequest({ + url: "https://api.example.com/v1/organizations/org_X/projects", + bearer: `tok_user_${i}`, + }), + `req_${i}_${j}`, + env, + "project", + ); + consumed++; + if (r.kind === "denied") { + overflow = r; + break; + } + } + } + expect(overflow).not.toBeNull(); + if (!overflow || overflow.kind !== "denied") return; + const body = (await overflow.response.json()) as { + error: { details: { scope: string } }; + }; + expect(body.error.details.scope).toBe("org"); + expect(consumed).toBeGreaterThan(orgLimit); + }); + }); + + describe("anon traffic limited by IP", () => { + it("same IP exhausts anon bucket", async () => { + const kv = createFakeKv(); + const env = makeEnv(kv.binding); + const limit = __rateLimitConfigForTest.auth.identity.limit; + for (let i = 0; i < limit; i++) { + const r = await enforceRateLimit( + makeRequest({ ip: "5.5.5.5" }), + `req_${i}`, + env, + "auth", + ); + expect(r.kind).toBe("allowed"); + } + const denied = await enforceRateLimit( + makeRequest({ ip: "5.5.5.5" }), + "req_overflow", + env, + "auth", + ); + expect(denied.kind).toBe("denied"); + }); + + it("different IPs do NOT share the same bucket", async () => { + const kv = createFakeKv(); + const env = makeEnv(kv.binding); + const limit = __rateLimitConfigForTest.auth.identity.limit; + for (let i = 0; i < limit; i++) { + await enforceRateLimit(makeRequest({ ip: "1.1.1.1" }), `r${i}`, env, "auth"); + } + const otherIp = await enforceRateLimit( + makeRequest({ ip: "2.2.2.2" }), + "r_other", + env, + "auth", + ); + expect(otherIp.kind).toBe("allowed"); + }); + }); + + describe("fail open", () => { + it("missing IDEMPOTENCY_KV → admits the request with no rate-limit headers", async () => { + const result = await enforceRateLimit( + makeRequest({ ip: "1.2.3.4" }), + "req", + makeEnv(undefined), + "auth", + ); + expect(result.kind).toBe("allowed"); + if (result.kind !== "allowed") return; + expect(Object.keys(result.headers)).toHaveLength(0); + }); + + it("KV get failure → admits the request", async () => { + const kv = createFakeKv(); + kv.getThrows.value = true; + const original = console.warn; + let warned = false; + console.warn = () => { warned = true; }; + const result = await enforceRateLimit( + makeRequest({ ip: "1.2.3.4" }), + "req", + makeEnv(kv.binding), + "auth", + ); + console.warn = original; + expect(result.kind).toBe("allowed"); + expect(warned).toBe(true); + }); + + it("KV put failure → admits the request", async () => { + const kv = createFakeKv(); + kv.putThrows.value = true; + const original = console.warn; + let warned = false; + console.warn = () => { warned = true; }; + const result = await enforceRateLimit( + makeRequest({ ip: "1.2.3.4" }), + "req", + makeEnv(kv.binding), + "auth", + ); + console.warn = original; + expect(result.kind).toBe("allowed"); + expect(warned).toBe(true); + }); + }); + + describe("refill correctness across simulated time", () => { + it("after window elapses, bucket refills to capacity", async () => { + const kv = createFakeKv(); + const env = makeEnv(kv.binding); + const limit = __rateLimitConfigForTest.auth.identity.limit; + const window = __rateLimitConfigForTest.auth.identity.windowSec; + + // Exhaust. + for (let i = 0; i < limit; i++) { + await enforceRateLimit(makeRequest({ ip: "7.7.7.7" }), `r${i}`, env, "auth"); + } + // Mutate stored refilledAt to far past so the next call sees full refill. + const key = [...kv.store.keys()].find((k) => k.includes("identity")); + expect(key).toBeDefined(); + const parsed = JSON.parse(kv.store.get(key!)!) as { t: number; r: number }; + parsed.r = parsed.r - window - 1; + kv.store.set(key!, JSON.stringify(parsed)); + + const after = await enforceRateLimit( + makeRequest({ ip: "7.7.7.7" }), + "r_after", + env, + "auth", + ); + expect(after.kind).toBe("allowed"); + }); + }); + + describe("key isolation", () => { + it("different orgs do NOT share the same org bucket", async () => { + const kv = createFakeKv(); + const env = makeEnv(kv.binding); + const orgLimit = __rateLimitConfigForTest.project.org.limit; + // Exhaust orgA (using many identities so identity cap doesn't fire). + const idLimit = __rateLimitConfigForTest.project.identity.limit; + const identitiesNeeded = Math.ceil(orgLimit / idLimit) + 1; + let exhausted = false; + for (let i = 0; i < identitiesNeeded && !exhausted; i++) { + for (let j = 0; j < idLimit; j++) { + const r = await enforceRateLimit( + makeRequest({ + url: "https://api.example.com/v1/organizations/org_A/projects", + bearer: `tA_${i}`, + }), + `r_${i}_${j}`, + env, + "project", + ); + if (r.kind === "denied") { + exhausted = true; + break; + } + } + } + expect(exhausted).toBe(true); + + // org_B is unaffected. + const otherOrg = await enforceRateLimit( + makeRequest({ + url: "https://api.example.com/v1/organizations/org_B/projects", + bearer: "tB", + }), + "r_other_org", + env, + "project", + ); + expect(otherOrg.kind).toBe("allowed"); + }); + + it("different route families do NOT share the same identity bucket", async () => { + const kv = createFakeKv(); + const env = makeEnv(kv.binding); + const limit = __rateLimitConfigForTest.auth.identity.limit; + + for (let i = 0; i < limit; i++) { + await enforceRateLimit( + makeRequest({ ip: "8.8.8.8" }), + `r${i}`, + env, + "auth", + ); + } + const otherFamily = await enforceRateLimit( + makeRequest({ ip: "8.8.8.8" }), + "r_billing", + env, + "billing", + ); + expect(otherFamily.kind).toBe("allowed"); + }); + }); + + describe("safe (read) methods use the in-isolate limiter (PERF5 Stage A)", () => { + beforeEach(() => { + __resetRateLimitMemoryForTest(); + }); + + it("a GET does NOT touch KV but is still allowed and emits headers", async () => { + const kv = createFakeKv(); + const result = await enforceRateLimit( + makeRequest({ + url: "https://api.example.com/v1/organizations/org_read/projects", + method: "GET", + bearer: "tok_read", + }), + "req_get", + makeEnv(kv.binding), + "project", + ); + expect(result.kind).toBe("allowed"); + if (result.kind !== "allowed") return; + // No rl:* (or any) key was written to KV — the read path is I/O-free. + expect(kv.store.size).toBe(0); + // Both scopes still reported. + expect(result.headers["X-RateLimit-Limit-org"]).toBeDefined(); + expect(result.headers["X-RateLimit-Limit-identity"]).toBeDefined(); + }); + + it("reads are limited WITHOUT a KV binding (in-memory needs no backend)", async () => { + const result = await enforceRateLimit( + makeRequest({ url: "https://api.example.com/v1/auth/session", method: "GET", ip: "3.3.3.3" }), + "req_get_nokv", + makeEnv(undefined), + "auth", + ); + expect(result.kind).toBe("allowed"); + if (result.kind !== "allowed") return; + // Unlike the unsafe-method no-KV path (admit, no headers), reads still get + // real headers from the in-isolate bucket. + expect(result.headers["X-RateLimit-Limit-identity"]).toBe( + String(__rateLimitConfigForTest.auth.identity.limit), + ); + }); + + it("a GET flood overflows the in-isolate identity bucket → 429", async () => { + const env = makeEnv(createFakeKv().binding); + const limit = __rateLimitConfigForTest.auth.identity.limit; + for (let i = 0; i < limit; i++) { + const r = await enforceRateLimit( + makeRequest({ url: "https://api.example.com/v1/auth/session", method: "GET", ip: "4.4.4.4" }), + `r${i}`, + env, + "auth", + ); + expect(r.kind).toBe("allowed"); + } + const denied = await enforceRateLimit( + makeRequest({ url: "https://api.example.com/v1/auth/session", method: "GET", ip: "4.4.4.4" }), + "r_overflow", + env, + "auth", + ); + expect(denied.kind).toBe("denied"); + if (denied.kind !== "denied") return; + expect(denied.response.status).toBe(429); + // Still no KV writes for the read path even at overflow. + // (env's KV store was created fresh and never used by the read path.) + }); + + it("different IPs do NOT share the in-isolate read bucket", async () => { + const env = makeEnv(undefined); + const limit = __rateLimitConfigForTest.auth.identity.limit; + for (let i = 0; i < limit; i++) { + await enforceRateLimit( + makeRequest({ url: "https://api.example.com/v1/auth/session", method: "GET", ip: "4.4.4.4" }), + `r${i}`, + env, + "auth", + ); + } + const other = await enforceRateLimit( + makeRequest({ url: "https://api.example.com/v1/auth/session", method: "GET", ip: "5.6.7.8" }), + "r_other", + env, + "auth", + ); + expect(other.kind).toBe("allowed"); + }); + }); + + describe("unsafe methods still use the durable KV limiter", () => { + it("a POST writes rl:* bucket state to KV", async () => { + const kv = createFakeKv(); + const result = await enforceRateLimit( + makeRequest({ + url: "https://api.example.com/v1/organizations/org_w/projects", + method: "POST", + bearer: "tok_w", + }), + "req_post", + makeEnv(kv.binding), + "project", + ); + expect(result.kind).toBe("allowed"); + const rlKeys = [...kv.store.keys()].filter((k) => k.startsWith("rl:v1:")); + // org + identity buckets both persisted. + expect(rlKeys.length).toBe(2); + }); + }); + + describe("integration via handleAuthRoute (replayOrExecute chokepoint)", () => { + it("under-limit POST: response carries rate-limit headers", async () => { + const kv = createFakeKv(); + const fetcher = { + fetch(): Promise { + return Promise.resolve( + Response.json({ + data: { ok: true }, + meta: { requestId: "req_inner", cursor: null }, + }), + ); + }, + connect() { + throw new Error("not used"); + }, + } as unknown as Fetcher; + const env = { + IDENTITY_WORKER: fetcher, + IDEMPOTENCY_KV: kv.binding, + ENVIRONMENT: "test", + } as Env; + const req = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { + "content-type": "application/json", + "CF-Connecting-IP": "10.10.10.10", + }, + body: '{"email":"u@test.com"}', + }); + + const response = await handleAuthRoute(req, env, "req_test", "/v1/auth/login/start"); + expect(response.status).toBe(200); + expect(response.headers.get("X-RateLimit-Limit-identity")).toBe( + String(__rateLimitConfigForTest.auth.identity.limit), + ); + }); + + it("denied request short-circuits before idempotency KV is touched", async () => { + const kv = createFakeKv(); + const env = makeEnv(kv.binding); + const limit = __rateLimitConfigForTest.auth.identity.limit; + // Drain bucket via direct calls. + for (let i = 0; i < limit; i++) { + await enforceRateLimit( + makeRequest({ ip: "11.11.11.11" }), + `r${i}`, + env, + "auth", + ); + } + // The rl bucket has its own put calls; clear store of `idem:` keys. + const fetcher = { + fetch(): Promise { + return Promise.resolve(Response.json({ data: { ok: true } })); + }, + connect() { + throw new Error("not used"); + }, + } as unknown as Fetcher; + const idemKeysBefore = [...kv.store.keys()].filter((k) => + k.startsWith("idem:"), + ); + expect(idemKeysBefore).toHaveLength(0); + + const VALID_KEY = "550e8400-e29b-41d4-a716-446655440000"; + const req = new Request("https://api.example.com/v1/auth/login/start", { + method: "POST", + headers: { + "content-type": "application/json", + "CF-Connecting-IP": "11.11.11.11", + "idempotency-key": VALID_KEY, + }, + body: '{"email":"u@test.com"}', + }); + const fullEnv = { + IDENTITY_WORKER: fetcher, + IDEMPOTENCY_KV: kv.binding, + ENVIRONMENT: "test", + } as Env; + const response = await handleAuthRoute(req, fullEnv, "req_test", "/v1/auth/login/start"); + expect(response.status).toBe(429); + // No idem:* key was ever written by replayOrExecute. + const idemKeysAfter = [...kv.store.keys()].filter((k) => + k.startsWith("idem:"), + ); + expect(idemKeysAfter).toHaveLength(0); + }); + }); +}); diff --git a/tests/api-edge/src/resolve-actor.test.ts b/tests/api-edge/src/resolve-actor.test.ts new file mode 100644 index 0000000..c3d077d --- /dev/null +++ b/tests/api-edge/src/resolve-actor.test.ts @@ -0,0 +1,134 @@ +import { resolveActor, type ActorInfo, type ActorFailure } from "@api-edge/resolve-actor"; +import { hashToken, noopStore, type ActorCacheStore } from "@api-edge/actor-cache"; +import type { Env } from "@api-edge/env"; + +// In-memory cache store keyed by token (for asserting hit/miss/evict logic). +function memStore(): ActorCacheStore & { size: () => number } { + const m = new Map(); + return { + async get(token) { + return m.get(token) ?? null; + }, + async set(token, actor) { + m.set(token, actor); + }, + async evict(token) { + m.delete(token); + }, + size: () => m.size, + }; +} + +// Counting identity-worker fetcher. +function identityFetcher(opts: { ok?: boolean; actorId?: string } = {}) { + let calls = 0; + const fetcher = { + fetch: async () => { + calls += 1; + if (opts.ok === false) { + return new Response(JSON.stringify({ error: { code: "unauthenticated" } }), { status: 401 }); + } + return new Response( + JSON.stringify({ + data: { + actor: { actorType: "user", actorId: opts.actorId ?? "usr_abc", orgId: "org_1" }, + user: { id: opts.actorId ?? "usr_abc", email: "a@x.io" }, + }, + }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + }, + } as unknown as Fetcher; + return { fetcher, calls: () => calls }; +} + +function req(token: string | null): Request { + const headers = new Headers(); + if (token) headers.set("authorization", `Bearer ${token}`); + return new Request("https://edge.test/v1/organizations", { headers }); +} +const isActor = (r: ActorInfo | ActorFailure): r is ActorInfo => !("error" in r); + +describe("resolveActor bearer cache (PERF2)", () => { + it("resolves via identity on a cold miss and caches the result", async () => { + const { fetcher, calls } = identityFetcher(); + const cache = memStore(); + const env = { IDENTITY_WORKER: fetcher } as unknown as Env; + const r = await resolveActor(req("tok_1"), env, "req_1", { cache }); + expect(isActor(r)).toBe(true); + if (isActor(r)) expect(r.subjectId).toBe("usr_abc"); + expect(calls()).toBe(1); + expect(cache.size()).toBe(1); + }); + + it("serves a warm hit WITHOUT calling identity again", async () => { + const { fetcher, calls } = identityFetcher(); + const cache = memStore(); + const env = { IDENTITY_WORKER: fetcher } as unknown as Env; + await resolveActor(req("tok_1"), env, "req_1", { cache }); + const r2 = await resolveActor(req("tok_1"), env, "req_2", { cache }); + expect(isActor(r2)).toBe(true); + expect(calls()).toBe(1); // identity hit only once + }); + + it("does NOT cache a denied resolution (re-hits identity next time)", async () => { + const { fetcher, calls } = identityFetcher({ ok: false }); + const cache = memStore(); + const env = { IDENTITY_WORKER: fetcher } as unknown as Env; + const r = await resolveActor(req("bad"), env, "req_1", { cache }); + expect(isActor(r)).toBe(false); + expect(cache.size()).toBe(0); + await resolveActor(req("bad"), env, "req_2", { cache }); + expect(calls()).toBe(2); // not served from cache + }); + + it("re-resolves after eviction (logout)", async () => { + const { fetcher, calls } = identityFetcher(); + const cache = memStore(); + const env = { IDENTITY_WORKER: fetcher } as unknown as Env; + await resolveActor(req("tok_1"), env, "req_1", { cache }); + await cache.evict("tok_1"); + await resolveActor(req("tok_1"), env, "req_2", { cache }); + expect(calls()).toBe(2); + }); + + it("keeps tokens isolated — a different token is a separate cache entry", async () => { + const { fetcher, calls } = identityFetcher(); + const cache = memStore(); + const env = { IDENTITY_WORKER: fetcher } as unknown as Env; + await resolveActor(req("tok_a"), env, "r1", { cache }); + await resolveActor(req("tok_b"), env, "r2", { cache }); + expect(calls()).toBe(2); + expect(cache.size()).toBe(2); + }); + + it("rejects a missing/invalid Authorization header before any identity call or cache write", async () => { + const { fetcher, calls } = identityFetcher(); + const cache = memStore(); + const env = { IDENTITY_WORKER: fetcher } as unknown as Env; + const r = await resolveActor(req(null), env, "req_1", { cache }); + expect(isActor(r)).toBe(false); + expect(calls()).toBe(0); + expect(cache.size()).toBe(0); + }); + + it("noopStore never caches (every get misses)", async () => { + const { fetcher, calls } = identityFetcher(); + const env = { IDENTITY_WORKER: fetcher } as unknown as Env; + await resolveActor(req("tok_1"), env, "r1", { cache: noopStore() }); + await resolveActor(req("tok_1"), env, "r2", { cache: noopStore() }); + expect(calls()).toBe(2); + }); +}); + +describe("hashToken", () => { + it("is a deterministic 64-char hex digest and differs per token", async () => { + const a1 = await hashToken("tok_1"); + const a2 = await hashToken("tok_1"); + const b = await hashToken("tok_2"); + expect(a1).toMatch(/^[0-9a-f]{64}$/); + expect(a1).toBe(a2); + expect(a1).not.toBe(b); + expect(a1).not.toContain("tok_1"); // never embeds the raw token + }); +}); diff --git a/tests/api-edge/src/solo-mode.test.ts b/tests/api-edge/src/solo-mode.test.ts new file mode 100644 index 0000000..2575d4e --- /dev/null +++ b/tests/api-edge/src/solo-mode.test.ts @@ -0,0 +1,188 @@ +import worker from "@api-edge/index"; +import { isSoloMode, isSoloSuppressed } from "@api-edge/solo-mode"; + +// ── Fake service bindings (mirrors the other facade tests) ────────────── + +function ok200(body: unknown = { data: {}, meta: { requestId: "req_inner", cursor: null } }): Fetcher { + return { + fetch(): Promise { + return Promise.resolve(Response.json(body)); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; +} + +// IDENTITY_WORKER stub that resolves any bearer token to a user actor, so the +// baseline (SOLO_MODE off) pass-through paths reach their downstream worker. +function sessionFetcher(userId = "usr_abc123"): Fetcher { + return { + fetch(input: string | Request | URL): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + if (url.includes("/v1/auth/resolve")) { + return Promise.resolve( + Response.json({ + data: { + actor: { actorType: "user", actorId: userId, email: "user@test.com" }, + session: { id: "ses_abc" }, + user: { id: userId, email: "user@test.com", displayName: "Test" }, + }, + meta: { requestId: "req_inner", cursor: null }, + }), + ); + } + return Promise.resolve(Response.json({ data: {}, meta: { requestId: "req_inner", cursor: null } })); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; +} + +function makeEnv(soloMode: boolean) { + return { + ENVIRONMENT: "test", + ...(soloMode ? { SOLO_MODE: "true" } : {}), + IDENTITY_WORKER: sessionFetcher(), + MEMBERSHIP_WORKER: ok200(), + PROJECTS_WORKER: ok200(), + EVENTS_WORKER: ok200(), + CONFIG_WORKER: ok200(), + WEBHOOKS_WORKER: ok200(), + METERING_WORKER: ok200(), + BILLING_WORKER: ok200(), + NOTIFICATIONS_WORKER: ok200(), + INTEGRATIONS_WORKER: ok200(), + }; +} + +function req(path: string, method = "GET"): Request { + return new Request(`https://api.test${path}`, { + method, + headers: { authorization: "Bearer tok_test", "x-request-id": "req_test" }, + }); +} + +// ── Pure predicate: isSoloMode ────────────────────────────────────────── + +describe("isSoloMode", () => { + it('is true only for the exact string "true"', () => { + expect(isSoloMode({ SOLO_MODE: "true" } as never)).toBe(true); + expect(isSoloMode({} as never)).toBe(false); + expect(isSoloMode({ SOLO_MODE: "false" } as never)).toBe(false); + expect(isSoloMode({ SOLO_MODE: "1" } as never)).toBe(false); + expect(isSoloMode({ SOLO_MODE: "TRUE" } as never)).toBe(false); + }); +}); + +// ── Pure predicate: isSoloSuppressed (the suppression policy) ──────────── + +describe("isSoloSuppressed — suppressed surfaces", () => { + const suppressed: Array<[string, string]> = [ + ["/v1/organizations/org_x/members", "GET"], + ["/v1/organizations/org_x/members/mbr_y", "DELETE"], + ["/v1/organizations/org_x/invitations", "POST"], + ["/v1/organizations/org_x/invitations/inv_y", "DELETE"], + ["/v1/organizations/org_x/invitations/accept", "POST"], + ["/v1/organizations/org_x/api-keys", "POST"], + ["/v1/organizations/org_x/api-keys/key_y", "DELETE"], + ["/v1/organizations/org_x/projects", "GET"], + ["/v1/organizations/org_x/projects/prj_y", "GET"], + ["/v1/organizations/org_x/projects/prj_y/environments", "GET"], + ["/v1/organizations/org_x/usage", "GET"], + ["/v1/organizations/org_x/usage/summary", "GET"], + ["/v1/organizations/org_x/quotas/check", "POST"], + ["/v1/organizations/org_x/webhooks/ep_y", "GET"], + ["/v1/organizations/org_x/integrations", "GET"], + ["/v1/organizations/org_x/integrations/github", "GET"], + ["/ingress/github/webhook", "POST"], + ]; + it.each(suppressed)("suppresses %s %s", (path, method) => { + expect(isSoloSuppressed(path, method)).toBe(true); + }); +}); + +describe("isSoloSuppressed — kept (single-user) surfaces", () => { + const kept: Array<[string, string]> = [ + ["/v1/organizations", "GET"], // list (resolve the personal org) + ["/v1/organizations/org_x", "GET"], // read the personal org + // Bootstrapping the personal org. The one-org rule is enforced in + // membership-worker (which can count the account's orgs); suppressing the + // verb here also blocked the FIRST org, stranding any account whose + // login-time auto-provisioning didn't land. + ["/v1/organizations", "POST"], + ["/v1/auth/session", "GET"], + ["/v1/auth/login/start", "POST"], + ["/v1/auth/profile", "PATCH"], + ["/v1/organizations/org_x/billing/checkout", "POST"], + ["/v1/organizations/org_x/billing/portal", "POST"], + ["/v1/billing/webhooks/polar", "POST"], // provider webhook ≠ outbound webhooks + ["/v1/organizations/org_x/config/feature-flags", "GET"], + ["/v1/organizations/org_x/config/settings", "GET"], + ["/v1/organizations/org_x/audit", "GET"], // silent audit kept + ["/v1/notifications/preferences", "GET"], + ["/health", "GET"], + ]; + it.each(kept)("keeps %s %s", (path, method) => { + expect(isSoloSuppressed(path, method)).toBe(false); + }); +}); + +// ── Integration: the switch through the worker entrypoint ─────────────── + +describe("worker.fetch with SOLO_MODE on", () => { + const env = makeEnv(true); + + it.each([ + "/v1/organizations/org_x/members", + "/v1/organizations/org_x/projects", + "/v1/organizations/org_x/usage", + "/v1/organizations/org_x/integrations", + "/v1/organizations/org_x/webhooks/ep_1", + ])("404s suppressed route %s", async (path) => { + const res = await worker.fetch(req(path), env as never); + expect(res.status).toBe(404); + }); + + it("keeps org bootstrap reachable (POST /v1/organizations)", async () => { + // The Solo one-org rule is membership-worker's call — the edge must let the + // account's FIRST org through, or an account whose login-time provisioning + // no-oped can never obtain one (the console's onboarding fallback 404s). + const res = await worker.fetch(req("/v1/organizations", "POST"), env as never); + expect(res.status).not.toBe(404); + }); + + it("keeps the personal-org list reachable (GET /v1/organizations)", async () => { + const res = await worker.fetch(req("/v1/organizations"), env as never); + expect(res.status).not.toBe(404); + }); + + it.each([ + "/health", + "/v1/organizations/org_x/billing/summary", + "/v1/organizations/org_x/config/feature-flags", + ])("keeps single-user surface %s reachable", async (path) => { + const res = await worker.fetch(req(path), env as never); + expect(res.status).not.toBe(404); + }); +}); + +describe("worker.fetch with SOLO_MODE off (baseline restored)", () => { + const env = makeEnv(false); + + it.each([ + "/v1/organizations/org_x/members", + "/v1/organizations/org_x/projects", + "/v1/organizations/org_x/usage", + "/v1/organizations/org_x/integrations", + ])("does NOT suppress %s (reaches its facade)", async (path) => { + const res = await worker.fetch(req(path), env as never); + expect(res.status).not.toBe(404); + }); + + it("allows creating an org (POST /v1/organizations) in baseline", async () => { + const res = await worker.fetch(req("/v1/organizations", "POST"), env as never); + expect(res.status).not.toBe(404); + }); +}); diff --git a/tests/api-edge/src/webhooks-facade.test.ts b/tests/api-edge/src/webhooks-facade.test.ts new file mode 100644 index 0000000..3b54ab5 --- /dev/null +++ b/tests/api-edge/src/webhooks-facade.test.ts @@ -0,0 +1,226 @@ +import { isWebhooksRoute, handleWebhooksRoute } from "@api-edge/webhooks-facade"; + +interface FetchCall { + url: string; + init: RequestInit; +} + +function createFakeFetcher( + response: Response = Response.json({ data: { endpoints: [] }, meta: { requestId: "req_test", cursor: null } }), +): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init: init ?? {} }); + return Promise.resolve(response.clone()); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +function createThrowingFetcher(): Fetcher { + return { + fetch(): Promise { + return Promise.reject(new Error("connection refused")); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; +} + +function createSessionFetcher(userId: string): { fetcher: Fetcher; calls: FetchCall[] } { + const calls: FetchCall[] = []; + const fetcher = { + fetch(input: string | Request | URL, init?: RequestInit): Promise { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + calls.push({ url, init: init ?? {} }); + if (url.includes("/v1/auth/resolve")) { + return Promise.resolve( + Response.json({ + data: { actor: { actorType: "user", actorId: userId, email: "user@test.com" }, session: { id: "ses_abc" }, user: { id: userId, email: "user@test.com", displayName: "Test" } }, + meta: { requestId: "req_inner", cursor: null }, + }), + ); + } + return Promise.resolve(Response.json({ data: { endpoints: [] }, meta: { requestId: "req_test", cursor: null } })); + }, + connect() { + throw new Error("not implemented"); + }, + } as unknown as Fetcher; + return { fetcher, calls }; +} + +function createEnv(overrides?: Record) { + const { fetcher: identityFetcher } = createSessionFetcher("usr_abc123"); + const { fetcher: webhooksFetcher } = createFakeFetcher(); + return { + IDENTITY_WORKER: identityFetcher, + WEBHOOKS_WORKER: webhooksFetcher, + CONFIG_WORKER: createFakeFetcher().fetcher, + MEMBERSHIP_WORKER: createFakeFetcher().fetcher, + PROJECTS_WORKER: createFakeFetcher().fetcher, + EVENTS_WORKER: createFakeFetcher().fetcher, + ENVIRONMENT: "test", + ...overrides, + }; +} + +describe("api-edge webhooks facade", () => { + describe("isWebhooksRoute", () => { + it("matches org-scoped webhook endpoints", () => { + expect(isWebhooksRoute("/v1/organizations/org_abc/webhooks/endpoints")).toBe(true); + }); + + it("matches org-scoped webhook endpoint item", () => { + expect(isWebhooksRoute("/v1/organizations/org_abc/webhooks/endpoints/whe_abc123")).toBe(true); + }); + + it("matches org-scoped webhook subscriptions", () => { + expect(isWebhooksRoute("/v1/organizations/org_abc/webhooks/subscriptions")).toBe(true); + }); + + it("matches org-scoped webhook delivery attempts", () => { + expect(isWebhooksRoute("/v1/organizations/org_abc/webhooks/delivery-attempts/whd_abc123")).toBe(true); + }); + + it("matches org-scoped webhook delivery-attempt replay (Task 0126)", () => { + expect(isWebhooksRoute("/v1/organizations/org_abc/webhooks/delivery-attempts/whd_abc123/replay")).toBe(true); + }); + + it("matches project-scoped webhook endpoints", () => { + expect(isWebhooksRoute("/v1/organizations/org_abc/projects/prj_def/webhooks/endpoints")).toBe(true); + }); + + it("matches endpoint disable route", () => { + expect(isWebhooksRoute("/v1/organizations/org_abc/webhooks/endpoints/whe_abc123/disable")).toBe(true); + }); + + it("matches endpoint enable route", () => { + expect(isWebhooksRoute("/v1/organizations/org_abc/webhooks/endpoints/whe_abc123/enable")).toBe(true); + }); + + it("matches endpoint rotate-secret route", () => { + expect(isWebhooksRoute("/v1/organizations/org_abc/webhooks/endpoints/whe_abc123/rotate-secret")).toBe(true); + }); + + it("matches endpoint subscriptions list", () => { + expect(isWebhooksRoute("/v1/organizations/org_abc/webhooks/endpoints/whe_abc123/subscriptions")).toBe(true); + }); + + it("matches endpoint delivery-attempts list", () => { + expect(isWebhooksRoute("/v1/organizations/org_abc/webhooks/endpoints/whe_abc123/delivery-attempts")).toBe(true); + }); + + // Non-matches + it("does not match config routes", () => { + expect(isWebhooksRoute("/v1/organizations/org_abc/config/settings")).toBe(false); + }); + + it("does not match org routes", () => { + expect(isWebhooksRoute("/v1/organizations/org_abc")).toBe(false); + }); + + it("does not match project routes", () => { + expect(isWebhooksRoute("/v1/organizations/org_abc/projects")).toBe(false); + }); + }); + + describe("handleWebhooksRoute", () => { + it("forwards GET to webhooks-worker", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_test"); + const { fetcher: webhooksFetcher, calls: webhooksCalls } = createFakeFetcher(); + const env = createEnv({ + IDENTITY_WORKER: identityFetcher, + WEBHOOKS_WORKER: webhooksFetcher, + }); + const req = new Request("https://api-edge/v1/organizations/org_abc/webhooks/endpoints?limit=10", { + method: "GET", + headers: { authorization: "Bearer tok_test", "x-request-id": "req_fwd" }, + }); + const res = await handleWebhooksRoute(req, env as never, "req_fwd", "/v1/organizations/org_abc/webhooks/endpoints"); + expect(res.status).toBe(200); + expect(webhooksCalls.length).toBe(1); + expect(webhooksCalls[0]!.url).toContain("/v1/organizations/org_abc/webhooks/endpoints?limit=10"); + }); + + it("forwards POST to webhooks-worker (create)", async () => { + const env = createEnv(); + const req = new Request("https://api-edge/v1/organizations/org_abc/webhooks/endpoints", { + method: "POST", + headers: { "content-type": "application/json", authorization: "Bearer tok_test" }, + body: JSON.stringify({ url: "https://example.com/hook", name: "test" }), + }); + const res = await handleWebhooksRoute(req, env as never, "req_test", "/v1/organizations/org_abc/webhooks/endpoints"); + expect([200, 503]).toContain(res.status); + }); + + it("returns 405 for PUT (unsupported method)", async () => { + const env = createEnv(); + const req = new Request("https://api-edge/v1/organizations/org_abc/webhooks/endpoints", { + method: "PUT", + headers: { authorization: "Bearer tok_test" }, + }); + const res = await handleWebhooksRoute(req, env as never, "req_test", "/v1/organizations/org_abc/webhooks/endpoints"); + expect(res.status).toBe(405); + }); + + it("returns 503 when IDENTITY_WORKER is missing", async () => { + const env = createEnv({ IDENTITY_WORKER: undefined }); + const req = new Request("https://api-edge/v1/organizations/org_abc/webhooks/endpoints", { + method: "GET", + headers: { authorization: "Bearer tok_test" }, + }); + const res = await handleWebhooksRoute(req, env as never, "req_test", "/v1/organizations/org_abc/webhooks/endpoints"); + expect(res.status).toBe(503); + }); + + it("returns 503 when WEBHOOKS_WORKER is missing", async () => { + const env = createEnv({ WEBHOOKS_WORKER: undefined }); + const req = new Request("https://api-edge/v1/organizations/org_abc/webhooks/endpoints", { + method: "GET", + headers: { authorization: "Bearer tok_test" }, + }); + const res = await handleWebhooksRoute(req, env as never, "req_test", "/v1/organizations/org_abc/webhooks/endpoints"); + expect(res.status).toBe(503); + }); + + it("returns 503 when WEBHOOKS_WORKER fetch throws", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_test"); + const env = createEnv({ + IDENTITY_WORKER: identityFetcher, + WEBHOOKS_WORKER: createThrowingFetcher(), + }); + const req = new Request("https://api-edge/v1/organizations/org_abc/webhooks/endpoints", { + method: "GET", + headers: { authorization: "Bearer tok_test" }, + }); + const res = await handleWebhooksRoute(req, env as never, "req_test", "/v1/organizations/org_abc/webhooks/endpoints"); + expect(res.status).toBe(503); + }); + + it("injects actor headers when forwarding to webhooks-worker", async () => { + const { fetcher: identityFetcher } = createSessionFetcher("usr_test"); + const { fetcher: webhooksFetcher, calls: webhooksCalls } = createFakeFetcher(); + const env = createEnv({ + IDENTITY_WORKER: identityFetcher, + WEBHOOKS_WORKER: webhooksFetcher, + }); + const req = new Request("https://api-edge/v1/organizations/org_abc/webhooks/endpoints", { + method: "GET", + headers: { authorization: "Bearer tok_test", "x-request-id": "req_actor" }, + }); + await handleWebhooksRoute(req, env as never, "req_actor", "/v1/organizations/org_abc/webhooks/endpoints"); + expect(webhooksCalls.length).toBe(1); + const fwdHeaders = webhooksCalls[0]!.init.headers as Headers; + expect(fwdHeaders.get("x-actor-subject-id")).toBe("usr_test"); + expect(fwdHeaders.get("x-actor-subject-type")).toBe("user"); + expect(fwdHeaders.get("x-request-id")).toBe("req_actor"); + }); + }); +}); diff --git a/tests/api-edge/tsconfig.json b/tests/api-edge/tsconfig.json new file mode 100644 index 0000000..98de508 --- /dev/null +++ b/tests/api-edge/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "types": ["jest", "node", "@cloudflare/workers-types"], + "allowSyntheticDefaultImports": true, + "composite": false, + "incremental": false, + "declaration": false, + "declarationMap": false, + "baseUrl": ".", + "paths": { + "@saas/contracts": ["../../packages/contracts/src/index.ts"], + "@saas/contracts/*": ["../../packages/contracts/src/*.ts"], + "@api-edge/*": ["../../apps/api-edge/src/*.ts"] + } + }, + "include": ["src/**/*.ts", "../../apps/api-edge/src/**/*.ts"], + "exclude": ["node_modules", "dist"] +}