import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import jwt from "jsonwebtoken"; import { app as apiApp, configureApiAppDependenciesForTests, type ApiAppDependencies } from "./app.js"; import { LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS, LOGIN_RATE_LIMIT_IP_ATTEMPTS } from "./auth/login-rate-limit.js"; import { apiSessionStore } from "./auth/session/session-store.js"; import { resetApiRuntimeConfigForTests, setApiRuntimeConfigForTests } from "./config.js"; import { apiLogger } from "./logger.js"; import { resetPublicApiRateLimiterForTests } from "./public-api/auth.js"; import type { ApiConfig } from "@hivegrid/config"; import type { LegacyTenantWithDetails } from "@hivegrid/db/accounts.server"; import type { ExportJobDownloadRecord } from "@hivegrid/db/export-jobs.server"; import { WorkspaceContextRevalidationError, type WorkspaceAuthProviderDto } from "@hivegrid/db/auth-providers.server"; import { WorkspaceInviteError, type WorkspaceInviteCreateResult, type WorkspaceInviteDto } from "@hivegrid/db/workspace-invites.server"; import type { NotificationStreamSnapshot } from "@hivegrid/db/notifications.server"; import { derivePublicApiSecretMetadata } from "@hivegrid/db/public-api.server"; const originalEnv = { ...process.env }; const TEST_JWT_SECRET = "test-jwt-secret"; const TEST_MAILJET_WEBHOOK_SECRET = "test-mailjet-webhook-secret"; const TEST_PRODUCTION_ROUTING: ApiConfig["routing"] = { appBaseDomain: "example.com", webAppHost: "app.example.com", adminAppHost: "admin.example.com", apiHost: "api.example.com", protocol: "https", }; const expectedApiSecurityHeaders = { "x-content-type-options": "nosniff", "referrer-policy": "no-referrer", "x-frame-options": "DENY", "permissions-policy": "camera=(), microphone=(), geolocation=(), payment=()", "cross-origin-opener-policy": "same-origin", "cross-origin-resource-policy": "same-origin", }; const OMIT_TEST_CONTENT_LENGTH = "x-test-omit-content-length"; const app: Pick = { request: ((input, init, ...rest) => apiApp.request(input, addTestContentLength(init), ...rest)) as typeof apiApp.request, }; function addTestContentLength(init: T): T { if (!init?.body) { return init; } const headers = new Headers(init.headers); if (headers.has(OMIT_TEST_CONTENT_LENGTH)) { headers.delete(OMIT_TEST_CONTENT_LENGTH); return { ...init, headers } as T; } if (headers.has("content-length")) { return init; } const length = getTestBodyLength(init.body); if (length === null) { return init; } headers.set("content-length", String(length)); return { ...init, headers } as T; } function getTestBodyLength(body: BodyInit): number | null { if (typeof body === "string") { return Buffer.byteLength(body); } if (body instanceof URLSearchParams) { return Buffer.byteLength(body.toString()); } if (body instanceof Blob) { return body.size; } return null; } function expectApiSecurityHeaders(response: Response) { for (const [header, value] of Object.entries(expectedApiSecurityHeaders)) { expect(response.headers.get(header)).toBe(value); } } type StoredApiKeyFixture = { id: string; alias: string; expires: Date | null; tenantId: string; active: boolean; scopes: unknown; entities: { create: boolean; read: boolean; update: boolean; delete: boolean; entityId: string; }[]; tenant: { id: string; name: string; slug: string; deactivatedReason: string | null }; }; function createStoredApiKeyFixture(patch: Partial = {}): StoredApiKeyFixture { return { id: "api_key_1", alias: "Primary integration key", expires: null, tenantId: "tenant_1", active: true, scopes: ["*"], entities: [], tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null }, ...patch, }; } function createLegacyTenantFixture(patch: Partial = {}): LegacyTenantWithDetails { return { id: "tenant_1", createdAt: new Date("2024-01-01T00:00:00.000Z"), updatedAt: new Date("2024-01-01T00:00:00.000Z"), slug: "acme", name: "Acme", icon: null, logo: null, subscriptionId: null, active: true, deactivatedReason: null, theme: null, themeConfig: null, anrede: null, inboundAddresses: [], users: [], subscription: null, types: [], ...patch, }; } function createWorkspaceInviteFixture(patch: Partial = {}): WorkspaceInviteDto { return { id: "invite_1", tenantId: "tenant_1", email: "member@example.com", firstName: "Member", lastName: "One", type: 1, status: "pending", pending: true, tokenPrefix: "tok_prefix", createdUserId: null, fromUserId: null, acceptedByUserId: null, revokedByUserId: null, expiresAt: new Date("2030-01-01T00:00:00.000Z"), acceptedAt: null, revokedAt: null, ...patch, }; } function createWorkspaceInviteCreateResult(patch: Partial = {}): WorkspaceInviteCreateResult { return { ...createWorkspaceInviteFixture(patch), token: "plain-create-token", ...patch, }; } function createWorkspaceAuthProviderFixture(patch: Partial = {}): WorkspaceAuthProviderDto { return { id: "provider_1", tenantId: "tenant_1", kind: "oidc", name: "Okta", slug: "okta", enabled: true, status: "enabled", issuer: "https://idp.example.com", authorizationUrl: "https://idp.example.com/oauth2/authorize", tokenUrl: "https://idp.example.com/oauth2/token", jwksUrl: "https://idp.example.com/oauth2/keys", clientId: "client_public_id", entityId: null, ssoUrl: null, certificateFingerprint: null, metadataUpdatedAt: new Date("2026-01-01T00:00:00.000Z"), createdAt: new Date("2026-01-01T00:00:00.000Z"), updatedAt: new Date("2026-01-02T00:00:00.000Z"), ...patch, }; } function createExportDownloadJobFixture(patch: Partial = {}): ExportJobDownloadRecord { return { id: "export_job_1", tenantId: "tenant_1", requestedByUserId: "user_1", format: "csv", status: "COMPLETED", artifactBucket: "exports-bucket", artifactKey: "tenants/tenant_1/exports/export_job_1.csv", rowCount: 2, expiresAt: new Date("2030-01-01T00:00:00.000Z"), errorName: null, requestId: "req_export_created", ...patch, }; } function mailjetBasicAuthHeader(secret: string = TEST_MAILJET_WEBHOOK_SECRET) { return `Basic ${Buffer.from(`mailjet:${secret}`, "utf8").toString("base64")}`; } function createMailjetWebhookRequest(body: unknown, overrides: Record = {}) { const rawBody = typeof body === "string" ? body : JSON.stringify(body); const headers: Record = { "content-type": "application/json", authorization: mailjetBasicAuthHeader(), }; for (const [name, value] of Object.entries(overrides)) { if (value === undefined) { delete headers[name]; } else { headers[name] = value; } } return { headers, body: rawBody }; } const TEST_API_CONFIG: ApiConfig = { appName: "Test API", nodeEnv: "test", revision: "unknown", listen: { port: 3001 }, routing: { appBaseDomain: "localhost:3000", webAppHost: "app.localhost:3000", adminAppHost: "admin.localhost:3000", apiHost: "api.localhost:3000", protocol: "http", }, origins: {}, apiAccessToken: "test-api-access-token", jwtSecret: TEST_JWT_SECRET, analytics: { token: "test-analytics-token", }, mailjet: { webhookSecret: TEST_MAILJET_WEBHOOK_SECRET, }, lago: { timeoutMs: 10000 }, mollie: { timeoutMs: 10000 }, apiKeys: { allowLegacyPlaintextFallback: true, }, storage: {}, }; let testApiRuntimeConfig: ApiConfig = TEST_API_CONFIG; let resetApiAppDependencies: (() => void) | undefined; function patchTestApiRuntimeConfig(patch: Partial) { testApiRuntimeConfig = { ...testApiRuntimeConfig, ...patch }; setApiRuntimeConfigForTests(testApiRuntimeConfig); if ("apiAccessToken" in patch && patch.apiAccessToken) { process.env.API_ACCESS_TOKEN = patch.apiAccessToken; } if ("jwtSecret" in patch && patch.jwtSecret) { process.env.JWT_SECRET = patch.jwtSecret; } if ("analytics" in patch) { if (patch.analytics?.token) { process.env.ANALYTICS_TOKEN = patch.analytics.token; } else { delete process.env.ANALYTICS_TOKEN; } } if ("mailjet" in patch) { if (patch.mailjet?.webhookSecret) { process.env.MAILJET_WEBHOOK_SECRET = patch.mailjet.webhookSecret; } else { delete process.env.MAILJET_WEBHOOK_SECRET; } } if ("mollie" in patch) { if (patch.mollie?.apiKey) { process.env.MOLLIE_API_KEY = patch.mollie.apiKey; } else { delete process.env.MOLLIE_API_KEY; } } if ("storage" in patch) { if (patch.storage?.endpoint) { process.env.STORAGE_ENDPOINT = patch.storage.endpoint; } else { delete process.env.STORAGE_ENDPOINT; } if (patch.storage?.region) { process.env.STORAGE_REGION = patch.storage.region; } else { delete process.env.STORAGE_REGION; } if (patch.storage?.bucket) { process.env.STORAGE_BUCKET = patch.storage.bucket; } else { delete process.env.STORAGE_BUCKET; } if (patch.storage?.accessKeyId) { process.env.STORAGE_ACCESS_KEY_ID = patch.storage.accessKeyId; } else { delete process.env.STORAGE_ACCESS_KEY_ID; } if (patch.storage?.secretAccessKey) { process.env.STORAGE_SECRET_ACCESS_KEY = patch.storage.secretAccessKey; } else { delete process.env.STORAGE_SECRET_ACCESS_KEY; } if (patch.storage?.sessionToken) { process.env.STORAGE_SESSION_TOKEN = patch.storage.sessionToken; } else { delete process.env.STORAGE_SESSION_TOKEN; } if (patch.storage?.publicBaseUrl) { process.env.STORAGE_PUBLIC_BASE_URL = patch.storage.publicBaseUrl; } else { delete process.env.STORAGE_PUBLIC_BASE_URL; } if (patch.storage?.forcePathStyle) { process.env.STORAGE_FORCE_PATH_STYLE = patch.storage.forcePathStyle; } else { delete process.env.STORAGE_FORCE_PATH_STYLE; } } } afterEach(async () => { vi.useRealTimers(); process.env = { ...originalEnv }; resetApiRuntimeConfigForTests(); await resetPublicApiRateLimiterForTests(); resetApiAppDependencies?.(); resetApiAppDependencies = undefined; }); describe("api app", () => { beforeEach(() => { testApiRuntimeConfig = { ...TEST_API_CONFIG, origins: { web: "http://app.localhost", admin: "http://admin.localhost", }, mailjet: { ...TEST_API_CONFIG.mailjet, }, }; patchTestApiRuntimeConfig(testApiRuntimeConfig); }); test("uses export artifact format for non-CSV download filenames", async () => { vi.useFakeTimers(); vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z")); patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const findExportJobForDownload = vi.fn().mockResolvedValue( createExportDownloadJobFixture({ format: "json", artifactKey: "tenants/tenant_1/exports/export_job_1.json", }), ); const createSignedDownloadUrl = vi.fn().mockResolvedValue({ method: "GET", url: "https://storage.example.com/signed/export_job_1?signature=redacted", expiresAt: new Date("2026-01-01T00:05:00.000Z"), expiresInSeconds: 300, headers: { accept: "application/json" }, }); resetApiAppDependencies = configureApiAppDependenciesForTests({ findExportJobForDownload, createSignedDownloadUrl }); const response = await app.request("/v1/exports/export_job_1/download-url?tenantId=tenant_1", { headers: { authorization: "Bearer service-secret" }, }); expect(response.status).toBe(200); expect(createSignedDownloadUrl).toHaveBeenCalledWith("exports-bucket", { key: "tenants/tenant_1/exports/export_job_1.json", expiresInSeconds: 300, responseContentDisposition: 'attachment; filename="export_job_1.json"', }); }); test("returns health with generated request id", async () => { const response = await app.request("/healthz"); expect(response.status).toBe(200); const requestId = response.headers.get("x-request-id"); expect(requestId).toEqual(expect.any(String)); expectApiSecurityHeaders(response); await expect(response.json()).resolves.toMatchObject({ status: "ok", service: "api", revision: "unknown", requestId, }); }); test("returns health with trusted request id", async () => { const response = await app.request("/healthz", { headers: { "x-request-id": "req_test" }, }); expect(response.status).toBe(200); expect(response.headers.get("x-request-id")).toBe("req_test"); expectApiSecurityHeaders(response); await expect(response.json()).resolves.toMatchObject({ status: "ok", service: "api", revision: "unknown", requestId: "req_test", }); }); test("returns readiness with request id after dependency check", async () => { const checkReadiness = vi.fn().mockResolvedValue(undefined); resetApiAppDependencies = configureApiAppDependenciesForTests({ checkReadiness }); const response = await app.request("/readyz", { headers: { "x-request-id": "req_ready" }, }); expect(checkReadiness).toHaveBeenCalledOnce(); expect(response.status).toBe(200); expect(response.headers.get("x-request-id")).toBe("req_ready"); await expect(response.json()).resolves.toEqual({ status: "ready", service: "api", revision: "unknown", requestId: "req_ready", }); }); test("returns redacted readiness failure with request id", async () => { const checkReadiness = vi.fn().mockRejectedValue(new Error("postgres://user:secret@db.local/app token=super-secret stack trace")); resetApiAppDependencies = configureApiAppDependenciesForTests({ checkReadiness }); const response = await app.request("/readyz", { headers: { "x-request-id": "req_not_ready" }, }); expect(response.status).toBe(503); expect(response.headers.get("x-request-id")).toBe("req_not_ready"); const bodyText = await response.text(); expect(bodyText).not.toContain("postgres://user:secret@db.local/app"); expect(bodyText).not.toContain("super-secret"); expect(bodyText).not.toContain("stack trace"); expect(JSON.parse(bodyText)).toEqual({ status: "not_ready", service: "api", requestId: "req_not_ready", error: { code: "dependency_unavailable", message: "A required dependency is unavailable.", }, }); }); test("returns maintenance response before protected handlers when enabled", async () => { process.env.HIVEGRID_API_MAINTENANCE_MODE = "1"; process.env.HIVEGRID_API_MAINTENANCE_RETRY_AFTER_SECONDS = "300"; const response = await app.request("/v1/entities/widgets/rows", { headers: { "x-request-id": "req_app_maintenance" }, }); const bodyText = await response.text(); expect(response.status).toBe(503); expect(response.headers.get("x-request-id")).toBe("req_app_maintenance"); expect(response.headers.get("retry-after")).toBe("300"); expect(bodyText).not.toContain(TEST_JWT_SECRET); expect(bodyText).not.toContain(TEST_MAILJET_WEBHOOK_SECRET); expect(JSON.parse(bodyText)).toEqual({ status: "maintenance", service: "api", requestId: "req_app_maintenance", error: { code: "maintenance_mode", message: "The API is temporarily unavailable for maintenance. Please retry later.", }, }); }); test("ignores invalid maintenance retry-after values", async () => { process.env.HIVEGRID_API_MAINTENANCE_MODE = "1"; process.env.HIVEGRID_API_MAINTENANCE_RETRY_AFTER_SECONDS = "postgres://user:secret@db.local/app"; const response = await app.request("/v1/entities/widgets/rows", { headers: { "x-request-id": "req_invalid_retry" }, }); const bodyText = await response.text(); expect(response.status).toBe(503); expect(response.headers.get("retry-after")).toBeNull(); expect(bodyText).not.toContain("postgres://user:secret@db.local/app"); expect(JSON.parse(bodyText)).toMatchObject({ status: "maintenance", requestId: "req_invalid_retry", error: { code: "maintenance_mode" }, }); }); test("exempts operator endpoints during maintenance", async () => { const checkReadiness = vi.fn().mockResolvedValue(undefined); resetApiAppDependencies = configureApiAppDependenciesForTests({ checkReadiness }); process.env.HIVEGRID_API_MAINTENANCE_MODE = "1"; const health = await app.request("/healthz", { headers: { "x-request-id": "req_maint_health" } }); const ready = await app.request("/readyz", { headers: { "x-request-id": "req_maint_ready" } }); const openapi = await app.request("/v1/openapi.json", { headers: { "x-request-id": "req_maint_openapi" } }); const docs = await app.request("/v1/docs", { headers: { "x-request-id": "req_maint_docs" } }); expect(health.status).toBe(200); expect(ready.status).toBe(200); expect(openapi.status).toBe(200); expect(docs.status).toBe(200); expect(checkReadiness).toHaveBeenCalledOnce(); }); test("returns versioned health with request id", async () => { const response = await app.request("/v1/health", { headers: { "x-request-id": "req_v1_health" }, }); expect(response.status).toBe(200); expect(response.headers.get("x-request-id")).toBe("req_v1_health"); expectApiSecurityHeaders(response); await expect(response.json()).resolves.toEqual({ status: "ok", service: "api", revision: "unknown", requestId: "req_v1_health", }); }); test("does not serve removed /api/v1 compatibility paths", async () => { const response = await app.request("/api/v1/health?check=deep"); expect(response.status).toBe(404); expect(response.headers.get("location")).toBeNull(); expectApiSecurityHeaders(response); }); test("rejects removed API-host paths inside the API runtime", async () => { const cases = [ "/api/workflows/run/workflow_1?tenantId=tenant_1", "/api/workflows/executions/execution_1", "/api/workflows/executions/execution_1/continue", "/api/workflows/stream/execution_1", ] as const; for (const legacyPath of cases) { const response = await app.request(legacyPath); expect(response.status).toBe(404); await expect(response.json()).resolves.toEqual({ error: { code: "not_found", message: "Endpoint not found.", requestId: expect.any(String), }, }); } }); test("uses JSON error shape for missing routes", async () => { const response = await app.request("/v1/missing", { headers: { "x-request-id": "req_missing" }, }); expect(response.status).toBe(404); expect(response.headers.get("x-request-id")).toBe("req_missing"); expectApiSecurityHeaders(response); await expect(response.json()).resolves.toEqual({ error: { code: "not_found", message: "Endpoint not found.", requestId: "req_missing", }, }); }); test("serves self-contained API docs page", async () => { patchTestApiRuntimeConfig({ appName: "HiveGrid " }); const response = await app.request("/v1/docs", { headers: { "x-request-id": "req_docs" }, }); expect(response.status).toBe(200); expect(response.headers.get("x-request-id")).toBe("req_docs"); expect(response.headers.get("content-type")).toContain("text/html"); const body = await response.text(); expect(body).toContain('fetch("/v1/openapi.json")'); expect(body).toContain('OpenAPI JSON'); expect(body).toContain("API Documentation | HiveGrid <API>"); expect(body).toContain("Swagger-style OpenAPI 3.1 explorer"); expect(body).toContain('id="operation-nav"'); expect(body).toContain('id="operation-detail"'); expect(body).toContain("Try request"); expect(body).toContain('headers: apiKey ? { "x-api-key": apiKey } : {}'); }); test("handles canonical usage requests inside the API runtime", async () => { const apiKey = createStoredApiKeyFixture(); const findLegacyApiKeyByKey = vi.fn().mockResolvedValue(apiKey); const createLegacyApiKeyLog = vi.fn().mockResolvedValue({ id: "api_key_log_1", tenantId: apiKey.tenantId }); const setLegacyApiKeyLogStatus = vi.fn().mockResolvedValue({ count: 1 }); const createUniqueLegacyTenantIpAddress = vi.fn().mockResolvedValue({ id: "tenant_ip_1" }); const getTenantSubscription = vi.fn().mockResolvedValue(null); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyApiKeyByKey, createLegacyApiKeyLog, setLegacyApiKeyLogStatus, createUniqueLegacyTenantIpAddress, getTenantSubscription, }); const response = await app.request("/v1/usage", { headers: { "x-api-key": "tenant-api-key", "x-request-id": "req_usage", "x-hivegrid-internal-web-api-proxy": "attacker-forged", "x-hivegrid-internal-web-api-proxy-signature": "attacker-signature", }, }); expect(response.status).toBe(200); await expect(response.json()).resolves.toEqual({ plan: "" }); expect(findLegacyApiKeyByKey).toHaveBeenCalledWith("tenant-api-key", undefined, TEST_JWT_SECRET, { allowPlaintextFallback: true }); expect(createLegacyApiKeyLog).toHaveBeenCalledWith( expect.objectContaining({ tenantId: apiKey.tenantId, apiKeyId: apiKey.id, endpoint: "/v1/usage", method: "GET", }) ); expect(setLegacyApiKeyLogStatus).toHaveBeenCalledWith({ id: "api_key_log_1", tenantId: apiKey.tenantId }, expect.objectContaining({ status: 200 })); expect(createUniqueLegacyTenantIpAddress).toHaveBeenCalledWith(expect.objectContaining({ tenantId: apiKey.tenantId, apiKeyId: apiKey.id })); }); test("serves public API read endpoints with tenant API-key scope, sparse fields and usage logging", async () => { const apiKey = createStoredApiKeyFixture(); const findLegacyApiKeyByKey = vi.fn().mockResolvedValue(apiKey); const createLegacyApiKeyLog = vi.fn().mockResolvedValue({ id: "api_key_log_1", tenantId: apiKey.tenantId }); const setLegacyApiKeyLogStatus = vi.fn().mockResolvedValue({ count: 1 }); const createUniqueLegacyTenantIpAddress = vi.fn().mockResolvedValue({ id: "tenant_ip_1" }); const getTenantSubscription = vi.fn().mockResolvedValue(null); const getTenantApiUsage = vi.fn().mockResolvedValue({ title: "API access", type: 1, value: 0, used: 0, remaining: 0, enabled: true, message: "", }); const listPublicApiResource = vi.fn().mockResolvedValue({ data: [{ id: "contact_1", email: "a@example.test" }], pageInfo: { limit: 1, nextCursor: null, sort: "createdAt.desc" }, }); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyApiKeyByKey, createLegacyApiKeyLog, setLegacyApiKeyLogStatus, createUniqueLegacyTenantIpAddress, getTenantSubscription, getTenantApiUsage, listPublicApiResource, }); const response = await app.request("/v1/contacts?limit=1&fields=email&q=Meyer", { headers: { "x-api-key": "tenant-api-key", "x-request-id": "req_public_contacts", }, }); expect(response.status).toBe(200); await expect(response.json()).resolves.toEqual({ data: [{ id: "contact_1", email: "a@example.test" }], pageInfo: { limit: 1, nextCursor: null, sort: "createdAt.desc" }, meta: { resource: "contacts", readOnly: true, requestId: "req_public_contacts", }, }); expect(findLegacyApiKeyByKey).toHaveBeenCalledWith("tenant-api-key", undefined, TEST_JWT_SECRET, { allowPlaintextFallback: true }); expect(createLegacyApiKeyLog).toHaveBeenCalledWith( expect.objectContaining({ tenantId: apiKey.tenantId, apiKeyId: apiKey.id, endpoint: "/v1/contacts", params: "limit=1&fields=email&q=Meyer", method: "GET", }), ); expect(getTenantApiUsage).toHaveBeenCalledWith(apiKey.tenantId, null); expect(listPublicApiResource).toHaveBeenCalledWith({ tenantId: apiKey.tenantId, resource: "contacts", query: expect.objectContaining({ limit: 1, fields: ["email"], filters: expect.objectContaining({ q: "Meyer" }), }), }); expect(setLegacyApiKeyLogStatus).toHaveBeenCalledWith({ id: "api_key_log_1", tenantId: apiKey.tenantId }, expect.objectContaining({ status: 200 })); expect(createUniqueLegacyTenantIpAddress).toHaveBeenCalledWith(expect.objectContaining({ tenantId: apiKey.tenantId, apiKeyId: apiKey.id })); }); test("rejects malformed public API read queries before executing the resource read", async () => { const apiKey = createStoredApiKeyFixture(); const findLegacyApiKeyByKey = vi.fn().mockResolvedValue(apiKey); const createLegacyApiKeyLog = vi.fn().mockResolvedValue({ id: "api_key_log_1", tenantId: apiKey.tenantId }); const setLegacyApiKeyLogStatus = vi.fn().mockResolvedValue({ count: 1 }); const listPublicApiResource = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyApiKeyByKey, createLegacyApiKeyLog, setLegacyApiKeyLogStatus, listPublicApiResource, }); const response = await app.request("/v1/contacts?fields=passwordHash", { headers: { "x-api-key": "tenant-api-key", "x-request-id": "req_public_invalid", }, }); expect(response.status).toBe(400); await expect(response.json()).resolves.toEqual({ error: { code: "invalid_fields", message: "fields contains an unsupported field.", params: { field: "passwordHash", resource: "contacts" }, requestId: "req_public_invalid", }, }); expect(listPublicApiResource).not.toHaveBeenCalled(); expect(setLegacyApiKeyLogStatus).toHaveBeenCalledWith( { id: "api_key_log_1", tenantId: apiKey.tenantId }, expect.objectContaining({ status: 400, error: "fields contains an unsupported field." }), ); }); test("gates public API read endpoints when the API module is not included", async () => { const apiKey = createStoredApiKeyFixture(); const findLegacyApiKeyByKey = vi.fn().mockResolvedValue(apiKey); const createLegacyApiKeyLog = vi.fn().mockResolvedValue({ id: "api_key_log_1", tenantId: apiKey.tenantId }); const setLegacyApiKeyLogStatus = vi.fn().mockResolvedValue({ count: 1 }); const createUniqueLegacyTenantIpAddress = vi.fn().mockResolvedValue({ id: "tenant_ip_1" }); const getTenantSubscription = vi.fn().mockResolvedValue(null); const getTenantApiUsage = vi.fn().mockResolvedValue(undefined); const listPublicApiResource = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyApiKeyByKey, createLegacyApiKeyLog, setLegacyApiKeyLogStatus, createUniqueLegacyTenantIpAddress, getTenantSubscription, getTenantApiUsage, listPublicApiResource, }); const response = await app.request("/v1/projects", { headers: { "x-api-key": "tenant-api-key", "x-request-id": "req_public_gated", }, }); expect(response.status).toBe(402); await expect(response.json()).resolves.toMatchObject({ error: { code: "payment_required", message: "Public API access is disabled or exhausted for this tenant.", params: { plan: "API access not included", remaining: "0" }, requestId: "req_public_gated", }, }); expect(listPublicApiResource).not.toHaveBeenCalled(); expect(setLegacyApiKeyLogStatus).toHaveBeenCalledWith( { id: "api_key_log_1", tenantId: apiKey.tenantId }, expect.objectContaining({ status: 402, error: "Public API access is disabled or exhausted for this tenant." }), ); }); test("ingests incoming public lead webhooks with URL-token auth and rate-limit headers", async () => { const token = "hgwh_test_url_token"; const endpoint = { id: "incoming_webhook_1", createdAt: new Date("2026-01-01T00:00:00.000Z"), updatedAt: new Date("2026-01-01T00:00:00.000Z"), tenantId: "tenant_1", slug: "leadbox", name: "Leadbox", authMode: "url_token" as const, apiKeyId: null, tokenHash: derivePublicApiSecretMetadata(token).hash, tokenPrefix: "hgwh_test_", tokenLastFour: "oken", hmacSecretHash: null, hmacSecretPrefix: null, hmacSecretLastFour: null, payloadMapping: {}, autoMatchRules: {}, status: "active" as const, pausedAt: null, archivedAt: null, isDemoData: false, }; const findLegacyTenantByIdOrSlug = vi.fn().mockResolvedValue({ id: "tenant_1" }); const findPublicIncomingWebhookEndpoint = vi.fn().mockResolvedValue(endpoint); const createPublicWebhookIngestionLog = vi.fn().mockResolvedValue({ id: "ingestion_log_1" }); const getTenantSubscription = vi.fn().mockResolvedValue(null); const getTenantApiUsage = vi.fn().mockResolvedValue({ title: "API access", type: 1, value: 0, used: 0, remaining: 0, enabled: true, message: "", }); const ingestPublicLeadWebhook = vi.fn().mockResolvedValue({ lead: { id: "lead_1" }, log: { id: "ingestion_log_1" }, matchedKontaktId: "kontakt_1", automationExecutionIds: ["automation_execution_1"], }); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyTenantByIdOrSlug, findPublicIncomingWebhookEndpoint, createPublicWebhookIngestionLog, getTenantSubscription, getTenantApiUsage, ingestPublicLeadWebhook, }); const response = await app.request("/v1/webhooks/incoming/acme/leadbox", { method: "POST", headers: { "content-type": "application/json", "x-hivegrid-webhook-token": token, "x-request-id": "req_public_incoming_webhook", }, body: JSON.stringify({ email: "lead@example.test", firstName: "Ada", message: "Bitte melden." }), }); expect(response.status).toBe(201); expect(response.headers.get("x-ratelimit-limit")).toBe("1000"); expect(response.headers.get("x-ratelimit-remaining")).toBe("999"); await expect(response.json()).resolves.toEqual({ data: { leadId: "lead_1", matchedKontaktId: "kontakt_1", automationExecutionIds: ["automation_execution_1"], }, meta: { requestId: "req_public_incoming_webhook", endpoint: "leadbox", }, }); expect(findLegacyTenantByIdOrSlug).toHaveBeenCalledWith("acme"); expect(findPublicIncomingWebhookEndpoint).toHaveBeenCalledWith({ tenantId: "tenant_1", slug: "leadbox" }); expect(ingestPublicLeadWebhook).toHaveBeenCalledWith({ tenantId: "tenant_1", endpoint, payload: { email: "lead@example.test", firstName: "Ada", message: "Bitte melden." }, requestId: "req_public_incoming_webhook", sourceIp: "", }); expect(createPublicWebhookIngestionLog).not.toHaveBeenCalled(); }); test("rejects incoming public webhook API keys without the webhook scope and closes the API-key log", async () => { const apiKey = createStoredApiKeyFixture({ scopes: ["public_api:read"] }); const endpoint = { id: "incoming_webhook_1", createdAt: new Date("2026-01-01T00:00:00.000Z"), updatedAt: new Date("2026-01-01T00:00:00.000Z"), tenantId: "tenant_1", slug: "leadbox", name: "Leadbox", authMode: "api_key" as const, apiKeyId: null, tokenHash: null, tokenPrefix: null, tokenLastFour: null, hmacSecretHash: null, hmacSecretPrefix: null, hmacSecretLastFour: null, payloadMapping: {}, autoMatchRules: {}, status: "active" as const, pausedAt: null, archivedAt: null, isDemoData: false, }; const findLegacyTenantByIdOrSlug = vi.fn().mockResolvedValue({ id: "tenant_1" }); const findPublicIncomingWebhookEndpoint = vi.fn().mockResolvedValue(endpoint); const findLegacyApiKeyByKey = vi.fn().mockResolvedValue(apiKey); const createLegacyApiKeyLog = vi.fn().mockResolvedValue({ id: "api_key_log_1", tenantId: apiKey.tenantId }); const setLegacyApiKeyLogStatus = vi.fn().mockResolvedValue({ count: 1 }); const createPublicWebhookIngestionLog = vi.fn().mockResolvedValue({ id: "ingestion_log_1" }); const getTenantSubscription = vi.fn().mockResolvedValue(null); const getTenantApiUsage = vi.fn().mockResolvedValue({ title: "API access", type: 1, value: 0, used: 0, remaining: 0, enabled: true, message: "", }); const ingestPublicLeadWebhook = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyTenantByIdOrSlug, findPublicIncomingWebhookEndpoint, findLegacyApiKeyByKey, createLegacyApiKeyLog, setLegacyApiKeyLogStatus, createPublicWebhookIngestionLog, getTenantSubscription, getTenantApiUsage, ingestPublicLeadWebhook, }); const response = await app.request("/v1/webhooks/incoming/acme/leadbox", { method: "POST", headers: { "content-type": "application/json", "x-api-key": "tenant-api-key", "x-request-id": "req_public_incoming_scope", }, body: JSON.stringify({ email: "lead@example.test" }), }); expect(response.status).toBe(403); await expect(response.json()).resolves.toMatchObject({ error: { code: "insufficient_scope", message: "API key scope does not allow this operation.", requestId: "req_public_incoming_scope", }, }); expect(setLegacyApiKeyLogStatus).toHaveBeenCalledWith( { id: "api_key_log_1", tenantId: "tenant_1" }, expect.objectContaining({ status: 403, error: "API key scope does not allow this operation." }), ); expect(createPublicWebhookIngestionLog).toHaveBeenCalledWith(expect.objectContaining({ result: "insufficient_scope", status: 403 })); expect(ingestPublicLeadWebhook).not.toHaveBeenCalled(); }); test("handles canonical Mollie webhook requests inside the API runtime", async () => { patchTestApiRuntimeConfig({ mollie: { apiKey: "test_mollie_key", timeoutMs: 10000 } }); const resolveMollieWebhookPayment = vi.fn().mockResolvedValue({ provider: "mollie", providerPaymentId: "tr_test_123", externalId: "payment_external_123", status: "paid", amountCents: 4900, amountRefundedCents: null, amountRemainingCents: 0, currency: "EUR", checkoutUrl: null, paidAt: "2026-07-04T03:00:00Z", expiresAt: null, metadata: { tenantId: "tenant_1", invoiceExternalId: "invoice_1", paymentExternalId: "payment_external_123", lagoCustomerId: null, lagoSubscriptionId: null, planCode: null, seatQuantity: null, }, }); const findLegacyTenantById = vi.fn().mockResolvedValue({ id: "tenant_1", name: "Acme" }); const applyMolliePaymentSync = vi.fn().mockResolvedValue({ tenantId: "tenant_1", provider: "mollie", idempotencyKey: "mollie:webhook:tr_test_123:paid:none", replayed: false, status: "active", }); const applyLagoSubscriptionSync = vi.fn(); const updateLagoInvoicePaymentStatus = vi.fn().mockResolvedValue({ provider: "lago", providerInvoiceId: "invoice_1", number: "LAG-001", externalCustomerId: "tenant_1", status: "finalized", paymentStatus: "succeeded", invoiceType: "subscription", currency: "EUR", totalAmountCents: 4900, issuingDate: "2026-07-04", fileUrl: null, }); resetApiAppDependencies = configureApiAppDependenciesForTests({ resolveMollieWebhookPayment, findLegacyTenantById: findLegacyTenantById as unknown as ApiAppDependencies["findLegacyTenantById"], applyLagoSubscriptionSync: applyLagoSubscriptionSync as unknown as ApiAppDependencies["applyLagoSubscriptionSync"], applyMolliePaymentSync: applyMolliePaymentSync as unknown as ApiAppDependencies["applyMolliePaymentSync"], updateLagoInvoicePaymentStatus: updateLagoInvoicePaymentStatus as unknown as ApiAppDependencies["updateLagoInvoicePaymentStatus"], }); const response = await app.request("/v1/billing/mollie/webhooks", { method: "POST", body: "id=tr_test_123", headers: { "content-type": "application/x-www-form-urlencoded", "x-request-id": "req_mollie_webhook", }, }); expect(response.status).toBe(200); await expect(response.json()).resolves.toMatchObject({ received: true, provider: "mollie", paymentId: "tr_test_123", synced: true, billingStatus: "active", }); expect(resolveMollieWebhookPayment).toHaveBeenCalledWith(expect.any(URLSearchParams)); expect(findLegacyTenantById).toHaveBeenCalledWith("tenant_1"); expect(applyMolliePaymentSync).toHaveBeenCalledWith( expect.objectContaining({ tenantId: "tenant_1", eventKey: "mollie:webhook:tr_test_123:paid:none", paymentExternalId: "payment_external_123", invoiceExternalId: "invoice_1", status: "paid", }) ); expect(updateLagoInvoicePaymentStatus).toHaveBeenCalledWith({ tenantId: "tenant_1", invoiceExternalId: "invoice_1", amountCents: 4900, paymentStatus: "succeeded", }); }); test("does not expose disabled workflow plugin routes through the API runtime", async () => { const routes = [ { method: "POST", path: "/v1/workflows/run/workflow_1?tenantId=tenant_1" }, { method: "GET", path: "/v1/workflows/executions/execution_1?tenantId=tenant_1" }, { method: "POST", path: "/v1/workflows/executions/execution_1/continue?tenantId=tenant_1" }, { method: "GET", path: "/v1/workflows/stream/execution_1?tenantId=tenant_1" }, ]; for (const route of routes) { const response = await app.request(route.path, { method: route.method, headers: { "x-request-id": `req_disabled_${route.method.toLowerCase()}` }, }); expect(response.status).toBe(404); await expect(response.json()).resolves.toMatchObject({ error: { code: "not_found", }, }); } }); test("documents API key validation input options and response envelope in OpenAPI", async () => { const response = await app.request("/v1/openapi.json?source=apps/api/src/openapi.ts", { headers: { "x-request-id": "req_openapi" }, }); expect(response.status).toBe(200); expect(response.headers.get("x-request-id")).toBe("req_openapi"); const document = await response.json(); expect(document.components.securitySchemes).toMatchObject({ bearerAuth: { type: "http", scheme: "bearer", }, apiKeyHeader: { type: "apiKey", in: "header", name: "x-api-key", }, }); expect(document.paths["/v1/api-keys/validate"].post).toMatchObject({ operationId: "validateApiKey", security: [{ bearerAuth: [] }, { apiKeyHeader: [] }, {}], requestBody: { required: false, content: { "application/json": { schema: { type: "object", properties: { apiKey: { type: "string" }, }, }, }, }, }, responses: { "200": { description: "API key validation result.", content: { "application/json": { schema: { type: "object", properties: { active: { type: "boolean" }, keyType: { type: "string", enum: ["stored-api-key", "service-token"] }, apiKey: { description: expect.stringContaining("plaintext key material is never returned"), properties: { id: { type: "string" }, alias: { type: "string" }, tenantId: { type: "string" }, tenant: { properties: { id: { type: "string" }, name: { type: "string" }, slug: { type: "string" }, }, }, expires: { type: ["string", "null"], format: "date-time" }, }, }, }, required: ["active", "keyType"], }, }, }, }, "400": { description: "Missing or invalid API key validation input.", content: { "application/json": { schema: { type: "object", properties: { error: { type: "object", properties: { code: { type: "string", enum: ["invalid_request", "api_key_required"] }, message: { type: "string" }, params: { type: "object", }, requestId: { type: "string" }, }, required: ["code", "message", "requestId"], }, }, required: ["error"], }, }, }, }, }, }); }); test("documents analytics endpoints in OpenAPI", async () => { const response = await app.request("/v1/openapi.json?source=apps/api/src/openapi.ts", { headers: { "x-request-id": "req_openapi_analytics" }, }); expect(response.status).toBe(200); expect(response.headers.get("x-request-id")).toBe("req_openapi_analytics"); const document = await response.json(); expect(document.components.securitySchemes.analyticsTokenHeader).toMatchObject({ type: "apiKey", in: "header", name: "x-analytics-token", }); expect(document.paths["/v1/analytics/events"].post).toMatchObject({ operationId: "createAnalyticsEvent", security: [{ analyticsTokenHeader: [] }], requestBody: { required: true, content: { "application/json": { schema: { required: ["action", "category", "analytics"], properties: { analytics: { required: ["userAnalyticsId"], properties: { userAnalyticsId: { type: "string", minLength: 1 }, }, }, }, }, }, }, }, responses: { "400": { content: { "application/json": { schema: { properties: { error: { properties: { code: { type: "string", enum: ["invalid_request"] }, requestId: { type: "string" }, }, required: ["code", "message", "requestId"], }, }, required: ["error"], }, }, }, }, }, }); expect(document.paths["/v1/analytics/page-views"].post).toMatchObject({ operationId: "createAnalyticsPageView", security: [{ analyticsTokenHeader: [] }], requestBody: { required: true, content: { "application/json": { schema: { required: ["url", "analytics"], properties: { analytics: { required: ["userAnalyticsId"], }, }, }, }, }, }, responses: { "400": { content: { "application/json": { schema: { properties: { error: { properties: { code: { type: "string", enum: ["invalid_request"] }, requestId: { type: "string" }, }, }, }, }, }, }, }, }, }); expect(document.paths["/v1/analytics/public"].get).toMatchObject({ operationId: "getPublicAnalyticsOverview", security: [{ analyticsTokenHeader: [] }], responses: { "200": { headers: { "x-request-id": expect.any(Object) }, content: { "application/json": { schema: { required: ["uniqueVisitors", "pageViews", "events", "liveVisitors", "top", "charts"], }, }, }, }, "400": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["invalid_period"] }, requestId: { type: "string" } } } }, }, }, }, }, "401": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["unauthorized"] }, requestId: { type: "string" } } } }, }, }, }, }, "403": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["forbidden"] }, requestId: { type: "string" } } } }, }, }, }, }, "500": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["analytics_token_not_configured", "analytics_overview_failed"] } } }, }, }, }, }, }, }, }); expect(document.paths["/v1/analytics/public"].get.parameters).toEqual([ expect.objectContaining({ name: "period", in: "query", required: false }), ]); expect(document.paths["/v1/analytics/admin"].get).toMatchObject({ operationId: "getAdminAnalyticsOverview", security: [{ bearerAuth: [] }], responses: { "200": { headers: { "x-request-id": expect.any(Object) }, content: { "application/json": { schema: { required: ["uniqueVisitors", "pageViews", "events", "liveVisitors", "top", "charts"], }, }, }, }, "400": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["invalid_period"] }, requestId: { type: "string" } } } }, }, }, }, }, "401": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["unauthorized"] }, requestId: { type: "string" } } } }, }, }, }, }, "500": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["analytics_overview_failed"] }, requestId: { type: "string" } } } }, }, }, }, }, }, }); expect(document.paths["/v1/analytics/admin"].get.parameters).toEqual( expect.arrayContaining([ expect.objectContaining({ name: "period", in: "query", required: false }), expect.objectContaining({ name: "portalId", in: "query", required: false }), ]) ); expect(document.paths["/v1/maintenance/export-retention/enqueue"].post).toMatchObject({ operationId: "enqueueExportArtifactRetention", security: [{ bearerAuth: [] }], parameters: [expect.objectContaining({ name: "Idempotency-Key", in: "header", required: false })], requestBody: { required: false, content: { "application/json": { schema: { properties: { take: { type: "integer", minimum: 1, maximum: 500 }, }, }, }, }, }, responses: { "202": { content: { "application/json": { schema: { required: ["enqueued", "task", "jobId", "requestId"], }, }, }, }, "503": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["maintenance_queue_unavailable"] }, requestId: { type: "string" } } } }, }, }, }, }, }, }); }); test("allows canonical app origin through CORS alongside security and request id headers", async () => { const response = await app.request("/healthz", { headers: { origin: "http://app.localhost:3000", "x-request-id": "req_cors_security", }, }); expect(response.status).toBe(200); expect(response.headers.get("access-control-allow-origin")).toBe("http://app.localhost:3000"); expect(response.headers.get("x-request-id")).toBe("req_cors_security"); expectApiSecurityHeaders(response); }); test("allows canonical admin origin through CORS alongside security and request id headers", async () => { const response = await app.request("/healthz", { headers: { origin: "http://admin.localhost:3000", "x-request-id": "req_admin_cors_security", }, }); expect(response.headers.get("access-control-allow-origin")).toBe("http://admin.localhost:3000"); expect(response.headers.get("x-request-id")).toBe("req_admin_cors_security"); expectApiSecurityHeaders(response); }); test("denies attacker origin without losing request id or security headers", async () => { const response = await app.request("/healthz", { headers: { origin: "https://attacker.example", "x-request-id": "req_denied_cors_security", }, }); expect(response.status).toBe(200); expect(response.headers.get("access-control-allow-origin")).toBeNull(); expect(response.headers.get("x-request-id")).toBe("req_denied_cors_security"); expectApiSecurityHeaders(response); }); test("retains CORS, request id, and security headers on allowed preflight", async () => { const response = await app.request("/healthz", { method: "OPTIONS", headers: { origin: "http://admin.localhost:3000", "access-control-request-method": "GET", "access-control-request-headers": "authorization,x-request-id", "x-request-id": "req_preflight_cors_security", }, }); expect(response.status).toBe(204); expect(response.headers.get("access-control-allow-origin")).toBe("http://admin.localhost:3000"); expect(response.headers.get("access-control-allow-credentials")).toBe("true"); expect(response.headers.get("access-control-allow-methods")).toContain("OPTIONS"); expect(response.headers.get("x-request-id")).toBe("req_preflight_cors_security"); expectApiSecurityHeaders(response); }); test("allows documented analytics and upload headers through CORS preflight", async () => { const analytics = await app.request("/v1/analytics/events", { method: "OPTIONS", headers: { origin: "http://app.localhost:3000", "access-control-request-method": "POST", "access-control-request-headers": "content-type,x-analytics-token,x-request-id", "x-request-id": "req_analytics_preflight", }, }); expect(analytics.status).toBe(204); expect(analytics.headers.get("access-control-allow-origin")).toBe("http://app.localhost:3000"); expect(analytics.headers.get("access-control-allow-headers")?.toLowerCase()).toContain("x-analytics-token"); expect(analytics.headers.get("x-request-id")).toBe("req_analytics_preflight"); expectApiSecurityHeaders(analytics); const upload = await app.request("/v1/ai/upload", { method: "OPTIONS", headers: { origin: "http://admin.localhost:3000", "access-control-request-method": "POST", "access-control-request-headers": "authorization,content-type,x-tenant-id,x-filename,x-storage-object-status", "x-request-id": "req_upload_preflight", }, }); expect(upload.status).toBe(204); expect(upload.headers.get("access-control-allow-origin")).toBe("http://admin.localhost:3000"); const allowedHeaders = upload.headers.get("access-control-allow-headers")?.toLowerCase() ?? ""; expect(allowedHeaders).toContain("x-filename"); expect(allowedHeaders).toContain("x-storage-object-status"); expect(upload.headers.get("x-request-id")).toBe("req_upload_preflight"); expectApiSecurityHeaders(upload); const notificationStream = await app.request("/v1/notifications/stream", { method: "OPTIONS", headers: { origin: "http://app.localhost:3000", "access-control-request-method": "GET", "access-control-request-headers": "authorization,x-hivegrid-tenant-id,x-hivegrid-user-id,last-event-id", "x-request-id": "req_notification_stream_preflight", }, }); expect(notificationStream.status).toBe(204); expect(notificationStream.headers.get("access-control-allow-origin")).toBe("http://app.localhost:3000"); const notificationHeaders = notificationStream.headers.get("access-control-allow-headers")?.toLowerCase() ?? ""; expect(notificationHeaders).toContain("x-hivegrid-tenant-id"); expect(notificationHeaders).toContain("x-hivegrid-user-id"); expect(notificationHeaders).toContain("last-event-id"); expect(notificationStream.headers.get("x-request-id")).toBe("req_notification_stream_preflight"); expectApiSecurityHeaders(notificationStream); }); test("protects current-user session primitive", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "secret" }); const unauthorized = await app.request("/v1/session/current-user", { headers: { "x-request-id": "req_current_user_missing" }, }); expect(unauthorized.status).toBe(401); expect(unauthorized.headers.get("x-request-id")).toBe("req_current_user_missing"); await expect(unauthorized.json()).resolves.toEqual({ error: { code: "unauthorized", message: "A valid bearer token is required.", requestId: "req_current_user_missing", }, }); const invalid = await app.request("/v1/session/current-user", { headers: { authorization: "Bearer leaked-invalid-service-token", "x-request-id": "req_current_user_invalid", }, }); expect(invalid.status).toBe(401); expect(invalid.headers.get("x-request-id")).toBe("req_current_user_invalid"); const invalidBody = await invalid.json(); expect(invalidBody).toEqual({ error: { code: "unauthorized", message: "A valid bearer token is required.", requestId: "req_current_user_invalid", }, }); expect(JSON.stringify(invalidBody)).not.toContain("leaked-invalid-service-token"); const authorized = await app.request("/v1/session/current-user", { headers: { authorization: "Bearer secret", "x-request-id": "req_current_user_success", }, }); expect(authorized.status).toBe(200); expect(authorized.headers.get("x-request-id")).toBe("req_current_user_success"); await expect(authorized.json()).resolves.toMatchObject({ authenticated: true, principal: { type: "service-token" }, }); }); test("serves accounts from canonical v1 API routes with service credentials", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const subscription = { id: "subscription_1", billingProviderCustomerId: "cus_123", products: [ { id: "tenant_product_1", subscriptionProduct: { title: "pricing.pro", model: 2 }, quantity: 3, currentPeriodStart: new Date("2026-01-01T00:00:00.000Z"), currentPeriodEnd: new Date("2026-02-01T00:00:00.000Z"), cancelledAt: null, endsAt: null, billingProviderSubscriptionId: "sub_123", prices: [ { id: "tenant_price_1", subscriptionPrice: { billingProviderId: "price_123", type: 1, billingPeriod: 3, price: "19.99", currency: "usd", }, subscriptionUsageBasedPrice: null, }, ], }, ], }; const tenant = { id: "tenant_1", createdAt: new Date("2026-01-01T00:00:00.000Z"), updatedAt: new Date("2026-01-02T00:00:00.000Z"), slug: "acme", name: "Acme", icon: null, subscription, }; const adminGetAllLegacyTenants = vi.fn().mockResolvedValue([tenant]); const findLegacyTenantByIdOrSlug = vi.fn().mockResolvedValue({ id: "tenant_1" }); const findLegacyTenantById = vi.fn().mockResolvedValue(tenant); const getTenantSubscription = vi.fn().mockResolvedValue(subscription); resetApiAppDependencies = configureApiAppDependenciesForTests({ adminGetAllLegacyTenants, findLegacyTenantByIdOrSlug, findLegacyTenantById, getTenantSubscription, }); const list = await app.request("/v1/accounts", { headers: { authorization: "Bearer service-secret", "x-request-id": "req_accounts_list", }, }); expect(list.status).toBe(200); expect(adminGetAllLegacyTenants).toHaveBeenCalledOnce(); expect(getTenantSubscription).not.toHaveBeenCalled(); await expect(list.json()).resolves.toMatchObject({ success: true, total_results: 1, data: [ { id: "tenant_1", slug: "acme", name: "Acme", subscription: { id: "subscription_1", products: [ { id: "tenant_product_1", product: "pricing.pro", prices: [{ id: "tenant_price_1", price: 19.99 }], }, ], }, }, ], }); const single = await app.request("/v1/accounts/acme", { headers: { authorization: "Bearer service-secret", "x-request-id": "req_accounts_single", }, }); expect(single.status).toBe(200); expect(findLegacyTenantByIdOrSlug).toHaveBeenCalledWith("acme"); expect(findLegacyTenantById).toHaveBeenCalledWith("tenant_1"); expect(getTenantSubscription).toHaveBeenCalledWith("tenant_1"); await expect(single.json()).resolves.toMatchObject({ success: true, data: { id: "tenant_1", subscription: { id: "subscription_1" } }, }); }); test("protects canonical accounts API routes with service credentials", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const adminGetAllLegacyTenants = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ adminGetAllLegacyTenants }); const response = await app.request("/v1/accounts", { headers: { "x-request-id": "req_accounts_missing" }, }); expect(response.status).toBe(401); expect(adminGetAllLegacyTenants).not.toHaveBeenCalled(); await expect(response.json()).resolves.toEqual({ error: { code: "unauthorized", message: "A valid service credential is required.", requestId: "req_accounts_missing", }, }); }); test("streams scoped sanitized notification snapshots for service credentials", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "secret" }); const snapshot: NotificationStreamSnapshot = { cursor: "2026-01-01T00:00:00.000Z:delivery_1", items: [ { id: "delivery_1", cursor: "2026-01-01T00:00:00.000Z:delivery_1", tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "billing", messageKey: "invoice.ready", status: "SENT", attemptsMade: 1, createdAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", sentAt: "2026-01-01T00:00:01.000Z", readAt: null, deeplink: null, lastError: null, }, ], }; const getNotificationStreamSnapshot = vi.fn(async () => snapshot); const revalidateWorkspaceContext = vi.fn(async () => ({ valid: true as const, tenantId: "tenant_1", userId: "user_1", membership: {} as never })); resetApiAppDependencies = configureApiAppDependenciesForTests({ getNotificationStreamSnapshot, revalidateWorkspaceContext }); const response = await app.request("/v1/notifications/stream?tenantId=tenant_1&userId=user_1", { headers: { authorization: "Bearer secret", "last-event-id": "2025-12-31T00:00:00.000Z:delivery_0", "x-request-id": "req_notification_stream", }, }); expect(response.status).toBe(200); expect(response.headers.get("content-type")).toContain("text/event-stream"); expect(response.headers.get("cache-control")).toBe("no-cache"); expect(response.headers.get("x-request-id")).toBe("req_notification_stream"); expectApiSecurityHeaders(response); expect(getNotificationStreamSnapshot).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1", afterCursor: "2025-12-31T00:00:00.000Z:delivery_0", }); expect(revalidateWorkspaceContext).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1" }); const body = await response.text(); expect(body).toContain("event: notification.snapshot"); expect(body).not.toContain("event: snapshot"); expect(body).not.toContain("event: notification\n"); expect(body).toContain("id: 2026-01-01T00:00:00.000Z:delivery_1"); expect(body).toContain(": keepalive"); expect(body).toContain("event: keepalive"); expect(body).toContain('"requestId":"req_notification_stream"'); expect(body).toContain('"tenantId":"tenant_1"'); expect(body).toContain('"userId":"user_1"'); expect(body).toContain("invoice.ready"); expect(body).not.toContain("providerMessageId"); expect(body).not.toContain("payloadMetadata"); }); test("passes exact notification stream scope and cursor to DB dependency", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "secret" }); const getNotificationStreamSnapshot = vi.fn(async (): Promise => ({ cursor: null, items: [] })); const revalidateWorkspaceContext = vi.fn(async ({ tenantId, userId }: { tenantId?: string | null; userId?: string | null }) => ({ valid: true as const, tenantId: tenantId ?? "", userId: userId ?? "", membership: {} as never })); resetApiAppDependencies = configureApiAppDependenciesForTests({ getNotificationStreamSnapshot, revalidateWorkspaceContext }); const response = await app.request("/v1/notifications/stream?tenantId=%20tenant_scope%20&userId=%20user_scope%20&afterCursor=%20cursor_scope%20", { headers: { authorization: "Bearer secret", }, }); expect(response.status).toBe(200); expect(getNotificationStreamSnapshot).toHaveBeenCalledTimes(1); expect(getNotificationStreamSnapshot).toHaveBeenCalledWith({ tenantId: "tenant_scope", userId: "user_scope", afterCursor: "cursor_scope", }); expect(revalidateWorkspaceContext).toHaveBeenCalledWith({ tenantId: "tenant_scope", userId: "user_scope" }); const body = await response.text(); expect(body).toContain("id: cursor_scope"); expect(body).toContain('"cursor":"cursor_scope"'); }); test("rejects unauthorized and missing notification stream scopes with JSON envelopes", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "secret" }); const unauthorized = await app.request("/v1/notifications/stream?tenantId=tenant_1&userId=user_1", { headers: { "x-request-id": "req_notification_stream_unauthorized" }, }); expect(unauthorized.status).toBe(401); expect(unauthorized.headers.get("content-type")).toContain("application/json"); await expect(unauthorized.json()).resolves.toEqual({ error: { code: "unauthorized", message: "A valid bearer token is required.", requestId: "req_notification_stream_unauthorized", }, }); for (const [path, requestId, message] of [ ["/v1/notifications/stream?tenantId=tenant_1", "req_notification_stream_missing_user", "userId is required"], ["/v1/notifications/stream?userId=user_1", "req_notification_stream_missing_tenant", "tenantId is required"], ["/v1/notifications/stream?tenantId=%20%20&userId=user_1", "req_notification_stream_blank_tenant", "tenantId must not be empty"], ]) { const missingScope = await app.request(path, { headers: { authorization: "Bearer secret", "x-request-id": requestId, }, }); expect(missingScope.status).toBe(400); expect(missingScope.headers.get("content-type")).toContain("application/json"); await expect(missingScope.json()).resolves.toEqual({ error: { code: "invalid_request", message, requestId, }, }); } }); test("rejects notification streams when tenant user membership is not valid", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "secret" }); const getNotificationStreamSnapshot = vi.fn(async (): Promise => ({ cursor: null, items: [] })); const revalidateWorkspaceContext = vi.fn(async () => { throw new WorkspaceContextRevalidationError("context_membership_not_found"); }); resetApiAppDependencies = configureApiAppDependenciesForTests({ getNotificationStreamSnapshot, revalidateWorkspaceContext }); const response = await app.request("/v1/notifications/stream?tenantId=tenant_1&userId=user_2", { headers: { authorization: "Bearer secret", "x-request-id": "req_notification_stream_foreign_user", }, }); expect(response.status).toBe(403); expect(getNotificationStreamSnapshot).not.toHaveBeenCalled(); await expect(response.json()).resolves.toEqual({ error: { code: "context_membership_not_found", message: "Workspace context is not valid for this tenant and user.", requestId: "req_notification_stream_foreign_user", }, }); }); test("revalidates workspace context and lists redacted auth providers with service credentials", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const enabledProvider = createWorkspaceAuthProviderFixture(); const disabledProvider = createWorkspaceAuthProviderFixture({ id: "provider_2", kind: "saml", name: "SAML", slug: "saml", enabled: false, status: "disabled", tokenUrl: null, entityId: "urn:example", ssoUrl: "https://idp.example.com/saml", certificateFingerprint: "sha256:abc123" }); const revalidateWorkspaceContext = vi.fn(async ({ tenantId, userId }: { tenantId?: string | null; userId?: string | null }) => ({ valid: true as const, tenantId: tenantId ?? "", userId: userId ?? "", membership: {} as never })); const listWorkspaceAuthProviders = vi.fn(async () => [enabledProvider, disabledProvider]); const findLegacyTenantById = vi.fn(async () => createLegacyTenantFixture()); resetApiAppDependencies = configureApiAppDependenciesForTests({ revalidateWorkspaceContext, listWorkspaceAuthProviders, findLegacyTenantById }); const contextResponse = await app.request("/v1/workspaces/tenant_1/context/revalidate", { method: "POST", headers: { authorization: "Bearer service-secret", "content-type": "application/json", "x-request-id": "req_context_valid" }, body: JSON.stringify({ userId: "user_1", providerSlug: "okta" }), }); expect(contextResponse.status).toBe(200); expect(revalidateWorkspaceContext).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1" }); await expect(contextResponse.json()).resolves.toEqual({ context: { valid: true, tenantId: "tenant_1", userId: "user_1", providerSlug: "okta" } }); const providersResponse = await app.request("/v1/workspaces/tenant_1/auth/providers?kind=oidc&enabled=false", { headers: { authorization: "Bearer service-secret", "x-request-id": "req_provider_list" }, }); expect(providersResponse.status).toBe(200); expect(findLegacyTenantById).toHaveBeenCalledWith("tenant_1"); expect(listWorkspaceAuthProviders).toHaveBeenCalledWith({ tenantId: "tenant_1", kind: "oidc", enabled: false }); const providersBody = await providersResponse.json(); expect(providersBody).toMatchObject({ providers: [{ slug: "okta", status: "enabled" }, { slug: "saml", enabled: false, certificateFingerprint: "sha256:abc123" }] }); expect(JSON.stringify(providersBody)).not.toContain("secret"); expect(JSON.stringify(providersBody)).not.toContain("privateKey"); }); test("returns redacted workspace context/provider errors for auth, malformed payloads, wrong tenants, invalid providers, and backend failures", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const revalidateWorkspaceContext = vi.fn(async ({ tenantId, userId }: { tenantId?: string | null; userId?: string | null }) => { if (tenantId === "wrong_tenant") { throw new WorkspaceContextRevalidationError("context_membership_not_found"); } if (userId === "inactive_user") { throw new WorkspaceContextRevalidationError("context_membership_not_active"); } throw new Error("database client_secret=super-secret failed"); }); const listWorkspaceAuthProviders = vi.fn(async () => { throw new Error("provider privateKey=super-secret failed"); }); const findLegacyTenantById = vi.fn(async (tenantId: string) => { if (tenantId === "missing_tenant") { return null; } if (tenantId === "inactive_tenant") { return createLegacyTenantFixture({ id: tenantId, active: false }); } return createLegacyTenantFixture({ id: tenantId }); }); resetApiAppDependencies = configureApiAppDependenciesForTests({ revalidateWorkspaceContext, listWorkspaceAuthProviders, findLegacyTenantById }); const unauthorized = await app.request("/v1/workspaces/tenant_1/context/revalidate", { method: "POST", headers: { "content-type": "application/json", "x-request-id": "req_context_unauthorized" }, body: JSON.stringify({ userId: "user_1" }), }); expect(unauthorized.status).toBe(401); expect(JSON.stringify(await unauthorized.json())).not.toContain("service-secret"); const invalidPayload = await app.request("/v1/workspaces/tenant_1/context/revalidate", { method: "POST", headers: { authorization: "Bearer service-secret", "content-type": "application/json", "x-request-id": "req_context_invalid" }, body: JSON.stringify({ userId: { token: "tok_live_secret" }, providerSlug: "okta" }), }); expect(invalidPayload.status).toBe(400); const invalidPayloadBody = await invalidPayload.json(); expect(invalidPayloadBody).toEqual({ error: { code: "invalid_request", message: "Request validation failed.", params: { reason: "field_type_invalid", field: "userId", expected: "string" }, requestId: "req_context_invalid", }, }); expect(JSON.stringify(invalidPayloadBody)).not.toContain("tok_live_secret"); const wrongTenant = await app.request("/v1/workspaces/wrong_tenant/context/revalidate", { method: "POST", headers: { authorization: "Bearer service-secret", "content-type": "application/json", "x-request-id": "req_context_wrong_tenant" }, body: JSON.stringify({ userId: "user_1", providerSlug: "invalid-secret-provider" }), }); expect(wrongTenant.status).toBe(403); const wrongTenantBody = await wrongTenant.json(); expect(wrongTenantBody).toEqual({ error: { code: "context_membership_not_found", message: "Workspace context is not valid for this tenant and user.", requestId: "req_context_wrong_tenant" } }); expect(JSON.stringify(wrongTenantBody)).not.toContain("invalid-secret-provider"); const inactive = await app.request("/v1/workspaces/tenant_1/context/revalidate", { method: "POST", headers: { authorization: "Bearer service-secret", "content-type": "application/json", "x-request-id": "req_context_inactive" }, body: JSON.stringify({ userId: "inactive_user" }), }); expect(inactive.status).toBe(403); await expect(inactive.json()).resolves.toEqual({ error: { code: "context_membership_not_active", message: "Workspace context is not valid for this tenant and user.", requestId: "req_context_inactive" } }); const unexpectedContext = await app.request("/v1/workspaces/tenant_1/context/revalidate", { method: "POST", headers: { authorization: "Bearer service-secret", "content-type": "application/json", "x-request-id": "req_context_failed" }, body: JSON.stringify({ userId: "user_1" }), }); expect(unexpectedContext.status).toBe(500); const unexpectedContextBody = await unexpectedContext.json(); expect(unexpectedContextBody).toEqual({ error: { code: "workspace_context_revalidation_failed", message: "Workspace context revalidation failed.", requestId: "req_context_failed" } }); expect(JSON.stringify(unexpectedContextBody)).not.toContain("super-secret"); const providersFailed = await app.request("/v1/workspaces/tenant_1/auth/providers", { headers: { authorization: "Bearer service-secret", "x-request-id": "req_provider_failed" }, }); expect(providersFailed.status).toBe(500); const providersFailedBody = await providersFailed.json(); expect(providersFailedBody).toEqual({ error: { code: "workspace_auth_provider_failed", message: "Workspace auth provider request failed.", requestId: "req_provider_failed" } }); expect(JSON.stringify(providersFailedBody)).not.toContain("super-secret"); const providersMissingTenant = await app.request("/v1/workspaces/missing_tenant/auth/providers", { headers: { authorization: "Bearer service-secret", "x-request-id": "req_provider_missing_tenant" }, }); expect(providersMissingTenant.status).toBe(404); await expect(providersMissingTenant.json()).resolves.toEqual({ error: { code: "tenant_not_found", message: "Workspace tenant was not found.", requestId: "req_provider_missing_tenant" } }); expect(listWorkspaceAuthProviders).not.toHaveBeenCalledWith(expect.objectContaining({ tenantId: "missing_tenant" })); const providersInactiveTenant = await app.request("/v1/workspaces/inactive_tenant/auth/providers", { headers: { authorization: "Bearer service-secret", "x-request-id": "req_provider_inactive_tenant" }, }); expect(providersInactiveTenant.status).toBe(403); await expect(providersInactiveTenant.json()).resolves.toEqual({ error: { code: "tenant_inactive", message: "Workspace tenant is inactive.", requestId: "req_provider_inactive_tenant" } }); }); test("creates, lists, accepts, and revokes workspace invites with service credentials", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const created = createWorkspaceInviteCreateResult(); const accepted = createWorkspaceInviteFixture({ status: "accepted", pending: false, acceptedAt: new Date("2026-01-02T00:00:00.000Z"), acceptedByUserId: "user_1" }); const revoked = createWorkspaceInviteFixture({ status: "revoked", pending: false, revokedAt: new Date("2026-01-03T00:00:00.000Z"), revokedByUserId: "admin_1" }); const createWorkspaceInvite = vi.fn(async () => created); const listWorkspaceInvites = vi.fn(async () => [created]); const acceptWorkspaceInvite = vi.fn(async () => accepted); const revokeWorkspaceInvite = vi.fn(async () => revoked); const findLegacyTenantById = vi.fn(async () => createLegacyTenantFixture()); resetApiAppDependencies = configureApiAppDependenciesForTests({ createWorkspaceInvite, listWorkspaceInvites, acceptWorkspaceInvite, revokeWorkspaceInvite, findLegacyTenantById }); const createResponse = await app.request("/v1/workspaces/tenant_1/invites", { method: "POST", headers: { authorization: "Bearer service-secret", "content-type": "application/json", "x-request-id": "req_invite_create" }, body: JSON.stringify({ email: "Member@Example.com", firstName: "Member", lastName: "One", type: 1, expiresAt: "2030-01-01T00:00:00.000Z" }), }); expect(createResponse.status).toBe(201); expect(createWorkspaceInvite).toHaveBeenCalledWith({ tenantId: "tenant_1", email: "Member@Example.com", firstName: "Member", lastName: "One", type: 1, expiresAt: new Date("2030-01-01T00:00:00.000Z") }); const createBody = await createResponse.json(); expect(createBody).toMatchObject({ token: "plain-create-token", invite: { id: "invite_1", tenantId: "tenant_1", status: "pending", expiresAt: "2030-01-01T00:00:00.000Z" } }); expect(createBody.invite).not.toHaveProperty("token"); const listResponse = await app.request("/v1/workspaces/tenant_1/invites?status=pending&email=member%40example.com", { headers: { authorization: "Bearer service-secret", "x-request-id": "req_invite_list" }, }); expect(listResponse.status).toBe(200); expect(listWorkspaceInvites).toHaveBeenCalledWith({ tenantId: "tenant_1", status: "pending", email: "member@example.com" }); await expect(listResponse.json()).resolves.toMatchObject({ invites: [{ id: "invite_1", tokenPrefix: "tok_prefix" }] }); const acceptResponse = await app.request("/v1/workspaces/tenant_1/invites/invite_1/accept", { method: "POST", headers: { authorization: "Bearer service-secret", "content-type": "application/json", "x-request-id": "req_invite_accept" }, body: JSON.stringify({ token: "accept-token", userId: "user_1" }), }); expect(acceptResponse.status).toBe(200); expect(acceptWorkspaceInvite).toHaveBeenCalledWith({ tenantId: "tenant_1", inviteId: "invite_1", token: "accept-token", acceptedByUserId: "user_1" }); await expect(acceptResponse.json()).resolves.toMatchObject({ invite: { status: "accepted", acceptedAt: "2026-01-02T00:00:00.000Z" } }); const revokeResponse = await app.request("/v1/workspaces/tenant_1/invites/invite_1/revoke", { method: "POST", headers: { authorization: "Bearer service-secret", "content-type": "application/json", "x-request-id": "req_invite_revoke" }, body: JSON.stringify({ revokedByUserId: "admin_1", reason: "cleanup" }), }); expect(revokeResponse.status).toBe(200); expect(revokeWorkspaceInvite).toHaveBeenCalledWith({ tenantId: "tenant_1", inviteId: "invite_1", revokedByUserId: "admin_1" }); await expect(revokeResponse.json()).resolves.toMatchObject({ invite: { status: "revoked", revokedAt: "2026-01-03T00:00:00.000Z" } }); }); test("returns redacted workspace invite errors for auth, validation, duplicate, expired, not-found, tenant scope, and unexpected failures", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const createWorkspaceInvite = vi.fn(async () => { throw new WorkspaceInviteError("duplicate_active_invite"); }); const acceptWorkspaceInvite = vi.fn(async ({ tenantId }: { tenantId: string }) => { throw new WorkspaceInviteError(tenantId === "wrong_tenant" ? "invite_not_found" : "invite_expired"); }); const revokeWorkspaceInvite = vi.fn(async () => { throw new WorkspaceInviteError("invite_not_found"); }); const listWorkspaceInvites = vi.fn(async () => { throw new Error("database token=super-secret failed"); }); const findLegacyTenantById = vi.fn(async (tenantId: string) => { if (tenantId === "wrong_tenant") { return null; } return createLegacyTenantFixture({ id: tenantId }); }); resetApiAppDependencies = configureApiAppDependenciesForTests({ createWorkspaceInvite, acceptWorkspaceInvite, revokeWorkspaceInvite, listWorkspaceInvites, findLegacyTenantById }); const unauthorized = await app.request("/v1/workspaces/tenant_1/invites", { headers: { "x-request-id": "req_invite_unauthorized" } }); expect(unauthorized.status).toBe(401); expect(JSON.stringify(await unauthorized.json())).not.toContain("service-secret"); const invalidPayload = await app.request("/v1/workspaces/tenant_1/invites/invite_1/accept", { method: "POST", headers: { authorization: "Bearer service-secret", "content-type": "application/json", "x-request-id": "req_invite_invalid" }, body: JSON.stringify({ token: { secret: "tok_live_secret" } }), }); expect(invalidPayload.status).toBe(400); const invalidBody = await invalidPayload.json(); expect(invalidBody).toEqual({ error: { code: "invalid_request", message: "Request validation failed.", params: { reason: "field_type_invalid", field: "token", expected: "string" }, requestId: "req_invite_invalid", }, }); expect(JSON.stringify(invalidBody)).not.toContain("tok_live_secret"); const duplicate = await app.request("/v1/workspaces/tenant_1/invites", { method: "POST", headers: { authorization: "Bearer service-secret", "content-type": "application/json", "x-request-id": "req_invite_duplicate" }, body: JSON.stringify({ email: "duplicate@example.com", firstName: "Dupe", lastName: "One", type: 1 }), }); expect(duplicate.status).toBe(409); await expect(duplicate.json()).resolves.toEqual({ error: { code: "duplicate_active_invite", message: "An active workspace invite already exists.", requestId: "req_invite_duplicate" } }); const expired = await app.request("/v1/workspaces/tenant_1/invites/invite_1/accept", { method: "POST", headers: { authorization: "Bearer service-secret", "content-type": "application/json", "x-request-id": "req_invite_expired" }, body: JSON.stringify({ token: "expired-secret-token", userId: "user_1" }), }); expect(expired.status).toBe(410); const expiredBody = await expired.json(); expect(expiredBody).toEqual({ error: { code: "invite_expired", message: "Workspace invite has expired.", requestId: "req_invite_expired" } }); expect(JSON.stringify(expiredBody)).not.toContain("expired-secret-token"); const wrongTenant = await app.request("/v1/workspaces/wrong_tenant/invites/invite_1/accept", { method: "POST", headers: { authorization: "Bearer service-secret", "content-type": "application/json", "x-request-id": "req_invite_wrong_tenant" }, body: JSON.stringify({ token: "wrong-tenant-secret", userId: "user_1" }), }); expect(wrongTenant.status).toBe(404); expect(acceptWorkspaceInvite).not.toHaveBeenCalledWith(expect.objectContaining({ tenantId: "wrong_tenant" })); expect(JSON.stringify(await wrongTenant.json())).not.toContain("wrong-tenant-secret"); const notFound = await app.request("/v1/workspaces/tenant_1/invites/missing/revoke", { method: "POST", headers: { authorization: "Bearer service-secret", "content-type": "application/json", "x-request-id": "req_invite_missing" }, body: JSON.stringify({ revokedByUserId: "admin_1" }), }); expect(notFound.status).toBe(404); await expect(notFound.json()).resolves.toEqual({ error: { code: "invite_not_found", message: "Workspace invite was not found.", requestId: "req_invite_missing" } }); const unexpected = await app.request("/v1/workspaces/tenant_1/invites", { headers: { authorization: "Bearer service-secret", "x-request-id": "req_invite_failed" } }); expect(unexpected.status).toBe(500); const failedBody = await unexpected.json(); expect(failedBody).toEqual({ error: { code: "workspace_invite_failed", message: "Workspace invite request failed.", requestId: "req_invite_failed" } }); expect(JSON.stringify(failedBody)).not.toContain("super-secret"); }); test("emits redacted notification stream errors without leaking diagnostics exceptions", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "secret" }); const getNotificationStreamSnapshot = vi.fn(async () => { throw new Error("database secret token should not leak"); }); const revalidateWorkspaceContext = vi.fn(async () => ({ valid: true as const, tenantId: "tenant_1", userId: "user_1", membership: {} as never })); resetApiAppDependencies = configureApiAppDependenciesForTests({ getNotificationStreamSnapshot, revalidateWorkspaceContext }); const response = await app.request("/v1/notifications/stream?tenantId=tenant_1&userId=user_1", { headers: { authorization: "Bearer secret", "last-event-id": "stale-cursor", "x-request-id": "req_notification_stream_error", }, }); expect(response.status).toBe(200); expect(response.headers.get("content-type")).toContain("text/event-stream"); expect(getNotificationStreamSnapshot).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1", afterCursor: "stale-cursor" }); const body = await response.text(); expect(body).toContain("event: error"); expect(body).toContain("id: stale-cursor"); expect(body).toContain("req_notification_stream_error"); expect(body).toContain("notification_stream_failed"); expect(body).not.toContain("database secret token should not leak"); expect(body).not.toContain("stack"); }); test.each([ ["/v1/auth/verify-token", "req_removed_verify_token"], ["/v1/auth/me", "req_removed_auth_me"], ])("returns not found for removed legacy auth route %s with request id", async (path, requestId) => { const response = await app.request(path, { headers: { authorization: "Bearer invalid-token", "x-request-id": requestId, }, }); expect(response.status).toBe(404); expect(response.headers.get("x-request-id")).toBe(requestId); expectApiSecurityHeaders(response); await expect(response.json()).resolves.toEqual({ error: { code: "not_found", message: "Endpoint not found.", requestId, }, }); }); test("mirrors legacy auth/login invalid JSON response", async () => { const response = await app.request("/v1/auth/login", { method: "POST", headers: { "content-type": "application/json" }, body: "{", }); expect(response.status).toBe(400); await expect(response.json()).resolves.toMatchObject({ error: { code: "invalid_request", message: "Request body must be a JSON object.", params: { reason: "body_invalid", bodyType: "login_credentials" }, requestId: expect.any(String), }, }); }); test("mirrors legacy auth/login invalid credentials responses", async () => { patchTestApiRuntimeConfig({ jwtSecret: "jwt_secret" }); const findLegacyLoginUserByEmail = vi.fn().mockResolvedValue(null); const comparePassword = vi.fn().mockResolvedValue(false); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyLoginUserByEmail, comparePassword, }); const missingFields = await app.request("/v1/auth/login", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ email: "user@example.com" }), }); expect(missingFields.status).toBe(400); await expect(missingFields.json()).resolves.toMatchObject({ error: { code: "invalid_credentials", message: "Authentication failed.", requestId: expect.any(String), }, }); const missingUser = await app.request("/v1/auth/login", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ email: "missing@example.com", password: "password" }), }); expect(missingUser.status).toBe(400); await expect(missingUser.json()).resolves.toMatchObject({ error: { code: "invalid_credentials", message: "Authentication failed.", requestId: expect.any(String), }, }); findLegacyLoginUserByEmail.mockResolvedValue({ id: "user_1", email: "user@example.com", passwordHash: "hash", }); const badPassword = await app.request("/v1/auth/login", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ email: "user@example.com", password: "wrong" }), }); expect(badPassword.status).toBe(400); await expect(badPassword.json()).resolves.toMatchObject({ error: { code: "invalid_credentials", message: "Authentication failed.", requestId: expect.any(String), }, }); expect(comparePassword).toHaveBeenCalledWith("wrong", "hash"); }); test("rejects legacy auth/login users without password hashes using a dummy-hash comparison (no null compare, constant time)", async () => { patchTestApiRuntimeConfig({ jwtSecret: "jwt_secret" }); const findLegacyLoginUserByEmail = vi.fn().mockResolvedValue({ id: "user_magic_link", email: "magic@example.com", passwordHash: null, }); const comparePassword = vi.fn().mockResolvedValue(false); const recordFailedLoginAttempt = vi.fn().mockResolvedValue(undefined); const recordSuccessfulLogin = vi.fn().mockResolvedValue(undefined); const recordLegacyLogin = vi.fn().mockResolvedValue(undefined); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyLoginUserByEmail, comparePassword, recordFailedLoginAttempt, recordSuccessfulLogin, recordLegacyLogin, }); const response = await app.request("/v1/auth/login", { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": "203.0.113.25", "x-request-id": "req_null_password_hash", }, body: JSON.stringify({ email: "magic@example.com", password: "password" }), }); expect(response.status).toBe(400); expect(response.headers.get("x-request-id")).toBe("req_null_password_hash"); await expect(response.json()).resolves.toMatchObject({ error: { code: "invalid_credentials", message: "Authentication failed.", requestId: "req_null_password_hash", }, }); expect(findLegacyLoginUserByEmail).toHaveBeenCalledWith("magic@example.com"); // A dummy-hash comparison runs to keep the response time constant and avoid // leaking that this is a passwordless account — but never against a null hash. expect(comparePassword).toHaveBeenCalledTimes(1); expect(comparePassword).toHaveBeenCalledWith("password", expect.stringMatching(/^\$2[aby]\$/)); expect(comparePassword).not.toHaveBeenCalledWith("password", null); expect(recordFailedLoginAttempt).toHaveBeenCalledTimes(1); expect(recordFailedLoginAttempt).toHaveBeenCalledWith(expect.objectContaining({ remoteAddress: null, account: "magic@example.com", })); const failedLoginRequest = recordFailedLoginAttempt.mock.calls[0]?.[0]; expect(failedLoginRequest?.headers?.get("x-forwarded-for")).toBe("203.0.113.25"); expect(recordSuccessfulLogin).not.toHaveBeenCalled(); expect(recordLegacyLogin).not.toHaveBeenCalled(); }); test("returns legacy auth/login token and user envelope for valid credentials", async () => { patchTestApiRuntimeConfig({ jwtSecret: "jwt_secret", nodeEnv: "production", routing: TEST_PRODUCTION_ROUTING }); const findLegacyLoginUserByEmail = vi.fn().mockResolvedValue({ id: "user_1", email: "user@example.com", passwordHash: "hash", }); const recordLegacyLogin = vi.fn().mockResolvedValue(undefined); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyLoginUserByEmail, recordLegacyLogin, comparePassword: vi.fn().mockResolvedValue(true), }); const response = await app.request("/v1/auth/login", { method: "POST", headers: { "content-type": "application/json", "x-request-id": "req_login", }, body: JSON.stringify({ email: "user@example.com", password: "password" }), }); expect(response.status).toBe(200); expect(response.headers.get("x-request-id")).toBe("req_login"); expect(findLegacyLoginUserByEmail).toHaveBeenCalledWith("user@example.com"); expect(recordLegacyLogin).toHaveBeenCalledWith("user_1"); const body = (await response.json()) as { token: string; user: { id: string; email: string } }; expect(body.user).toEqual({ id: "user_1", email: "user@example.com", }); const decoded = jwt.verify(body.token, testApiRuntimeConfig.jwtSecret ?? TEST_JWT_SECRET) as jwt.JwtPayload; expect(decoded).toMatchObject({ userId: "user_1", sessionId: expect.any(String), }); expect(apiSessionStore.getActiveSession(decoded.sessionId)).toMatchObject({ userId: "user_1", sessionId: decoded.sessionId, }); const setCookie = response.headers.get("set-cookie") ?? ""; expect(setCookie).toContain("hivegrid_api_session="); expect(setCookie).toContain("Domain=example.com"); expect(setCookie).toContain("SameSite=Lax"); expect(setCookie).toContain("Secure"); expect(setCookie).toContain("HttpOnly"); expect(setCookie).toContain("Path=/"); expect(setCookie).not.toContain("jwt_secret"); }); test("redacts legacy auth/login dependency failures", async () => { resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyLoginUserByEmail: vi.fn().mockRejectedValue(new Error("database unavailable jwt_secret user@example.com")), }); const response = await app.request("/v1/auth/login", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ email: "user@example.com", password: "password" }), }); expect(response.status).toBe(401); const body = await response.json(); expect(body).toMatchObject({ error: { code: "invalid_credentials", message: "Authentication failed.", requestId: expect.any(String) } }); expect(body).not.toHaveProperty("stack"); const serializedBody = JSON.stringify(body); expect(serializedBody).not.toContain("database unavailable"); expect(serializedBody).not.toContain("jwt_secret"); expect(serializedBody).not.toContain("user@example.com"); }); test("rate limits repeated legacy auth/login attempts by client IP before dependencies", async () => { patchTestApiRuntimeConfig({ jwtSecret: "jwt_secret" }); const findLegacyLoginUserByEmail = vi.fn().mockResolvedValue(null); const comparePassword = vi.fn().mockResolvedValue(false); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyLoginUserByEmail, comparePassword, }); for (let index = 0; index < LOGIN_RATE_LIMIT_IP_ATTEMPTS; index += 1) { const response = await app.request("/v1/auth/login", { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": "203.0.113.10", }, body: JSON.stringify({ email: `missing-${index}@example.com`, password: "wrong-password" }), }); expect(response.status).toBe(400); } findLegacyLoginUserByEmail.mockClear(); comparePassword.mockClear(); const loggerWarn = vi.spyOn(apiLogger, "warn").mockImplementation(() => undefined); const blocked = await app.request("/v1/auth/login", { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": "203.0.113.10", "x-request-id": "req_ip_limited", }, body: JSON.stringify({ email: "another@example.com", password: "super-secret-password" }), }); expect(blocked.status).toBe(429); expect(blocked.headers.get("Retry-After")).toBe("60"); expect(blocked.headers.get("x-request-id")).toBe("req_ip_limited"); const body = await blocked.json(); expect(body).toEqual({ error: { code: "rate_limited", message: "Too many login attempts. Try again later.", params: { retryAfterSeconds: 60 }, requestId: "req_ip_limited", }, }); expect(JSON.stringify(body)).not.toContain("another@example.com"); expect(JSON.stringify(body)).not.toContain("super-secret-password"); expect(findLegacyLoginUserByEmail).not.toHaveBeenCalled(); expect(comparePassword).not.toHaveBeenCalled(); expect(loggerWarn).toHaveBeenCalledWith( { requestId: "req_ip_limited", scope: "ip", retryAfterSeconds: 60, accountFingerprint: expect.stringMatching(/^acct_[0-9a-f]{8}$/), }, "Login rate limit blocked request" ); const serializedLog = JSON.stringify(loggerWarn.mock.calls); expect(serializedLog).not.toContain("another@example.com"); expect(serializedLog).not.toContain("super-secret-password"); loggerWarn.mockRestore(); }); test("rate limits legacy auth/login attempts by account across client IPs", async () => { patchTestApiRuntimeConfig({ jwtSecret: "jwt_secret" }); const findLegacyLoginUserByEmail = vi.fn().mockResolvedValue({ id: "user_1", email: "User@Example.com", passwordHash: "hash", }); const comparePassword = vi.fn().mockResolvedValue(false); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyLoginUserByEmail, comparePassword, }); for (let index = 0; index < LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS; index += 1) { const response = await app.request("/v1/auth/login", { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": `198.51.100.${index}`, }, body: JSON.stringify({ email: " User@Example.com ", password: "wrong-password" }), }); expect(response.status).toBe(400); } findLegacyLoginUserByEmail.mockClear(); comparePassword.mockClear(); const blocked = await app.request("/v1/auth/login", { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": "198.51.100.200", }, body: JSON.stringify({ email: "user@example.com", password: "wrong-password" }), }); expect(blocked.status).toBe(429); expect(blocked.headers.get("Retry-After")).toBe("60"); const accountRequestId = blocked.headers.get("x-request-id"); await expect(blocked.json()).resolves.toEqual({ error: { code: "rate_limited", message: "Too many login attempts. Try again later.", params: { retryAfterSeconds: 60 }, requestId: accountRequestId, }, }); expect(findLegacyLoginUserByEmail).not.toHaveBeenCalled(); expect(comparePassword).not.toHaveBeenCalled(); }); test("clears legacy auth/login account lockout after successful login", async () => { patchTestApiRuntimeConfig({ jwtSecret: "jwt_secret" }); const findLegacyLoginUserByEmail = vi.fn().mockResolvedValue({ id: "user_1", email: "user@example.com", passwordHash: "hash", }); const comparePassword = vi.fn().mockResolvedValue(false); const recordLegacyLogin = vi.fn().mockResolvedValue(undefined); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyLoginUserByEmail, comparePassword, recordLegacyLogin, }); for (let index = 0; index < LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS - 1; index += 1) { const response = await app.request("/v1/auth/login", { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": `192.0.2.${index}`, }, body: JSON.stringify({ email: "user@example.com", password: "wrong-password" }), }); expect(response.status).toBe(400); } comparePassword.mockResolvedValue(true); const success = await app.request("/v1/auth/login", { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": "192.0.2.100", }, body: JSON.stringify({ email: "user@example.com", password: "correct-password" }), }); expect(success.status).toBe(200); expect(recordLegacyLogin).toHaveBeenCalledWith("user_1"); comparePassword.mockResolvedValue(false); const afterReset = await app.request("/v1/auth/login", { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": "192.0.2.101", }, body: JSON.stringify({ email: "user@example.com", password: "wrong-password" }), }); expect(afterReset.status).toBe(400); expect(comparePassword).toHaveBeenLastCalledWith("wrong-password", "hash"); }); test("mirrors legacy auth refresh-token responses", async () => { patchTestApiRuntimeConfig({ jwtSecret: "jwt_secret", nodeEnv: "production", routing: TEST_PRODUCTION_ROUTING }); const findLegacyAuthUserById = vi.fn().mockResolvedValue({ id: "user_1", email: "user@example.com", }); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyAuthUserById, }); const session = apiSessionStore.createSession("user_1"); const token = jwt.sign({ userId: "user_1", sessionId: session.sessionId }, "jwt_secret"); const missing = await app.request("/v1/auth/refresh-token", { method: "POST", }); expect(missing.status).toBe(401); await expect(missing.json()).resolves.toMatchObject({ error: { code: "missing_token", message: "Authentication token is required.", requestId: expect.any(String) } }); const invalid = await app.request("/v1/auth/refresh-token", { method: "POST", headers: { authorization: "Bearer invalid-token" }, }); expect(invalid.status).toBe(401); await expect(invalid.json()).resolves.toMatchObject({ error: { code: "invalid_token", message: "Authentication token is invalid or expired.", requestId: expect.any(String) } }); const valid = await app.request("/v1/auth/refresh-token", { method: "POST", headers: { authorization: `Bearer ${token}`, "x-request-id": "req_refresh", }, }); expect(valid.status).toBe(200); expect(valid.headers.get("x-request-id")).toBe("req_refresh"); expect(findLegacyAuthUserById).toHaveBeenCalledWith("user_1"); expect(apiSessionStore.getActiveSession(session.sessionId)).toBeUndefined(); const body = await valid.json(); expect(body).toMatchObject({ user: { id: "user_1", email: "user@example.com", }, }); const decoded = jwt.verify(body.token, testApiRuntimeConfig.jwtSecret ?? TEST_JWT_SECRET) as jwt.JwtPayload; expect(decoded).toMatchObject({ userId: "user_1", sessionId: expect.any(String), }); expect(decoded.sessionId).not.toBe(session.sessionId); expect(apiSessionStore.getActiveSession(decoded.sessionId)).toMatchObject({ userId: "user_1", sessionId: decoded.sessionId, }); const setCookie = valid.headers.get("set-cookie") ?? ""; expect(setCookie).toContain("hivegrid_api_session="); expect(setCookie).toContain("Domain=example.com"); expect(setCookie).toContain("SameSite=Lax"); expect(setCookie).toContain("Secure"); expect(setCookie).toContain("HttpOnly"); expect(setCookie).toContain("Path=/"); expect(setCookie).not.toContain("jwt_secret"); const reused = await app.request("/v1/auth/refresh-token", { method: "POST", headers: { authorization: `Bearer ${token}` }, }); expect(reused.status).toBe(401); await expect(reused.json()).resolves.toMatchObject({ error: { code: "invalid_token", message: "Authentication token is invalid or expired.", requestId: expect.any(String) } }); }); test("revokes active API sessions on logout and clears the cookie", async () => { patchTestApiRuntimeConfig({ jwtSecret: "jwt_secret", nodeEnv: "production", routing: TEST_PRODUCTION_ROUTING }); resetApiAppDependencies = configureApiAppDependenciesForTests(); const session = apiSessionStore.createSession("user_1"); const token = jwt.sign({ userId: "user_1", sessionId: session.sessionId }, "jwt_secret"); const response = await app.request("/v1/auth/logout", { method: "POST", headers: { authorization: `Bearer ${token}`, "x-request-id": "req_logout", }, }); expect(response.status).toBe(200); expect(response.headers.get("x-request-id")).toBe("req_logout"); await expect(response.json()).resolves.toEqual({ success: true }); expect(apiSessionStore.getActiveSession(session.sessionId)).toBeUndefined(); expect(apiSessionStore.getSession(session.sessionId)).toMatchObject({ sessionId: session.sessionId, userId: "user_1", revokeReason: "logout", revokedAt: expect.any(Date), }); const setCookie = response.headers.get("set-cookie") ?? ""; expect(setCookie).toContain("hivegrid_api_session="); expect(setCookie).toContain("Max-Age=0"); expect(setCookie).toContain("Expires=Thu, 01 Jan 1970 00:00:00 GMT"); expect(setCookie).toContain("Domain=example.com"); expect(setCookie).toContain("SameSite=Lax"); expect(setCookie).toContain("Secure"); expect(setCookie).toContain("HttpOnly"); expect(setCookie).toContain("Path=/"); expect(setCookie).not.toContain(token); expect(setCookie).not.toContain("jwt_secret"); }); test("rejects refresh after logout and keeps repeated logout redacted", async () => { patchTestApiRuntimeConfig({ jwtSecret: "jwt_secret" }); const findLegacyAuthUserById = vi.fn().mockResolvedValue({ id: "user_1", email: "user@example.com", }); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyAuthUserById, }); const session = apiSessionStore.createSession("user_1"); const token = jwt.sign({ userId: "user_1", sessionId: session.sessionId }, "jwt_secret"); const logout = await app.request("/v1/auth/logout", { method: "POST", headers: { authorization: `Bearer ${token}` }, }); expect(logout.status).toBe(200); const refresh = await app.request("/v1/auth/refresh-token", { method: "POST", headers: { authorization: `Bearer ${token}` }, }); expect(refresh.status).toBe(401); await expect(refresh.json()).resolves.toMatchObject({ error: { code: "invalid_token", message: "Authentication token is invalid or expired.", requestId: expect.any(String) } }); const repeated = await app.request("/v1/auth/logout", { method: "POST", headers: { authorization: `Bearer ${token}` }, }); expect(repeated.status).toBe(401); const body = await repeated.json(); expect(body).toMatchObject({ error: { code: "invalid_token", message: "Authentication token is invalid or expired.", requestId: expect.any(String) } }); expect(apiSessionStore.getActiveSession(session.sessionId)).toBeUndefined(); const serializedBody = JSON.stringify(body); expect(serializedBody).not.toContain(token); expect(serializedBody).not.toContain("jwt_secret"); expect(serializedBody).not.toContain(session.sessionId); expect(findLegacyAuthUserById).not.toHaveBeenCalled(); }); test("rejects logout requests without valid bearer sessions", async () => { patchTestApiRuntimeConfig({ jwtSecret: "jwt_secret" }); const activeSession = apiSessionStore.createSession("user_1"); const invalidSessionToken = jwt.sign({ userId: "user_1", sessionId: "missing_session" }, "jwt_secret"); for (const headers of [undefined, { authorization: "Bearer invalid-token" }, { authorization: `Bearer ${invalidSessionToken}` }]) { const response = await app.request("/v1/auth/logout", { method: "POST", headers, }); expect(response.status).toBe(401); const body = await response.json(); expect(body).toMatchObject({ error: { code: "invalid_token", message: "Authentication token is invalid or expired.", requestId: expect.any(String) } }); const serializedBody = JSON.stringify(body); expect(serializedBody).not.toContain("invalid-token"); expect(serializedBody).not.toContain(invalidSessionToken); expect(serializedBody).not.toContain("missing_session"); expect(response.headers.get("set-cookie")).toBeNull(); } expect(apiSessionStore.getActiveSession(activeSession.sessionId)).toMatchObject(activeSession); }); test("returns legacy refresh-token error when user no longer exists", async () => { patchTestApiRuntimeConfig({ jwtSecret: "jwt_secret" }); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyAuthUserById: vi.fn().mockResolvedValue(null), }); const session = apiSessionStore.createSession("missing_user"); const token = jwt.sign({ userId: "missing_user", sessionId: session.sessionId }, testApiRuntimeConfig.jwtSecret ?? TEST_JWT_SECRET); const response = await app.request("/v1/auth/refresh-token", { method: "POST", headers: { authorization: `Bearer ${token}` }, }); expect(response.status).toBe(400); await expect(response.json()).resolves.toMatchObject({ error: { code: "invalid_credentials", message: "Authentication failed.", requestId: expect.any(String) } }); }); test("fails closed for refresh tokens without active sessions and redacts token details", async () => { patchTestApiRuntimeConfig({ jwtSecret: "jwt_secret" }); const findLegacyAuthUserById = vi.fn().mockResolvedValue({ id: "user_1", email: "user@example.com", }); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyAuthUserById, }); const legacyToken = jwt.sign({ userId: "user_1" }, "jwt_secret"); const missingSessionToken = jwt.sign({ userId: "user_1", sessionId: "missing_session" }, "jwt_secret"); const revokedSession = apiSessionStore.createSession("user_1"); apiSessionStore.revokeSession(revokedSession.sessionId, "test"); const revokedToken = jwt.sign({ userId: "user_1", sessionId: revokedSession.sessionId }, "jwt_secret"); for (const token of [legacyToken, missingSessionToken, revokedToken]) { const response = await app.request("/v1/auth/refresh-token", { method: "POST", headers: { authorization: `Bearer ${token}` }, }); expect(response.status).toBe(401); const body = await response.json(); expect(body).toMatchObject({ error: { code: "invalid_token", message: "Authentication token is invalid or expired.", requestId: expect.any(String) } }); const serializedBody = JSON.stringify(body); expect(serializedBody).not.toContain(token); expect(serializedBody).not.toContain("jwt_secret"); expect(serializedBody).not.toContain("missing_session"); expect(serializedBody).not.toContain(revokedSession.sessionId); } expect(findLegacyAuthUserById).not.toHaveBeenCalled(); }); test("validates stored API keys without echoing submitted key material", async () => { patchTestApiRuntimeConfig({ jwtSecret: "stored-hash-secret", apiAccessToken: "service-secret" }); const findLegacyApiKeyByKey = vi.fn().mockResolvedValue(createStoredApiKeyFixture({ expires: new Date("2030-01-02T03:04:05.000Z") })); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyApiKeyByKey }); const response = await app.request("/v1/api-keys/validate", { method: "POST", headers: { "content-type": "application/json", "x-request-id": "req_stored_api_key", }, body: JSON.stringify({ apiKey: "stored-plaintext-secret" }), }); expect(response.status).toBe(200); expect(response.headers.get("x-request-id")).toBe("req_stored_api_key"); expect(findLegacyApiKeyByKey).toHaveBeenCalledWith("stored-plaintext-secret", undefined, "stored-hash-secret", { allowPlaintextFallback: true }); const body = await response.json(); expect(body).toEqual({ active: true, keyType: "stored-api-key", apiKey: { id: "api_key_1", alias: "Primary integration key", tenantId: "tenant_1", tenant: { id: "tenant_1", name: "Acme", slug: "acme" }, expires: "2030-01-02T03:04:05.000Z", }, }); expect(JSON.stringify(body)).not.toContain("stored-plaintext-secret"); }); test("validates migrated API-key fixtures through hash-backed lookup without echoing submitted material", async () => { patchTestApiRuntimeConfig({ jwtSecret: "migrated-hash-secret", apiAccessToken: "service-secret" }); const migratedPlaintext = "migrated-plaintext-secret"; const findLegacyApiKeyByKey = vi.fn().mockResolvedValue( createStoredApiKeyFixture({ id: "api_key_migrated", alias: "Migrated integration key", expires: new Date("2031-02-03T04:05:06.000Z"), }), ); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyApiKeyByKey }); const response = await app.request("/v1/api-keys/validate", { method: "POST", headers: { "content-type": "application/json", "x-request-id": "req_migrated_api_key", }, body: JSON.stringify({ apiKey: migratedPlaintext }), }); expect(response.status).toBe(200); expect(response.headers.get("x-request-id")).toBe("req_migrated_api_key"); expect(findLegacyApiKeyByKey).toHaveBeenCalledWith(migratedPlaintext, undefined, "migrated-hash-secret", { allowPlaintextFallback: true }); const body = await response.json(); expect(body).toEqual({ active: true, keyType: "stored-api-key", apiKey: { id: "api_key_migrated", alias: "Migrated integration key", tenantId: "tenant_1", tenant: { id: "tenant_1", name: "Acme", slug: "acme" }, expires: "2031-02-03T04:05:06.000Z", }, }); expect(JSON.stringify(body)).not.toContain(migratedPlaintext); }); test("treats rotated API-key old plaintext as inactive fallback and new plaintext as active stored key", async () => { patchTestApiRuntimeConfig({ jwtSecret: "rotation-hash-secret", apiAccessToken: "service-secret" }); const oldPlaintext = "rotated-old-plaintext-secret"; const newPlaintext = "rotated-new-plaintext-secret"; const findLegacyApiKeyByKey = vi .fn() .mockResolvedValueOnce(null) .mockResolvedValueOnce(createStoredApiKeyFixture({ id: "api_key_rotated", alias: "Rotated integration key" })); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyApiKeyByKey }); const oldResponse = await app.request("/v1/api-keys/validate", { method: "POST", headers: { "content-type": "application/json", "x-request-id": "req_rotated_old_api_key", }, body: JSON.stringify({ apiKey: oldPlaintext }), }); expect(oldResponse.status).toBe(200); expect(oldResponse.headers.get("x-request-id")).toBe("req_rotated_old_api_key"); const oldBody = await oldResponse.json(); expect(oldBody).toEqual({ active: false, keyType: "service-token" }); expect(JSON.stringify(oldBody)).not.toContain(oldPlaintext); const newResponse = await app.request("/v1/api-keys/validate", { method: "POST", headers: { "content-type": "application/json", "x-request-id": "req_rotated_new_api_key", }, body: JSON.stringify({ apiKey: newPlaintext }), }); expect(newResponse.status).toBe(200); expect(newResponse.headers.get("x-request-id")).toBe("req_rotated_new_api_key"); expect(findLegacyApiKeyByKey).toHaveBeenNthCalledWith(1, oldPlaintext, undefined, "rotation-hash-secret", { allowPlaintextFallback: true }); expect(findLegacyApiKeyByKey).toHaveBeenNthCalledWith(2, newPlaintext, undefined, "rotation-hash-secret", { allowPlaintextFallback: true }); const newBody = await newResponse.json(); expect(newBody).toMatchObject({ active: true, keyType: "stored-api-key", apiKey: { id: "api_key_rotated", alias: "Rotated integration key", tenantId: "tenant_1", }, }); const serializedNewBody = JSON.stringify(newBody); expect(serializedNewBody).not.toContain(oldPlaintext); expect(serializedNewBody).not.toContain(newPlaintext); }); test("preserves service-token validation from API-key fields and bearer auth without accepting bearer stored-key lookup", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "secret" }); const findLegacyApiKeyByKey = vi.fn().mockResolvedValue(null); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyApiKeyByKey }); const fromBody = await app.request("/v1/api-keys/validate", { method: "POST", headers: { "content-type": "application/json", "x-request-id": "req_api_key_body", }, body: JSON.stringify({ apiKey: "secret" }), }); expect(fromBody.status).toBe(200); expect(fromBody.headers.get("x-request-id")).toBe("req_api_key_body"); await expect(fromBody.json()).resolves.toMatchObject({ active: true, keyType: "service-token", }); expect(findLegacyApiKeyByKey).not.toHaveBeenCalled(); const fromHeader = await app.request("/v1/api-keys/validate", { method: "POST", headers: { "x-api-key": "secret", "x-request-id": "req_api_key_header", }, }); expect(fromHeader.status).toBe(200); expect(fromHeader.headers.get("x-request-id")).toBe("req_api_key_header"); await expect(fromHeader.json()).resolves.toMatchObject({ active: true, keyType: "service-token", }); expect(findLegacyApiKeyByKey).not.toHaveBeenCalled(); const fromBearer = await app.request("/v1/api-keys/validate", { method: "POST", headers: { authorization: "Bearer secret", "x-request-id": "req_api_key_bearer", }, }); expect(fromBearer.status).toBe(200); expect(fromBearer.headers.get("x-request-id")).toBe("req_api_key_bearer"); await expect(fromBearer.json()).resolves.toMatchObject({ active: true, keyType: "service-token", }); expect(findLegacyApiKeyByKey).not.toHaveBeenCalled(); const invalidBearer = await app.request("/v1/api-keys/validate", { method: "POST", headers: { authorization: "Bearer stored-key-not-service-token", "x-request-id": "req_api_key_invalid_bearer", }, }); expect(invalidBearer.status).toBe(400); await expect(invalidBearer.json()).resolves.toMatchObject({ error: { code: "api_key_required", message: "API key is required.", params: { credential: "api_key", sources: "body.apiKey,x-api-key,service-bearer" }, requestId: "req_api_key_invalid_bearer", }, }); expect(findLegacyApiKeyByKey).not.toHaveBeenCalled(); }); test("passes API-key plaintext fallback cutover flag to stored-key lookup", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret", jwtSecret: "cutover-secret", apiKeys: { allowLegacyPlaintextFallback: false }, }); const findLegacyApiKeyByKey = vi.fn().mockResolvedValue(null); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyApiKeyByKey }); const response = await app.request("/v1/api-keys/validate", { method: "POST", headers: { "content-type": "application/json", "x-request-id": "req_api_key_cutover", }, body: JSON.stringify({ apiKey: "legacy-plaintext-secret" }), }); expect(response.status).toBe(200); expect(findLegacyApiKeyByKey).toHaveBeenCalledWith("legacy-plaintext-secret", undefined, "cutover-secret", { allowPlaintextFallback: false }); const body = await response.json(); expect(body).toEqual({ active: false, keyType: "service-token" }); expect(JSON.stringify(body)).not.toContain("legacy-plaintext-secret"); }); test("reports inactive and expired stored API keys as inactive", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const findLegacyApiKeyByKey = vi .fn() .mockResolvedValueOnce(createStoredApiKeyFixture({ active: false })) .mockResolvedValueOnce(createStoredApiKeyFixture({ expires: new Date("2000-01-01T00:00:00.000Z") })) .mockResolvedValueOnce(createStoredApiKeyFixture({ tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: "closed" } })); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyApiKeyByKey }); for (const apiKey of ["inactive-secret", "expired-secret", "deactivated-tenant-secret"]) { const response = await app.request("/v1/api-keys/validate", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ apiKey }), }); expect(response.status).toBe(200); const body = await response.json(); expect(body).toMatchObject({ active: false, keyType: "stored-api-key" }); expect(JSON.stringify(body)).not.toContain(apiKey); } }); test("returns structured API key validation errors without echoing secret material", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "secret" }); const missing = await app.request("/v1/api-keys/validate", { method: "POST", headers: { "x-request-id": "req_api_key_missing" }, }); expect(missing.status).toBe(400); expect(missing.headers.get("x-request-id")).toBe("req_api_key_missing"); await expect(missing.json()).resolves.toEqual({ error: { code: "api_key_required", message: "API key is required.", params: { credential: "api_key", sources: "body.apiKey,x-api-key,service-bearer" }, requestId: "req_api_key_missing", }, }); const invalid = await app.request("/v1/api-keys/validate", { method: "POST", headers: { "content-type": "application/json", "x-request-id": "req_api_key_invalid", }, body: "{", }); expect(invalid.status).toBe(400); const invalidBody = await invalid.json(); expect(invalidBody).toEqual({ error: { code: "api_key_required", message: "API key is required.", params: { credential: "api_key", sources: "body.apiKey,x-api-key,service-bearer" }, requestId: "req_api_key_invalid", }, }); expect(JSON.stringify(invalidBody)).not.toContain("secret"); const secretLikeInvalidShape = await app.request("/v1/api-keys/validate", { method: "POST", headers: { "content-type": "application/json", "x-request-id": "req_api_key_secret_shape", }, body: JSON.stringify({ apiKey: ["sk_live_secret_like_value"] }), }); expect(secretLikeInvalidShape.status).toBe(400); const secretLikeInvalidShapeBody = await secretLikeInvalidShape.json(); expect(secretLikeInvalidShapeBody).toEqual({ error: { code: "invalid_request", message: "Request validation failed.", params: { reason: "field_type_invalid", field: "apiKey", expected: "string" }, requestId: "req_api_key_secret_shape", }, }); expect(JSON.stringify(secretLikeInvalidShapeBody)).not.toContain("sk_live_secret_like_value"); }); test("keeps service-token fallback redacted when stored API-key lookup fails", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const findLegacyApiKeyByKey = vi.fn().mockResolvedValue(null); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyApiKeyByKey }); const response = await app.request("/v1/api-keys/validate", { method: "POST", headers: { "content-type": "application/json", "x-request-id": "req_api_key_wrong", }, body: JSON.stringify({ apiKey: "wrong-plaintext-secret" }), }); expect(response.status).toBe(200); expect(response.headers.get("x-request-id")).toBe("req_api_key_wrong"); const body = await response.json(); expect(body).toEqual({ active: false, keyType: "service-token" }); expect(JSON.stringify(body)).not.toContain("wrong-plaintext-secret"); }); test("rejects oversized JSON before route dependencies run", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const secretLikeBody = "sk_live_oversized_body_secret"; const findLegacyApiKeyByKey = vi.fn(); const getOrCreateAnalyticsUniqueVisitor = vi.fn(); const createAnalyticsEvent = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyApiKeyByKey, getOrCreateAnalyticsUniqueVisitor, createAnalyticsEvent, }); const response = await app.request("/v1/analytics/events", { method: "POST", headers: { "content-length": "1048577", "content-type": "application/json", authorization: "Bearer service-secret", "x-request-id": "req_body_too_large", }, body: JSON.stringify({ secretLikeBody }), }); expect(response.status).toBe(413); expect(response.headers.get("x-request-id")).toBe("req_body_too_large"); const body = await response.json(); expect(body).toEqual({ error: { code: "body_too_large", message: "Request body is too large.", requestId: "req_body_too_large", }, }); expect(JSON.stringify(body)).not.toContain(secretLikeBody); expect(JSON.stringify(body)).not.toContain("service-secret"); expect(findLegacyApiKeyByKey).not.toHaveBeenCalled(); expect(getOrCreateAnalyticsUniqueVisitor).not.toHaveBeenCalled(); expect(createAnalyticsEvent).not.toHaveBeenCalled(); }); test("returns signed export download URL for a completed service-token export without exposing artifact storage keys", async () => { vi.useFakeTimers(); vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z")); patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const exportJob = createExportDownloadJobFixture(); const findExportJobForDownload = vi.fn().mockResolvedValue(exportJob); const createSignedDownloadUrl = vi.fn().mockResolvedValue({ method: "GET", url: "https://storage.example.com/signed/export_job_1?signature=redacted", expiresAt: new Date("2026-01-01T00:05:00.000Z"), expiresInSeconds: 300, headers: { accept: "text/csv" }, }); resetApiAppDependencies = configureApiAppDependenciesForTests({ findExportJobForDownload, createSignedDownloadUrl }); const response = await app.request("/v1/exports/export_job_1/download-url?tenantId=tenant_1", { headers: { authorization: "Bearer service-secret", "x-request-id": "req_export_download_success", }, }); expect(response.status).toBe(200); expect(response.headers.get("x-request-id")).toBe("req_export_download_success"); expect(findExportJobForDownload).toHaveBeenCalledWith({ id: "export_job_1", tenantId: "tenant_1" }); expect(createSignedDownloadUrl).toHaveBeenCalledWith("exports-bucket", { key: "tenants/tenant_1/exports/export_job_1.csv", expiresInSeconds: 300, responseContentDisposition: 'attachment; filename="export_job_1.csv"', }); const body = await response.json(); expect(body).toEqual({ exportJobId: "export_job_1", requestId: "req_export_download_success", method: "GET", url: "https://storage.example.com/signed/export_job_1?signature=redacted", expiresAt: "2026-01-01T00:05:00.000Z", expiresInSeconds: 300, headers: { accept: "text/csv" }, }); expect(JSON.stringify(body)).not.toContain("exports-bucket"); expect(JSON.stringify(body)).not.toContain("tenants/tenant_1/exports/export_job_1.csv"); }); test("rejects cross-tenant export download API keys before looking up or signing storage URLs", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret", jwtSecret: "stored-hash-secret" }); const findLegacyApiKeyByKey = vi.fn().mockResolvedValue(createStoredApiKeyFixture({ tenantId: "tenant_2", tenant: { id: "tenant_2", name: "Other", slug: "other", deactivatedReason: null } })); const findExportJobForDownload = vi.fn().mockResolvedValue(null); const createSignedDownloadUrl = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyApiKeyByKey, findExportJobForDownload, createSignedDownloadUrl }); const response = await app.request("/v1/exports/export_job_1/download-url?tenantId=tenant_1", { headers: { "x-api-key": "stored-api-key-secret", "x-request-id": "req_export_download_missing", }, }); expect(response.status).toBe(403); expect(response.headers.get("x-request-id")).toBe("req_export_download_missing"); expect(findLegacyApiKeyByKey).toHaveBeenCalledWith("stored-api-key-secret", undefined, "stored-hash-secret", { allowPlaintextFallback: true }); expect(findExportJobForDownload).not.toHaveBeenCalled(); expect(createSignedDownloadUrl).not.toHaveBeenCalled(); const body = await response.json(); expect(body).toEqual({ error: { code: "forbidden", message: "API key is not authorized for this entity operation.", requestId: "req_export_download_missing", }, }); expect(JSON.stringify(body)).not.toContain("exports-bucket"); expect(JSON.stringify(body)).not.toContain("tenants/tenant_1/exports/export_job_1.csv"); expect(JSON.stringify(body)).not.toContain("stored-api-key-secret"); }); test("requires tenant scope for service-token export download requests", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const findExportJobForDownload = vi.fn().mockResolvedValue(createExportDownloadJobFixture({ status: "RUNNING" })); const createSignedDownloadUrl = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ findExportJobForDownload, createSignedDownloadUrl }); const response = await app.request("/v1/exports/export_job_1/download-url", { headers: { authorization: "Bearer service-secret", "x-request-id": "req_export_download_running", }, }); expect(response.status).toBe(400); expect(findExportJobForDownload).not.toHaveBeenCalled(); expect(createSignedDownloadUrl).not.toHaveBeenCalled(); await expect(response.json()).resolves.toEqual({ error: { code: "invalid_request", message: "tenantId is required.", requestId: "req_export_download_running", }, }); }); test("returns API error envelope when AI upload config is missing", async () => { const storageSecret = "storage_secret_key"; patchTestApiRuntimeConfig({ storage: { endpoint: "https://storage.example.com", region: "us-east-1", bucket: "novel", accessKeyId: "storage-access-key", secretAccessKey: storageSecret, }, }); patchTestApiRuntimeConfig({ storage: {} }); const response = await app.request("/v1/ai/upload", { method: "POST", headers: { authorization: `Bearer ${TEST_API_CONFIG.apiAccessToken}`, "x-request-id": "req_ai_upload_config" }, }); expect(response.status).toBe(401); expect(response.headers.get("x-request-id")).toBe("req_ai_upload_config"); const body = await response.json(); expect(body).toEqual({ error: { code: "upload_config_missing", message: "AI upload storage is not configured.", requestId: "req_ai_upload_config", }, }); expect(JSON.stringify(body)).not.toContain(storageSecret); expect(JSON.stringify(body)).not.toContain("STORAGE_SECRET_ACCESS_KEY"); }); test("rejects AI upload without service credentials before exposing storage config", async () => { patchTestApiRuntimeConfig({ storage: { endpoint: "https://storage.example.com", region: "us-east-1", bucket: "novel", accessKeyId: "storage-access-key", secretAccessKey: "storage_secret_key", }, }); const response = await app.request("/v1/ai/upload", { method: "POST", headers: { "x-request-id": "req_ai_upload_unauthorized", "x-tenant-id": "tenant_1" }, body: "file-body", }); expect(response.status).toBe(401); await expect(response.json()).resolves.toEqual({ error: { code: "unauthorized", message: "A valid service credential is required.", requestId: "req_ai_upload_unauthorized", }, }); }); test("rejects oversized AI upload before storage without echoing request secrets", async () => { patchTestApiRuntimeConfig({ storage: { endpoint: "https://storage.example.com", region: "us-east-1", bucket: "novel", accessKeyId: "storage-access-key", secretAccessKey: "storage_secret_key", }, }); const uploadFile = vi.fn().mockResolvedValue({ id: "file-id", publicUrl: null }); resetApiAppDependencies = configureApiAppDependenciesForTests({ uploadFile }); const response = await app.request("/v1/ai/upload", { method: "POST", headers: { "content-length": "10485761", "content-type": "application/octet-stream", "x-api-key": "sk_live_upload_secret", "x-request-id": "req_ai_upload_body_limit", "x-storage-secret": "storage_secret_key", "x-tenant-id": "tenant_1", }, body: "upload-body-secret", }); const responseText = await response.text(); expect(response.status).toBe(413); expect(response.headers.get("x-request-id")).toBe("req_ai_upload_body_limit"); expect(response.headers.get("x-api-body-limit")).toBe("10485760"); expect(responseText).not.toContain("sk_live_upload_secret"); expect(responseText).not.toContain("storage_secret_key"); expect(responseText).not.toContain("upload-body-secret"); expect(JSON.parse(responseText)).toEqual({ error: { code: "body_too_large", message: "Request body is too large.", requestId: "req_ai_upload_body_limit", }, }); expect(uploadFile).not.toHaveBeenCalled(); }); test.each([ ["missing", undefined], ["malformed", "not-a-number"], ])("rejects AI upload with %s content-length before storage", async (_case, contentLength) => { patchTestApiRuntimeConfig({ storage: { endpoint: "https://storage.example.com", region: "us-east-1", bucket: "novel", accessKeyId: "storage-access-key", secretAccessKey: "storage_secret_key", }, }); const uploadFile = vi.fn().mockResolvedValue({ id: "file-id", publicUrl: null }); resetApiAppDependencies = configureApiAppDependenciesForTests({ uploadFile }); const headers: Record = { authorization: `Bearer ${TEST_API_CONFIG.apiAccessToken}`, "content-type": "image/png", "x-request-id": `req_ai_upload_${_case}_length`, "x-tenant-id": "tenant_1", }; if (contentLength !== undefined) { headers["content-length"] = contentLength; } else { headers[OMIT_TEST_CONTENT_LENGTH] = "1"; } const response = await app.request("/v1/ai/upload", { method: "POST", headers, body: "file-body", }); expect(response.status).toBe(411); expect(uploadFile).not.toHaveBeenCalled(); await expect(response.json()).resolves.toEqual({ error: { code: "content_length_required", message: "Write requests with a body require a valid Content-Length header.", requestId: `req_ai_upload_${_case}_length`, }, }); }); test("preserves AI upload success response and storage dependency call", async () => { vi.useFakeTimers(); vi.setSystemTime(new Date("2026-01-01T00:00:00.123Z")); patchTestApiRuntimeConfig({ storage: { endpoint: "https://storage.example.com", region: "us-east-1", bucket: "novel", accessKeyId: "storage-access-key", secretAccessKey: "storage-secret", }, }); const uploadFile = vi.fn().mockResolvedValue({ id: "file-id", publicUrl: "https://cdn.example.com/upload.png", }); const findLegacyTenantById = vi.fn().mockResolvedValue(createLegacyTenantFixture()); resetApiAppDependencies = configureApiAppDependenciesForTests({ uploadFile, findLegacyTenantById, }); const response = await app.request("/v1/ai/upload", { method: "POST", headers: { authorization: `Bearer ${TEST_API_CONFIG.apiAccessToken}`, "content-length": "9", "content-type": "image/png", "x-filename": "hero", "x-request-id": "req_ai_upload_success", "x-tenant-id": "tenant_1", }, body: "file-body", }); expect(response.status).toBe(200); expect(response.headers.get("x-request-id")).toBe("req_ai_upload_success"); expect(findLegacyTenantById).toHaveBeenCalledWith("tenant_1"); expect(uploadFile).toHaveBeenCalledWith("novel", "tenants/tenant_1/1767225600123-hero.png", expect.any(ReadableStream), "image/png"); await expect(response.json()).resolves.toEqual({ success: true, url: "https://cdn.example.com/upload.png", }); }); test("rejects unsupported AI upload content types before writing storage", async () => { patchTestApiRuntimeConfig({ storage: { endpoint: "https://storage.example.com", region: "us-east-1", bucket: "novel", accessKeyId: "storage-access-key", secretAccessKey: "storage_secret_key", }, }); const uploadFile = vi.fn().mockResolvedValue({ id: "file-id", publicUrl: null }); resetApiAppDependencies = configureApiAppDependenciesForTests({ uploadFile }); const response = await app.request("/v1/ai/upload", { method: "POST", headers: { authorization: `Bearer ${TEST_API_CONFIG.apiAccessToken}`, "content-length": "18", "content-type": "application/x-msdownload", "x-request-id": "req_ai_upload_unsupported_type", "x-storage-secret": "storage_secret_key", "x-tenant-id": "tenant_1", }, body: "upload-body-secret", }); const responseText = await response.text(); expect(response.status).toBe(415); expect(uploadFile).not.toHaveBeenCalled(); expect(responseText).not.toContain("storage_secret_key"); expect(responseText).not.toContain("upload-body-secret"); expect(JSON.parse(responseText)).toEqual({ error: { code: "unsupported_content_type", message: "AI upload storage access denied.", requestId: "req_ai_upload_unsupported_type", }, }); }); test("denies AI upload without tenant before writing storage", async () => { patchTestApiRuntimeConfig({ storage: { endpoint: "https://storage.example.com", region: "us-east-1", bucket: "novel", accessKeyId: "storage-access-key", secretAccessKey: "storage_secret_key", }, }); const uploadFile = vi.fn().mockResolvedValue({ id: "file-id", publicUrl: null }); resetApiAppDependencies = configureApiAppDependenciesForTests({ uploadFile }); const response = await app.request("/v1/ai/upload", { method: "POST", headers: { authorization: `Bearer ${TEST_API_CONFIG.apiAccessToken}`, "content-length": "9", "x-request-id": "req_ai_upload_missing_tenant", }, body: "file-body", }); expect(response.status).toBe(400); expect(uploadFile).not.toHaveBeenCalled(); await expect(response.json()).resolves.toEqual({ error: { code: "invalid_request", message: "tenantId is required.", requestId: "req_ai_upload_missing_tenant", }, }); }); test("rejects conflicting AI upload tenant scope before writing storage", async () => { patchTestApiRuntimeConfig({ storage: { endpoint: "https://storage.example.com", region: "us-east-1", bucket: "novel", accessKeyId: "storage-access-key", secretAccessKey: "storage_secret_key", }, }); const uploadFile = vi.fn().mockResolvedValue({ id: "file-id", publicUrl: null }); const findLegacyTenantById = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ uploadFile, findLegacyTenantById }); const response = await app.request("/v1/ai/upload?tenantId=tenant_1", { method: "POST", headers: { authorization: `Bearer ${TEST_API_CONFIG.apiAccessToken}`, "content-length": "9", "content-type": "image/png", "x-request-id": "req_ai_upload_conflicting_tenant", "x-tenant-id": "tenant_2", }, body: "file-body", }); expect(response.status).toBe(400); expect(findLegacyTenantById).not.toHaveBeenCalled(); expect(uploadFile).not.toHaveBeenCalled(); await expect(response.json()).resolves.toEqual({ error: { code: "invalid_request", message: "Conflicting tenant scope values.", requestId: "req_ai_upload_conflicting_tenant", }, }); }); test.each([ ["missing tenant", null, 404, "tenant_not_found", "AI upload tenant was not found."], ["inactive tenant", createLegacyTenantFixture({ active: false, deactivatedReason: "closed" }), 403, "tenant_inactive", "AI upload tenant is not active."], ])("denies AI upload for %s before writing storage", async (_case, tenant, status, code, message) => { patchTestApiRuntimeConfig({ storage: { endpoint: "https://storage.example.com", region: "us-east-1", bucket: "novel", accessKeyId: "storage-access-key", secretAccessKey: "storage_secret_key", }, }); const uploadFile = vi.fn().mockResolvedValue({ id: "file-id", publicUrl: null }); const findLegacyTenantById = vi.fn().mockResolvedValue(tenant); resetApiAppDependencies = configureApiAppDependenciesForTests({ uploadFile, findLegacyTenantById }); const response = await app.request("/v1/ai/upload", { method: "POST", headers: { authorization: `Bearer ${TEST_API_CONFIG.apiAccessToken}`, "content-length": "9", "content-type": "image/png", "x-request-id": `req_ai_upload_${code}`, "x-tenant-id": "tenant_1", }, body: "file-body", }); expect(response.status).toBe(status); expect(findLegacyTenantById).toHaveBeenCalledWith("tenant_1"); expect(uploadFile).not.toHaveBeenCalled(); await expect(response.json()).resolves.toEqual({ error: { code, message, requestId: `req_ai_upload_${code}`, }, }); }); test("denies blocked and quarantined AI uploads before writing storage", async () => { patchTestApiRuntimeConfig({ storage: { endpoint: "https://storage.example.com", region: "us-east-1", bucket: "novel", accessKeyId: "storage-access-key", secretAccessKey: "storage_secret_key", }, }); const uploadFile = vi.fn().mockResolvedValue({ id: "file-id", publicUrl: null }); resetApiAppDependencies = configureApiAppDependenciesForTests({ uploadFile }); for (const [status, code, requestId] of [ ["blocked", "blocked_object", "req_ai_upload_blocked"], ["quarantined", "quarantined_object", "req_ai_upload_quarantined"], ] as const) { const response = await app.request("/v1/ai/upload", { method: "POST", headers: { authorization: `Bearer ${TEST_API_CONFIG.apiAccessToken}`, "content-length": "9", "x-request-id": requestId, "x-tenant-id": "tenant_1", "x-storage-object-status": status, }, body: "file-body", }); expect(response.status).toBe(403); await expect(response.json()).resolves.toEqual({ error: { code, message: "AI upload storage access denied.", requestId, }, }); } expect(uploadFile).not.toHaveBeenCalled(); }); test("denies malicious AI upload filenames without leaking body or storage secret", async () => { patchTestApiRuntimeConfig({ storage: { endpoint: "https://storage.example.com", region: "us-east-1", bucket: "novel", accessKeyId: "storage-access-key", secretAccessKey: "storage_secret_key", }, }); const uploadFile = vi.fn().mockResolvedValue({ id: "file-id", publicUrl: null }); resetApiAppDependencies = configureApiAppDependenciesForTests({ uploadFile }); const response = await app.request("/v1/ai/upload", { method: "POST", headers: { authorization: `Bearer ${TEST_API_CONFIG.apiAccessToken}`, "content-length": "9", "content-type": "image/png", "x-filename": "../storage_secret_key", "x-request-id": "req_ai_upload_bad_filename", "x-tenant-id": "tenant_1", }, body: "file-body", }); expect(response.status).toBe(400); expect(uploadFile).not.toHaveBeenCalled(); const body = await response.json(); expect(body).toEqual({ error: { code: "invalid_key", message: "AI upload storage access denied.", requestId: "req_ai_upload_bad_filename", }, }); expect(JSON.stringify(body)).not.toContain("storage_secret_key"); expect(JSON.stringify(body)).not.toContain("file-body"); }); test("returns redacted API error envelope for AI upload defaults and upload failures", async () => { vi.useFakeTimers(); vi.setSystemTime(new Date("2026-01-01T00:00:00.123Z")); patchTestApiRuntimeConfig({ storage: { endpoint: "https://storage.example.com", region: "us-east-1", bucket: "novel", accessKeyId: "storage-access-key", secretAccessKey: "storage_secret_key", }, }); const uploadFile = vi.fn().mockRejectedValue(new Error("upload failed with storage_secret_key body=file-body")); const findLegacyTenantById = vi.fn().mockResolvedValue(createLegacyTenantFixture()); resetApiAppDependencies = configureApiAppDependenciesForTests({ uploadFile, findLegacyTenantById, }); const response = await app.request("/v1/ai/upload?tenantId=tenant_1", { method: "POST", headers: { authorization: `Bearer ${TEST_API_CONFIG.apiAccessToken}`, "content-length": "0", "x-request-id": "req_ai_upload_failed", }, }); expect(response.status).toBe(500); expect(response.headers.get("x-request-id")).toBe("req_ai_upload_failed"); expect(findLegacyTenantById).toHaveBeenCalledWith("tenant_1"); expect(uploadFile).toHaveBeenCalledWith("novel", "tenants/tenant_1/1767225600123-file.txt.plain", "", "text/plain"); const body = await response.json(); expect(body).toEqual({ error: { code: "ai_upload_failed", message: "AI file upload failed.", requestId: "req_ai_upload_failed", }, }); expect(JSON.stringify(body)).not.toContain("storage_secret_key"); expect(JSON.stringify(body)).not.toContain("file-body"); expect(JSON.stringify(body)).not.toContain("upload failed with storage_secret_key"); }); test("documents AI upload success and error envelopes in OpenAPI", async () => { const response = await app.request("/v1/openapi.json?source=apps/api/src/openapi.ts", { headers: { "x-request-id": "req_openapi_ai_upload" }, }); expect(response.status).toBe(200); expect(response.headers.get("x-request-id")).toBe("req_openapi_ai_upload"); const document = await response.json(); expect(document.paths["/v1/ai/upload"].post.parameters).toEqual( expect.arrayContaining([ expect.objectContaining({ name: "x-tenant-id", in: "header", required: false, schema: { type: "string", minLength: 1 }, }), expect.objectContaining({ name: "tenantId", in: "query", required: false, schema: { type: "string", minLength: 1 }, }), expect.objectContaining({ name: "x-storage-object-status", in: "header", required: false, schema: { type: "string", enum: ["available", "clean", "blocked", "quarantined"] }, }), ]) ); expect(document.paths["/v1/ai/upload"].post.security).toEqual([{ bearerAuth: [] }]); expect(document.paths["/v1/ai/upload"].post.responses).toMatchObject({ "200": { headers: { "x-request-id": expect.any(Object) }, content: { "application/json": { schema: { properties: { success: { type: "boolean", const: true }, url: { type: ["string", "null"] }, }, required: ["success", "url"], }, }, }, }, "400": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["invalid_tenant", "invalid_key"] }, requestId: { type: "string" } } }, }, }, }, }, }, "401": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["unauthorized", "upload_config_missing"] }, requestId: { type: "string" } } }, }, }, }, }, }, "403": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["tenant_mismatch", "tenant_inactive", "blocked_object", "quarantined_object"] }, requestId: { type: "string" }, }, }, }, }, }, }, }, "404": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["tenant_not_found"] }, requestId: { type: "string" } } }, }, }, }, }, }, "411": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["content_length_required"] }, requestId: { type: "string" } } }, }, }, }, }, }, "500": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["ai_upload_failed"] }, requestId: { type: "string" } } }, }, }, }, }, }, }); }); test("records analytics events through the API boundary", async () => { const visitor = createAnalyticsVisitor("visitor_1"); const getOrCreateAnalyticsUniqueVisitor = vi.fn().mockResolvedValue(visitor); const findFeatureFlagByName = vi.fn().mockResolvedValue({ id: "flag_1" }); const createAnalyticsEvent = vi.fn().mockResolvedValue(undefined); resetApiAppDependencies = configureApiAppDependenciesForTests({ getOrCreateAnalyticsUniqueVisitor, findFeatureFlagByName, createAnalyticsEvent, }); const response = await app.request("/v1/analytics/events", { method: "POST", headers: { "content-type": "application/json", "x-analytics-token": "test-analytics-token", origin: "http://app.localhost", }, body: JSON.stringify({ action: "new-dashboard", category: "featureFlag", label: "enabled", value: "1", url: "/dashboard", route: "routes/app.$tenant/dashboard", analytics: createAnalyticsInfo({ userAnalyticsId: "analytics_1", portalId: "portal_1" }), }), }); expect(response.status).toBe(201); expect(response.headers.get("access-control-allow-origin")).toBe("http://app.localhost"); expect(getOrCreateAnalyticsUniqueVisitor).toHaveBeenCalledWith({ cookie: "analytics_1", fromUrl: "/dashboard", fromRoute: "routes/app.$tenant/dashboard", analytics: expect.objectContaining({ userAnalyticsId: "analytics_1" }), }); expect(findFeatureFlagByName).toHaveBeenCalledWith("new-dashboard"); expect(createAnalyticsEvent).toHaveBeenCalledWith({ uniqueVisitorId: "visitor_1", action: "new-dashboard", category: "featureFlag", label: "enabled", value: "1", url: "/dashboard", route: "routes/app.$tenant/dashboard", featureFlagId: "flag_1", portalId: "portal_1", portalUserId: null, }); await expect(response.json()).resolves.toEqual({ success: true }); }); test("rejects analytics writes without the analytics token", async () => { const getOrCreateAnalyticsUniqueVisitor = vi.fn(); const createAnalyticsEvent = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ getOrCreateAnalyticsUniqueVisitor, createAnalyticsEvent, }); const response = await app.request("/v1/analytics/events", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ action: "clicked", category: "button", analytics: createAnalyticsInfo({ userAnalyticsId: "analytics_1" }), }), }); expect(response.status).toBe(401); expect(getOrCreateAnalyticsUniqueVisitor).not.toHaveBeenCalled(); expect(createAnalyticsEvent).not.toHaveBeenCalled(); await expect(response.json()).resolves.toMatchObject({ error: { code: "unauthorized", message: "Invalid analytics token." }, }); }); test("rejects analytics events without explicit analytics id", async () => { const secretLikeValue = "sk_live_analytics_body_secret"; const getOrCreateAnalyticsUniqueVisitor = vi.fn(); const createAnalyticsEvent = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ getOrCreateAnalyticsUniqueVisitor, createAnalyticsEvent, }); const response = await app.request("/v1/analytics/events", { method: "POST", headers: { "content-type": "application/json", "x-analytics-token": "test-analytics-token", "x-request-id": "req_analytics_invalid" }, body: JSON.stringify({ action: "clicked", category: "button", analytics: { userAnalyticsId: [secretLikeValue] }, }), }); expect(response.status).toBe(400); expect(getOrCreateAnalyticsUniqueVisitor).not.toHaveBeenCalled(); expect(createAnalyticsEvent).not.toHaveBeenCalled(); const body = await response.json(); expect(body).toEqual({ error: { code: "invalid_request", message: "Request validation failed.", params: { reason: "field_type_invalid", field: "analytics.userAnalyticsId", expected: "string" }, requestId: "req_analytics_invalid", }, }); expect(JSON.stringify(body)).not.toContain(secretLikeValue); }); test("records analytics page views and ignores configured URLs with empty 204", async () => { const visitor = createAnalyticsVisitor("visitor_1"); const getAnalyticsSettings = vi.fn().mockResolvedValueOnce({ ignorePages: "/analytics,/internal" }).mockResolvedValueOnce({ ignorePages: "/analytics" }); const getOrCreateAnalyticsUniqueVisitor = vi.fn().mockResolvedValue(visitor); const updateAnalyticsUniqueVisitorSource = vi.fn().mockResolvedValue(undefined); const createAnalyticsPageView = vi.fn().mockResolvedValue(undefined); resetApiAppDependencies = configureApiAppDependenciesForTests({ getAnalyticsSettings, getOrCreateAnalyticsUniqueVisitor, updateAnalyticsUniqueVisitorSource, createAnalyticsPageView, }); const ignored = await app.request("/v1/analytics/page-views", { method: "POST", headers: { "content-type": "application/json", "x-analytics-token": "test-analytics-token" }, body: JSON.stringify({ url: "/analytics", route: "routes/admin/analytics", analytics: createAnalyticsInfo({ userAnalyticsId: "analytics_1" }), }), }); expect(ignored.status).toBe(204); await expect(ignored.text()).resolves.toBe(""); expect(getAnalyticsSettings).toHaveBeenCalledTimes(1); expect(getOrCreateAnalyticsUniqueVisitor).not.toHaveBeenCalled(); const recorded = await app.request("/v1/analytics/page-views", { method: "POST", headers: { "content-type": "application/json", "x-analytics-token": "test-analytics-token" }, body: JSON.stringify({ url: "/dashboard", route: "routes/app.$tenant/dashboard", analytics: createAnalyticsInfo({ userAnalyticsId: "analytics_2", portalUserId: "portal_user_1" }), }), }); expect(recorded.status).toBe(201); expect(getAnalyticsSettings).toHaveBeenCalledTimes(1); expect(getOrCreateAnalyticsUniqueVisitor).toHaveBeenCalledWith({ cookie: "analytics_2", fromUrl: "/dashboard", fromRoute: "routes/app.$tenant/dashboard", analytics: expect.objectContaining({ userAnalyticsId: "analytics_2" }), }); expect(updateAnalyticsUniqueVisitorSource).toHaveBeenCalledWith(visitor, expect.objectContaining({ userAnalyticsId: "analytics_2" })); expect(createAnalyticsPageView).toHaveBeenCalledWith({ uniqueVisitorId: "visitor_1", url: "/dashboard", route: "routes/app.$tenant/dashboard", portalId: null, portalUserId: "portal_user_1", }); await expect(recorded.json()).resolves.toEqual({ success: true }); }); test("refreshes cached analytics ignored pages after the cache ttl", async () => { vi.useFakeTimers(); vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z")); const visitor = createAnalyticsVisitor("visitor_1"); const getAnalyticsSettings = vi.fn().mockResolvedValueOnce({ ignorePages: "/cached" }).mockResolvedValueOnce({ ignorePages: "/fresh" }); const getOrCreateAnalyticsUniqueVisitor = vi.fn().mockResolvedValue(visitor); const updateAnalyticsUniqueVisitorSource = vi.fn().mockResolvedValue(undefined); const createAnalyticsPageView = vi.fn().mockResolvedValue(undefined); resetApiAppDependencies = configureApiAppDependenciesForTests({ getAnalyticsSettings, getOrCreateAnalyticsUniqueVisitor, updateAnalyticsUniqueVisitorSource, createAnalyticsPageView, }); const firstIgnored = await app.request("/v1/analytics/page-views", { method: "POST", headers: { "content-type": "application/json", "x-analytics-token": "test-analytics-token" }, body: JSON.stringify({ url: "/cached", analytics: createAnalyticsInfo({ userAnalyticsId: "analytics_1" }), }), }); expect(firstIgnored.status).toBe(204); const cachedRecorded = await app.request("/v1/analytics/page-views", { method: "POST", headers: { "content-type": "application/json", "x-analytics-token": "test-analytics-token" }, body: JSON.stringify({ url: "/fresh", analytics: createAnalyticsInfo({ userAnalyticsId: "analytics_2" }), }), }); expect(cachedRecorded.status).toBe(201); expect(getAnalyticsSettings).toHaveBeenCalledTimes(1); expect(createAnalyticsPageView).toHaveBeenCalledTimes(1); vi.advanceTimersByTime(5_001); const refreshedIgnored = await app.request("/v1/analytics/page-views", { method: "POST", headers: { "content-type": "application/json", "x-analytics-token": "test-analytics-token" }, body: JSON.stringify({ url: "/fresh", analytics: createAnalyticsInfo({ userAnalyticsId: "analytics_3" }), }), }); expect(refreshedIgnored.status).toBe(204); expect(getAnalyticsSettings).toHaveBeenCalledTimes(2); expect(createAnalyticsPageView).toHaveBeenCalledTimes(1); }); test("returns public analytics overview with token auth", async () => { patchTestApiRuntimeConfig({ analytics: { token: "analytics-secret" } }); const overview = createAnalyticsOverview(); const getAnalyticsOverview = vi.fn().mockResolvedValue(overview); resetApiAppDependencies = configureApiAppDependenciesForTests({ getAnalyticsOverview, getAnalyticsSettings: vi.fn().mockResolvedValue({ public: true, ignorePages: "" }), }); const missing = await app.request("/v1/analytics/public", { headers: { "x-request-id": "req_public_missing" }, }); expect(missing.status).toBe(401); await expect(missing.json()).resolves.toMatchObject({ error: { code: "unauthorized", requestId: "req_public_missing", }, }); const response = await app.request("/v1/analytics/public?period=last-7-days", { headers: { "x-analytics-token": "analytics-secret", "x-request-id": "req_public_success", }, }); expect(response.status).toBe(200); expect(response.headers.get("x-request-id")).toBe("req_public_success"); expect(getAnalyticsOverview).toHaveBeenCalledWith({ period: "last-7-days", portalId: null }); await expect(response.json()).resolves.toEqual(overview); }); test("rejects public analytics overview when settings are not public", async () => { patchTestApiRuntimeConfig({ analytics: { token: "analytics-secret" } }); const getAnalyticsOverview = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ getAnalyticsOverview, getAnalyticsSettings: vi.fn().mockResolvedValue({ public: false, ignorePages: "" }), }); const response = await app.request("/v1/analytics/public?period=last-7-days", { headers: { "x-analytics-token": "analytics-secret", "x-request-id": "req_public_disabled", }, }); expect(response.status).toBe(403); expect(getAnalyticsOverview).not.toHaveBeenCalled(); await expect(response.json()).resolves.toEqual({ error: { code: "forbidden", message: "Public analytics overview is disabled.", requestId: "req_public_disabled", }, }); }); test("returns admin analytics overview with bearer service auth", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const overview = createAnalyticsOverview(); const getAnalyticsOverview = vi.fn().mockResolvedValue(overview); resetApiAppDependencies = configureApiAppDependenciesForTests({ getAnalyticsOverview, }); const response = await app.request("/v1/analytics/admin?period=last-30-days&portalId=portal_1", { headers: { authorization: "Bearer service-secret", "x-request-id": "req_admin_bearer", }, }); expect(response.status).toBe(200); expect(response.headers.get("x-request-id")).toBe("req_admin_bearer"); expect(getAnalyticsOverview).toHaveBeenCalledWith({ period: "last-30-days", portalId: "portal_1" }); await expect(response.json()).resolves.toEqual(overview); }); test("returns admin analytics overview with x-api-key service auth and default period", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const overview = createAnalyticsOverview(); const getAnalyticsOverview = vi.fn().mockResolvedValue(overview); resetApiAppDependencies = configureApiAppDependenciesForTests({ getAnalyticsOverview, }); const response = await app.request("/v1/analytics/admin", { headers: { authorization: "Bearer service-secret", "x-request-id": "req_admin_api_key", }, }); expect(response.status).toBe(200); expect(response.headers.get("x-request-id")).toBe("req_admin_api_key"); expect(getAnalyticsOverview).toHaveBeenCalledWith({ period: "last-30-days", portalId: undefined }); await expect(response.json()).resolves.toEqual(overview); }); test("rejects unauthenticated admin analytics requests", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const getAnalyticsOverview = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ getAnalyticsOverview, }); const response = await app.request("/v1/analytics/admin", { headers: { "x-request-id": "req_admin_missing" }, }); expect(response.status).toBe(401); expect(getAnalyticsOverview).not.toHaveBeenCalled(); await expect(response.json()).resolves.toEqual({ error: { code: "unauthorized", message: "A valid service credential is required.", requestId: "req_admin_missing", }, }); }); test("rejects invalid admin analytics periods", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const getAnalyticsOverview = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ getAnalyticsOverview, }); const response = await app.request("/v1/analytics/admin?period=tomorrow", { headers: { authorization: "Bearer service-secret", "x-request-id": "req_admin_invalid_period", }, }); expect(response.status).toBe(400); expect(getAnalyticsOverview).not.toHaveBeenCalled(); await expect(response.json()).resolves.toEqual({ error: { code: "invalid_period", message: "Invalid period.", params: { period: "tomorrow" }, requestId: "req_admin_invalid_period", }, }); }); test("redacts unhandled API errors while preserving request id parity", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const loggerError = vi.spyOn(apiLogger, "error").mockImplementation(() => undefined); const getAnalyticsOverview = vi.fn().mockRejectedValue(new Error("postgres://user:secret@db.local/app token=super-secret stack trace")); resetApiAppDependencies = configureApiAppDependenciesForTests({ getAnalyticsOverview, }); const response = await app.request("/v1/analytics/admin", { headers: { authorization: "Bearer service-secret", "x-request-id": "req_unhandled_secret", }, }); expect(response.status).toBe(500); expect(response.headers.get("x-request-id")).toBe("req_unhandled_secret"); expectApiSecurityHeaders(response); const bodyText = await response.text(); expect(bodyText).not.toContain("postgres://user:secret@db.local/app"); expect(bodyText).not.toContain("super-secret"); expect(bodyText).not.toContain("stack trace"); expect(JSON.parse(bodyText)).toEqual({ error: { code: "internal_error", message: "Internal server error.", requestId: "req_unhandled_secret", }, }); expect(loggerError).toHaveBeenCalledWith( { requestId: "req_unhandled_secret", error: expect.any(Error), }, "Unhandled API error", ); loggerError.mockRestore(); }); test("rejects invalid public analytics configuration and periods", async () => { patchTestApiRuntimeConfig({ analytics: {} }); const missingConfig = await app.request("/v1/analytics/public"); expect(missingConfig.status).toBe(500); await expect(missingConfig.json()).resolves.toMatchObject({ error: { code: "analytics_token_not_configured", }, }); patchTestApiRuntimeConfig({ analytics: { token: "1234567890" } }); const defaultToken = await app.request("/v1/analytics/public"); expect(defaultToken.status).toBe(500); patchTestApiRuntimeConfig({ analytics: { token: "analytics-secret" } }); resetApiAppDependencies = configureApiAppDependenciesForTests({ getAnalyticsSettings: vi.fn().mockResolvedValue({ public: true, ignorePages: "" }), }); const invalidPeriod = await app.request("/v1/analytics/public?period=tomorrow", { headers: { "x-analytics-token": "analytics-secret" }, }); expect(invalidPeriod.status).toBe(400); await expect(invalidPeriod.json()).resolves.toMatchObject({ error: { code: "invalid_period", message: "Invalid period.", params: { period: "tomorrow" }, }, }); }); test("mirrors legacy event webhook attempt invalid id response after valid signature", async () => { const findLegacyEventWebhookAttemptById = vi.fn().mockResolvedValue(null); const updateLegacyEventWebhookAttempt = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyEventWebhookAttemptById, updateLegacyEventWebhookAttempt, }); const request = createMailjetWebhookRequest({ event: "test" }); const response = await app.request("/v1/events/webhooks/attempts/missing", { method: "POST", headers: request.headers, body: request.body, }); expect(response.status).toBe(400); expect(findLegacyEventWebhookAttemptById).toHaveBeenCalledWith("missing"); expect(updateLegacyEventWebhookAttempt).not.toHaveBeenCalled(); await expect(response.json()).resolves.toMatchObject({ error: { code: "webhook_delivery_failed", message: "Webhook delivery request could not be accepted.", }, }); }); test("rejects event webhook attempts when signing secret is not configured before DB lookup", async () => { patchTestApiRuntimeConfig({ mailjet: {} }); const findLegacyEventWebhookAttemptById = vi.fn(); const updateLegacyEventWebhookAttempt = vi.fn(); const queueLegacyEventWebhookAttemptDelivery = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyEventWebhookAttemptById, updateLegacyEventWebhookAttempt, queueLegacyEventWebhookAttemptDelivery, }); const request = createMailjetWebhookRequest({ event: "test" }); const response = await app.request("/v1/events/webhooks/attempts/attempt_1", { method: "POST", headers: { ...request.headers, "x-request-id": "req_missing_webhook_secret" }, body: request.body, }); expect(response.status).toBe(500); expect(findLegacyEventWebhookAttemptById).not.toHaveBeenCalled(); expect(updateLegacyEventWebhookAttempt).not.toHaveBeenCalled(); expect(queueLegacyEventWebhookAttemptDelivery).not.toHaveBeenCalled(); const responseText = await response.text(); expect(responseText).not.toContain(TEST_MAILJET_WEBHOOK_SECRET); expect(responseText).not.toContain(request.body); expect(responseText).not.toContain(request.headers["authorization"]); expect(JSON.parse(responseText)).toEqual({ error: { code: "webhook_signing_not_configured", message: "Mailjet webhook authentication is not configured.", requestId: "req_missing_webhook_secret", }, }); }); test("rejects event webhook attempts with missing, stale, or invalid signatures before DB lookup", async () => { const findLegacyEventWebhookAttemptById = vi.fn(); const updateLegacyEventWebhookAttempt = vi.fn(); const queueLegacyEventWebhookAttemptDelivery = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyEventWebhookAttemptById, updateLegacyEventWebhookAttempt, queueLegacyEventWebhookAttemptDelivery, }); const validRequest = createMailjetWebhookRequest({ event: "test" }); const cases = [ { label: "missing credentials", headers: createMailjetWebhookRequest({ event: "test" }, { authorization: undefined }).headers }, { label: "malformed credentials", headers: createMailjetWebhookRequest({ event: "test" }, { authorization: "Basic not-base64!" }).headers }, { label: "wrong password", headers: createMailjetWebhookRequest({ event: "test" }, { authorization: mailjetBasicAuthHeader("wrong-secret") }).headers }, ]; for (const testCase of cases) { const headers = new Headers(testCase.headers); headers.set("x-request-id", `req_${testCase.label.replaceAll(" ", "_")}`); const response = await app.request("/v1/events/webhooks/attempts/attempt_1", { method: "POST", headers, body: validRequest.body, }); expect(response.status).toBe(401); const responseText = await response.text(); expect(responseText).not.toContain(TEST_MAILJET_WEBHOOK_SECRET); expect(responseText).not.toContain(validRequest.body); expect(responseText).not.toContain(validRequest.headers["authorization"]); expect(JSON.parse(responseText)).toMatchObject({ error: { code: "invalid_webhook_signature", message: expect.stringMatching(/^Invalid Mailjet webhook credentials: (missing-credentials|malformed-credentials|credentials-mismatch)\.$/), }, }); } expect(findLegacyEventWebhookAttemptById).not.toHaveBeenCalled(); expect(updateLegacyEventWebhookAttempt).not.toHaveBeenCalled(); expect(queueLegacyEventWebhookAttemptDelivery).not.toHaveBeenCalled(); }); test("creates support ticket from signed inbound email webhook", async () => { const createInboundSupportTicketFromEmail = vi.fn().mockResolvedValue({ status: "created", ticketId: "ticket_1", tenantId: "tenant_1" }); resetApiAppDependencies = configureApiAppDependenciesForTests({ createInboundSupportTicketFromEmail, }); const body = { messageId: "message_1", from: { email: "customer@example.test" }, to: [{ email: "support-acme@example.test" }], subject: "Need help", text: "Something is broken.", }; const request = createMailjetWebhookRequest(body); const response = await app.request("/v1/support/inbound-email", { method: "POST", headers: { ...request.headers, "x-request-id": "req_support_inbound" }, body: request.body, }); expect(response.status).toBe(201); expect(createInboundSupportTicketFromEmail).toHaveBeenCalledWith({ messageId: "message_1", fromEmail: "customer@example.test", toEmail: "support-acme@example.test", subject: "Need help", message: "Something is broken.", }); await expect(response.json()).resolves.toMatchObject({ accepted: true, status: "created", ticketId: "ticket_1", }); }); test("rejects inbound support email with invalid signature before ticket creation", async () => { const createInboundSupportTicketFromEmail = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ createInboundSupportTicketFromEmail, }); const request = createMailjetWebhookRequest({ messageId: "message_1", text: "body" }, { authorization: mailjetBasicAuthHeader("wrong-secret") }); const response = await app.request("/v1/support/inbound-email", { method: "POST", headers: request.headers, body: request.body, }); expect(response.status).toBe(401); expect(createInboundSupportTicketFromEmail).not.toHaveBeenCalled(); }); test("marks email sequence deliveries bounced from authenticated Mailjet webhooks", async () => { const markEmailSequenceDeliveryBounced = vi.fn().mockResolvedValue({ status: "bounced", deliveryId: "delivery_1", runId: "run_1", }); resetApiAppDependencies = configureApiAppDependenciesForTests({ markEmailSequenceDeliveryBounced, }); const request = createMailjetWebhookRequest({ event: "bounce", Message_GUID: "msg_sequence_1", time: "2026-01-02T03:04:05.000Z", error: "mailbox disabled", }); const response = await app.request("/v1/email-sequences/mailjet/webhooks", { method: "POST", headers: { ...request.headers, "x-request-id": "req_sequence_bounce" }, body: request.body, }); expect(response.status).toBe(202); expect(markEmailSequenceDeliveryBounced).toHaveBeenCalledWith({ providerMessageId: "msg_sequence_1", bouncedAt: new Date("2026-01-02T03:04:05.000Z"), errorMessage: "bounce: mailbox disabled", }); await expect(response.json()).resolves.toEqual({ accepted: true, status: "bounced" }); }); test("accepts numeric Mailjet message ids and ignores unknown delivery rows", async () => { const markEmailSequenceDeliveryBounced = vi.fn().mockResolvedValue({ status: "unknown_delivery" }); resetApiAppDependencies = configureApiAppDependenciesForTests({ markEmailSequenceDeliveryBounced, }); const request = createMailjetWebhookRequest({ event: "blocked", MessageID: 998877, time: 1_767_323_045, }); const response = await app.request("/v1/email-sequences/mailjet/webhooks", { method: "POST", headers: request.headers, body: request.body, }); expect(response.status).toBe(202); expect(markEmailSequenceDeliveryBounced).toHaveBeenCalledWith({ providerMessageId: "998877", bouncedAt: new Date("2026-01-02T03:04:05.000Z"), errorMessage: "blocked", }); await expect(response.json()).resolves.toEqual({ accepted: true, status: "ignored" }); }); test("ignores non-bounce Mailjet sequence events without DB writes", async () => { const markEmailSequenceDeliveryBounced = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ markEmailSequenceDeliveryBounced, }); const request = createMailjetWebhookRequest({ event: "open" }); const response = await app.request("/v1/email-sequences/mailjet/webhooks", { method: "POST", headers: request.headers, body: request.body, }); expect(response.status).toBe(202); expect(markEmailSequenceDeliveryBounced).not.toHaveBeenCalled(); await expect(response.json()).resolves.toEqual({ accepted: true, status: "ignored" }); }); test("rejects email sequence webhooks without valid Mailjet credentials before DB writes", async () => { const markEmailSequenceDeliveryBounced = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ markEmailSequenceDeliveryBounced, }); const request = createMailjetWebhookRequest({ event: "bounce", Message_GUID: "msg_1" }, { authorization: mailjetBasicAuthHeader("wrong-secret") }); const response = await app.request("/v1/email-sequences/mailjet/webhooks", { method: "POST", headers: request.headers, body: request.body, }); expect(response.status).toBe(401); expect(markEmailSequenceDeliveryBounced).not.toHaveBeenCalled(); const responseText = await response.text(); expect(responseText).not.toContain(TEST_MAILJET_WEBHOOK_SECRET); expect(responseText).not.toContain(request.body); expect(responseText).not.toContain(request.headers["authorization"]); }); test("queues legacy event webhook attempt delivery without synchronous fetch", async () => { vi.useFakeTimers(); vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z")); const attempt = { id: "attempt_1", endpoint: "https://webhook.example.com/events", tenantId: "tenant_1", }; const findLegacyEventWebhookAttemptById = vi.fn().mockResolvedValue(attempt); const updateLegacyEventWebhookAttempt = vi.fn().mockResolvedValue(undefined); const queueLegacyEventWebhookAttemptDelivery = vi.fn().mockResolvedValue({ enqueued: true, job: { id: "job_1" } }); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyEventWebhookAttemptById, updateLegacyEventWebhookAttempt, queueLegacyEventWebhookAttemptDelivery, }); const body = { event: "test" }; const request = createMailjetWebhookRequest(body); const response = await app.request("/v1/events/webhooks/attempts/attempt_1", { method: "POST", headers: { ...request.headers, "x-request-id": "req_webhook_enqueue", }, body: request.body, }); expect(response.status).toBe(200); expect(updateLegacyEventWebhookAttempt).toHaveBeenCalledTimes(1); expect(updateLegacyEventWebhookAttempt).toHaveBeenNthCalledWith(1, { id: "attempt_1", tenantId: "tenant_1" }, { startedAt: new Date("2026-01-01T00:00:00.000Z"), }); expect(queueLegacyEventWebhookAttemptDelivery).toHaveBeenCalledWith({ attempt, body, requestId: "req_webhook_enqueue" }); await expect(response.json()).resolves.toEqual({}); }); test("marks legacy event webhook attempt failed when queue connection is missing", async () => { vi.useFakeTimers(); vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z")); const updateLegacyEventWebhookAttempt = vi.fn().mockResolvedValue(undefined); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyEventWebhookAttemptById: vi.fn().mockResolvedValue({ id: "attempt_1", endpoint: "https://webhook.example.com/events", tenantId: "tenant_1", }), updateLegacyEventWebhookAttempt, queueLegacyEventWebhookAttemptDelivery: vi.fn().mockResolvedValue({ enqueued: false, reason: "missing-redis-connection" }), }); const request = createMailjetWebhookRequest({ event: "test" }); const response = await app.request("/v1/events/webhooks/attempts/attempt_1", { method: "POST", headers: request.headers, body: request.body, }); expect(response.status).toBe(503); expect(updateLegacyEventWebhookAttempt).toHaveBeenNthCalledWith(2, { id: "attempt_1", tenantId: "tenant_1" }, { finishedAt: new Date("2026-01-01T00:00:00.000Z"), success: false, status: 503, message: "Webhook delivery queue is unavailable.", }); await expect(response.json()).resolves.toMatchObject({ error: { code: "maintenance_queue_unavailable", message: "Webhook delivery queue is unavailable.", }, }); }); test("marks legacy event webhook attempt failed when enqueue throws", async () => { vi.useFakeTimers(); vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z")); const updateLegacyEventWebhookAttempt = vi.fn().mockResolvedValue(undefined); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyEventWebhookAttemptById: vi.fn().mockResolvedValue({ id: "attempt_1", endpoint: "https://webhook.example.com/events", tenantId: "tenant_1", }), updateLegacyEventWebhookAttempt, queueLegacyEventWebhookAttemptDelivery: vi.fn().mockRejectedValue(new Error("queue add failed")), }); const request = createMailjetWebhookRequest({ event: "test" }); const response = await app.request("/v1/events/webhooks/attempts/attempt_1", { method: "POST", headers: request.headers, body: request.body, }); expect(response.status).toBe(503); expect(updateLegacyEventWebhookAttempt).toHaveBeenNthCalledWith(2, { id: "attempt_1", tenantId: "tenant_1" }, { finishedAt: new Date("2026-01-01T00:00:00.000Z"), success: false, status: 503, message: "Webhook delivery queue is unavailable.", }); await expect(response.json()).resolves.toMatchObject({ error: { code: "maintenance_queue_unavailable", message: "Webhook delivery queue is unavailable.", }, }); }); test("enqueues export artifact retention cleanup from an operator endpoint", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const queueExportArtifactRetention = vi.fn().mockResolvedValue({ enqueued: true, job: { id: "retention_job_1" } }); resetApiAppDependencies = configureApiAppDependenciesForTests({ queueExportArtifactRetention }); const response = await app.request("/v1/maintenance/export-retention/enqueue", { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer service-secret", "idempotency-key": " retention-key-1 ", "x-request-id": "req_retention_enqueue", }, body: JSON.stringify({ take: 25 }), }); expect(response.status).toBe(202); expect(queueExportArtifactRetention).toHaveBeenCalledWith({ requestId: "req_retention_enqueue", idempotencyKey: "retention-key-1", take: 25 }); const body = await response.json(); expect(body).toEqual({ enqueued: true, task: "expired-export-artifacts", jobId: "retention_job_1", requestId: "req_retention_enqueue", }); expect(JSON.stringify(body)).not.toContain("retention-key-1"); }); test("rejects malformed or unexpected export retention enqueue payloads", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const queueExportArtifactRetention = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ queueExportArtifactRetention }); const malformed = await app.request("/v1/maintenance/export-retention/enqueue", { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer service-secret", "x-request-id": "req_retention_malformed", }, body: "{", }); expect(malformed.status).toBe(400); await expect(malformed.json()).resolves.toEqual({ error: { code: "invalid_request", message: "JSON body must be valid JSON when provided.", requestId: "req_retention_malformed", }, }); const unexpected = await app.request("/v1/maintenance/export-retention/enqueue", { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer service-secret", "x-request-id": "req_retention_unexpected", }, body: JSON.stringify({ take: 25, token: "secret-token" }), }); expect(unexpected.status).toBe(400); await expect(unexpected.json()).resolves.toEqual({ error: { code: "invalid_request", message: "Unexpected export retention enqueue fields.", requestId: "req_retention_unexpected", }, }); expect(queueExportArtifactRetention).not.toHaveBeenCalled(); }); test("rejects export retention enqueue when maintenance queue is unavailable", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const queueExportArtifactRetention = vi.fn().mockResolvedValue({ enqueued: false, reason: "missing-redis-connection" }); resetApiAppDependencies = configureApiAppDependenciesForTests({ queueExportArtifactRetention }); const response = await app.request("/v1/maintenance/export-retention/enqueue", { method: "POST", headers: { authorization: "Bearer service-secret", "x-request-id": "req_retention_missing_redis", }, }); expect(response.status).toBe(503); await expect(response.json()).resolves.toEqual({ error: { code: "maintenance_queue_unavailable", message: "Maintenance queue is unavailable: missing Redis connection.", requestId: "req_retention_missing_redis", }, }); }); test("rejects export retention enqueue when retention worker is disabled", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const queueExportArtifactRetention = vi.fn().mockResolvedValue({ enqueued: false, reason: "maintenance-worker-disabled" }); resetApiAppDependencies = configureApiAppDependenciesForTests({ queueExportArtifactRetention }); const response = await app.request("/v1/maintenance/export-retention/enqueue", { method: "POST", headers: { authorization: "Bearer service-secret", "x-request-id": "req_retention_disabled", }, }); expect(response.status).toBe(503); await expect(response.json()).resolves.toEqual({ error: { code: "maintenance_queue_unavailable", message: "Maintenance queue is unavailable: export retention worker is disabled.", requestId: "req_retention_disabled", }, }); }); test("rejects export retention enqueue when queue add fails", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const queueExportArtifactRetention = vi.fn().mockRejectedValue(new Error("queue add failed")); resetApiAppDependencies = configureApiAppDependenciesForTests({ queueExportArtifactRetention }); const response = await app.request("/v1/maintenance/export-retention/enqueue", { method: "POST", headers: { authorization: "Bearer service-secret", "x-request-id": "req_retention_queue_failed", }, }); expect(response.status).toBe(503); await expect(response.json()).resolves.toEqual({ error: { code: "maintenance_queue_unavailable", message: "Maintenance queue is unavailable: queue enqueue failed.", requestId: "req_retention_queue_failed", }, }); }); test("requires service credentials and bounded take for export retention enqueue", async () => { patchTestApiRuntimeConfig({ apiAccessToken: "service-secret" }); const queueExportArtifactRetention = vi.fn(); resetApiAppDependencies = configureApiAppDependenciesForTests({ queueExportArtifactRetention }); const unauthorized = await app.request("/v1/maintenance/export-retention/enqueue", { method: "POST", headers: { "x-request-id": "req_retention_unauthorized" }, }); expect(unauthorized.status).toBe(401); const invalidTake = await app.request("/v1/maintenance/export-retention/enqueue", { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer service-secret", "x-request-id": "req_retention_invalid_take", }, body: JSON.stringify({ take: 501 }), }); expect(invalidTake.status).toBe(400); await expect(invalidTake.json()).resolves.toEqual({ error: { code: "invalid_request", message: "take must be an integer between 1 and 500 when provided.", requestId: "req_retention_invalid_take", }, }); expect(queueExportArtifactRetention).not.toHaveBeenCalled(); }); test("does not expose disabled widget plugin routes through the API runtime", async () => { const routes = [ { method: "GET", path: "/v1/widgets/widget_1?tenantId=tenant_1" }, { method: "POST", path: "/v1/widgets/widget_1?tenantId=tenant_1" }, ]; for (const route of routes) { const response = await app.request(route.path, { method: route.method, headers: { "x-request-id": `req_disabled_widget_${route.method.toLowerCase()}` }, }); expect(response.status).toBe(404); await expect(response.json()).resolves.toMatchObject({ error: { code: "not_found", }, }); } }); }); function createAnalyticsInfo(overrides: Record = {}) { return { userId: null, userAnalyticsId: "analytics_1", referrer: { source: "newsletter", utm_medium: "email", }, region: { country: "DE", city: "Berlin", }, userAgent: { type: "desktop", os: { family: "macOS", version: "15", }, browser: { name: "Chrome", version: "120", }, }, ...overrides, }; } function createAnalyticsVisitor(id: string) { return { id, cookie: "analytics_1", source: null, medium: null, campaign: null, content: null, term: null, country: null, city: null, userId: null, portalUserId: null, }; } function createAnalyticsOverview() { return { uniqueVisitors: 2, pageViews: 5, events: 3, liveVisitors: 1, top: { sources: [{ name: "newsletter", count: 2 }], httpReferrers: [], urls: [{ name: "/dashboard", count: 5 }], routes: [], os: [], devices: [], countries: [], via: [], medium: [], campaign: [], user: [], }, charts: { pageViewsAndUniqueVisitors: [{ date: "Jan 1", "Page views": 5, "Unique visitors": 2 }], }, }; }