import { describe, expect, test } from "vitest"; import { createOpenApiDocument, openApiDocument } from "./openapi.js"; describe("openApiDocument", () => { test("derives OpenAPI servers from runtime routing config", () => { expect( createOpenApiDocument({ routing: { protocol: "https", apiHost: "api.example.test", webAppHost: "app.example.test", adminAppHost: "admin.example.test", portalAppHost: "portal.example.test", appBaseDomain: "example.test", }, }).servers ).toEqual([{ url: "https://api.example.test", description: "API host" }]); }); test("documents health and readiness probes", () => { expect(openApiDocument.paths["/healthz"].get).toMatchObject({ operationId: "getHealthz", security: [], responses: { "200": { headers: { "x-request-id": { schema: { type: "string" } } }, content: { "application/json": { schema: { properties: { status: { enum: ["ok"] }, service: { enum: ["api"] }, revision: { type: "string" }, requestId: { type: "string" }, }, required: ["status", "service", "revision", "requestId"], }, }, }, }, }, }); expect(openApiDocument.paths["/v1/health"].get).toMatchObject({ operationId: "getV1Health", security: [], responses: { "200": { content: { "application/json": { schema: { properties: { status: { enum: ["ok"] }, service: { enum: ["api"] }, revision: { type: "string" }, requestId: { type: "string" }, }, required: ["status", "service", "revision", "requestId"], }, }, }, }, }, }); expect(openApiDocument.paths["/readyz"].get).toMatchObject({ operationId: "getReadyz", security: [], responses: { "200": { content: { "application/json": { schema: { properties: { status: { enum: ["ready"] }, service: { enum: ["api"] }, revision: { type: "string" }, requestId: { type: "string" }, }, required: ["status", "service", "revision", "requestId"], }, }, }, }, "503": { headers: { "x-request-id": { schema: { type: "string" } } }, content: { "application/json": { schema: { properties: { status: { enum: ["not_ready"] }, service: { enum: ["api"] }, requestId: { type: "string" }, error: { properties: { code: { enum: ["dependency_unavailable"] }, message: { type: "string" }, }, required: ["code", "message"], }, }, required: ["status", "service", "requestId", "error"], }, }, }, }, }, }); }); test("documents auth primitive request correlation and credential inputs", () => { expect(openApiDocument.paths["/v1/session/current-user"].get).toMatchObject({ security: [{ bearerAuth: [] }], responses: { "401": { description: expect.stringContaining("request-ID-correlated JSON error envelope"), headers: { "x-request-id": { schema: { type: "string" }, }, }, content: { "application/json": { schema: { properties: { error: { required: ["code", "message", "requestId"], }, }, required: ["error"], }, }, }, }, }, }); const validateOperation = openApiDocument.paths["/v1/api-keys/validate"].post; expect(validateOperation).toMatchObject({ security: [{ bearerAuth: [] }, { apiKeyHeader: [] }, {}], requestBody: { required: false, content: { "application/json": { schema: { properties: { apiKey: { type: "string" }, }, }, }, }, }, responses: { "200": { content: { "application/json": { schema: { 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" }, }, required: ["id", "name", "slug"], }, expires: { type: ["string", "null"], format: "date-time" }, }, required: ["id", "alias", "tenantId", "tenant", "expires"], }, }, required: ["active", "keyType"], }, }, }, }, "400": { headers: { "x-request-id": { schema: { type: "string" }, }, }, content: { "application/json": { schema: { properties: { error: { required: ["code", "message", "requestId"], }, }, required: ["error"], }, }, }, }, }, }); expect(validateOperation.requestBody.content["application/json"].schema).toMatchObject({ additionalProperties: false, properties: { apiKey: { type: "string", maxLength: 4_096 } }, }); expect(validateOperation.requestBody.content["application/json"].schema.properties.apiKey).not.toHaveProperty("minLength"); const validationProperties = validateOperation.responses["200"].content["application/json"].schema.properties; expect(validationProperties).not.toHaveProperty("key"); expect(validationProperties.apiKey.properties).not.toHaveProperty("key"); expect(validationProperties.apiKey.properties).not.toHaveProperty("apiKey"); expect(JSON.stringify(validateOperation.responses["200"])).not.toMatch(/sk_live_[A-Za-z0-9]+|secret_[A-Za-z0-9]+/i); }); test("documents reusable body-limit envelopes only for mutating JSON boundaries", () => { const bodyLimitedOperations = [ ["/v1/auth/login", "post"], ["/v1/api-keys/validate", "post"], ["/v1/platform/leads", "post"], ["/v1/analytics/events", "post"], ["/v1/analytics/page-views", "post"], ["/v1/workspaces/{tenantId}/context/revalidate", "post"], ["/v1/workspaces/{tenantId}/invites", "post"], ["/v1/workspaces/{tenantId}/invites/{inviteId}/accept", "post"], ["/v1/workspaces/{tenantId}/invites/{inviteId}/revoke", "post"], ["/v1/support/inbound-email", "post"], ["/v1/email/inbound-mailjet", "post"], ["/v1/email-sequences/mailjet/webhooks", "post"], ["/v1/admin-sales/email/provider-events", "post"], ["/v1/admin-sales/email/bcc-inbound", "post"], ["/v1/billing/lago/webhooks", "post"], ["/v1/billing/mollie/webhooks", "post"], ["/v1/events/webhooks/attempts/{id}", "post"], ] as const; const response413s = bodyLimitedOperations.map(([path, method]) => { const documentedOperation = (openApiDocument.paths[path] as unknown as Record }>)[method]; expect(documentedOperation.responses["413"], `${path} ${method} should document body-limit rejection`).toMatchObject({ headers: { "x-request-id": { schema: { type: "string" } } }, content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["body_too_large"] }, message: { type: "string" }, requestId: { type: "string" }, }, required: ["code", "message", "requestId"], }, }, required: ["error"], }, }, }, }); return documentedOperation.responses["413"]; }); expect(new Set(response413s).size).toBe(1); const bodyLimitExcludedOperations = [ ["/healthz", "get"], ["/readyz", "get"], ["/v1/analytics/public", "get"], ["/v1/analytics/admin", "get"], ["/v1/accounts", "get"], ["/v1/accounts/{id}", "get"], ["/v1/workspaces/{tenantId}/invites", "get"], ["/v1/exports/{exportJobId}/download-url", "get"], ] as const; for (const [path, method] of bodyLimitExcludedOperations) { const documentedOperation = (openApiDocument.paths[path] as unknown as Record }>)[method]; expect(documentedOperation.responses, `${path} ${method} should not document JSON body-limit rejection`).not.toHaveProperty("413"); } }); test("documents validator-aligned request body constraints without secret examples", () => { expect(openApiDocument.paths["/v1/auth/login"].post.requestBody.content["application/json"].schema).toMatchObject({ additionalProperties: false, required: ["email", "password"], properties: { email: { type: "string", minLength: 1, maxLength: 320 }, password: { type: "string", minLength: 1, maxLength: 1_024 }, }, }); const loginRateLimitedResponse = openApiDocument.paths["/v1/auth/login"].post.responses["429"]; expect(loginRateLimitedResponse).toMatchObject({ description: expect.stringContaining("redacted"), headers: { "Retry-After": { description: expect.stringContaining("Seconds"), schema: { type: "integer", minimum: 1 }, }, "x-request-id": { schema: { type: "string" } }, }, content: { "application/json": { schema: { additionalProperties: false, properties: { error: { additionalProperties: false, properties: { code: { enum: ["rate_limited"] }, message: { type: "string" }, requestId: { type: "string" }, }, required: ["code", "message", "requestId"], }, }, required: ["error"], }, }, }, }); const serializedLoginRateLimitSchema = JSON.stringify(loginRateLimitedResponse.content["application/json"].schema); expect(serializedLoginRateLimitSchema).not.toMatch( /email|password|credential|account|token|api[-_ ]?key|[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|secret|Bearer\s+[A-Za-z0-9._~+/-]{12,}/i ); expect(openApiDocument.paths["/v1/auth/login"].post.responses["200"].description).toContain("HttpOnly hivegrid_api_session cookie"); expect(openApiDocument.paths["/v1/auth/refresh-token"].post.responses["200"].description).toContain("HttpOnly hivegrid_api_session cookie"); expect(openApiDocument.paths["/v1/auth/logout"].post).toMatchObject({ operationId: "logoutApiSession", security: [{ apiSessionBearer: [] }], responses: { "200": { description: expect.stringContaining("clears the HttpOnly hivegrid_api_session cookie") }, "401": { description: expect.stringContaining("invalid") }, }, }); expect(JSON.stringify(openApiDocument.paths["/v1/auth/login"].post.responses["200"])).not.toMatch(/jwt_secret|Bearer\s+[A-Za-z0-9._~+/-]{12,}/i); expect(JSON.stringify(openApiDocument.paths["/v1/auth/refresh-token"].post.responses["200"])).not.toMatch(/jwt_secret|Bearer\s+[A-Za-z0-9._~+/-]{12,}/i); expect(JSON.stringify(openApiDocument.paths["/v1/auth/logout"].post)).not.toMatch(/jwt_secret|Bearer\s+[A-Za-z0-9._~+/-]{12,}/i); expect(openApiDocument.paths["/v1/auth/login"].post).not.toHaveProperty("x-idempotency-key"); expect(openApiDocument.paths["/v1/auth/login"].post).not.toHaveProperty("x-api-key-permissions"); expect(openApiDocument.paths["/v1/analytics/events"].post.requestBody.content["application/json"].schema).toMatchObject({ additionalProperties: false, required: ["action", "category", "analytics"], properties: { action: { type: "string", minLength: 1, maxLength: 128 }, category: { type: "string", minLength: 1, maxLength: 128 }, label: { type: "string", maxLength: 512 }, value: { type: "string", maxLength: 2_048 }, url: { type: "string", maxLength: 4_096 }, route: { type: "string", maxLength: 1_024 }, analytics: { additionalProperties: false, required: ["userAnalyticsId"], properties: { userAnalyticsId: { type: "string", minLength: 1, maxLength: 191 }, }, }, }, }); expect(openApiDocument.paths["/v1/analytics/page-views"].post.requestBody.content["application/json"].schema).toMatchObject({ additionalProperties: false, required: ["url", "analytics"], properties: { url: { type: "string", minLength: 1, maxLength: 4_096 }, route: { type: "string", maxLength: 1_024 }, analytics: { additionalProperties: false, required: ["userAnalyticsId"], }, }, }); expect(openApiDocument.paths["/v1/api-keys/validate"].post.responses).toMatchObject({ "429": expect.any(Object), "503": expect.any(Object) }); expect(openApiDocument.paths["/v1/analytics/events"].post.responses).toMatchObject({ "429": expect.any(Object), "503": expect.any(Object) }); expect(openApiDocument.paths["/v1/analytics/page-views"].post.responses).toMatchObject({ "429": expect.any(Object), "503": expect.any(Object) }); expect(openApiDocument.paths["/v1/analytics/public"].get.responses).toMatchObject({ "429": expect.any(Object), "503": expect.any(Object) }); expect(openApiDocument.paths["/v1/billing/lago/webhooks"].post.responses).toMatchObject({ "429": expect.any(Object), "503": expect.any(Object) }); expect(openApiDocument.paths["/v1/billing/mollie/webhooks"].post.responses).toMatchObject({ "429": expect.any(Object), "503": expect.any(Object) }); expect(JSON.stringify(openApiDocument)).not.toMatch(/(?:sk|pk)_(?:live|test)_[A-Za-z0-9]+|jwt_secret|secret_[A-Za-z0-9]+|Bearer\s+[A-Za-z0-9._~+/-]{12,}/i); }); test("keeps representative public, optional-auth, and analytics-token security arrays stable", () => { expect(openApiDocument.paths["/healthz"].get.security).toEqual([]); expect(openApiDocument.paths["/readyz"].get.security).toEqual([]); expect(openApiDocument.paths["/v1/api-keys/validate"].post.security).toEqual([{ bearerAuth: [] }, { apiKeyHeader: [] }, {}]); expect(openApiDocument.paths["/v1/analytics/events"].post.security).toEqual([{ analyticsTokenHeader: [] }]); expect(openApiDocument.paths["/v1/analytics/page-views"].post.security).toEqual([{ analyticsTokenHeader: [] }]); expect(openApiDocument.paths["/v1/analytics/public"].get.security).toEqual([]); }); test("documents the source-authenticated idempotent platform lead contract without body-selected authority", () => { const operation = openApiDocument.paths["/v1/platform/leads"].post; const requestSchema = operation.requestBody.content["application/json"].schema; const metadataSchema = requestSchema.properties.metadata; expect(operation).toMatchObject({ operationId: "createPlatformLead", security: [{ platformLeadSourceBearer: [] }], parameters: [ { name: "Idempotency-Key", in: "header", required: true, schema: { type: "string", minLength: 1, maxLength: 200 }, }, ], responses: { "201": expect.any(Object), "400": expect.any(Object), "401": expect.any(Object), "409": expect.any(Object), "413": expect.any(Object), "429": expect.any(Object), }, }); expect(requestSchema).toMatchObject({ type: "object", additionalProperties: false, properties: { externalId: { type: ["string", "null"], maxLength: 256 }, sourceDetail: { type: ["string", "null"], maxLength: 500 }, firstName: { type: ["string", "null"], maxLength: 200 }, lastName: { type: ["string", "null"], maxLength: 200 }, email: { type: ["string", "null"], maxLength: 320 }, phone: { type: ["string", "null"], maxLength: 100 }, company: { type: ["string", "null"], maxLength: 300 }, message: { type: ["string", "null"], maxLength: 8_000 }, referrer: { type: ["string", "null"], maxLength: 2_048 }, landingPage: { type: ["string", "null"], maxLength: 2_048 }, }, anyOf: expect.arrayContaining([ { required: ["email"] }, { required: ["phone"] }, { required: ["company"] }, { required: ["firstName"] }, { required: ["lastName"] }, { required: ["message"] }, ]), }); expect(requestSchema.properties).not.toHaveProperty("source"); expect(metadataSchema).toMatchObject({ type: ["object", "null"], additionalProperties: false, properties: { consent: expect.any(Object), formId: expect.any(Object), formName: expect.any(Object), legacyId: expect.any(Object), legacyStore: expect.any(Object), locale: expect.any(Object), productInterest: expect.any(Object), submissionId: expect.any(Object), }, }); expect(Object.keys(metadataSchema.properties).sort()).toEqual([ "consent", "formId", "formName", "legacyId", "legacyStore", "locale", "productInterest", "submissionId", ]); expect(operation.responses["201"]).toMatchObject({ headers: { "Idempotency-Replayed": { schema: { type: "boolean" } }, "X-RateLimit-Scope": { schema: { enum: ["platform-lead-source"] } }, }, content: { "application/json": { schema: { additionalProperties: false, required: ["id", "status", "createdAt"], properties: { status: { enum: ["new", "contacted", "qualified", "disqualified"] } }, }, }, }, }); expect(operation.responses["409"].content["application/json"].schema.properties.error.properties.code.enum).toEqual([ "idempotency_key_conflict", "idempotency_key_in_progress", ]); expect(operation.responses["429"]).toMatchObject({ headers: { "Retry-After": { schema: { type: "integer", minimum: 1 } }, "X-RateLimit-Limit": expect.any(Object), "X-RateLimit-Remaining": expect.any(Object), "X-RateLimit-Reset": expect.any(Object), }, }); expect(JSON.stringify(operation)).not.toMatch(/Bearer\s+[A-Za-z0-9._~+/-]{12,}|source[_-]credential\s*[:=]/i); }); test("documents service credential gates for export download endpoints", () => { const serviceCredentialOperations = [["/v1/exports/{exportJobId}/download-url", "get"]] as const; for (const [path, method] of serviceCredentialOperations) { const documentedOperation = ( openApiDocument.paths[path] as unknown as Record< typeof method, { security: unknown; responses: Record; "x-api-key-permissions"?: unknown } > )[method]; expect(documentedOperation.security).toEqual([{ bearerAuth: [] }, { apiKeyHeader: [] }]); expect(documentedOperation.responses["401"]).toMatchObject({ headers: { "x-request-id": { schema: { type: "string" } } }, content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["unauthorized"] }, message: { type: "string" }, requestId: { type: "string" }, }, required: ["code", "message", "requestId"], }, }, required: ["error"], }, }, }, }); expect(documentedOperation).not.toHaveProperty("x-api-key-permissions"); } }); test("documents notification SSE stream contract and redaction boundaries", () => { const documentedOperation = openApiDocument.paths["/v1/notifications/stream"].get; expect(documentedOperation).toMatchObject({ operationId: "streamNotifications", description: expect.stringContaining("tenant/user scoped notification delivery diagnostics"), security: [{ bearerAuth: [] }], parameters: [ { name: "x-hivegrid-tenant-id", in: "header", required: false, schema: { type: "string", minLength: 1 } }, { name: "x-hivegrid-user-id", in: "header", required: false, schema: { type: "string", minLength: 1 } }, { name: "tenantId", in: "query", required: false, deprecated: true, schema: { type: "string", minLength: 1 } }, { name: "userId", in: "query", required: false, deprecated: true, schema: { type: "string", minLength: 1 } }, expect.objectContaining({ name: "Last-Event-ID", in: "header", required: false, description: expect.stringContaining("resume"), schema: { type: "string", minLength: 1 }, }), ], responses: { "200": { description: expect.stringContaining("bounded sanitized snapshot"), headers: { "x-request-id": { schema: { type: "string" } }, "cache-control": { schema: { type: "string", enum: ["no-cache"] } }, }, content: { "text/event-stream": { schema: { type: "string", description: expect.stringContaining("snapshot, notification, and error"), }, }, }, }, "400": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["invalid_request"] } } } } } } } }, "401": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["unauthorized"] } } } } } } } }, "500": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["notification_stream_failed"] } } } } } } } }, }, }); expect(documentedOperation.responses["200"].content).not.toHaveProperty("application/json"); expect(JSON.stringify(documentedOperation)).not.toMatch(/Bearer\s+[A-Za-z0-9._~+/-]{12,}|secret_[A-Za-z0-9]+/i); expect(JSON.stringify(documentedOperation)).toMatch(/provider payloads.*provider message ids.*metadata.*tokens.*request bodies.*raw secrets/i); }); test("documents canonical accounts API routes", () => { expect(openApiDocument.paths["/v1/accounts"].get).toMatchObject({ operationId: "listAccounts", security: [{ bearerAuth: [] }], parameters: [ expect.objectContaining({ name: "x-hivegrid-operator-user-id", in: "header", required: true, schema: { type: "string", minLength: 1, maxLength: 191 }, }), ], responses: { "200": { headers: { "x-request-id": { schema: { type: "string" } } }, content: { "application/json": { schema: { properties: { success: { const: true }, total_results: { type: "number" }, data: { type: "array" }, }, required: ["success", "total_results", "data"], }, }, }, }, "401": { content: { "application/json": { schema: { properties: { error: { required: ["code", "message", "requestId"] } } }, }, }, }, "403": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["operator_identity_required"] } } } } }, }, }, }, }, }); expect(openApiDocument.paths["/v1/accounts/{id}"].get).toMatchObject({ operationId: "getAccount", security: [{ bearerAuth: [] }], parameters: [ expect.objectContaining({ name: "x-hivegrid-operator-user-id", in: "header", required: true }), { name: "id", in: "path", required: true, schema: { type: "string", minLength: 1 } }, ], responses: { "200": { content: { "application/json": { schema: { properties: { success: { const: true }, data: expect.objectContaining({ required: expect.arrayContaining(["id", "slug", "name", "subscription"]) }), }, }, }, }, }, "404": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["account_not_found"] } } } } }, }, }, }, "403": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["operator_identity_required"] } } } } }, }, }, }, }, }); }); test("documents active canonical API-host proxy routes and omits disabled plugin surfaces", () => { expect(openApiDocument.paths["/v1/usage"].get).toMatchObject({ operationId: "getApiUsage", security: [{ apiKeyHeader: [] }], }); expect(openApiDocument.paths["/v1/contacts"].get).toMatchObject({ operationId: "listPublicApiContacts", security: [{ apiKeyHeader: [] }], parameters: expect.arrayContaining([ expect.objectContaining({ name: "x-api-key", in: "header", required: true }), expect.objectContaining({ name: "limit", in: "query" }), expect.objectContaining({ name: "cursor", in: "query" }), expect.objectContaining({ name: "fields", in: "query" }), ]), responses: { "200": expect.objectContaining({ description: expect.stringContaining("contacts"), }), "400": expect.any(Object), "401": expect.any(Object), "402": expect.any(Object), }, }); expect(openApiDocument.paths["/v1/leads"].get!.parameters).toEqual( expect.arrayContaining([expect.objectContaining({ name: "embed", description: expect.stringContaining("leadSource") })]) ); expect(openApiDocument.paths["/v1/billing/mollie/webhooks"].post).toMatchObject({ operationId: "receiveMollieBillingWebhook", security: [], requestBody: { content: { "application/x-www-form-urlencoded": { schema: expect.objectContaining({ required: ["id"] }), }, }, }, }); expect(openApiDocument.paths["/v1/billing/lago/webhooks"].post).toMatchObject({ operationId: "receiveLagoBillingWebhook", security: [ { lagoWebhookHmac: [], lagoWebhookSignatureAlgorithm: [], lagoWebhookUniqueKey: [], }, ], requestBody: { content: { "application/json": { schema: expect.objectContaining({ required: ["webhook_type", "object_type", "organization_id"], }), }, }, }, }); expect(openApiDocument.paths["/v1/webhooks/telephony/aircall"].post).toMatchObject({ operationId: "receiveAircallTelephonyWebhook", security: [], responses: { "202": expect.any(Object), "503": expect.any(Object) }, }); expect(openApiDocument.paths["/v1/webhooks/admin-telephony/aircall"].post).toMatchObject({ operationId: "receiveAdminAircallTelephonyWebhook", security: [], responses: { "202": expect.any(Object), "503": expect.any(Object) }, }); expect(openApiDocument.paths["/v1/email-sequences/mailjet/webhooks"].post).toMatchObject({ operationId: "receiveEmailSequenceMailjetWebhook", security: [{ mailjetWebhookAuth: [] }], }); expect(openApiDocument.paths).not.toHaveProperty("/v1/workflows/run/{id}"); expect(openApiDocument.paths).not.toHaveProperty("/v1/workflows/executions/{id}"); expect(openApiDocument.paths).not.toHaveProperty("/v1/workflows/executions/{id}/continue"); expect(openApiDocument.paths).not.toHaveProperty("/v1/workflows/stream/{executionId}"); expect(openApiDocument.paths).not.toHaveProperty("/v1/widgets/{id}"); }); test("documents the export download URL response envelope and error cases without artifact metadata", () => { const documentedOperation = openApiDocument.paths["/v1/exports/{exportJobId}/download-url"].get; expect(documentedOperation).toMatchObject({ operationId: "getExportDownloadUrl", description: expect.stringContaining("short-lived signed GET URL"), security: [{ bearerAuth: [] }, { apiKeyHeader: [] }], "x-api-key-placeholder": "", parameters: [ { name: "exportJobId", in: "path", required: true, schema: { type: "string", minLength: 1 } }, expect.objectContaining({ name: "tenantId", in: "query", required: false, description: expect.stringContaining("Stored API keys always use the key tenant"), }), ], responses: { "200": { headers: { "x-request-id": { schema: { type: "string" } } }, content: { "application/json": { schema: { properties: { exportJobId: { type: "string" }, requestId: { type: "string" }, method: { type: "string", enum: ["GET"] }, url: { type: "string", format: "uri" }, expiresAt: { type: "string", format: "date-time" }, expiresInSeconds: { type: "integer", enum: [300] }, headers: { type: "object", additionalProperties: { type: "string" } }, }, required: ["exportJobId", "requestId", "method", "url", "expiresAt", "expiresInSeconds", "headers"], }, }, }, }, "400": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["invalid_request"] } } } } } } } }, "401": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["unauthorized"] } } } } } } } }, "403": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["forbidden"] } } } } } } } }, "404": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["export_job_not_found"] } } } } } } } }, "409": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["export_job_paused", "export_job_not_completed", "export_artifact_missing", "export_job_expired"] } } }, }, }, }, }, }, "500": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["export_download_url_failed"] } } } } } } } }, }, }); expect(documentedOperation).not.toHaveProperty("x-api-key-permissions"); expect(documentedOperation.responses["200"].content["application/json"].schema.properties).not.toHaveProperty("artifactBucket"); expect(documentedOperation.responses["200"].content["application/json"].schema.properties).not.toHaveProperty("artifactKey"); expect(documentedOperation.responses["409"].description).toContain("paused"); expect(documentedOperation.responses["409"].description).toContain("pause reason internals are not exposed"); expect(JSON.stringify(documentedOperation.responses["200"].content["application/json"].schema.properties)).not.toMatch( /storage credentials|payload filters|object bodies/i ); expect(JSON.stringify(documentedOperation)).not.toMatch(/secret_token|super-secret-value|pause reason:|retention pause secret/i); }); test("documents workspace invite lifecycle OpenAPI contract with redacted token boundaries", () => { const listOperation = openApiDocument.paths["/v1/workspaces/{tenantId}/invites"].get; const createOperation = openApiDocument.paths["/v1/workspaces/{tenantId}/invites"].post; const acceptOperation = openApiDocument.paths["/v1/workspaces/{tenantId}/invites/{inviteId}/accept"].post; const revokeOperation = openApiDocument.paths["/v1/workspaces/{tenantId}/invites/{inviteId}/revoke"].post; expect(listOperation.operationId).toBe("listWorkspaceInvites"); expect(createOperation.operationId).toBe("createWorkspaceInvite"); expect(acceptOperation.operationId).toBe("acceptWorkspaceInvite"); expect(revokeOperation.operationId).toBe("revokeWorkspaceInvite"); for (const operation of [listOperation, createOperation, acceptOperation, revokeOperation]) { expect(operation.security).toEqual([{ bearerAuth: [] }]); expect(operation.responses["401"]).toMatchObject({ headers: { "x-request-id": { schema: { type: "string" } } }, content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["unauthorized"] } } } } } } }, }); expect(operation.responses["403"]).toMatchObject({ content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["tenant_inactive"] } } } } } } }, }); expect(JSON.stringify(operation)).not.toMatch( /tokenHash|plaintext token (?:value|sample)|(?:sk|pk)_(?:live|test)_[A-Za-z0-9]+|secret_[A-Za-z0-9]+|Bearer\s+[A-Za-z0-9._~+/-]{12,}|[A-Za-z0-9_-]{32,}\.[A-Za-z0-9_-]{16,}/i ); } expect(listOperation.parameters).toEqual([ { name: "tenantId", in: "path", required: true, schema: { type: "string", minLength: 1 } }, { name: "status", in: "query", required: false, schema: { type: "string", enum: ["pending", "accepted", "revoked", "expired"] } }, { name: "email", in: "query", required: false, schema: { type: "string", minLength: 1, format: "email" } }, ]); expect(listOperation.responses["200"].content["application/json"].schema.properties.invites.items).toMatchObject({ description: expect.stringContaining("Redacted workspace invite lifecycle envelope"), properties: { status: { enum: ["pending", "accepted", "revoked", "expired"] }, tokenPrefix: { description: expect.stringContaining("non-secret token prefix") }, createdAt: { type: ["string", "null"], format: "date-time" }, expiresAt: { type: ["string", "null"], format: "date-time" }, acceptedAt: { type: ["string", "null"], format: "date-time" }, revokedAt: { type: ["string", "null"], format: "date-time" }, }, required: expect.arrayContaining(["status", "tokenPrefix", "createdAt", "expiresAt", "acceptedAt", "revokedAt"]), }); expect(createOperation.requestBody.content["application/json"].schema).toMatchObject({ additionalProperties: true, required: ["email", "firstName", "lastName", "type"], properties: { email: { type: "string", minLength: 1, format: "email" }, firstName: { type: "string", minLength: 1 }, lastName: { type: "string", minLength: 1 }, type: { type: "integer" }, expiresAt: { type: "string", format: "date-time" }, }, }); expect(createOperation.responses["201"].content["application/json"].schema.properties.token.description).toContain("No example value"); expect(listOperation.responses["404"].content["application/json"].schema.properties.error.properties.code.enum).toEqual(["tenant_not_found"]); expect(createOperation.responses["404"].content["application/json"].schema.properties.error.properties.code.enum).toEqual(["tenant_not_found"]); expect(createOperation.responses["409"].content["application/json"].schema.properties.error.properties.code.enum).toEqual(["duplicate_active_invite"]); expect(acceptOperation.requestBody.content["application/json"].schema).toMatchObject({ additionalProperties: true, required: ["token"], properties: { token: { type: "string", minLength: 1, description: expect.stringContaining("never echoed") }, userId: { type: "string", minLength: 1 }, }, }); expect(acceptOperation.responses).toMatchObject({ "404": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["invite_not_found", "tenant_not_found"] } } } } } } }, }, "410": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["invite_expired"] } } } } } } } }, "500": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["workspace_invite_failed"] } } } } } } } }, }); expect(revokeOperation.requestBody.content["application/json"].schema).toMatchObject({ additionalProperties: true, properties: { reason: { type: "string" }, revokedByUserId: { type: "string", minLength: 1 } }, }); expect(revokeOperation.responses).toMatchObject({ "404": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["invite_not_found", "tenant_not_found"] } } } } } } }, }, "500": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["workspace_invite_failed"] } } } } } } } }, }); }); test("documents webhook retry queue outage response", () => { const operation = openApiDocument.paths["/v1/events/webhooks/attempts/{id}"].post; expect(operation.responses["503"]).toMatchObject({ content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["maintenance_queue_unavailable"] }, requestId: { type: "string" }, }, }, }, }, }, }, }); }); test("documents workspace context and auth-provider boundary contracts", () => { const revalidateOperation = openApiDocument.paths["/v1/workspaces/{tenantId}/context/revalidate"].post; const providersOperation = openApiDocument.paths["/v1/workspaces/{tenantId}/auth/providers"].get; expect(revalidateOperation).toMatchObject({ operationId: "revalidateWorkspaceContext", security: [{ bearerAuth: [] }], parameters: [{ name: "tenantId", in: "path", required: true, schema: { type: "string", minLength: 1 } }], requestBody: { required: true, content: { "application/json": { schema: { additionalProperties: true, required: ["userId"], properties: { userId: { type: "string", minLength: 1 }, providerSlug: { type: "string", minLength: 1, description: expect.stringContaining("non-authoritative") }, }, }, }, }, }, responses: { "200": { headers: { "x-request-id": { schema: { type: "string" } } }, content: { "application/json": { schema: { properties: { context: { description: expect.stringContaining("Redacted workspace context"), required: ["valid", "tenantId", "userId"], properties: { valid: { type: "boolean", const: true }, tenantId: { type: "string" }, userId: { type: "string" }, providerSlug: { type: "string" }, }, }, }, required: ["context"], }, }, }, }, "400": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["invalid_request", "context_missing_tenant_id", "context_missing_user_id"] } } } }, }, }, }, }, "401": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["unauthorized"] } } } } } } } }, "403": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["context_membership_not_found", "context_membership_not_active"] } } } } }, }, }, }, "413": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["body_too_large"] } } } } } } } }, "500": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["workspace_context_revalidation_failed"] } } } } } } }, }, }, }); expect(providersOperation).toMatchObject({ operationId: "listWorkspaceAuthProviders", security: [{ bearerAuth: [] }], parameters: [ { name: "tenantId", in: "path", required: true, schema: { type: "string", minLength: 1 } }, { name: "kind", in: "query", required: false, schema: { type: "string", enum: ["oidc", "saml"] } }, { name: "enabled", in: "query", required: false, schema: { type: "boolean" } }, ], responses: { "200": { headers: { "x-request-id": { schema: { type: "string" } } }, content: { "application/json": { schema: { properties: { providers: { type: "array", items: { description: expect.stringContaining("Redacted tenant-scoped OIDC/SAML provider metadata"), required: expect.arrayContaining([ "id", "tenantId", "kind", "slug", "enabled", "status", "certificateFingerprint", "createdAt", "updatedAt", ]), properties: { kind: { type: "string", enum: ["oidc", "saml"] }, status: { type: "string", enum: ["enabled", "disabled"] }, clientId: { type: ["string", "null"], description: expect.stringContaining("client secrets are never") }, certificateFingerprint: { type: ["string", "null"], description: expect.stringContaining("full certificate material is never returned"), }, }, }, }, }, required: ["providers"], }, }, }, }, "400": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["invalid_request"] } } } } } } } }, "401": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["unauthorized"] } } } } } } } }, "403": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["tenant_inactive", "forbidden"] } } } } } } } }, "404": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["tenant_not_found"] } } } } } } } }, "500": { content: { "application/json": { schema: { properties: { error: { properties: { code: { enum: ["workspace_auth_provider_failed", "workspace_tenant_failed"] } } } } }, }, }, }, }, }); expect(JSON.stringify(revalidateOperation)).not.toMatch( /clientSecret|tokenHash|certificatePem|privateKey|plaintext token|Bearer\s+[A-Za-z0-9._~+/-]{12,}|secret_[A-Za-z0-9]+/i ); expect(JSON.stringify(providersOperation)).not.toMatch( /clientSecret|tokenHash|certificatePem|privateKey|plaintext token|Bearer\s+[A-Za-z0-9._~+/-]{12,}|secret_[A-Za-z0-9]+/i ); }); test("documents API-session-bound device registration and revocation without response token leakage", () => { const registerOperation = openApiDocument.paths["/v1/devices/register"].post; const revokeOperation = openApiDocument.paths["/v1/devices/revoke"].post; for (const operation of [registerOperation, revokeOperation]) { expect(operation.security).toEqual([{ apiSessionBearer: [] }]); expect("parameters" in operation ? operation.parameters : []).not.toContainEqual(expect.objectContaining({ name: "x-hivegrid-user-id" })); expect(operation.responses).toHaveProperty("403"); } expect(registerOperation.requestBody.content["application/json"].schema).toMatchObject({ additionalProperties: false, required: ["token", "platform"], properties: { tenantId: { type: "string", maxLength: 128 }, pushProvider: { type: "string", enum: ["webpush"] }, }, }); expect(registerOperation.requestBody.content["application/json"].schema.properties).not.toHaveProperty("userId"); expect(registerOperation.requestBody.content["application/json"].schema.properties).not.toHaveProperty("provider"); expect(registerOperation.responses["200"].content["application/json"].schema).toMatchObject({ required: ["success", "data"], properties: { data: { required: expect.arrayContaining(["id", "userId", "tenantId", "lastSeenAt"]) } }, }); expect(revokeOperation.requestBody.content["application/json"].schema.properties).toHaveProperty("tenantId"); expect(revokeOperation.responses).toHaveProperty("404"); const revokeResponseSchema = revokeOperation.responses["200"].content["application/json"].schema; expect(revokeResponseSchema).toMatchObject({ required: ["success", "data"], properties: { data: { required: ["id", "revokedAt"] } }, }); expect(JSON.stringify(revokeResponseSchema)).not.toMatch(/"token"/i); }); test("documents stable redaction-safe security schemes", () => { expect(Object.keys(openApiDocument.components.securitySchemes).sort()).toEqual([ "analyticsTokenHeader", "apiKeyHeader", "apiSessionBearer", "bearerAuth", "lagoWebhookHmac", "lagoWebhookSignatureAlgorithm", "lagoWebhookUniqueKey", "mailjetWebhookAuth", "platformLeadSourceBearer", "providerWebhookHmac", "providerWebhookTimestamp", "webhookHmac", "webhookTokenHeader", ]); expect(openApiDocument.components.securitySchemes.bearerAuth).toMatchObject({ type: "http", scheme: "bearer", bearerFormat: "service-token", description: expect.stringContaining("Authorization header"), }); expect(openApiDocument.components.securitySchemes.apiSessionBearer).toMatchObject({ type: "http", scheme: "bearer", bearerFormat: "api-session-jwt", description: expect.stringContaining("login endpoint"), }); expect(openApiDocument.components.securitySchemes.platformLeadSourceBearer).toMatchObject({ type: "http", scheme: "bearer", bearerFormat: "platform-lead-source-key", description: expect.stringContaining("source-scoped"), }); expect(openApiDocument.components.securitySchemes.apiKeyHeader).toMatchObject({ type: "apiKey", in: "header", name: "x-api-key", description: expect.stringContaining("Service-token endpoints"), }); expect(openApiDocument.components.securitySchemes.mailjetWebhookAuth).toMatchObject({ type: "http", scheme: "basic", description: expect.stringContaining("HTTP Basic-Auth"), }); expect(openApiDocument.components.securitySchemes.analyticsTokenHeader).toMatchObject({ type: "apiKey", in: "header", name: "x-analytics-token", description: expect.stringContaining("analytics ingestion capability"), }); for (const [schemeName, scheme] of Object.entries(openApiDocument.components.securitySchemes)) { expect(scheme.description, `${schemeName} should describe its credential header`).toEqual(expect.any(String)); expect(scheme.description, `${schemeName} must not contain raw-looking secret examples`).not.toMatch( /(?:sk|pk)_(?:live|test)_[A-Za-z0-9]+|secret_[A-Za-z0-9]+|Bearer\s+[A-Za-z0-9._~+/-]{12,}/i ); } }); test("does not advertise idempotency for unsupported mutating operations", () => { const unsupportedMutatingOperations = [ ["/v1/auth/login", "post"], ["/v1/auth/refresh-token", "post"], ["/v1/api-keys/validate", "post"], ["/v1/support/inbound-email", "post"], ["/v1/email/inbound-mailjet", "post"], ["/v1/email-sequences/mailjet/webhooks", "post"], ["/v1/admin-sales/email/provider-events", "post"], ["/v1/admin-sales/email/bcc-inbound", "post"], ["/v1/billing/lago/webhooks", "post"], ["/v1/billing/mollie/webhooks", "post"], ["/v1/analytics/events", "post"], ["/v1/analytics/page-views", "post"], ["/v1/events/webhooks/attempts/{id}", "post"], ] as const; for (const [path, method] of unsupportedMutatingOperations) { const documentedOperation = ( openApiDocument.paths[path] as unknown as Record< typeof method, { parameters?: Array>; responses: Record; "x-idempotency-key"?: unknown } > )[method]; expect(documentedOperation, `${path} ${method} should not advertise unsupported idempotency`).not.toHaveProperty("x-idempotency-key"); expect(documentedOperation.responses, `${path} ${method} should not document idempotency conflicts`).not.toHaveProperty("409"); expect(documentedOperation.parameters ?? []).not.toContainEqual(expect.objectContaining({ name: "Idempotency-Key" })); } }); });