From 7e0bdb868831dbbd62deb6106931ff2c1a5c6219 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Sat, 7 Nov 2026 19:18:10 -0500 Subject: [PATCH 1/9] fix(audit): record passkey deletion DELETE /users/credentials removed a passkey without writing an audit event, so a change to what an account can sign in with left no trace. It now writes credentials_deleted naming the passkey. --- src/controllers/user.ts | 7 +++++++ tests/integration/user/user.spec.ts | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/controllers/user.ts b/src/controllers/user.ts index e5d17a89..cda2290a 100644 --- a/src/controllers/user.ts +++ b/src/controllers/user.ts @@ -217,6 +217,13 @@ export const deleteCredential = async (req: Request, res: Response) => { await cred.destroy(); + await AuthEventService.log({ + userId: authUser.id, + type: 'credentials_deleted', + req, + metadata: { credential: 'passkey', credentialId: cred.id }, + }); + return res.json({ message: 'Credential deleted' }); } catch (err) { logger.error(`Failed to delete credential: ${err}`); diff --git a/tests/integration/user/user.spec.ts b/tests/integration/user/user.spec.ts index 83ca1370..19b16713 100644 --- a/tests/integration/user/user.spec.ts +++ b/tests/integration/user/user.spec.ts @@ -6,6 +6,7 @@ import { createApp } from '../../../src/app'; import { Credential } from '../../../src/models/credentials.js'; import { Session } from '../../../src/models/sessions.js'; import { User } from '../../../src/models/users.js'; +import { AuthEventService } from '../../../src/services/authEventService.js'; import { buildCredential } from '../../factories/credentialFactory.js'; import { buildFreshStepUpSession } from '../../factories/sessionFactory.js'; @@ -177,6 +178,26 @@ describe('DELETE /users/credentials', () => { expect(cred.destroy).toHaveBeenCalled(); }); + // Removing a passkey changes what the account can sign in with, so it has to leave an + // audit record, and the credential.removed webhook is built from it. + it('audits the removal of a passkey', async () => { + const cred = buildCredential(); + + (Credential.findOne as any).mockResolvedValue(cred); + (Credential.count as any).mockResolvedValue(2); + + const res = await request(app).delete('/users/credentials').send({ id: 'cred-1' }); + + expect(res.status).toBe(200); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + userId: 'user-1', + type: 'credentials_deleted', + metadata: expect.objectContaining({ credential: 'passkey', credentialId: cred.id }), + }), + ); + }); + it('rejects deleting last credential', async () => { const cred = buildCredential(); From 6b1205abeb12e4faf08fc9477e51c07e8c045071 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Sat, 7 Nov 2026 19:18:36 -0500 Subject: [PATCH 2/9] feat(webhooks): signed, retried webhooks built from the audit log Adds webhook endpoints and deliveries behind an audited admin API with step-up on every write. Payloads use the Standard Webhooks signature scheme, are built from committed audit rows past a cursor, and are retried eight times over just under 42 hours before they are dead lettered. An endpoint that answers 410 or fails for three days is disabled. Every callout to an adopter URL goes through one transport that checks the address it connects to, never reaches link-local, multicast or the API itself, never follows redirects, and in production refuses private addresses unless CALLOUT_PRIVATE_HOSTS lists the host. Signing secrets are encrypted under CALLOUT_SECRET_ENCRYPTION_KEY. Writes session_created once per completed sign-in, which user.signed_in is built from, since login_success precedes any factor. Records the design in ADR 0005. Closes #418. --- .changeset/signed-webhooks.md | 12 + adapter-manifest.json | 14 + docs/adr/0005-extensibility-callouts.md | 121 + docs/configuration.md | 20 +- docs/production-operations.md | 1 + openapi.json | 2694 ++++++++++++++++- src/config/authSecrets.ts | 32 +- src/controllers/organizations.ts | 1 + src/controllers/webauthn.ts | 18 +- src/controllers/webhooks.ts | 181 ++ src/generated/api.ts | 2249 ++++++++++++++ src/lib/authEventCategories.ts | 2 + src/lib/calloutSigning.ts | 94 + src/lib/calloutTransport.ts | 268 ++ src/lib/oauthProviderPolicy.ts | 85 +- src/lib/outboundAddress.ts | 89 + .../20261107120000-add-webhooks.cjs | 93 + src/models/webhookDeliveries.ts | 84 + src/models/webhookEndpoints.ts | 107 + src/routes/webhooks.routes.ts | 209 ++ src/schemas/authEvent.types.ts | 7 + src/schemas/webhook.schemas.ts | 20 + src/server.ts | 8 +- src/services/sessionIssuance.ts | 11 + src/services/webhookCatalog.ts | 175 ++ src/services/webhookService.ts | 659 ++++ tests/integration/admin/adminStepUp.spec.ts | 6 + tests/integration/admin/webhooks.spec.ts | 256 ++ .../organizationRoleSecurity.spec.ts | 1 + tests/postgres/webhooks.spec.ts | 143 + tests/setup/mocks.ts | 20 + tests/unit/config/authSecrets.spec.ts | 81 +- tests/unit/lib/calloutSigning.spec.ts | 115 + tests/unit/lib/calloutTransport.spec.ts | 311 ++ tests/unit/models/models.spec.ts | 2 + .../unit/services/sessionIssueService.spec.ts | 34 + tests/unit/services/webhookCatalog.spec.ts | 196 ++ tests/unit/services/webhookService.spec.ts | 772 +++++ 38 files changed, 9074 insertions(+), 117 deletions(-) create mode 100644 .changeset/signed-webhooks.md create mode 100644 docs/adr/0005-extensibility-callouts.md create mode 100644 src/controllers/webhooks.ts create mode 100644 src/lib/calloutSigning.ts create mode 100644 src/lib/calloutTransport.ts create mode 100644 src/lib/outboundAddress.ts create mode 100644 src/migrations/20261107120000-add-webhooks.cjs create mode 100644 src/models/webhookDeliveries.ts create mode 100644 src/models/webhookEndpoints.ts create mode 100644 src/routes/webhooks.routes.ts create mode 100644 src/schemas/webhook.schemas.ts create mode 100644 src/services/webhookCatalog.ts create mode 100644 src/services/webhookService.ts create mode 100644 tests/integration/admin/webhooks.spec.ts create mode 100644 tests/postgres/webhooks.spec.ts create mode 100644 tests/unit/lib/calloutSigning.spec.ts create mode 100644 tests/unit/lib/calloutTransport.spec.ts create mode 100644 tests/unit/services/webhookCatalog.spec.ts create mode 100644 tests/unit/services/webhookService.spec.ts diff --git a/.changeset/signed-webhooks.md b/.changeset/signed-webhooks.md new file mode 100644 index 00000000..f38002cc --- /dev/null +++ b/.changeset/signed-webhooks.md @@ -0,0 +1,12 @@ +--- +'seamless-auth-api': minor +--- + +Add signed, retried webhooks (ADR 0005, #418). + +- Admin API under `/admin/webhooks` and `/admin/webhook-deliveries`: create, update, disable and delete endpoints, rotate the signing secret (the old one signs beside the new one for 24 hours), send a test event, list deliveries with a dead letter filter, and redeliver. Every write takes step-up and is audited. +- Payloads are signed with the Standard Webhooks scheme (`webhook-id`, `webhook-timestamp`, `webhook-signature`), so any Standard Webhooks verifier checks them. +- Events are built from committed audit rows, retried eight times over just under 42 hours, then dead-lettered. An endpoint that answers 410, or fails every delivery for three days, is disabled. +- Every callout to an adopter URL refuses link-local, multicast and the API's own host, never follows redirects, and in production refuses private addresses unless the host is listed in the new `CALLOUT_PRIVATE_HOSTS`. +- New env var `CALLOUT_SECRET_ENCRYPTION_KEY` encrypts stored signing secrets. Production requires it once a webhook exists. +- New audit event `session_created`, written once per completed sign-in. Deleting a passkey is now audited as `credentials_deleted`, and passkey registration names the credential. diff --git a/adapter-manifest.json b/adapter-manifest.json index 68a07d00..923aa4d6 100644 --- a/adapter-manifest.json +++ b/adapter-manifest.json @@ -106,6 +106,20 @@ "credential": "access" }, { "method": "POST", "path": "/admin/users/import", "credential": "access" }, + { "method": "GET", "path": "/admin/webhook-deliveries", "credential": "access" }, + { "method": "GET", "path": "/admin/webhook-deliveries/{deliveryId}", "credential": "access" }, + { + "method": "POST", + "path": "/admin/webhook-deliveries/{deliveryId}/redeliver", + "credential": "access" + }, + { "method": "GET", "path": "/admin/webhooks", "credential": "access" }, + { "method": "POST", "path": "/admin/webhooks", "credential": "access" }, + { "method": "DELETE", "path": "/admin/webhooks/{id}", "credential": "access" }, + { "method": "GET", "path": "/admin/webhooks/{id}", "credential": "access" }, + { "method": "PATCH", "path": "/admin/webhooks/{id}", "credential": "access" }, + { "method": "POST", "path": "/admin/webhooks/{id}/secret", "credential": "access" }, + { "method": "POST", "path": "/admin/webhooks/{id}/test", "credential": "access" }, { "method": "GET", "path": "/internal/auth-events/grouped", "credential": "access" }, { "method": "GET", "path": "/internal/auth-events/login-stats", "credential": "access" }, { "method": "GET", "path": "/internal/auth-events/summary", "credential": "access" }, diff --git a/docs/adr/0005-extensibility-callouts.md b/docs/adr/0005-extensibility-callouts.md new file mode 100644 index 00000000..11718d7d --- /dev/null +++ b/docs/adr/0005-extensibility-callouts.md @@ -0,0 +1,121 @@ +# ADR 0005: Webhooks, login hooks, custom claims and SIEM streaming + +- **Status:** Accepted +- **Date:** 2026-11-07 +- **Issues:** #417, #418, #419, #420, seamless-auth-types#146. Consumers follow in seamless-auth-oidc-provider#47, seamless-auth-server#269, seamless-auth-admin-dashboard#335 and #336, and seamless-cli#343. + +## Context + +Events are pull-only, and an app cannot change what a sign-in does or what a token carries without forking. Each of the four features makes the API call a URL an adopter chose, so they share one set of rules for reaching it. + +What already exists to build on: + +- `providerFetch` resolves DNS inside the socket's `lookup`, so the address checked is the address connected to. It refuses link-local addresses in every mode, decodes NAT64, 6to4 and IPv4-mapped forms, and never follows redirects. +- Every sign-in completes in `issueSessionAndRespond`, and every first-party token is minted in `mintAccessToken` (ADR 0004). +- `auth_events` is hash chained by a trigger, and the `seamless-auth-events/1` export carries the exact text hashed. +- TOTP seeds are AES-256-GCM encrypted under an env key. + +## Decisions + +### E1. Signatures follow Standard Webhooks + +Webhooks and login hook calls are signed with the [Standard Webhooks](https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md) scheme: headers `webhook-id`, `webhook-timestamp` and `webhook-signature`, HMAC-SHA256 over `${id}.${timestamp}.${body}`, sent as `v1,`. Secrets are `whsec_` and base64 of 32 random bytes. + +- Rotating keeps the old secret signing beside the new one for 24 hours, so the header carries two signatures and a receiver holding either verifies. Only two secrets ever sign. +- Receivers reject a timestamp more than 300 seconds from their clock and dedupe on `webhook-id`. +- Receivers in any language can use an existing verifier. Asymmetric `v1a` is left for later; it would be another signature in the same header. + +### E2. Events come from the committed audit log + +A dispatcher reads `auth_events` past a cursor (`event_dispatch_cursors`) by `seq` and turns matching rows into deliveries. An event is sent only once its row has committed, nothing is lost between happening and being queued, and the SIEM stream (#420) reads the same rows with the same hashes. + +The chain trigger updates the chain head row on every insert and holds that lock until commit, so committed rows always form a gapless prefix of `seq`: the cursor cannot step past a row that is still to commit. On first run the cursor starts at the newest row, so turning webhooks on does not replay history. Replicas take turns through an advisory lock. Delivery workers claim due rows with `FOR UPDATE SKIP LOCKED` and lease them past the request timeout, so a replica that dies mid-send leaves the delivery due again shortly after. The loop polls once a second. + +### E3. A small, versioned event catalog + +| Webhook type | From audit types | +| ----------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| `user.created` | `user_created` | +| `user.deleted` | `user_deleted` | +| `user.signed_in` | `session_created` | +| `user.recovered` | `account_recovery_completed` | +| `session.revoked` | `logout_success`, `admin_session_revoked`, `session_evicted`, `oidc_session_revoked` | +| `credential.added` | `registration_success` naming a passkey, `totp_enrollment_success`, `recovery_codes_generated` | +| `credential.removed` | `credentials_deleted` naming a passkey, `totp_disabled` | +| `organization.member_added` / `_updated` / `_removed` | `organization_member_*` | + +`webhook.test` is sent only by the test endpoint. The mapping is one table in `webhookCatalog.ts`, pinned by a test, so a new audit type reaches no receiver until it is added there. + +```json +{ + "id": "delivery uuid, the same as webhook-id", + "type": "user.signed_in", + "version": 1, + "timestamp": "when the event happened", + "data": { "userId": "...", "sessionId": "...", "method": "passkey", "organizationId": null } +} +``` + +- `data` carries identifiers and the few fields a receiver acts on. `user.created` also carries the email or phone the account was made with, read from the user at dispatch. No IP address, user agent or free-form metadata: those go to the SIEM. +- Delivery is at least once and unordered. + +### E4. Retries, dead letters and storage + +- Success is a 2xx within 15 seconds. A redirect is a failure and is not followed. +- Attempts at 0 s, then 5 s, 5 min, 30 min, 2 h, 5 h, 10 h and 24 h after the previous one, with up to 10% jitter: eight attempts, dead just under 42 hours after the event. A longer `Retry-After` is honored, up to 24 hours. +- `410 Gone` disables the endpoint. So do three days in which every delivery failed. Both write `webhook_endpoint_disabled`. +- A delivery stores the exact body sent, so a retry or redelivery sends the same bytes. Responses are read for the status alone, and only the status and a coarse failure reason are kept. Deliveries are pruned after 30 days. +- Redeliver is one attempt now with the same `webhook-id` and body and a fresh timestamp and signature. A delivery whose endpoint was disabled after it was queued is held, and redeliver can still send it. + +### E5. Login hooks + +- `post_login` runs once the factor is proven and before the session exists. It may allow or deny. It cannot add claims. +- `pre_token` runs when a token is minted for a new session and on organization switch. It may add claims or deny. It is not called on refresh: its claims are kept on the session, so refresh never waits on an adopter's server. +- One hook per trigger. Timeout 2 seconds by default, 5 at most, one attempt. +- Failure mode per hook, `closed` by default. A timeout, a non-2xx, a body that does not parse, or claims over the budget fail the sign-in when closed and are ignored when open. Every invocation is audited. +- Break-glass sign-in and recovery sessions never call a hook, so a hook that is down cannot lock out the administrator who would fix it. +- The call carries the user, method, organization, OpenID client, IP and user agent, never a token, code or secret. `reason` in the answer is audited and not shown; `userMessage` (200 characters) is. + +### E6. Custom claims + +Sources, lowest precedence first: an instance role, an organization role (while that organization is active), an OpenID Provider client (provider tokens only), then the `pre_token` hook. Values are literal JSON up to depth 3, with names matching `^[a-z][a-z0-9_]{0,63}$`. + +Reserved, refused when written and stripped (and audited) when a hook returns them: JWT registered claims, OpenID and OAuth protocol claims including `act` and `may_act`, Seamless's own claims, the OpenID standard identity claims (so no source can assert an email address the user never proved), and any name starting `seamless_` or `org_`. The list lives in `@seamless-auth/types/customClaim/reserved`, shared with the provider. + +All custom claims together get 1 KiB serialized, on top of ADR 0004's permission budget. Unlike permissions they are never dropped: a static set over the budget is refused when written, and a hook over it has failed. + +### E7. SIEM streaming + +- OTLP/HTTP with JSON encoding to `/v1/logs`, and syslog (RFC 5424) over TLS (RFC 5425) with octet counting. Plain TCP only outside production, never UDP. +- Every record carries the event's `seamless-auth-events/1` line, with `seq`, `prevHash`, `hash` and `payload`, so the chain verifies downstream as an export does. +- Each sink has its own cursor and retries until its destination takes the events, backing off to one minute. There is no dead letter: a sink falls behind and reports its lag. +- Credentials are never stored. A sink names env vars ending `_AUDIT_SINK_SECRET`, the same pattern OAuth providers use. + +### E8. Every callout follows the same reachability rules + +`calloutTransport.ts` serves webhooks, hooks and sinks: + +- `https` only in production, no userinfo, never the API's own issuer host. +- DNS resolves inside the socket's `lookup`, and every address a name resolves to must be allowed, which defeats rebinding. +- Link-local, unspecified, multicast and broadcast addresses are never reachable, in any mode, for any host. +- Other private and loopback addresses are refused in production unless the host is listed in `CALLOUT_PRIVATE_HOSTS`. It is an env var, so nothing written through the API can widen it, and it is separate from `OAUTH_PROVIDER_PRIVATE_HOSTS`, so allowing an internal hook service does not also allow it as an identity provider. +- Redirects are never followed. Responses are capped at 64 KiB. The deadline covers the whole request, so a destination that trickles bytes cannot hold a sign-in open. +- URLs are checked when written and again at connect time. +- Failures are reported as `refused`, `timed_out`, `connection_failed`, `http_status`, `invalid_response` or `too_large`, never with the resolved address or the socket's error text, so the delivery log cannot be used to map the internal network. + +### E9. Signing secrets are encrypted at rest + +They must be read back to sign, so they cannot be hashed. They are AES-256-GCM encrypted under `CALLOUT_SECRET_ENCRYPTION_KEY`, which production requires once a webhook or hook exists, and creating one is refused without it. A secret is shown once, on create and on rotate. + +## Found while building + +- `login_success` is written when `/login` resolves which methods an identifier may use, before any factor is proven, so it cannot be the source of `user.signed_in`. No event recorded that a session was created. `issueSessionAndRespond` now writes `session_created`, with the method and organization. +- Deleting a passkey (`DELETE /users/credentials`) wrote no audit event. It now writes `credentials_deleted` naming the passkey. Reproducing test first. +- Passkey registration and account registration both write `registration_success`. The passkey path now names the credential in metadata, which is how the catalog tells them apart. +- `organization_member_updated` recorded only what was added and removed. It now records the roles after the change too, which the webhook carries. + +## Consequences + +- No `system_config` key is added: every setting is a table behind admin routes with step-up on every write, so the CLI's writable keys do not change. +- Webhooks are at least once and unordered, which the guide (seamless-auth-docs#153) states, along with the retry schedule and dead letters. +- `pre_token` claims are as fresh as the session, not the token. The Auth0 mapping in seamless-auth-docs#154 has to say so. diff --git a/docs/configuration.md b/docs/configuration.md index 9217514e..0f81d507 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -114,15 +114,17 @@ then daily, and each run also logs the audit chain head as an external anchor. S ### Service tokens and secrets -| Variable | Required | Default | Notes | -| ------------------------------ | ------------------------------------ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `SEAMLESS_SERVICE_TOKEN` | Yes | - | Trusted server-adapter and internal bearer secret. No other secret falls back to it. | -| `API_SERVICE_TOKEN` | No | - | Supported fallback name for `SEAMLESS_SERVICE_TOKEN`. Used only when `SEAMLESS_SERVICE_TOKEN` is unset, with an info notice at boot. Setting both to different values stops the server at boot. | -| `REFRESH_TOKEN_LOOKUP_SECRET` | Production | development-only value | HMAC key for indexed refresh-token lookup fingerprints. Always required in production. | -| `TOTP_SECRET_ENCRYPTION_KEY` | Production, once TOTP is used | development-only value | Encrypts stored TOTP secrets (hashed with SHA-256 to derive the key, so any high-entropy value works). Production refuses to start while any TOTP credential exists without it, and `POST /totp/enroll/start` answers `409 secret_required` until it is set. | -| `OAUTH_STATE_SECRET` | Production, once OAuth is configured | development-only value | Signs OAuth state. Production refuses to start with a provider configured and no value, and adding a provider answers `409 secret_required` until it is set. | -| `DECOY_SUBJECT_SECRET` | Production | development-only value | HMAC key the decoy pre-auth subjects on `POST /login` derive from. Always required in production. Rotating it re-maps which subject an unknown identifier gets, which is harmless: decoys are stateless and pre-auth tokens live five minutes. | -| `OAUTH_PROVIDER_PRIVATE_HOSTS` | No | - | Comma-separated OAuth provider hosts allowed to resolve to private or loopback addresses in production, for an on-premises IdP. Other provider hosts must resolve to public addresses. Link-local is always refused. | +| Variable | Required | Default | Notes | +| ------------------------------- | ------------------------------------ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `SEAMLESS_SERVICE_TOKEN` | Yes | - | Trusted server-adapter and internal bearer secret. No other secret falls back to it. | +| `API_SERVICE_TOKEN` | No | - | Supported fallback name for `SEAMLESS_SERVICE_TOKEN`. Used only when `SEAMLESS_SERVICE_TOKEN` is unset, with an info notice at boot. Setting both to different values stops the server at boot. | +| `REFRESH_TOKEN_LOOKUP_SECRET` | Production | development-only value | HMAC key for indexed refresh-token lookup fingerprints. Always required in production. | +| `TOTP_SECRET_ENCRYPTION_KEY` | Production, once TOTP is used | development-only value | Encrypts stored TOTP secrets (hashed with SHA-256 to derive the key, so any high-entropy value works). Production refuses to start while any TOTP credential exists without it, and `POST /totp/enroll/start` answers `409 secret_required` until it is set. | +| `OAUTH_STATE_SECRET` | Production, once OAuth is configured | development-only value | Signs OAuth state. Production refuses to start with a provider configured and no value, and adding a provider answers `409 secret_required` until it is set. | +| `DECOY_SUBJECT_SECRET` | Production | development-only value | HMAC key the decoy pre-auth subjects on `POST /login` derive from. Always required in production. Rotating it re-maps which subject an unknown identifier gets, which is harmless: decoys are stateless and pre-auth tokens live five minutes. | +| `OAUTH_PROVIDER_PRIVATE_HOSTS` | No | - | Comma-separated OAuth provider hosts allowed to resolve to private or loopback addresses in production, for an on-premises IdP. Other provider hosts must resolve to public addresses. Link-local is always refused. | +| `CALLOUT_SECRET_ENCRYPTION_KEY` | Production, once a webhook exists | development-only value | Encrypts stored webhook signing secrets (hashed with SHA-256 to derive the key). Production refuses to start while any webhook exists without it, and creating one answers `409` until it is set. | +| `CALLOUT_PRIVATE_HOSTS` | No | - | Comma-separated webhook hosts allowed to resolve to private or loopback addresses in production, for a receiver inside your own network. Separate from `OAUTH_PROVIDER_PRIVATE_HOSTS`. Link-local, multicast and the unspecified address are always refused, and a webhook can never point at the API's own issuer host. | > None of these falls back to the service token. Development (any `NODE_ENV` other than > `production`) uses a fixed development-only value for each unset one, with a warning. See diff --git a/docs/production-operations.md b/docs/production-operations.md index 74d102c3..d7e05f5f 100644 --- a/docs/production-operations.md +++ b/docs/production-operations.md @@ -98,6 +98,7 @@ Production deployments should define: - `REFRESH_TOKEN_LOOKUP_SECRET` - `TOTP_SECRET_ENCRYPTION_KEY` - `OAUTH_STATE_SECRET` +- `CALLOUT_SECRET_ENCRYPTION_KEY`, once a webhook exists - `SEAMLESS_JWKS_ACTIVE_KID` - `SEAMLESS_JWKS_KEY__PRIVATE` - `SEAMLESS_JWKS_PUBLIC_KEYS` diff --git a/openapi.json b/openapi.json index 49f436fa..7bf24b7b 100644 --- a/openapi.json +++ b/openapi.json @@ -7293,7 +7293,14 @@ "webauthn_login_success", "webauthn_registration_challenge", "webauthn_registration_failed", - "webauthn_registration_suspicious" + "webauthn_registration_suspicious", + "admin_webhook_created", + "admin_webhook_deleted", + "admin_webhook_redelivered", + "admin_webhook_secret_rotated", + "admin_webhook_updated", + "session_created", + "webhook_endpoint_disabled" ] }, { "type": "string" }, @@ -7432,7 +7439,14 @@ "webauthn_login_success", "webauthn_registration_challenge", "webauthn_registration_failed", - "webauthn_registration_suspicious" + "webauthn_registration_suspicious", + "admin_webhook_created", + "admin_webhook_deleted", + "admin_webhook_redelivered", + "admin_webhook_secret_rotated", + "admin_webhook_updated", + "session_created", + "webhook_endpoint_disabled" ] }, { "type": "string" } @@ -32748,6 +32762,2682 @@ } } } + }, + "/admin/webhooks": { + "get": { + "summary": "List webhook endpoints", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { "endpoints": [null] }, + "schema": { + "type": "object", + "properties": { + "endpoints": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "url": { "type": "string" }, + "description": { "type": "string", "nullable": true }, + "eventTypes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + } + }, + "enabled": { "type": "boolean" }, + "disabledReason": { + "type": "string", + "nullable": true, + "enum": ["gone", "failing", "manual", null] + }, + "version": { "type": "number", "enum": [1] }, + "previousSecretExpiresAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "createdAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "updatedAt": { "type": "string", "nullable": true, "format": "date-time" } + }, + "required": [ + "id", + "url", + "description", + "eventTypes", + "enabled", + "disabledReason", + "version", + "previousSecretExpiresAt", + "createdAt", + "updatedAt" + ] + } + } + }, + "required": ["endpoints"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + }, + "post": { + "summary": "Create a webhook endpoint", + "description": "Returns the signing secret once. It cannot be read back.", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "url": { "type": "string", "maxLength": 2048 }, + "description": { "type": "string", "minLength": 1, "maxLength": 500 }, + "eventTypes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + }, + "minItems": 1 + }, + "enabled": { "type": "boolean" } + }, + "required": ["url", "eventTypes"] + } + } + } + }, + "responses": { + "201": { + "description": "HTTP 201", + "content": { + "application/json": { + "example": { + "endpoint": { + "id": "string", + "url": "string", + "description": "string", + "eventTypes": [null], + "enabled": true, + "disabledReason": null, + "version": null, + "previousSecretExpiresAt": null, + "createdAt": null, + "updatedAt": null + }, + "secret": "string" + }, + "schema": { + "type": "object", + "properties": { + "endpoint": { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "url": { "type": "string" }, + "description": { "type": "string", "nullable": true }, + "eventTypes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + } + }, + "enabled": { "type": "boolean" }, + "disabledReason": { + "type": "string", + "nullable": true, + "enum": ["gone", "failing", "manual", null] + }, + "version": { "type": "number", "enum": [1] }, + "previousSecretExpiresAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "createdAt": { "type": "string", "nullable": true, "format": "date-time" }, + "updatedAt": { "type": "string", "nullable": true, "format": "date-time" } + }, + "required": [ + "id", + "url", + "description", + "eventTypes", + "enabled", + "disabledReason", + "version", + "previousSecretExpiresAt", + "createdAt", + "updatedAt" + ] + }, + "secret": { "type": "string", "pattern": "^whsec_[A-Za-z0-9+/]{43}=$" } + }, + "required": ["endpoint", "secret"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "409": { + "description": "HTTP 409", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } + }, + "/admin/webhooks/{id}": { + "get": { + "summary": "Get a webhook endpoint", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { + "endpoint": { + "id": "string", + "url": "string", + "description": "string", + "eventTypes": [null], + "enabled": true, + "disabledReason": null, + "version": null, + "previousSecretExpiresAt": null, + "createdAt": null, + "updatedAt": null + } + }, + "schema": { + "type": "object", + "properties": { + "endpoint": { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "url": { "type": "string" }, + "description": { "type": "string", "nullable": true }, + "eventTypes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + } + }, + "enabled": { "type": "boolean" }, + "disabledReason": { + "type": "string", + "nullable": true, + "enum": ["gone", "failing", "manual", null] + }, + "version": { "type": "number", "enum": [1] }, + "previousSecretExpiresAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "createdAt": { "type": "string", "nullable": true, "format": "date-time" }, + "updatedAt": { "type": "string", "nullable": true, "format": "date-time" } + }, + "required": [ + "id", + "url", + "description", + "eventTypes", + "enabled", + "disabledReason", + "version", + "previousSecretExpiresAt", + "createdAt", + "updatedAt" + ] + } + }, + "required": ["endpoint"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + }, + "patch": { + "summary": "Update a webhook endpoint", + "description": "Turning an endpoint back on clears why it was disabled.", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "id", + "in": "path" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "url": { "type": "string", "maxLength": 2048 }, + "description": { + "type": "string", + "nullable": true, + "minLength": 1, + "maxLength": 500 + }, + "eventTypes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + }, + "minItems": 1 + }, + "enabled": { "type": "boolean" } + } + } + } + } + }, + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { + "endpoint": { + "id": "string", + "url": "string", + "description": "string", + "eventTypes": [null], + "enabled": true, + "disabledReason": null, + "version": null, + "previousSecretExpiresAt": null, + "createdAt": null, + "updatedAt": null + } + }, + "schema": { + "type": "object", + "properties": { + "endpoint": { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "url": { "type": "string" }, + "description": { "type": "string", "nullable": true }, + "eventTypes": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + } + }, + "enabled": { "type": "boolean" }, + "disabledReason": { + "type": "string", + "nullable": true, + "enum": ["gone", "failing", "manual", null] + }, + "version": { "type": "number", "enum": [1] }, + "previousSecretExpiresAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "createdAt": { "type": "string", "nullable": true, "format": "date-time" }, + "updatedAt": { "type": "string", "nullable": true, "format": "date-time" } + }, + "required": [ + "id", + "url", + "description", + "eventTypes", + "enabled", + "disabledReason", + "version", + "previousSecretExpiresAt", + "createdAt", + "updatedAt" + ] + } + }, + "required": ["endpoint"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + }, + "delete": { + "summary": "Delete a webhook endpoint", + "description": "Also deletes its delivery history.", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { "message": "string", "token": "string", "delivery": null }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "token": { "type": "string" }, + "delivery": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["otp_email"] }, + "to": { "type": "string" }, + "token": { "type": "string" }, + "purpose": { "type": "string", "enum": ["account_recovery"] } + }, + "required": ["kind", "to", "token"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["otp_sms"] }, + "to": { "type": "string" }, + "token": { "anyOf": [{ "type": "string" }, { "type": "number" }] }, + "purpose": { "type": "string", "enum": ["account_recovery"] } + }, + "required": ["kind", "to", "token"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["magic_link_email"] }, + "to": { "type": "string" }, + "token": { "type": "string" }, + "magicLinkUrl": { "type": "string" } + }, + "required": ["kind", "to", "magicLinkUrl"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["enrollment_invite_email"] }, + "to": { "type": "string" }, + "signInUrl": { "type": "string" } + }, + "required": ["kind", "to", "signInUrl"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["account_notice_email"] }, + "notice": { + "type": "string", + "enum": [ + "account_recovery_opened", + "account_recovery_completed", + "recovery_code_used", + "identity_changed", + "application_notice" + ] + }, + "to": { "type": "string" }, + "subject": { "type": "string" }, + "text": { "type": "string" }, + "cancelUrl": { "type": "string" }, + "application": { + "type": "object", + "properties": { + "clientId": { "type": "string" }, + "name": { "type": "string" } + }, + "required": ["clientId", "name"] + } + }, + "required": ["kind", "notice", "to", "subject", "text"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["account_notice_sms"] }, + "notice": { + "type": "string", + "enum": [ + "account_recovery_opened", + "account_recovery_completed", + "recovery_code_used", + "identity_changed", + "application_notice" + ] + }, + "to": { "type": "string" }, + "text": { "type": "string" }, + "cancelUrl": { "type": "string" }, + "application": { + "type": "object", + "properties": { + "clientId": { "type": "string" }, + "name": { "type": "string" } + }, + "required": ["clientId", "name"] + } + }, + "required": ["kind", "notice", "to", "text"] + } + ] + } + }, + "required": ["message"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } + }, + "/admin/webhooks/{id}/secret": { + "post": { + "summary": "Rotate a webhook signing secret", + "description": "Returns the new secret once. The previous one keeps signing beside it for 24 hours.", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { "secret": "string", "previousSecretExpiresAt": null }, + "schema": { + "type": "object", + "properties": { + "secret": { "type": "string", "pattern": "^whsec_[A-Za-z0-9+/]{43}=$" }, + "previousSecretExpiresAt": { + "type": "string", + "nullable": true, + "format": "date-time" + } + }, + "required": ["secret", "previousSecretExpiresAt"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "409": { + "description": "HTTP 409", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } + }, + "/admin/webhooks/{id}/test": { + "post": { + "summary": "Send a test event", + "description": "Sends `webhook.test` once, now, whatever the endpoint subscribes to.", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { "ok": true, "failure": null, "statusCode": 0, "durationMs": 0 }, + "schema": { + "type": "object", + "properties": { + "ok": { "type": "boolean" }, + "failure": { + "type": "string", + "nullable": true, + "enum": [ + "refused", + "timed_out", + "connection_failed", + "http_status", + "invalid_response", + "too_large", + null + ] + }, + "statusCode": { "type": "integer", "nullable": true }, + "durationMs": { "type": "integer", "minimum": 0 } + }, + "required": ["ok", "failure", "statusCode", "durationMs"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } + }, + "/admin/webhook-deliveries": { + "get": { + "summary": "List webhook deliveries", + "description": "Newest first. `status=dead` is the dead letter view. Kept for 30 days.", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": false, + "name": "endpointId", + "in": "query" + }, + { + "schema": { "type": "string", "enum": ["pending", "succeeded", "failed", "dead"] }, + "required": false, + "name": "status", + "in": "query" + }, + { + "schema": { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + }, + "required": false, + "name": "eventType", + "in": "query" + }, + { + "schema": { "type": "integer", "minimum": 1, "maximum": 100, "default": 50 }, + "required": false, + "name": "limit", + "in": "query" + }, + { + "schema": { "type": "string", "maxLength": 200 }, + "required": false, + "name": "cursor", + "in": "query" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { "deliveries": [null], "nextCursor": "string" }, + "schema": { + "type": "object", + "properties": { + "deliveries": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "endpointId": { "type": "string", "minLength": 1 }, + "eventType": { + "anyOf": [ + { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + }, + { "type": "string", "enum": ["webhook.test"] } + ] + }, + "status": { + "type": "string", + "enum": ["pending", "succeeded", "failed", "dead"] + }, + "attempts": { "type": "integer", "minimum": 0 }, + "nextAttemptAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "lastAttemptAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "lastStatusCode": { "type": "integer", "nullable": true }, + "lastFailure": { + "type": "string", + "nullable": true, + "enum": [ + "refused", + "timed_out", + "connection_failed", + "http_status", + "invalid_response", + "too_large", + null + ] + }, + "createdAt": { "type": "string", "nullable": true, "format": "date-time" } + }, + "required": [ + "id", + "endpointId", + "eventType", + "status", + "attempts", + "nextAttemptAt", + "lastAttemptAt", + "lastStatusCode", + "lastFailure", + "createdAt" + ] + } + }, + "nextCursor": { "type": "string", "nullable": true } + }, + "required": ["deliveries", "nextCursor"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } + }, + "/admin/webhook-deliveries/{deliveryId}": { + "get": { + "summary": "Get a webhook delivery and its event", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "deliveryId", + "in": "path" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { + "delivery": { + "id": "string", + "endpointId": "string", + "eventType": null, + "status": null, + "attempts": 0, + "nextAttemptAt": null, + "lastAttemptAt": null, + "lastStatusCode": 0, + "lastFailure": null, + "createdAt": null, + "event": null + } + }, + "schema": { + "type": "object", + "properties": { + "delivery": { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "endpointId": { "type": "string", "minLength": 1 }, + "eventType": { + "anyOf": [ + { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + }, + { "type": "string", "enum": ["webhook.test"] } + ] + }, + "status": { + "type": "string", + "enum": ["pending", "succeeded", "failed", "dead"] + }, + "attempts": { "type": "integer", "minimum": 0 }, + "nextAttemptAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "lastAttemptAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "lastStatusCode": { "type": "integer", "nullable": true }, + "lastFailure": { + "type": "string", + "nullable": true, + "enum": [ + "refused", + "timed_out", + "connection_failed", + "http_status", + "invalid_response", + "too_large", + null + ] + }, + "createdAt": { "type": "string", "nullable": true, "format": "date-time" }, + "event": { + "oneOf": [ + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["user.created"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { "type": "string", "minLength": 1 }, + "email": { "type": "string", "nullable": true }, + "phone": { "type": "string", "nullable": true } + }, + "required": ["userId", "email", "phone"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["user.deleted"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { "userId": { "type": "string", "minLength": 1 } }, + "required": ["userId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["user.signed_in"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { "type": "string", "minLength": 1 }, + "sessionId": { + "type": "string", + "nullable": true, + "minLength": 1 + }, + "method": { "type": "string", "nullable": true }, + "organizationId": { + "type": "string", + "nullable": true, + "minLength": 1 + } + }, + "required": ["userId", "sessionId", "method", "organizationId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["user.recovered"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { "userId": { "type": "string", "minLength": 1 } }, + "required": ["userId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["session.revoked"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { + "type": "string", + "nullable": true, + "minLength": 1 + }, + "sessionId": { + "type": "string", + "nullable": true, + "minLength": 1 + }, + "reason": { + "type": "string", + "enum": ["logout", "admin", "evicted", "provider"] + } + }, + "required": ["userId", "sessionId", "reason"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["credential.added"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { "type": "string", "minLength": 1 }, + "kind": { + "type": "string", + "enum": ["passkey", "totp", "recovery_codes"] + }, + "credentialId": { + "type": "string", + "nullable": true, + "minLength": 1 + } + }, + "required": ["userId", "kind", "credentialId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["credential.removed"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { "type": "string", "minLength": 1 }, + "kind": { + "type": "string", + "enum": ["passkey", "totp", "recovery_codes"] + }, + "credentialId": { + "type": "string", + "nullable": true, + "minLength": 1 + } + }, + "required": ["userId", "kind", "credentialId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["organization.member_added"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "organizationId": { "type": "string", "minLength": 1 }, + "userId": { "type": "string", "minLength": 1 }, + "roles": { "type": "array", "items": { "type": "string" } } + }, + "required": ["organizationId", "userId", "roles"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { + "type": "string", + "enum": ["organization.member_updated"] + }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "organizationId": { "type": "string", "minLength": 1 }, + "userId": { "type": "string", "minLength": 1 }, + "roles": { "type": "array", "items": { "type": "string" } } + }, + "required": ["organizationId", "userId", "roles"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { + "type": "string", + "enum": ["organization.member_removed"] + }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "organizationId": { "type": "string", "minLength": 1 }, + "userId": { "type": "string", "minLength": 1 }, + "roles": { "type": "array", "items": { "type": "string" } } + }, + "required": ["organizationId", "userId", "roles"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["webhook.test"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "endpointId": { "type": "string", "minLength": 1 } + }, + "required": ["endpointId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + } + ] + } + }, + "required": [ + "id", + "endpointId", + "eventType", + "status", + "attempts", + "nextAttemptAt", + "lastAttemptAt", + "lastStatusCode", + "lastFailure", + "createdAt", + "event" + ] + } + }, + "required": ["delivery"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } + }, + "/admin/webhook-deliveries/{deliveryId}/redeliver": { + "post": { + "summary": "Redeliver a webhook", + "description": "One attempt now, with the same `webhook-id` and body and a fresh timestamp and signature.", + "tags": ["Admin", "Webhooks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "deliveryId", + "in": "path" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { + "delivery": { + "id": "string", + "endpointId": "string", + "eventType": null, + "status": null, + "attempts": 0, + "nextAttemptAt": null, + "lastAttemptAt": null, + "lastStatusCode": 0, + "lastFailure": null, + "createdAt": null, + "event": null + } + }, + "schema": { + "type": "object", + "properties": { + "delivery": { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "endpointId": { "type": "string", "minLength": 1 }, + "eventType": { + "anyOf": [ + { + "type": "string", + "enum": [ + "user.created", + "user.deleted", + "user.signed_in", + "user.recovered", + "session.revoked", + "credential.added", + "credential.removed", + "organization.member_added", + "organization.member_updated", + "organization.member_removed" + ] + }, + { "type": "string", "enum": ["webhook.test"] } + ] + }, + "status": { + "type": "string", + "enum": ["pending", "succeeded", "failed", "dead"] + }, + "attempts": { "type": "integer", "minimum": 0 }, + "nextAttemptAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "lastAttemptAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "lastStatusCode": { "type": "integer", "nullable": true }, + "lastFailure": { + "type": "string", + "nullable": true, + "enum": [ + "refused", + "timed_out", + "connection_failed", + "http_status", + "invalid_response", + "too_large", + null + ] + }, + "createdAt": { "type": "string", "nullable": true, "format": "date-time" }, + "event": { + "oneOf": [ + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["user.created"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { "type": "string", "minLength": 1 }, + "email": { "type": "string", "nullable": true }, + "phone": { "type": "string", "nullable": true } + }, + "required": ["userId", "email", "phone"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["user.deleted"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { "userId": { "type": "string", "minLength": 1 } }, + "required": ["userId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["user.signed_in"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { "type": "string", "minLength": 1 }, + "sessionId": { + "type": "string", + "nullable": true, + "minLength": 1 + }, + "method": { "type": "string", "nullable": true }, + "organizationId": { + "type": "string", + "nullable": true, + "minLength": 1 + } + }, + "required": ["userId", "sessionId", "method", "organizationId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["user.recovered"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { "userId": { "type": "string", "minLength": 1 } }, + "required": ["userId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["session.revoked"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { + "type": "string", + "nullable": true, + "minLength": 1 + }, + "sessionId": { + "type": "string", + "nullable": true, + "minLength": 1 + }, + "reason": { + "type": "string", + "enum": ["logout", "admin", "evicted", "provider"] + } + }, + "required": ["userId", "sessionId", "reason"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["credential.added"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { "type": "string", "minLength": 1 }, + "kind": { + "type": "string", + "enum": ["passkey", "totp", "recovery_codes"] + }, + "credentialId": { + "type": "string", + "nullable": true, + "minLength": 1 + } + }, + "required": ["userId", "kind", "credentialId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["credential.removed"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "userId": { "type": "string", "minLength": 1 }, + "kind": { + "type": "string", + "enum": ["passkey", "totp", "recovery_codes"] + }, + "credentialId": { + "type": "string", + "nullable": true, + "minLength": 1 + } + }, + "required": ["userId", "kind", "credentialId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["organization.member_added"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "organizationId": { "type": "string", "minLength": 1 }, + "userId": { "type": "string", "minLength": 1 }, + "roles": { "type": "array", "items": { "type": "string" } } + }, + "required": ["organizationId", "userId", "roles"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { + "type": "string", + "enum": ["organization.member_updated"] + }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "organizationId": { "type": "string", "minLength": 1 }, + "userId": { "type": "string", "minLength": 1 }, + "roles": { "type": "array", "items": { "type": "string" } } + }, + "required": ["organizationId", "userId", "roles"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { + "type": "string", + "enum": ["organization.member_removed"] + }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "organizationId": { "type": "string", "minLength": 1 }, + "userId": { "type": "string", "minLength": 1 }, + "roles": { "type": "array", "items": { "type": "string" } } + }, + "required": ["organizationId", "userId", "roles"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + }, + { + "type": "object", + "properties": { + "id": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "enum": ["webhook.test"] }, + "version": { "type": "number", "enum": [1] }, + "timestamp": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "data": { + "type": "object", + "properties": { + "endpointId": { "type": "string", "minLength": 1 } + }, + "required": ["endpointId"] + } + }, + "required": ["id", "type", "version", "timestamp", "data"] + } + ] + } + }, + "required": [ + "id", + "endpointId", + "eventType", + "status", + "attempts", + "nextAttemptAt", + "lastAttemptAt", + "lastStatusCode", + "lastFailure", + "createdAt", + "event" + ] + } + }, + "required": ["delivery"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } } } } diff --git a/src/config/authSecrets.ts b/src/config/authSecrets.ts index cf74d12d..ac4b38d3 100644 --- a/src/config/authSecrets.ts +++ b/src/config/authSecrets.ts @@ -23,6 +23,7 @@ export const AUTH_SECRETS = { DECOY_SUBJECT_SECRET: 'the decoy subjects /login answers for unknown identifiers', TOTP_SECRET_ENCRYPTION_KEY: 'every stored TOTP secret', OAUTH_STATE_SECRET: 'OAuth sign-ins in progress', + CALLOUT_SECRET_ENCRYPTION_KEY: 'every stored webhook and login hook signing secret', } as const; export type AuthSecretName = keyof typeof AUTH_SECRETS; @@ -53,6 +54,8 @@ function devFallback(name: AuthSecretName, env: EnvSource) { return `dev-oauth-state:${app}`; case 'DECOY_SUBJECT_SECRET': return `dev-decoy-subject:${app}`; + case 'CALLOUT_SECRET_ENCRYPTION_KEY': + return `dev-callout-secret:${app}:${env.ISSUER ?? 'local'}`; } } @@ -78,10 +81,16 @@ export function isAuthSecretSet(name: AuthSecretName, env: EnvSource = process.e return Boolean(env[name]?.trim()); } -/** The secrets a configuration needs, given whether any TOTP credential is stored. */ +export type StoredSecrets = { + totpCredentialsExist: boolean; + /** Any webhook endpoint or login hook, each of which holds an encrypted signing secret. */ + calloutSecretsExist?: boolean; +}; + +/** The secrets a configuration needs, given which encrypted secrets are stored. */ export function authSecretsRequiredBy( config: Pick, - { totpCredentialsExist }: { totpCredentialsExist: boolean }, + { totpCredentialsExist, calloutSecretsExist = false }: StoredSecrets, ): AuthSecretName[] { const required: AuthSecretName[] = ['REFRESH_TOKEN_LOOKUP_SECRET', 'DECOY_SUBJECT_SECRET']; @@ -95,6 +104,10 @@ export function authSecretsRequiredBy( required.push('OAUTH_STATE_SECRET'); } + if (calloutSecretsExist) { + required.push('CALLOUT_SECRET_ENCRYPTION_KEY'); + } + return required; } @@ -114,17 +127,28 @@ export function productionSecretMissing(name: AuthSecretName, env: EnvSource = p */ export function assertAuthSecrets( config: Pick, - totpCredentialsExist: boolean, + stored: StoredSecrets, env: EnvSource = process.env, ) { if (!isProduction(env)) return; - const missing = authSecretsRequiredBy(config, { totpCredentialsExist }).filter( + const missing = authSecretsRequiredBy(config, stored).filter( (name) => !isAuthSecretSet(name, env), ); if (missing.length === 0) return; + // This key never had a service token fallback: a webhook or login hook cannot be created in + // production without it, so it is only missing here if it was removed, and the service token + // would not read the stored secrets either. + if (missing.length === 1 && missing[0] === 'CALLOUT_SECRET_ENCRYPTION_KEY') { + throw new Error( + 'Refusing to start: CALLOUT_SECRET_ENCRYPTION_KEY is not set, and webhook or login hook ' + + 'signing secrets are stored under it. Restore the value they were created with, or ' + + 'delete the webhooks and hooks and create them again. See docs/production-operations.md.', + ); + } + throw new Error( `Refusing to start: ${missing.join(', ')} ${missing.length === 1 ? 'is' : 'are'} not set. ` + `Each protects ${missing.map((name) => AUTH_SECRETS[name]).join('; ')}. ` + diff --git a/src/controllers/organizations.ts b/src/controllers/organizations.ts index 883be58b..afe9cce0 100644 --- a/src/controllers/organizations.ts +++ b/src/controllers/organizations.ts @@ -351,6 +351,7 @@ export async function updateMember(req: RouteRequest, res: Response) { req, metadata: { organizationId, + roles: nextRoles, rolesAdded: nextRoles.filter((role) => !currentRoles.includes(role)), rolesRemoved: currentRoles.filter((role) => !nextRoles.includes(role)), ...(req.body.scopes === undefined ? {} : { scopes: membership.scopes }), diff --git a/src/controllers/webauthn.ts b/src/controllers/webauthn.ts index 0a93e7d7..a50e4aa9 100644 --- a/src/controllers/webauthn.ts +++ b/src/controllers/webauthn.ts @@ -389,13 +389,17 @@ const verifyWebAuthnRegistration = async (req: Request, res: Response) => { userId: user.id, type: 'registration_success', req, - metadata: breakGlassOverride - ? { - severity: 'high', - breakGlassWaived: ['authenticator_policy'], - authenticatorPolicyRefusal: verdict.detail, - } - : {}, + metadata: { + credential: 'passkey', + credentialId: created.id, + ...(breakGlassOverride + ? { + severity: 'high', + breakGlassWaived: ['authenticator_policy'], + authenticatorPolicyRefusal: verdict.detail, + } + : {}), + }, }); if (breakGlassOverride) { diff --git a/src/controllers/webhooks.ts b/src/controllers/webhooks.ts new file mode 100644 index 00000000..2a2f5f9e --- /dev/null +++ b/src/controllers/webhooks.ts @@ -0,0 +1,181 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import type { WebhookDeliveryQuery } from '@seamless-auth/types'; +import { Request, Response } from 'express'; + +import { AuthEventService } from '../services/authEventService.js'; +import { + createEndpoint, + deleteEndpoint, + getDelivery, + getEndpoint, + listDeliveries as listDeliveryRecords, + listEndpoints, + redeliver as redeliverRecord, + rotateEndpointSecret, + sendTestEvent, + serializeDelivery, + serializeEndpoint, + updateEndpoint, + WebhookError, +} from '../services/webhookService.js'; +import { AuthenticatedRequest, RouteRequest } from '../types/types.js'; + +function actorUserId(req: Request) { + return (req as AuthenticatedRequest).user?.id ?? null; +} + +/** + * The audit log is append-only, so a URL is recorded without its query string, where a receiver + * may have put a token. + */ +function auditedUrl(url: string) { + const parsed = new URL(url); + return `${parsed.origin}${parsed.pathname}`; +} + +function sendError(res: Response, error: unknown) { + if (error instanceof WebhookError) { + return res.status(error.status).json({ error: error.message }); + } + + throw error; +} + +export async function listWebhooks(_req: Request, res: Response) { + const endpoints = await listEndpoints(); + return res.json({ endpoints: endpoints.map(serializeEndpoint) }); +} + +export async function getWebhook(req: RouteRequest, res: Response) { + try { + return res.json({ endpoint: serializeEndpoint(await getEndpoint(req.params.id)) }); + } catch (error) { + return sendError(res, error); + } +} + +export async function createWebhook(req: Request, res: Response) { + try { + const { endpoint, secret } = await createEndpoint(req.body, actorUserId(req)); + + await AuthEventService.log({ + actorUserId: actorUserId(req), + type: 'admin_webhook_created', + req, + metadata: { + endpointId: endpoint.id, + url: auditedUrl(endpoint.url), + eventTypes: endpoint.eventTypes, + }, + }); + + return res.status(201).json({ endpoint: serializeEndpoint(endpoint), secret }); + } catch (error) { + return sendError(res, error); + } +} + +export async function updateWebhook(req: RouteRequest, res: Response) { + try { + const endpoint = await updateEndpoint(req.params.id, req.body); + + await AuthEventService.log({ + actorUserId: actorUserId(req), + type: 'admin_webhook_updated', + req, + metadata: { endpointId: endpoint.id, changed: Object.keys(req.body) }, + }); + + return res.json({ endpoint: serializeEndpoint(endpoint) }); + } catch (error) { + return sendError(res, error); + } +} + +export async function deleteWebhook(req: RouteRequest, res: Response) { + try { + const endpoint = await deleteEndpoint(req.params.id); + + await AuthEventService.log({ + actorUserId: actorUserId(req), + type: 'admin_webhook_deleted', + req, + metadata: { endpointId: endpoint.id, url: auditedUrl(endpoint.url) }, + }); + + return res.json({ message: 'Webhook deleted' }); + } catch (error) { + return sendError(res, error); + } +} + +export async function rotateWebhookSecret(req: RouteRequest, res: Response) { + try { + const { endpoint, secret, previousSecretExpiresAt } = await rotateEndpointSecret(req.params.id); + + await AuthEventService.log({ + actorUserId: actorUserId(req), + type: 'admin_webhook_secret_rotated', + req, + metadata: { endpointId: endpoint.id }, + }); + + return res.json({ secret, previousSecretExpiresAt: previousSecretExpiresAt.toISOString() }); + } catch (error) { + return sendError(res, error); + } +} + +export async function testWebhook(req: RouteRequest, res: Response) { + try { + return res.json(await sendTestEvent(req.params.id)); + } catch (error) { + return sendError(res, error); + } +} + +export async function listWebhookDeliveries(req: Request, res: Response) { + try { + const { deliveries, nextCursor } = await listDeliveryRecords( + req.query as unknown as WebhookDeliveryQuery, + ); + return res.json({ deliveries: deliveries.map(serializeDelivery), nextCursor }); + } catch (error) { + return sendError(res, error); + } +} + +export async function getWebhookDelivery(req: RouteRequest, res: Response) { + try { + const delivery = await getDelivery(req.params.deliveryId); + return res.json({ + delivery: { ...serializeDelivery(delivery), event: JSON.parse(delivery.payload) }, + }); + } catch (error) { + return sendError(res, error); + } +} + +export async function redeliverWebhook(req: RouteRequest, res: Response) { + try { + const delivery = await redeliverRecord(req.params.deliveryId); + + await AuthEventService.log({ + actorUserId: actorUserId(req), + type: 'admin_webhook_redelivered', + req, + metadata: { deliveryId: delivery.id, endpointId: delivery.endpointId }, + }); + + return res.json({ + delivery: { ...serializeDelivery(delivery), event: JSON.parse(delivery.payload) }, + }); + } catch (error) { + return sendError(res, error); + } +} diff --git a/src/generated/api.ts b/src/generated/api.ts index f17bc323..c5c25921 100644 --- a/src/generated/api.ts +++ b/src/generated/api.ts @@ -6900,6 +6900,13 @@ export interface paths { | 'webauthn_registration_challenge' | 'webauthn_registration_failed' | 'webauthn_registration_suspicious' + | 'admin_webhook_created' + | 'admin_webhook_deleted' + | 'admin_webhook_redelivered' + | 'admin_webhook_secret_rotated' + | 'admin_webhook_updated' + | 'session_created' + | 'webhook_endpoint_disabled' ) | string | ( @@ -7033,6 +7040,13 @@ export interface paths { | 'webauthn_registration_challenge' | 'webauthn_registration_failed' | 'webauthn_registration_suspicious' + | 'admin_webhook_created' + | 'admin_webhook_deleted' + | 'admin_webhook_redelivered' + | 'admin_webhook_secret_rotated' + | 'admin_webhook_updated' + | 'session_created' + | 'webhook_endpoint_disabled' ) | string )[]; @@ -32078,6 +32092,2241 @@ export interface paths { patch?: never; trace?: never; }; + '/admin/webhooks': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** List webhook endpoints */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "endpoints": [ + * null + * ] + * } + */ + 'application/json': { + endpoints: { + id: string; + url: string; + description: string | null; + eventTypes: ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + )[]; + enabled: boolean; + /** @enum {string|null} */ + disabledReason: 'gone' | 'failing' | 'manual' | null; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + previousSecretExpiresAt: string | null; + /** Format: date-time */ + createdAt: string | null; + /** Format: date-time */ + updatedAt: string | null; + }[]; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + put?: never; + /** + * Create a webhook endpoint + * @description Returns the signing secret once. It cannot be read back. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + 'application/json': { + url: string; + description?: string; + eventTypes: ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + )[]; + enabled?: boolean; + }; + }; + }; + responses: { + /** @description HTTP 201 */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "endpoint": { + * "id": "string", + * "url": "string", + * "description": "string", + * "eventTypes": [ + * null + * ], + * "enabled": true, + * "disabledReason": null, + * "version": null, + * "previousSecretExpiresAt": null, + * "createdAt": null, + * "updatedAt": null + * }, + * "secret": "string" + * } + */ + 'application/json': { + endpoint: { + id: string; + url: string; + description: string | null; + eventTypes: ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + )[]; + enabled: boolean; + /** @enum {string|null} */ + disabledReason: 'gone' | 'failing' | 'manual' | null; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + previousSecretExpiresAt: string | null; + /** Format: date-time */ + createdAt: string | null; + /** Format: date-time */ + updatedAt: string | null; + }; + secret: string; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 409 */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + '/admin/webhooks/{id}': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Get a webhook endpoint */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "endpoint": { + * "id": "string", + * "url": "string", + * "description": "string", + * "eventTypes": [ + * null + * ], + * "enabled": true, + * "disabledReason": null, + * "version": null, + * "previousSecretExpiresAt": null, + * "createdAt": null, + * "updatedAt": null + * } + * } + */ + 'application/json': { + endpoint: { + id: string; + url: string; + description: string | null; + eventTypes: ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + )[]; + enabled: boolean; + /** @enum {string|null} */ + disabledReason: 'gone' | 'failing' | 'manual' | null; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + previousSecretExpiresAt: string | null; + /** Format: date-time */ + createdAt: string | null; + /** Format: date-time */ + updatedAt: string | null; + }; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + put?: never; + post?: never; + /** + * Delete a webhook endpoint + * @description Also deletes its delivery history. + */ + delete: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "token": "string", + * "delivery": null + * } + */ + 'application/json': { + message: string; + token?: string; + delivery?: + | { + /** @enum {string} */ + kind: 'otp_email'; + to: string; + token: string; + /** @enum {string} */ + purpose?: 'account_recovery'; + } + | { + /** @enum {string} */ + kind: 'otp_sms'; + to: string; + token: string | number; + /** @enum {string} */ + purpose?: 'account_recovery'; + } + | { + /** @enum {string} */ + kind: 'magic_link_email'; + to: string; + token?: string; + magicLinkUrl: string; + } + | { + /** @enum {string} */ + kind: 'enrollment_invite_email'; + to: string; + signInUrl: string; + } + | { + /** @enum {string} */ + kind: 'account_notice_email'; + /** @enum {string} */ + notice: + | 'account_recovery_opened' + | 'account_recovery_completed' + | 'recovery_code_used' + | 'identity_changed' + | 'application_notice'; + to: string; + subject: string; + text: string; + cancelUrl?: string; + application?: { + clientId: string; + name: string; + }; + } + | { + /** @enum {string} */ + kind: 'account_notice_sms'; + /** @enum {string} */ + notice: + | 'account_recovery_opened' + | 'account_recovery_completed' + | 'recovery_code_used' + | 'identity_changed' + | 'application_notice'; + to: string; + text: string; + cancelUrl?: string; + application?: { + clientId: string; + name: string; + }; + }; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + options?: never; + head?: never; + /** + * Update a webhook endpoint + * @description Turning an endpoint back on clears why it was disabled. + */ + patch: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + 'application/json': { + url?: string; + description?: string | null; + eventTypes?: ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + )[]; + enabled?: boolean; + }; + }; + }; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "endpoint": { + * "id": "string", + * "url": "string", + * "description": "string", + * "eventTypes": [ + * null + * ], + * "enabled": true, + * "disabledReason": null, + * "version": null, + * "previousSecretExpiresAt": null, + * "createdAt": null, + * "updatedAt": null + * } + * } + */ + 'application/json': { + endpoint: { + id: string; + url: string; + description: string | null; + eventTypes: ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + )[]; + enabled: boolean; + /** @enum {string|null} */ + disabledReason: 'gone' | 'failing' | 'manual' | null; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + previousSecretExpiresAt: string | null; + /** Format: date-time */ + createdAt: string | null; + /** Format: date-time */ + updatedAt: string | null; + }; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + trace?: never; + }; + '/admin/webhooks/{id}/secret': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Rotate a webhook signing secret + * @description Returns the new secret once. The previous one keeps signing beside it for 24 hours. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "secret": "string", + * "previousSecretExpiresAt": null + * } + */ + 'application/json': { + secret: string; + /** Format: date-time */ + previousSecretExpiresAt: string | null; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 409 */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + '/admin/webhooks/{id}/test': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Send a test event + * @description Sends `webhook.test` once, now, whatever the endpoint subscribes to. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "ok": true, + * "failure": null, + * "statusCode": 0, + * "durationMs": 0 + * } + */ + 'application/json': { + ok: boolean; + /** @enum {string|null} */ + failure: + | 'refused' + | 'timed_out' + | 'connection_failed' + | 'http_status' + | 'invalid_response' + | 'too_large' + | null; + statusCode: number | null; + durationMs: number; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + '/admin/webhook-deliveries': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List webhook deliveries + * @description Newest first. `status=dead` is the dead letter view. Kept for 30 days. + */ + get: { + parameters: { + query?: { + endpointId?: string; + status?: 'pending' | 'succeeded' | 'failed' | 'dead'; + eventType?: + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed'; + limit?: number; + cursor?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "deliveries": [ + * null + * ], + * "nextCursor": "string" + * } + */ + 'application/json': { + deliveries: { + id: string; + endpointId: string; + eventType: + | ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + ) + | 'webhook.test'; + /** @enum {string} */ + status: 'pending' | 'succeeded' | 'failed' | 'dead'; + attempts: number; + /** Format: date-time */ + nextAttemptAt: string | null; + /** Format: date-time */ + lastAttemptAt: string | null; + lastStatusCode: number | null; + /** @enum {string|null} */ + lastFailure: + | 'refused' + | 'timed_out' + | 'connection_failed' + | 'http_status' + | 'invalid_response' + | 'too_large' + | null; + /** Format: date-time */ + createdAt: string | null; + }[]; + nextCursor: string | null; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + '/admin/webhook-deliveries/{deliveryId}': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Get a webhook delivery and its event */ + get: { + parameters: { + query?: never; + header?: never; + path: { + deliveryId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "delivery": { + * "id": "string", + * "endpointId": "string", + * "eventType": null, + * "status": null, + * "attempts": 0, + * "nextAttemptAt": null, + * "lastAttemptAt": null, + * "lastStatusCode": 0, + * "lastFailure": null, + * "createdAt": null, + * "event": null + * } + * } + */ + 'application/json': { + delivery: { + id: string; + endpointId: string; + eventType: + | ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + ) + | 'webhook.test'; + /** @enum {string} */ + status: 'pending' | 'succeeded' | 'failed' | 'dead'; + attempts: number; + /** Format: date-time */ + nextAttemptAt: string | null; + /** Format: date-time */ + lastAttemptAt: string | null; + lastStatusCode: number | null; + /** @enum {string|null} */ + lastFailure: + | 'refused' + | 'timed_out' + | 'connection_failed' + | 'http_status' + | 'invalid_response' + | 'too_large' + | null; + /** Format: date-time */ + createdAt: string | null; + event: + | { + id: string; + /** @enum {string} */ + type: 'user.created'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + email: string | null; + phone: string | null; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'user.deleted'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'user.signed_in'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + sessionId: string | null; + method: string | null; + organizationId: string | null; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'user.recovered'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'session.revoked'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string | null; + sessionId: string | null; + /** @enum {string} */ + reason: 'logout' | 'admin' | 'evicted' | 'provider'; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'credential.added'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + /** @enum {string} */ + kind: 'passkey' | 'totp' | 'recovery_codes'; + credentialId: string | null; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'credential.removed'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + /** @enum {string} */ + kind: 'passkey' | 'totp' | 'recovery_codes'; + credentialId: string | null; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'organization.member_added'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + organizationId: string; + userId: string; + roles: string[]; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'organization.member_updated'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + organizationId: string; + userId: string; + roles: string[]; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'organization.member_removed'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + organizationId: string; + userId: string; + roles: string[]; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'webhook.test'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + endpointId: string; + }; + }; + }; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + '/admin/webhook-deliveries/{deliveryId}/redeliver': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Redeliver a webhook + * @description One attempt now, with the same `webhook-id` and body and a fresh timestamp and signature. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + deliveryId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "delivery": { + * "id": "string", + * "endpointId": "string", + * "eventType": null, + * "status": null, + * "attempts": 0, + * "nextAttemptAt": null, + * "lastAttemptAt": null, + * "lastStatusCode": 0, + * "lastFailure": null, + * "createdAt": null, + * "event": null + * } + * } + */ + 'application/json': { + delivery: { + id: string; + endpointId: string; + eventType: + | ( + | 'user.created' + | 'user.deleted' + | 'user.signed_in' + | 'user.recovered' + | 'session.revoked' + | 'credential.added' + | 'credential.removed' + | 'organization.member_added' + | 'organization.member_updated' + | 'organization.member_removed' + ) + | 'webhook.test'; + /** @enum {string} */ + status: 'pending' | 'succeeded' | 'failed' | 'dead'; + attempts: number; + /** Format: date-time */ + nextAttemptAt: string | null; + /** Format: date-time */ + lastAttemptAt: string | null; + lastStatusCode: number | null; + /** @enum {string|null} */ + lastFailure: + | 'refused' + | 'timed_out' + | 'connection_failed' + | 'http_status' + | 'invalid_response' + | 'too_large' + | null; + /** Format: date-time */ + createdAt: string | null; + event: + | { + id: string; + /** @enum {string} */ + type: 'user.created'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + email: string | null; + phone: string | null; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'user.deleted'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'user.signed_in'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + sessionId: string | null; + method: string | null; + organizationId: string | null; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'user.recovered'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'session.revoked'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string | null; + sessionId: string | null; + /** @enum {string} */ + reason: 'logout' | 'admin' | 'evicted' | 'provider'; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'credential.added'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + /** @enum {string} */ + kind: 'passkey' | 'totp' | 'recovery_codes'; + credentialId: string | null; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'credential.removed'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + userId: string; + /** @enum {string} */ + kind: 'passkey' | 'totp' | 'recovery_codes'; + credentialId: string | null; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'organization.member_added'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + organizationId: string; + userId: string; + roles: string[]; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'organization.member_updated'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + organizationId: string; + userId: string; + roles: string[]; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'organization.member_removed'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + organizationId: string; + userId: string; + roles: string[]; + }; + } + | { + id: string; + /** @enum {string} */ + type: 'webhook.test'; + /** @enum {number} */ + version: 1; + /** Format: date-time */ + timestamp: string | null; + data: { + endpointId: string; + }; + }; + }; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; } export type webhooks = Record; export interface components { diff --git a/src/lib/authEventCategories.ts b/src/lib/authEventCategories.ts index b8f39a25..db7b4277 100644 --- a/src/lib/authEventCategories.ts +++ b/src/lib/authEventCategories.ts @@ -64,11 +64,13 @@ const EXACT_CATEGORIES: Readonly> = { notification_sent: 'system', // Session lifecycle sits with login, which is where logout_ already lands, and // an eviction is a direct consequence of a sign-in rather than an admin action. + session_created: 'login', session_evicted: 'login', session_exchange_replayed: 'login', session_exchanged: 'login', user_created: 'registration', user_deleted: 'system', + webhook_endpoint_disabled: 'system', }; // `suspicious` is checked first so security signals stay in one bucket rather than diff --git a/src/lib/calloutSigning.ts b/src/lib/calloutSigning.ts new file mode 100644 index 00000000..21d6f16c --- /dev/null +++ b/src/lib/calloutSigning.ts @@ -0,0 +1,94 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes } from 'node:crypto'; + +import { + WEBHOOK_ID_HEADER, + WEBHOOK_SECRET_PREFIX, + WEBHOOK_SIGNATURE_HEADER, + WEBHOOK_SIGNATURE_VERSION, + WEBHOOK_TIMESTAMP_HEADER, +} from '@seamless-auth/types'; + +import { authSecret } from '../config/authSecrets.js'; + +/** + * Standard Webhooks signing (ADR 0005, D1), for webhooks and login hook calls alike. The secret + * is `whsec_` and base64 of 32 random bytes, and the HMAC key is those decoded bytes. + */ +export function generateCalloutSecret() { + return `${WEBHOOK_SECRET_PREFIX}${randomBytes(32).toString('base64')}`; +} + +function secretKey(secret: string) { + return Buffer.from(secret.slice(WEBHOOK_SECRET_PREFIX.length), 'base64'); +} + +export function calloutSignature(id: string, timestamp: number, body: string, secret: string) { + const signature = createHmac('sha256', secretKey(secret)) + .update(`${id}.${timestamp}.${body}`) + .digest('base64'); + + return `${WEBHOOK_SIGNATURE_VERSION},${signature}`; +} + +/** + * The three Standard Webhooks headers. While a secret rotates, both secrets sign, separated by a + * space, so a receiver holding either one verifies. + */ +export function signedCalloutHeaders( + id: string, + body: string, + secrets: readonly string[], + now: Date = new Date(), +): Record { + const timestamp = Math.floor(now.getTime() / 1000); + + return { + 'content-type': 'application/json', + [WEBHOOK_ID_HEADER]: id, + [WEBHOOK_TIMESTAMP_HEADER]: String(timestamp), + [WEBHOOK_SIGNATURE_HEADER]: secrets + .map((secret) => calloutSignature(id, timestamp, body, secret)) + .join(' '), + }; +} + +const CIPHER = 'aes-256-gcm'; + +export type EncryptedCalloutSecret = { + ciphertext: string; + iv: string; + tag: string; +}; + +// Signing secrets have to be read back to sign, so they cannot be hashed (ADR 0005, D9). +function encryptionKey() { + return createHash('sha256').update(authSecret('CALLOUT_SECRET_ENCRYPTION_KEY')).digest(); +} + +export function encryptCalloutSecret(secret: string): EncryptedCalloutSecret { + const iv = randomBytes(12); + const cipher = createCipheriv(CIPHER, encryptionKey(), iv); + const ciphertext = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]); + + return { + ciphertext: ciphertext.toString('base64'), + iv: iv.toString('base64'), + tag: cipher.getAuthTag().toString('base64'), + }; +} + +export function decryptCalloutSecret({ ciphertext, iv, tag }: EncryptedCalloutSecret) { + const decipher = createDecipheriv(CIPHER, encryptionKey(), Buffer.from(iv, 'base64')); + decipher.setAuthTag(Buffer.from(tag, 'base64')); + + return Buffer.concat([ + decipher.update(Buffer.from(ciphertext, 'base64')), + decipher.final(), + ]).toString('utf8'); +} diff --git a/src/lib/calloutTransport.ts b/src/lib/calloutTransport.ts new file mode 100644 index 00000000..7c32410d --- /dev/null +++ b/src/lib/calloutTransport.ts @@ -0,0 +1,268 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import type { LookupAddress } from 'node:dns'; +import { lookup } from 'node:dns/promises'; +import { request as httpRequest } from 'node:http'; +import { request as httpsRequest } from 'node:https'; +import { BlockList, isIP, type LookupFunction } from 'node:net'; + +import type { CalloutFailure } from '@seamless-auth/types'; + +import { inList, neverReachable, nonPublic, unmapIPv4 } from './outboundAddress.js'; + +type EnvSource = Record; + +/** + * Hosts on a private address that webhooks, login hooks and audit sinks may reach in production + * (ADR 0005, D8). An env var, so it is the operator's call: nothing written through the API can + * widen it. Kept apart from `OAUTH_PROVIDER_PRIVATE_HOSTS`, so allowing an internal hook service + * does not also allow it as an identity provider. + */ +export const CALLOUT_PRIVATE_HOSTS_ENV = 'CALLOUT_PRIVATE_HOSTS'; + +// Multicast and broadcast never answer a request, and reaching them is only ever a probe. +const calloutNeverReachable = new BlockList(); +calloutNeverReachable.addSubnet('224.0.0.0', 4, 'ipv4'); +calloutNeverReachable.addAddress('255.255.255.255', 'ipv4'); +calloutNeverReachable.addSubnet('ff00::', 8, 'ipv6'); + +export class CalloutError extends Error { + readonly failure: CalloutFailure; + + constructor(failure: CalloutFailure, message: string) { + super(message); + this.name = 'CalloutError'; + this.failure = failure; + } +} + +function isProduction(env: EnvSource) { + return env.NODE_ENV === 'production'; +} + +function bare(hostname: string) { + return hostname.replace(/^\[|\]$/g, '').toLowerCase(); +} + +function privateHostsAllowed(env: EnvSource) { + return new Set( + (env[CALLOUT_PRIVATE_HOSTS_ENV] ?? '') + .split(',') + .map((host) => host.trim().toLowerCase()) + .filter(Boolean), + ); +} + +function hostMayBePrivate(hostname: string, env: EnvSource) { + return !isProduction(env) || privateHostsAllowed(env).has(bare(hostname)); +} + +function addressAllowed(address: string, hostAllowlisted: boolean) { + return ( + !inList(neverReachable, address) && + !inList(calloutNeverReachable, address) && + (hostAllowlisted || !inList(nonPublic, address)) + ); +} + +function issuerHost(env: EnvSource) { + try { + return env.ISSUER ? new URL(env.ISSUER).hostname.toLowerCase() : null; + } catch { + return null; + } +} + +/** Whether a host may be the target of a callout, before any DNS. */ +export function calloutHostProblem(hostname: string, env: EnvSource = process.env): string | null { + const host = bare(hostname); + + if (!host) return 'has no host'; + if (host === issuerHost(env)) return 'must not point at this server'; + + if (isIP(unmapIPv4(host)) && !addressAllowed(host, hostMayBePrivate(host, env))) { + return isProduction(env) && + !inList(neverReachable, host) && + !inList(calloutNeverReachable, host) + ? `points at a non-public address; list the host in ${CALLOUT_PRIVATE_HOSTS_ENV} to allow it` + : 'points at an address that is never reachable'; + } + + return null; +} + +/** + * What is wrong with a callout URL, for the API to refuse it when written. The same checks run + * again at connect time, where DNS is also checked. + */ +export function calloutUrlProblem(value: string, env: EnvSource = process.env): string | null { + let url: URL; + try { + url = new URL(value); + } catch { + return 'is not a valid URL'; + } + + if (url.protocol !== 'https:' && url.protocol !== 'http:') return 'must use https'; + if (isProduction(env) && url.protocol !== 'https:') return 'must use https'; + if (url.username || url.password) return 'must not carry a username or password'; + + return calloutHostProblem(url.hostname, env); +} + +type LookupCallback = ( + error: Error | null, + address: string | LookupAddress[], + family?: number, +) => void; + +/** + * DNS for the callout's own socket, so the addresses checked are the ones connected to and a + * name cannot answer one way for a check and another for the connection. Every address a name + * resolves to must be allowed, not just the first. + */ +export function calloutLookup(env: EnvSource = process.env): LookupFunction { + const guarded = ( + hostname: string, + options: { family?: number | string; all?: boolean }, + callback: LookupCallback, + ) => { + const family = + options.family === 6 || options.family === 'IPv6' + ? 6 + : options.family === 4 || options.family === 'IPv4' + ? 4 + : 0; + + lookup(hostname, { all: true, verbatim: true, family }).then( + (addresses) => { + const allowed = hostMayBePrivate(hostname, env); + if ( + addresses.length === 0 || + addresses.some((entry) => !addressAllowed(entry.address, allowed)) + ) { + callback(new CalloutError('refused', `${hostname} resolves to a refused address`), []); + return; + } + + if (options.all) { + callback(null, addresses); + } else { + callback(null, addresses[0].address, addresses[0].family); + } + }, + (error: Error) => callback(error, []), + ); + }; + + return guarded as unknown as LookupFunction; +} + +/** Throws a `refused` CalloutError for a URL no callout may reach. */ +export function assertCalloutDestination(target: string, env: EnvSource = process.env): URL { + const problem = calloutUrlProblem(target, env); + if (problem) throw new CalloutError('refused', `Callout URL ${problem}`); + return new URL(target); +} + +export type CalloutRequest = { + method?: 'GET' | 'POST'; + headers?: Record; + body?: string; + timeoutMs: number; + maxResponseBytes: number; +}; + +export type CalloutResponse = { + status: number; + headers: Record; + body: Buffer; +}; + +const USER_AGENT = 'seamless-auth-api'; + +/** + * One HTTP request to an adopter-supplied URL. Redirects are not followed: a 3xx comes back as a + * response, and the caller treats it as a failure, since following it would carry a signed body + * to a host that was never checked. + */ +export function calloutRequest( + target: string, + { method = 'POST', headers = {}, body, timeoutMs, maxResponseBytes }: CalloutRequest, + env: EnvSource = process.env, +): Promise { + let url: URL; + try { + url = assertCalloutDestination(target, env); + } catch (error) { + return Promise.reject(error); + } + + const send = url.protocol === 'https:' ? httpsRequest : httpRequest; + const outgoing: Record = { 'user-agent': USER_AGENT, ...headers }; + if (body !== undefined) outgoing['content-length'] = String(Buffer.byteLength(body)); + + return new Promise((resolve, reject) => { + let settled = false; + const fail = (error: CalloutError) => { + if (settled) return; + settled = true; + clearTimeout(timer); + request.destroy(); + reject(error); + }; + + const request = send( + url, + { method, headers: outgoing, lookup: calloutLookup(env) }, + (response) => { + const chunks: Buffer[] = []; + let size = 0; + + response.on('data', (chunk: Buffer) => { + size += chunk.length; + if (size > maxResponseBytes) { + fail(new CalloutError('too_large', 'Callout response is too large')); + return; + } + chunks.push(chunk); + }); + response.on('error', () => + fail(new CalloutError('connection_failed', 'Callout response failed')), + ); + response.on('end', () => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve({ + status: response.statusCode ?? 502, + headers: response.headers, + body: Buffer.concat(chunks), + }); + }); + }, + ); + + // A whole-request deadline rather than a socket idle timeout, so a destination that + // trickles a byte at a time cannot hold a sign-in open. + const timer = setTimeout( + () => fail(new CalloutError('timed_out', 'Callout timed out')), + timeoutMs, + ); + timer.unref(); + + request.on('error', (error: Error) => + fail( + error instanceof CalloutError + ? error + : new CalloutError('connection_failed', 'Callout connection failed'), + ), + ); + + request.end(body); + }); +} diff --git a/src/lib/oauthProviderPolicy.ts b/src/lib/oauthProviderPolicy.ts index 1f1048c2..82949d98 100644 --- a/src/lib/oauthProviderPolicy.ts +++ b/src/lib/oauthProviderPolicy.ts @@ -8,11 +8,12 @@ import type { LookupAddress } from 'node:dns'; import { lookup } from 'node:dns/promises'; import { request as httpRequest } from 'node:http'; import { request as httpsRequest } from 'node:https'; -import { BlockList, isIP, type LookupFunction } from 'node:net'; +import { isIP, type LookupFunction } from 'node:net'; import { missingOAuthProviderEndpoints } from '@seamless-auth/types'; import type { OAuthProviderConfig } from '../schemas/systemConfig.schema.js'; +import { inList, neverReachable, nonPublic, unmapIPv4 } from './outboundAddress.js'; import { sendProviderRequest } from './providerTransport.js'; type EnvSource = Record; @@ -30,88 +31,6 @@ export const PRIVATE_PROVIDER_HOSTS_ENV = 'OAUTH_PROVIDER_PRIVATE_HOSTS'; const PROVIDER_URL_FIELDS = ['authorizationUrl', 'tokenUrl', 'userInfoUrl', 'jwksUri'] as const; -const nonPublic = new BlockList(); -nonPublic.addSubnet('0.0.0.0', 8, 'ipv4'); -nonPublic.addSubnet('10.0.0.0', 8, 'ipv4'); -nonPublic.addSubnet('100.64.0.0', 10, 'ipv4'); -nonPublic.addSubnet('127.0.0.0', 8, 'ipv4'); -nonPublic.addSubnet('169.254.0.0', 16, 'ipv4'); -nonPublic.addSubnet('172.16.0.0', 12, 'ipv4'); -nonPublic.addSubnet('192.0.0.0', 24, 'ipv4'); -nonPublic.addSubnet('192.168.0.0', 16, 'ipv4'); -nonPublic.addSubnet('198.18.0.0', 15, 'ipv4'); -nonPublic.addSubnet('224.0.0.0', 3, 'ipv4'); -nonPublic.addAddress('::', 'ipv6'); -nonPublic.addAddress('::1', 'ipv6'); -nonPublic.addSubnet('64:ff9b:1::', 48, 'ipv6'); -nonPublic.addSubnet('fc00::', 7, 'ipv6'); -nonPublic.addSubnet('fe80::', 10, 'ipv6'); -nonPublic.addSubnet('ff00::', 8, 'ipv6'); - -// Never reachable, even for an allowlisted host: link-local carries cloud instance -// metadata, and the unspecified address means this machine. -const neverReachable = new BlockList(); -neverReachable.addSubnet('0.0.0.0', 8, 'ipv4'); -neverReachable.addSubnet('169.254.0.0', 16, 'ipv4'); -neverReachable.addAddress('::', 'ipv6'); -neverReachable.addSubnet('fe80::', 10, 'ipv6'); - -function unmapIPv4(address: string) { - const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address); - return mapped ? mapped[1] : address; -} - -function ipv6Hextets(address: string): number[] | null { - let text = address; - const dotted = /(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(text); - if (dotted) { - const [a, b, c, d] = dotted.slice(1).map(Number); - text = `${text.slice(0, dotted.index)}${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`; - } - - const [head, tail] = text.split('::'); - const left = head ? head.split(':') : []; - const right = tail ? tail.split(':') : []; - const fill = text.includes('::') ? 8 - left.length - right.length : 0; - const parts = [...left, ...Array(fill).fill('0'), ...right].map((part) => - parseInt(part, 16), - ); - - return parts.length === 8 && parts.every((part) => part >= 0 && part <= 0xffff) ? parts : null; -} - -/** - * The IPv4 address an IPv6 address carries, for the forms a gateway turns back into - * IPv4: IPv4-mapped and IPv4-compatible, NAT64 (64:ff9b::/96) and 6to4 (2002::/16). - * Classifying only the IPv6 form would let `[64:ff9b::a9fe:a9fe]` reach 169.254.169.254 - * through a NAT64 gateway. - */ -function embeddedIPv4(address: string): string | null { - const h = ipv6Hextets(address); - if (!h) return null; - - const quad = (high: number, low: number) => - `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`; - const zeros = (from: number, to: number) => h.slice(from, to).every((part) => part === 0); - - if (zeros(0, 5) && h[5] === 0xffff) return quad(h[6], h[7]); - if (zeros(0, 6) && (h[6] !== 0 || h[7] > 1)) return quad(h[6], h[7]); - if (h[0] === 0x64 && h[1] === 0xff9b && zeros(2, 6)) return quad(h[6], h[7]); - if (h[0] === 0x2002) return quad(h[1], h[2]); - - return null; -} - -function inList(list: BlockList, address: string) { - const plain = unmapIPv4(address.replace(/^\[|\]$/g, '')); - const version = isIP(plain); - if (!version) return false; - if (version === 4) return list.check(plain, 'ipv4'); - - const carried = embeddedIPv4(plain); - return list.check(plain, 'ipv6') || (carried !== null && list.check(carried, 'ipv4')); -} - function addressAllowed(address: string, hostAllowlisted: boolean) { return !inList(neverReachable, address) && (hostAllowlisted || !inList(nonPublic, address)); } diff --git a/src/lib/outboundAddress.ts b/src/lib/outboundAddress.ts new file mode 100644 index 00000000..0638c440 --- /dev/null +++ b/src/lib/outboundAddress.ts @@ -0,0 +1,89 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import { BlockList, isIP } from 'node:net'; + +export const nonPublic = new BlockList(); +nonPublic.addSubnet('0.0.0.0', 8, 'ipv4'); +nonPublic.addSubnet('10.0.0.0', 8, 'ipv4'); +nonPublic.addSubnet('100.64.0.0', 10, 'ipv4'); +nonPublic.addSubnet('127.0.0.0', 8, 'ipv4'); +nonPublic.addSubnet('169.254.0.0', 16, 'ipv4'); +nonPublic.addSubnet('172.16.0.0', 12, 'ipv4'); +nonPublic.addSubnet('192.0.0.0', 24, 'ipv4'); +nonPublic.addSubnet('192.168.0.0', 16, 'ipv4'); +nonPublic.addSubnet('198.18.0.0', 15, 'ipv4'); +nonPublic.addSubnet('224.0.0.0', 3, 'ipv4'); +nonPublic.addAddress('::', 'ipv6'); +nonPublic.addAddress('::1', 'ipv6'); +nonPublic.addSubnet('64:ff9b:1::', 48, 'ipv6'); +nonPublic.addSubnet('fc00::', 7, 'ipv6'); +nonPublic.addSubnet('fe80::', 10, 'ipv6'); +nonPublic.addSubnet('ff00::', 8, 'ipv6'); + +// Never reachable, even for an allowlisted host: link-local carries cloud instance +// metadata, and the unspecified address means this machine. +export const neverReachable = new BlockList(); +neverReachable.addSubnet('0.0.0.0', 8, 'ipv4'); +neverReachable.addSubnet('169.254.0.0', 16, 'ipv4'); +neverReachable.addAddress('::', 'ipv6'); +neverReachable.addSubnet('fe80::', 10, 'ipv6'); + +export function unmapIPv4(address: string) { + const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address); + return mapped ? mapped[1] : address; +} + +function ipv6Hextets(address: string): number[] | null { + let text = address; + const dotted = /(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(text); + if (dotted) { + const [a, b, c, d] = dotted.slice(1).map(Number); + text = `${text.slice(0, dotted.index)}${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`; + } + + const [head, tail] = text.split('::'); + const left = head ? head.split(':') : []; + const right = tail ? tail.split(':') : []; + const fill = text.includes('::') ? 8 - left.length - right.length : 0; + const parts = [...left, ...Array(fill).fill('0'), ...right].map((part) => + parseInt(part, 16), + ); + + return parts.length === 8 && parts.every((part) => part >= 0 && part <= 0xffff) ? parts : null; +} + +/** + * The IPv4 address an IPv6 address carries, for the forms a gateway turns back into + * IPv4: IPv4-mapped and IPv4-compatible, NAT64 (64:ff9b::/96) and 6to4 (2002::/16). + * Classifying only the IPv6 form would let `[64:ff9b::a9fe:a9fe]` reach 169.254.169.254 + * through a NAT64 gateway. + */ +function embeddedIPv4(address: string): string | null { + const h = ipv6Hextets(address); + if (!h) return null; + + const quad = (high: number, low: number) => + `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`; + const zeros = (from: number, to: number) => h.slice(from, to).every((part) => part === 0); + + if (zeros(0, 5) && h[5] === 0xffff) return quad(h[6], h[7]); + if (zeros(0, 6) && (h[6] !== 0 || h[7] > 1)) return quad(h[6], h[7]); + if (h[0] === 0x64 && h[1] === 0xff9b && zeros(2, 6)) return quad(h[6], h[7]); + if (h[0] === 0x2002) return quad(h[1], h[2]); + + return null; +} + +export function inList(list: BlockList, address: string) { + const plain = unmapIPv4(address.replace(/^\[|\]$/g, '')); + const version = isIP(plain); + if (!version) return false; + if (version === 4) return list.check(plain, 'ipv4'); + + const carried = embeddedIPv4(plain); + return list.check(plain, 'ipv6') || (carried !== null && list.check(carried, 'ipv4')); +} diff --git a/src/migrations/20261107120000-add-webhooks.cjs b/src/migrations/20261107120000-add-webhooks.cjs new file mode 100644 index 00000000..5885ad7f --- /dev/null +++ b/src/migrations/20261107120000-add-webhooks.cjs @@ -0,0 +1,93 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +'use strict'; + +/** + * Signed, retried webhooks (ADR 0005). Deliveries are made from committed audit rows, read past + * a cursor in `event_dispatch_cursors`, so an event is sent only once its row exists and none is + * lost between happening and being queued. A delivery's id is its `webhook-id`, and it stays the + * same across retries and redelivery. `(endpointId, authEventSeq)` is unique so that a dispatch + * repeated after a crash cannot queue the same event twice. + * + * @type {import('sequelize-cli').Migration} + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query(` + CREATE TABLE IF NOT EXISTS public.webhook_endpoints ( + id uuid NOT NULL, + url character varying(2048) NOT NULL, + description text, + "eventTypes" character varying(64)[] NOT NULL, + enabled boolean NOT NULL DEFAULT true, + "disabledReason" character varying(20), + version integer NOT NULL DEFAULT 1, + "secretCiphertext" text NOT NULL, + "secretIv" text NOT NULL, + "secretTag" text NOT NULL, + "previousSecretCiphertext" text, + "previousSecretIv" text, + "previousSecretTag" text, + "previousSecretExpiresAt" timestamp with time zone, + "failingSince" timestamp with time zone, + "createdBy" uuid, + "createdAt" timestamp with time zone NOT NULL, + "updatedAt" timestamp with time zone NOT NULL, + CONSTRAINT webhook_endpoints_pkey PRIMARY KEY (id), + CONSTRAINT webhook_endpoints_disabled_reason + CHECK ("disabledReason" IS NULL OR "disabledReason" IN ('gone', 'failing', 'manual')) + ); + + CREATE TABLE IF NOT EXISTS public.webhook_deliveries ( + id uuid NOT NULL, + "endpointId" uuid NOT NULL, + "eventType" character varying(64) NOT NULL, + "authEventSeq" bigint, + payload text NOT NULL, + status character varying(20) NOT NULL, + attempts integer NOT NULL DEFAULT 0, + "nextAttemptAt" timestamp with time zone, + "lastAttemptAt" timestamp with time zone, + "lastStatusCode" integer, + "lastFailure" character varying(32), + "createdAt" timestamp with time zone NOT NULL, + "updatedAt" timestamp with time zone NOT NULL, + CONSTRAINT webhook_deliveries_pkey PRIMARY KEY (id), + CONSTRAINT webhook_deliveries_endpoint_fkey + FOREIGN KEY ("endpointId") REFERENCES public.webhook_endpoints(id) ON DELETE CASCADE, + CONSTRAINT webhook_deliveries_status + CHECK (status IN ('pending', 'succeeded', 'failed', 'dead')), + CONSTRAINT webhook_deliveries_event_once UNIQUE ("endpointId", "authEventSeq") + ); + + CREATE INDEX IF NOT EXISTS webhook_deliveries_due_idx + ON public.webhook_deliveries ("nextAttemptAt") + WHERE status IN ('pending', 'failed'); + + CREATE INDEX IF NOT EXISTS webhook_deliveries_endpoint_created_idx + ON public.webhook_deliveries ("endpointId", "createdAt" DESC); + + CREATE INDEX IF NOT EXISTS webhook_deliveries_created_idx + ON public.webhook_deliveries ("createdAt"); + + CREATE TABLE IF NOT EXISTS public.event_dispatch_cursors ( + name character varying(100) NOT NULL, + "lastSeq" bigint NOT NULL, + "updatedAt" timestamp with time zone NOT NULL, + CONSTRAINT event_dispatch_cursors_pkey PRIMARY KEY (name) + ); + `); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query(` + DROP TABLE IF EXISTS public.webhook_deliveries; + DROP TABLE IF EXISTS public.webhook_endpoints; + DROP TABLE IF EXISTS public.event_dispatch_cursors; + `); + }, +}; diff --git a/src/models/webhookDeliveries.ts b/src/models/webhookDeliveries.ts new file mode 100644 index 00000000..8264e11d --- /dev/null +++ b/src/models/webhookDeliveries.ts @@ -0,0 +1,84 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import type { CalloutFailure, WebhookDeliveryStatus } from '@seamless-auth/types'; +import { DataTypes, Model, Optional, Sequelize } from 'sequelize'; + +export interface WebhookDeliveryAttributes { + /** The `webhook-id` header and the event's `id`. */ + id: string; + endpointId: string; + eventType: string; + /** The audit row the event came from. Null for a test event. */ + authEventSeq: string | null; + /** The exact body signed and sent, so a retry or redelivery sends the same bytes. */ + payload: string; + status: WebhookDeliveryStatus; + attempts: number; + nextAttemptAt: Date | null; + lastAttemptAt: Date | null; + lastStatusCode: number | null; + lastFailure: CalloutFailure | null; + createdAt?: Date; + updatedAt?: Date; +} + +type WebhookDeliveryCreationAttributes = Optional< + WebhookDeliveryAttributes, + | 'authEventSeq' + | 'attempts' + | 'nextAttemptAt' + | 'lastAttemptAt' + | 'lastStatusCode' + | 'lastFailure' + | 'createdAt' + | 'updatedAt' +>; + +export class WebhookDelivery + extends Model + implements WebhookDeliveryAttributes +{ + declare id: string; + declare endpointId: string; + declare eventType: string; + declare authEventSeq: string | null; + declare payload: string; + declare status: WebhookDeliveryStatus; + declare attempts: number; + declare nextAttemptAt: Date | null; + declare lastAttemptAt: Date | null; + declare lastStatusCode: number | null; + declare lastFailure: CalloutFailure | null; + declare readonly createdAt: Date; + declare readonly updatedAt: Date; +} + +const initializeWebhookDeliveryModel = (sequelize: Sequelize) => { + WebhookDelivery.init( + { + id: { type: DataTypes.UUID, primaryKey: true, allowNull: false }, + endpointId: { type: DataTypes.UUID, allowNull: false }, + eventType: { type: DataTypes.STRING(64), allowNull: false }, + authEventSeq: { type: DataTypes.BIGINT, allowNull: true }, + payload: { type: DataTypes.TEXT, allowNull: false }, + status: { type: DataTypes.STRING(20), allowNull: false }, + attempts: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 }, + nextAttemptAt: { type: DataTypes.DATE, allowNull: true }, + lastAttemptAt: { type: DataTypes.DATE, allowNull: true }, + lastStatusCode: { type: DataTypes.INTEGER, allowNull: true }, + lastFailure: { type: DataTypes.STRING(32), allowNull: true }, + }, + { + sequelize, + tableName: 'webhook_deliveries', + modelName: 'WebhookDelivery', + }, + ); + return WebhookDelivery; +}; + +export default initializeWebhookDeliveryModel; diff --git a/src/models/webhookEndpoints.ts b/src/models/webhookEndpoints.ts new file mode 100644 index 00000000..9ff68479 --- /dev/null +++ b/src/models/webhookEndpoints.ts @@ -0,0 +1,107 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import type { WebhookDisabledReason, WebhookEventType } from '@seamless-auth/types'; +import { DataTypes, Model, Optional, Sequelize } from 'sequelize'; + +export interface WebhookEndpointAttributes { + id: string; + url: string; + description: string | null; + eventTypes: WebhookEventType[]; + enabled: boolean; + disabledReason: WebhookDisabledReason | null; + version: number; + secretCiphertext: string; + secretIv: string; + secretTag: string; + previousSecretCiphertext: string | null; + previousSecretIv: string | null; + previousSecretTag: string | null; + previousSecretExpiresAt: Date | null; + /** When the current run of failed deliveries began. Cleared by any success. */ + failingSince: Date | null; + createdBy: string | null; + createdAt?: Date; + updatedAt?: Date; +} + +type WebhookEndpointCreationAttributes = Optional< + WebhookEndpointAttributes, + | 'id' + | 'description' + | 'enabled' + | 'disabledReason' + | 'version' + | 'previousSecretCiphertext' + | 'previousSecretIv' + | 'previousSecretTag' + | 'previousSecretExpiresAt' + | 'failingSince' + | 'createdBy' + | 'createdAt' + | 'updatedAt' +>; + +export class WebhookEndpoint + extends Model + implements WebhookEndpointAttributes +{ + declare id: string; + declare url: string; + declare description: string | null; + declare eventTypes: WebhookEventType[]; + declare enabled: boolean; + declare disabledReason: WebhookDisabledReason | null; + declare version: number; + declare secretCiphertext: string; + declare secretIv: string; + declare secretTag: string; + declare previousSecretCiphertext: string | null; + declare previousSecretIv: string | null; + declare previousSecretTag: string | null; + declare previousSecretExpiresAt: Date | null; + declare failingSince: Date | null; + declare createdBy: string | null; + declare readonly createdAt: Date; + declare readonly updatedAt: Date; +} + +const initializeWebhookEndpointModel = (sequelize: Sequelize) => { + WebhookEndpoint.init( + { + id: { + type: DataTypes.UUID, + primaryKey: true, + defaultValue: DataTypes.UUIDV4, + allowNull: false, + }, + url: { type: DataTypes.STRING(2048), allowNull: false }, + description: { type: DataTypes.TEXT, allowNull: true }, + eventTypes: { type: DataTypes.ARRAY(DataTypes.STRING(64)), allowNull: false }, + enabled: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true }, + disabledReason: { type: DataTypes.STRING(20), allowNull: true }, + version: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 1 }, + secretCiphertext: { type: DataTypes.TEXT, allowNull: false }, + secretIv: { type: DataTypes.TEXT, allowNull: false }, + secretTag: { type: DataTypes.TEXT, allowNull: false }, + previousSecretCiphertext: { type: DataTypes.TEXT, allowNull: true }, + previousSecretIv: { type: DataTypes.TEXT, allowNull: true }, + previousSecretTag: { type: DataTypes.TEXT, allowNull: true }, + previousSecretExpiresAt: { type: DataTypes.DATE, allowNull: true }, + failingSince: { type: DataTypes.DATE, allowNull: true }, + createdBy: { type: DataTypes.UUID, allowNull: true }, + }, + { + sequelize, + tableName: 'webhook_endpoints', + modelName: 'WebhookEndpoint', + }, + ); + return WebhookEndpoint; +}; + +export default initializeWebhookEndpointModel; diff --git a/src/routes/webhooks.routes.ts b/src/routes/webhooks.routes.ts new file mode 100644 index 00000000..b695fbbe --- /dev/null +++ b/src/routes/webhooks.routes.ts @@ -0,0 +1,209 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import { + createWebhook, + deleteWebhook, + getWebhook, + getWebhookDelivery, + listWebhookDeliveries, + listWebhooks, + redeliverWebhook, + rotateWebhookSecret, + testWebhook, + updateWebhook, +} from '../controllers/webhooks.js'; +import { createRouter } from '../lib/createRouter.js'; +import { requireAdmin } from '../middleware/requireAdmin.js'; +import { requireStepUp } from '../middleware/requireStepUp.js'; +import { ErrorSchema, MessageSchema } from '../schemas/generic.responses.js'; +import { StepUpRequiredErrorSchema } from '../schemas/stepUp.responses.js'; +import { + CalloutTestResponseSchema, + CreateWebhookEndpointRequestSchema, + UpdateWebhookEndpointRequestSchema, + WebhookDeliveryIdParamSchema, + WebhookDeliveryListResponseSchema, + WebhookDeliveryQuerySchema, + WebhookDeliveryResponseSchema, + WebhookEndpointCreatedResponseSchema, + WebhookEndpointIdParamSchema, + WebhookEndpointListResponseSchema, + WebhookEndpointResponseSchema, + WebhookSecretRotatedResponseSchema, +} from '../schemas/webhook.schemas.js'; + +/** + * Signed, retried webhooks (ADR 0005). Sending a test event and redelivering are writes: each + * makes a signed request to a URL an administrator chose, so they take step-up like the rest. + */ +const router = createRouter('/admin'); + +const tags = ['Admin', 'Webhooks']; +const read = { auth: 'access', tags, middleware: [requireAdmin('read')] }; +const write = { auth: 'access', tags, middleware: [requireAdmin('write'), requireStepUp()] }; + +router.get( + '/webhooks', + { + ...read, + summary: 'List webhook endpoints', + schemas: { response: { 200: WebhookEndpointListResponseSchema } }, + }, + listWebhooks, +); + +router.post( + '/webhooks', + { + ...write, + summary: 'Create a webhook endpoint', + description: 'Returns the signing secret once. It cannot be read back.', + schemas: { + body: CreateWebhookEndpointRequestSchema, + response: { + 201: WebhookEndpointCreatedResponseSchema, + 400: ErrorSchema, + 403: StepUpRequiredErrorSchema, + 409: ErrorSchema, + }, + }, + }, + createWebhook, +); + +router.get( + '/webhooks/:id', + { + ...read, + summary: 'Get a webhook endpoint', + schemas: { + params: WebhookEndpointIdParamSchema, + response: { 200: WebhookEndpointResponseSchema, 404: ErrorSchema }, + }, + }, + getWebhook, +); + +router.patch( + '/webhooks/:id', + { + ...write, + summary: 'Update a webhook endpoint', + description: 'Turning an endpoint back on clears why it was disabled.', + schemas: { + params: WebhookEndpointIdParamSchema, + body: UpdateWebhookEndpointRequestSchema, + response: { + 200: WebhookEndpointResponseSchema, + 400: ErrorSchema, + 403: StepUpRequiredErrorSchema, + 404: ErrorSchema, + }, + }, + }, + updateWebhook, +); + +router.delete( + '/webhooks/:id', + { + ...write, + summary: 'Delete a webhook endpoint', + description: 'Also deletes its delivery history.', + schemas: { + params: WebhookEndpointIdParamSchema, + response: { 200: MessageSchema, 403: StepUpRequiredErrorSchema, 404: ErrorSchema }, + }, + }, + deleteWebhook, +); + +router.post( + '/webhooks/:id/secret', + { + ...write, + summary: 'Rotate a webhook signing secret', + description: + 'Returns the new secret once. The previous one keeps signing beside it for 24 hours.', + schemas: { + params: WebhookEndpointIdParamSchema, + response: { + 200: WebhookSecretRotatedResponseSchema, + 403: StepUpRequiredErrorSchema, + 404: ErrorSchema, + 409: ErrorSchema, + }, + }, + }, + rotateWebhookSecret, +); + +router.post( + '/webhooks/:id/test', + { + ...write, + summary: 'Send a test event', + description: 'Sends `webhook.test` once, now, whatever the endpoint subscribes to.', + schemas: { + params: WebhookEndpointIdParamSchema, + response: { + 200: CalloutTestResponseSchema, + 403: StepUpRequiredErrorSchema, + 404: ErrorSchema, + }, + }, + }, + testWebhook, +); + +router.get( + '/webhook-deliveries', + { + ...read, + summary: 'List webhook deliveries', + description: 'Newest first. `status=dead` is the dead letter view. Kept for 30 days.', + schemas: { + query: WebhookDeliveryQuerySchema, + response: { 200: WebhookDeliveryListResponseSchema, 400: ErrorSchema }, + }, + }, + listWebhookDeliveries, +); + +router.get( + '/webhook-deliveries/:deliveryId', + { + ...read, + summary: 'Get a webhook delivery and its event', + schemas: { + params: WebhookDeliveryIdParamSchema, + response: { 200: WebhookDeliveryResponseSchema, 404: ErrorSchema }, + }, + }, + getWebhookDelivery, +); + +router.post( + '/webhook-deliveries/:deliveryId/redeliver', + { + ...write, + summary: 'Redeliver a webhook', + description: + 'One attempt now, with the same `webhook-id` and body and a fresh timestamp and signature.', + schemas: { + params: WebhookDeliveryIdParamSchema, + response: { + 200: WebhookDeliveryResponseSchema, + 403: StepUpRequiredErrorSchema, + 404: ErrorSchema, + }, + }, + }, + redeliverWebhook, +); + +export default router.router; diff --git a/src/schemas/authEvent.types.ts b/src/schemas/authEvent.types.ts index 0b565e29..7fdd5568 100644 --- a/src/schemas/authEvent.types.ts +++ b/src/schemas/authEvent.types.ts @@ -137,6 +137,13 @@ export const AUTH_EVENT_TYPES = [ 'webauthn_registration_challenge', 'webauthn_registration_failed', 'webauthn_registration_suspicious', + 'admin_webhook_created', + 'admin_webhook_deleted', + 'admin_webhook_redelivered', + 'admin_webhook_secret_rotated', + 'admin_webhook_updated', + 'session_created', + 'webhook_endpoint_disabled', ] as const; export const AuthEventTypeEnum = z.enum(AUTH_EVENT_TYPES); diff --git a/src/schemas/webhook.schemas.ts b/src/schemas/webhook.schemas.ts new file mode 100644 index 00000000..6c27382b --- /dev/null +++ b/src/schemas/webhook.schemas.ts @@ -0,0 +1,20 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +export { + CalloutTestResponseSchema, + CreateWebhookEndpointRequestSchema, + UpdateWebhookEndpointRequestSchema, + WebhookDeliveryIdParamSchema, + WebhookDeliveryListResponseSchema, + WebhookDeliveryQuerySchema, + WebhookDeliveryResponseSchema, + WebhookEndpointCreatedResponseSchema, + WebhookEndpointIdParamSchema, + WebhookEndpointListResponseSchema, + WebhookEndpointResponseSchema, + WebhookSecretRotatedResponseSchema, +} from '@seamless-auth/types'; diff --git a/src/server.ts b/src/server.ts index 307295db..326fb403 100644 --- a/src/server.ts +++ b/src/server.ts @@ -15,6 +15,7 @@ import { assertServiceTokenConfig } from './config/serviceToken.js'; import { connectToDb } from './db.js'; import { initializeModels } from './models/index.js'; import { TotpCredential } from './models/totpCredentials.js'; +import { WebhookEndpoint } from './models/webhookEndpoints.js'; import { startAuditMaintenance } from './services/auditRetention.js'; import { warnOnBreakGlassMisconfiguration } from './services/breakGlassService.js'; import { initializeMetadataService } from './services/metadataServiceBootstrap.js'; @@ -23,6 +24,7 @@ import { startBackchannelLogoutSweep } from './services/oidcBackchannelLogout.js import { startOidcPayloadPurge } from './services/oidcPayloadStore.js'; import { recordBootstrapPolicyVersion } from './services/policyVersionService.js'; import { assertSchemaCurrent } from './services/schemaGuard.js'; +import { startWebhookDelivery } from './services/webhookService.js'; import getLogger from './utils/logger.js'; import { initDevSigningKey } from './utils/signingKeyStore.js'; @@ -46,7 +48,10 @@ async function startServer() { await recordBootstrapPolicyVersion(); // After bootstrap, since which secrets are needed depends on the stored config. - assertAuthSecrets(await getSystemConfig(), (await TotpCredential.count()) > 0); + assertAuthSecrets(await getSystemConfig(), { + totpCredentialsExist: (await TotpCredential.count()) > 0, + calloutSecretsExist: (await WebhookEndpoint.count()) > 0, + }); await warnOnBreakGlassMisconfiguration(); // After config is bootstrapped, since it decides whether attestation is @@ -67,6 +72,7 @@ async function startServer() { startAuditMaintenance(); startOidcPayloadPurge(); startBackchannelLogoutSweep(); + startWebhookDelivery(); } catch (err) { logger.error('Failed to start server:', err); process.exit(1); diff --git a/src/services/sessionIssuance.ts b/src/services/sessionIssuance.ts index 69d7759b..e32f2a30 100644 --- a/src/services/sessionIssuance.ts +++ b/src/services/sessionIssuance.ts @@ -12,6 +12,7 @@ import { createRefreshTokenLookup, generateRefreshToken } from '../lib/token.js' import { Session, SessionAuthMethod } from '../models/sessions.js'; import { computeSessionTimes, parseDurationToSeconds } from '../utils/utils.js'; import { mintAccessToken } from './accessTokenService.js'; +import { AuthEventService } from './authEventService.js'; import { enforceConcurrentSessionLimit } from './concurrentSessionPolicy.js'; import { isPasskeyRequiredForUser } from './loginPolicyService.js'; import { getDefaultOrganizationIdForUser } from './organizationService.js'; @@ -170,6 +171,16 @@ export async function issueSessionAndRespond(params: IssueSessionParams): Promis user, }); + // The one record that a sign-in completed, whatever the factor: the factor events before it + // can be steps of a flow that still fails. The `user.signed_in` webhook is built from it. + await AuthEventService.log({ + userId: user.id, + sessionId: session.id, + type: 'session_created', + req, + metadata: { method, organizationId, ...(recovery ? { recovery: true } : {}) }, + }); + if (!token || !refreshToken) { throw new Error('Failed to issue session tokens'); } diff --git a/src/services/webhookCatalog.ts b/src/services/webhookCatalog.ts new file mode 100644 index 00000000..0ea82e2c --- /dev/null +++ b/src/services/webhookCatalog.ts @@ -0,0 +1,175 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import type { + CredentialKind, + SessionRevokedReason, + WebhookEvent, + WebhookEventType, +} from '@seamless-auth/types'; + +/** The audit row fields a webhook is built from. */ +export type DispatchableAuthEvent = { + seq: string; + type: string; + user_id: string | null; + session_id: string | null; + metadata: Record | null; + created_at: Date; +}; + +export type WebhookSubject = { email: string | null; phone: string | null }; + +export type WebhookEventBody = Extract; + +type Built = { type: WebhookEventType; data: WebhookEventBody['data'] }; + +const SESSION_REVOKED: Readonly> = { + logout_success: 'logout', + admin_session_revoked: 'admin', + session_evicted: 'evicted', + oidc_session_revoked: 'provider', +}; + +const ORGANIZATION_MEMBER: Readonly> = { + organization_member_added: 'organization.member_added', + organization_member_updated: 'organization.member_updated', + organization_member_removed: 'organization.member_removed', +}; + +function text(value: unknown): string | null { + return typeof value === 'string' && value ? value : null; +} + +function strings(value: unknown): string[] { + return Array.isArray(value) + ? value.filter((item): item is string => typeof item === 'string') + : []; +} + +/** + * Which audit types become which webhook (ADR 0005, D3). The audit types are internal and many; + * the webhook catalog is a public contract, so this table is the whole mapping and + * `tests/unit/services/webhookCatalog.spec.ts` pins it. An audit type added later reaches no + * receiver until it is added here. + */ +export const WEBHOOK_SOURCE_TYPES: Readonly> = { + user_created: 'user.created', + user_deleted: 'user.deleted', + session_created: 'user.signed_in', + account_recovery_completed: 'user.recovered', + logout_success: 'session.revoked', + admin_session_revoked: 'session.revoked', + session_evicted: 'session.revoked', + oidc_session_revoked: 'session.revoked', + registration_success: 'credential.added', + totp_enrollment_success: 'credential.added', + recovery_codes_generated: 'credential.added', + credentials_deleted: 'credential.removed', + totp_disabled: 'credential.removed', + organization_member_added: 'organization.member_added', + organization_member_updated: 'organization.member_updated', + organization_member_removed: 'organization.member_removed', +}; + +function credentialKind(event: DispatchableAuthEvent): CredentialKind | null { + switch (event.type) { + case 'totp_enrollment_success': + case 'totp_disabled': + return 'totp'; + case 'recovery_codes_generated': + return 'recovery_codes'; + default: + // `registration_success` is also written when an account is registered, and + // `credentials_deleted` when an account is deleted. Only the rows that name a passkey are + // about a credential. + return event.metadata?.credential === 'passkey' ? 'passkey' : null; + } +} + +/** + * The session a revocation is about. For a sign-out and a provider revocation that is the session + * the request came from. An administrator's revocation and an eviction name it in metadata, + * because the request's own session is the administrator's or the new one. Signing out everywhere + * names no single session. + */ +function revokedSessionId(event: DispatchableAuthEvent): string | null { + switch (event.type) { + case 'logout_success': + return event.metadata?.scope === 'current_session' ? event.session_id : null; + case 'oidc_session_revoked': + return event.session_id; + default: + return text(event.metadata?.sessionId); + } +} + +/** + * The webhook an audit row becomes, or null when it becomes none. `subject` is read from the + * user at dispatch, for `user.created`, which carries the address the account was made with. + */ +export function webhookEventFor( + event: DispatchableAuthEvent, + subject: WebhookSubject | null, +): Built | null { + const type = WEBHOOK_SOURCE_TYPES[event.type]; + if (!type) return null; + + const userId = event.user_id; + + switch (type) { + case 'user.created': + return userId + ? { + type, + data: { userId, email: subject?.email ?? null, phone: subject?.phone ?? null }, + } + : null; + case 'user.deleted': + case 'user.recovered': + return userId ? { type, data: { userId } } : null; + case 'user.signed_in': + return userId + ? { + type, + data: { + userId, + sessionId: event.session_id, + method: text(event.metadata?.method), + organizationId: text(event.metadata?.organizationId), + }, + } + : null; + case 'session.revoked': + return { + type, + data: { + userId, + sessionId: revokedSessionId(event), + reason: SESSION_REVOKED[event.type], + }, + }; + case 'credential.added': + case 'credential.removed': { + const kind = credentialKind(event); + return userId && kind + ? { type, data: { userId, kind, credentialId: text(event.metadata?.credentialId) } } + : null; + } + default: { + const organizationId = text(event.metadata?.organizationId); + if (!userId || !organizationId || !ORGANIZATION_MEMBER[event.type]) return null; + return { + type, + data: { + organizationId, + userId, + roles: event.type === 'organization_member_removed' ? [] : strings(event.metadata?.roles), + }, + }; + } + } +} diff --git a/src/services/webhookService.ts b/src/services/webhookService.ts new file mode 100644 index 00000000..e6ddfcf4 --- /dev/null +++ b/src/services/webhookService.ts @@ -0,0 +1,659 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import { randomUUID } from 'node:crypto'; + +import { + type CalloutFailure, + type CalloutTestResponse, + type CreateWebhookEndpointRequest, + type UpdateWebhookEndpointRequest, + WEBHOOK_FAILING_DISABLE_SECONDS, + WEBHOOK_PAYLOAD_VERSION, + WEBHOOK_RETRY_SCHEDULE_SECONDS, + WEBHOOK_SECRET_ROTATION_OVERLAP_SECONDS, + WEBHOOK_TEST_EVENT_TYPE, + WEBHOOK_TIMEOUT_MS, + type WebhookDeliveryQuery, + type WebhookDeliveryStatus, + type WebhookEventType, +} from '@seamless-auth/types'; +import { Op, QueryTypes, type Transaction, type WhereOptions } from 'sequelize'; + +import { productionSecretMissing } from '../config/authSecrets.js'; +import { + decryptCalloutSecret, + encryptCalloutSecret, + generateCalloutSecret, + signedCalloutHeaders, +} from '../lib/calloutSigning.js'; +import { CalloutError, calloutRequest, calloutUrlProblem } from '../lib/calloutTransport.js'; +import { getSequelize } from '../models/index.js'; +import { User } from '../models/users.js'; +import { WebhookDelivery, type WebhookDeliveryAttributes } from '../models/webhookDeliveries.js'; +import { WebhookEndpoint } from '../models/webhookEndpoints.js'; +import getLogger from '../utils/logger.js'; +import { AuthEventService } from './authEventService.js'; +import { + type DispatchableAuthEvent, + WEBHOOK_SOURCE_TYPES, + webhookEventFor, +} from './webhookCatalog.js'; + +const logger = getLogger('webhooks'); + +export class WebhookError extends Error { + constructor( + readonly status: number, + message: string, + ) { + super(message); + this.name = 'WebhookError'; + } +} + +// A receiver only needs to say yes or no, so its body is read for the status alone. +const MAX_RESPONSE_BYTES = 64 * 1024; +const DISPATCH_BATCH = 500; +const DELIVERY_BATCH = 50; +const DELIVERY_RETENTION_DAYS = 30; +const CURSOR_NAME = 'webhooks'; +// Distinct from the audit maintenance lock, so the two never wait on each other. +const DISPATCH_LOCK_KEY = 72_641_002; + +function now() { + return new Date(); +} + +function addSeconds(at: Date, seconds: number) { + return new Date(at.getTime() + seconds * 1000); +} + +export function serializeEndpoint(endpoint: WebhookEndpoint) { + const rotating = + endpoint.previousSecretExpiresAt && endpoint.previousSecretExpiresAt > now() + ? endpoint.previousSecretExpiresAt.toISOString() + : null; + + return { + id: endpoint.id, + url: endpoint.url, + description: endpoint.description ?? null, + eventTypes: endpoint.eventTypes, + enabled: endpoint.enabled, + disabledReason: endpoint.disabledReason ?? null, + version: WEBHOOK_PAYLOAD_VERSION, + previousSecretExpiresAt: rotating, + createdAt: endpoint.createdAt.toISOString(), + updatedAt: endpoint.updatedAt.toISOString(), + }; +} + +export function serializeDelivery(delivery: WebhookDelivery) { + return { + id: delivery.id, + endpointId: delivery.endpointId, + eventType: delivery.eventType, + status: delivery.status, + attempts: delivery.attempts, + nextAttemptAt: delivery.nextAttemptAt?.toISOString() ?? null, + lastAttemptAt: delivery.lastAttemptAt?.toISOString() ?? null, + lastStatusCode: delivery.lastStatusCode ?? null, + lastFailure: delivery.lastFailure ?? null, + createdAt: delivery.createdAt.toISOString(), + }; +} + +function assertUrl(url: string) { + const problem = calloutUrlProblem(url); + if (problem) throw new WebhookError(400, `url ${problem}`); +} + +function assertSecretKey() { + if (productionSecretMissing('CALLOUT_SECRET_ENCRYPTION_KEY')) { + throw new WebhookError( + 409, + 'CALLOUT_SECRET_ENCRYPTION_KEY must be set before a webhook can be created', + ); + } +} + +function secretColumns(secret: string) { + const { ciphertext, iv, tag } = encryptCalloutSecret(secret); + return { secretCiphertext: ciphertext, secretIv: iv, secretTag: tag }; +} + +/** Every secret that signs right now: the current one, and the previous one while it overlaps. */ +export function signingSecrets(endpoint: WebhookEndpoint, at: Date = now()): string[] { + const secrets = [ + decryptCalloutSecret({ + ciphertext: endpoint.secretCiphertext, + iv: endpoint.secretIv, + tag: endpoint.secretTag, + }), + ]; + + if ( + endpoint.previousSecretCiphertext && + endpoint.previousSecretIv && + endpoint.previousSecretTag && + endpoint.previousSecretExpiresAt && + endpoint.previousSecretExpiresAt > at + ) { + secrets.push( + decryptCalloutSecret({ + ciphertext: endpoint.previousSecretCiphertext, + iv: endpoint.previousSecretIv, + tag: endpoint.previousSecretTag, + }), + ); + } + + return secrets; +} + +export async function listEndpoints() { + return WebhookEndpoint.findAll({ order: [['createdAt', 'ASC']] }); +} + +export async function getEndpoint(id: string) { + const endpoint = await WebhookEndpoint.findByPk(id); + if (!endpoint) throw new WebhookError(404, 'Webhook not found'); + return endpoint; +} + +export async function createEndpoint( + input: CreateWebhookEndpointRequest, + actorUserId: string | null, +) { + assertUrl(input.url); + assertSecretKey(); + + const secret = generateCalloutSecret(); + const endpoint = await WebhookEndpoint.create({ + url: input.url, + description: input.description ?? null, + eventTypes: input.eventTypes, + enabled: input.enabled ?? true, + createdBy: actorUserId, + ...secretColumns(secret), + }); + + return { endpoint, secret }; +} + +export async function updateEndpoint(id: string, input: UpdateWebhookEndpointRequest) { + const endpoint = await getEndpoint(id); + if (input.url !== undefined) assertUrl(input.url); + + await endpoint.update({ + ...(input.url !== undefined ? { url: input.url } : {}), + ...(input.description !== undefined ? { description: input.description } : {}), + ...(input.eventTypes !== undefined ? { eventTypes: input.eventTypes } : {}), + ...(input.enabled !== undefined + ? { + enabled: input.enabled, + disabledReason: input.enabled ? null : 'manual', + failingSince: null, + } + : {}), + }); + + return endpoint; +} + +export async function deleteEndpoint(id: string) { + const endpoint = await getEndpoint(id); + await endpoint.destroy(); + return endpoint; +} + +/** + * The old secret keeps signing for a day beside the new one, so receivers move over without a + * dropped delivery. Rotating again within that day ends the old secret's overlap early: only two + * secrets ever sign. + */ +export async function rotateEndpointSecret(id: string) { + assertSecretKey(); + const endpoint = await getEndpoint(id); + const secret = generateCalloutSecret(); + const previousSecretExpiresAt = addSeconds(now(), WEBHOOK_SECRET_ROTATION_OVERLAP_SECONDS); + + await endpoint.update({ + previousSecretCiphertext: endpoint.secretCiphertext, + previousSecretIv: endpoint.secretIv, + previousSecretTag: endpoint.secretTag, + previousSecretExpiresAt, + ...secretColumns(secret), + }); + + return { endpoint, secret, previousSecretExpiresAt }; +} + +function body(id: string, type: string, timestamp: Date, data: unknown) { + return JSON.stringify({ + id, + type, + version: WEBHOOK_PAYLOAD_VERSION, + timestamp: timestamp.toISOString(), + data, + }); +} + +type Attempt = { + ok: boolean; + statusCode: number | null; + failure: CalloutFailure | null; + retryAfterSeconds: number | null; + durationMs: number; +}; + +function retryAfter(header: string | string[] | undefined): number | null { + const value = Array.isArray(header) ? header[0] : header; + if (!value) return null; + const seconds = Number(value); + if (Number.isFinite(seconds) && seconds >= 0) return seconds; + const date = Date.parse(value); + return Number.isNaN(date) ? null : Math.max(0, (date - Date.now()) / 1000); +} + +/** One signed POST. Anything but a 2xx is a failure, including a redirect, which is not followed. */ +export async function sendSigned( + url: string, + id: string, + payload: string, + secrets: string[], + timeoutMs: number = WEBHOOK_TIMEOUT_MS, +): Promise { + const started = Date.now(); + try { + const response = await calloutRequest(url, { + method: 'POST', + headers: signedCalloutHeaders(id, payload, secrets), + body: payload, + timeoutMs, + maxResponseBytes: MAX_RESPONSE_BYTES, + }); + const ok = response.status >= 200 && response.status < 300; + + return { + ok, + statusCode: response.status, + failure: ok ? null : 'http_status', + retryAfterSeconds: retryAfter(response.headers['retry-after']), + durationMs: Date.now() - started, + }; + } catch (error) { + return { + ok: false, + statusCode: null, + failure: error instanceof CalloutError ? error.failure : 'connection_failed', + retryAfterSeconds: null, + durationMs: Date.now() - started, + }; + } +} + +/** + * When the next attempt is due, or null when there is none and the delivery is dead. A + * `Retry-After` longer than the schedule's own delay is honored, up to the schedule's longest. + */ +export function nextAttemptAt(attempts: number, at: Date, retryAfterSeconds: number | null) { + const scheduled = WEBHOOK_RETRY_SCHEDULE_SECONDS[attempts]; + if (scheduled === undefined) return null; + + const longest = WEBHOOK_RETRY_SCHEDULE_SECONDS[WEBHOOK_RETRY_SCHEDULE_SECONDS.length - 1]; + const wait = Math.max(scheduled, Math.min(retryAfterSeconds ?? 0, longest)); + // Up to 10% later, so endpoints that failed together do not retry together. + return addSeconds(at, wait * (1 + Math.random() * 0.1)); +} + +async function recordOutcome( + delivery: WebhookDelivery, + endpoint: WebhookEndpoint, + attempt: Attempt, +) { + const at = now(); + const attempts = delivery.attempts + 1; + const next = attempt.ok ? null : nextAttemptAt(attempts, at, attempt.retryAfterSeconds); + const status: WebhookDeliveryStatus = attempt.ok ? 'succeeded' : next ? 'failed' : 'dead'; + + await delivery.update({ + status, + attempts, + nextAttemptAt: next, + lastAttemptAt: at, + lastStatusCode: attempt.statusCode, + lastFailure: attempt.failure, + }); + + if (attempt.ok) { + if (endpoint.failingSince) await endpoint.update({ failingSince: null }); + return; + } + + // 410 is the receiver saying the endpoint is gone for good. + if (attempt.statusCode === 410) { + await disableEndpoint(endpoint, 'gone'); + return; + } + + const failingSince = endpoint.failingSince ?? at; + if (at.getTime() - failingSince.getTime() >= WEBHOOK_FAILING_DISABLE_SECONDS * 1000) { + await disableEndpoint(endpoint, 'failing'); + } else if (!endpoint.failingSince) { + await endpoint.update({ failingSince }); + } +} + +async function disableEndpoint(endpoint: WebhookEndpoint, reason: 'gone' | 'failing') { + if (!endpoint.enabled) return; + await endpoint.update({ enabled: false, disabledReason: reason }); + logger.warn(`Webhook ${endpoint.id} disabled: ${reason}`); + await AuthEventService.logContext({ + type: 'webhook_endpoint_disabled', + metadata: { endpointId: endpoint.id, reason }, + }); +} + +export async function attemptDelivery(delivery: WebhookDelivery, endpoint: WebhookEndpoint) { + const attempt = await sendSigned( + endpoint.url, + delivery.id, + delivery.payload, + signingSecrets(endpoint), + ); + await recordOutcome(delivery, endpoint, attempt); + return attempt; +} + +/** Sends `webhook.test` to one endpoint now, whatever it subscribes to, and logs it as a delivery. */ +export async function sendTestEvent(id: string): Promise { + const endpoint = await getEndpoint(id); + const deliveryId = randomUUID(); + const delivery = await WebhookDelivery.create({ + id: deliveryId, + endpointId: endpoint.id, + eventType: WEBHOOK_TEST_EVENT_TYPE, + payload: body(deliveryId, WEBHOOK_TEST_EVENT_TYPE, now(), { endpointId: endpoint.id }), + status: 'pending', + nextAttemptAt: null, + }); + + const attempt = await sendSigned( + endpoint.url, + delivery.id, + delivery.payload, + signingSecrets(endpoint), + ); + // A test is one attempt: it is never retried and never disables the endpoint. + await delivery.update({ + status: attempt.ok ? 'succeeded' : 'dead', + attempts: 1, + lastAttemptAt: now(), + lastStatusCode: attempt.statusCode, + lastFailure: attempt.failure, + }); + + return { + ok: attempt.ok, + failure: attempt.failure, + statusCode: attempt.statusCode, + durationMs: attempt.durationMs, + }; +} + +export async function getDelivery(deliveryId: string) { + const delivery = await WebhookDelivery.findByPk(deliveryId); + if (!delivery) throw new WebhookError(404, 'Delivery not found'); + return delivery; +} + +/** + * One attempt now, with the same `webhook-id` and body and a fresh timestamp and signature, so a + * receiver that already has the event can drop it. + */ +export async function redeliver(deliveryId: string) { + const delivery = await getDelivery(deliveryId); + const endpoint = await getEndpoint(delivery.endpointId); + await attemptDelivery(delivery, endpoint); + return delivery; +} + +function encodeCursor(delivery: WebhookDelivery) { + return Buffer.from(`${delivery.createdAt.toISOString()}|${delivery.id}`).toString('base64url'); +} + +function decodeCursor(cursor: string): { createdAt: Date; id: string } { + const [createdAt, id] = Buffer.from(cursor, 'base64url').toString('utf8').split('|'); + const at = new Date(createdAt); + if (!id || Number.isNaN(at.getTime())) throw new WebhookError(400, 'Invalid cursor'); + return { createdAt: at, id }; +} + +export async function listDeliveries(query: WebhookDeliveryQuery) { + const conditions: WhereOptions[] = []; + if (query.endpointId) conditions.push({ endpointId: query.endpointId }); + if (query.status) conditions.push({ status: query.status }); + if (query.eventType) conditions.push({ eventType: query.eventType }); + if (query.cursor) { + const { createdAt, id } = decodeCursor(query.cursor); + conditions.push({ + [Op.or]: [{ createdAt: { [Op.lt]: createdAt } }, { createdAt, id: { [Op.lt]: id } }], + }); + } + + const rows = await WebhookDelivery.findAll({ + where: conditions.length ? { [Op.and]: conditions } : {}, + order: [ + ['createdAt', 'DESC'], + ['id', 'DESC'], + ], + limit: query.limit + 1, + }); + + const page = rows.slice(0, query.limit); + return { + deliveries: page, + nextCursor: rows.length > query.limit ? encodeCursor(page[page.length - 1]) : null, + }; +} + +type CursorRow = { lastSeq: string }; +type HeadRow = { head: string }; + +async function subjectFor(event: DispatchableAuthEvent, transaction: Transaction) { + if (WEBHOOK_SOURCE_TYPES[event.type] !== 'user.created' || !event.user_id) return null; + const user = await User.findByPk(event.user_id, { + attributes: ['email', 'phone'], + transaction, + }); + return user ? { email: user.email ?? null, phone: user.phone ?? null } : null; +} + +/** + * Turns committed audit rows past the cursor into deliveries (ADR 0005, D2). Rows are read by + * `seq`, and the chain trigger holds the chain head row from insert to commit, so committed rows + * always form a gapless prefix: a cursor never steps past a row still to commit. On first run the + * cursor starts at the newest row, so turning webhooks on does not replay history. + * + * Returns how many audit rows were read, so the loop knows whether to run again at once. + */ +export async function dispatchWebhooks(): Promise { + const sequelize = getSequelize(); + + return sequelize.transaction(async (transaction) => { + const [{ locked }] = await sequelize.query<{ locked: boolean }>( + 'SELECT pg_try_advisory_xact_lock(:key) AS locked', + { replacements: { key: DISPATCH_LOCK_KEY }, type: QueryTypes.SELECT, transaction }, + ); + if (!locked) return 0; + + const [cursor] = await sequelize.query( + 'SELECT "lastSeq" FROM public.event_dispatch_cursors WHERE name = :name', + { replacements: { name: CURSOR_NAME }, type: QueryTypes.SELECT, transaction }, + ); + + if (!cursor) { + const [{ head }] = await sequelize.query( + 'SELECT coalesce(max(seq), 0) AS head FROM public.auth_events', + { type: QueryTypes.SELECT, transaction }, + ); + await sequelize.query( + 'INSERT INTO public.event_dispatch_cursors (name, "lastSeq", "updatedAt") VALUES (:name, :head, now())', + { replacements: { name: CURSOR_NAME, head }, transaction }, + ); + return 0; + } + + const rows = await sequelize.query( + `SELECT seq, type, user_id, session_id, metadata, created_at + FROM public.auth_events + WHERE seq > :last + ORDER BY seq + LIMIT :limit`, + { + replacements: { last: cursor.lastSeq, limit: DISPATCH_BATCH }, + type: QueryTypes.SELECT, + transaction, + }, + ); + if (rows.length === 0) return 0; + + const endpoints = await WebhookEndpoint.findAll({ where: { enabled: true }, transaction }); + + for (const row of rows) { + const subscribed = endpoints.filter((endpoint) => + endpoint.eventTypes.includes(WEBHOOK_SOURCE_TYPES[row.type] as WebhookEventType), + ); + if (subscribed.length === 0) continue; + + const event = webhookEventFor(row, await subjectFor(row, transaction)); + if (!event) continue; + + for (const endpoint of subscribed) { + const id = randomUUID(); + await sequelize.query( + `INSERT INTO public.webhook_deliveries + (id, "endpointId", "eventType", "authEventSeq", payload, status, attempts, + "nextAttemptAt", "createdAt", "updatedAt") + VALUES (:id, :endpointId, :eventType, :seq, :payload, 'pending', 0, now(), now(), now()) + ON CONFLICT ("endpointId", "authEventSeq") DO NOTHING`, + { + replacements: { + id, + endpointId: endpoint.id, + eventType: event.type, + seq: row.seq, + payload: body(id, event.type, new Date(row.created_at), event.data), + }, + transaction, + }, + ); + } + } + + await sequelize.query( + 'UPDATE public.event_dispatch_cursors SET "lastSeq" = :seq, "updatedAt" = now() WHERE name = :name', + { replacements: { seq: rows[rows.length - 1].seq, name: CURSOR_NAME }, transaction }, + ); + + return rows.length; + }); +} + +/** + * Claims due deliveries and sends them. A claim pushes `nextAttemptAt` past the request timeout + * inside a short transaction with SKIP LOCKED, so two replicas never send the same attempt and a + * replica that dies mid-send leaves the delivery due again shortly after. + */ +export async function deliverDue(): Promise { + const sequelize = getSequelize(); + const lease = addSeconds(now(), WEBHOOK_TIMEOUT_MS / 1000 + 30); + + const claimed = await sequelize.transaction(async (transaction) => { + const rows = await sequelize.query<{ id: string }>( + `SELECT id FROM public.webhook_deliveries + WHERE status IN ('pending', 'failed') AND "nextAttemptAt" <= now() + ORDER BY "nextAttemptAt" + LIMIT :limit + FOR UPDATE SKIP LOCKED`, + { replacements: { limit: DELIVERY_BATCH }, type: QueryTypes.SELECT, transaction }, + ); + if (rows.length === 0) return []; + + const ids = rows.map((row) => row.id); + await WebhookDelivery.update( + { nextAttemptAt: lease }, + { where: { id: { [Op.in]: ids } }, transaction }, + ); + return ids; + }); + + if (claimed.length === 0) return 0; + + const deliveries = await WebhookDelivery.findAll({ where: { id: { [Op.in]: claimed } } }); + const endpoints = new Map( + ( + await WebhookEndpoint.findAll({ + where: { id: { [Op.in]: [...new Set(deliveries.map((d) => d.endpointId))] } }, + }) + ).map((endpoint) => [endpoint.id, endpoint]), + ); + + await Promise.all( + deliveries.map(async (delivery) => { + const endpoint = endpoints.get(delivery.endpointId); + // Disabled after it was queued: hold the delivery, so redeliver can still send it. + if (!endpoint || !endpoint.enabled) { + await delivery.update({ nextAttemptAt: null }); + return; + } + await attemptDelivery(delivery, endpoint); + }), + ); + + return claimed.length; +} + +export async function pruneDeliveries(at: Date = now()) { + return WebhookDelivery.destroy({ + where: { createdAt: { [Op.lt]: addSeconds(at, -DELIVERY_RETENTION_DAYS * 24 * 60 * 60) } }, + }); +} + +const TICK_MS = 1000; +const PRUNE_EVERY_TICKS = 3600; + +/** One pass of dispatch and delivery. Errors are logged, not thrown, so the loop keeps running. */ +export async function runWebhookTick(tick: number) { + try { + while ((await dispatchWebhooks()) === DISPATCH_BATCH) { + // A full batch means more rows are waiting. + } + while ((await deliverDue()) === DELIVERY_BATCH) { + // Likewise for due deliveries. + } + if (tick % PRUNE_EVERY_TICKS === 0) await pruneDeliveries(); + } catch (error) { + logger.error(`Webhook tick failed: ${(error as Error).message}`); + } +} + +/** Polls once a second. The loop is cheap when idle: two indexed reads. */ +export function startWebhookDelivery() { + let tick = 0; + let running = false; + const timer = setInterval(() => { + if (running) return; + running = true; + void runWebhookTick(tick++).finally(() => { + running = false; + }); + }, TICK_MS); + timer.unref(); + return timer; +} diff --git a/tests/integration/admin/adminStepUp.spec.ts b/tests/integration/admin/adminStepUp.spec.ts index 7f36f542..ad7dd745 100644 --- a/tests/integration/admin/adminStepUp.spec.ts +++ b/tests/integration/admin/adminStepUp.spec.ts @@ -43,6 +43,12 @@ const GUARDED = [ 'PATCH /admin/permissions/{permissionName}', 'DELETE /admin/permissions/{permissionName}', 'PUT /admin/roles/{kind}/{roleName}/permissions', + 'POST /admin/webhooks', + 'PATCH /admin/webhooks/{id}', + 'DELETE /admin/webhooks/{id}', + 'POST /admin/webhooks/{id}/secret', + 'POST /admin/webhooks/{id}/test', + 'POST /admin/webhook-deliveries/{deliveryId}/redeliver', 'POST /admin/users', 'POST /admin/users/import', 'DELETE /admin/users', diff --git a/tests/integration/admin/webhooks.spec.ts b/tests/integration/admin/webhooks.spec.ts new file mode 100644 index 00000000..789367b1 --- /dev/null +++ b/tests/integration/admin/webhooks.spec.ts @@ -0,0 +1,256 @@ +import { Application } from 'express'; +import request from 'supertest'; +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('../../../src/lib/calloutTransport.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, calloutRequest: vi.fn() }; +}); + +import { createApp } from '../../../src/app'; +import { calloutRequest } from '../../../src/lib/calloutTransport.js'; +import { encryptCalloutSecret } from '../../../src/lib/calloutSigning.js'; +import { Session } from '../../../src/models/sessions.js'; +import { WebhookDelivery } from '../../../src/models/webhookDeliveries.js'; +import { WebhookEndpoint } from '../../../src/models/webhookEndpoints.js'; +import { AuthEventService } from '../../../src/services/authEventService.js'; +import { buildFreshStepUpSession } from '../../factories/sessionFactory'; + +let app: Application; + +const now = new Date('2026-11-07T12:00:00.000Z'); +const endpointId = '5b8a1c2d-3e4f-4a5b-8c6d-7e8f9a0b1c2d'; +const deliveryId = '6c9b2d3e-4f5a-4b6c-9d7e-8f9a0b1c2d3e'; + +function buildEndpoint(overrides: Record = {}) { + const sealed = encryptCalloutSecret('whsec_' + Buffer.alloc(32, 2).toString('base64')); + const record: any = { + id: endpointId, + url: 'https://hooks.example.com/seamless', + description: null, + eventTypes: ['user.created'], + enabled: true, + disabledReason: null, + version: 1, + secretCiphertext: sealed.ciphertext, + secretIv: sealed.iv, + secretTag: sealed.tag, + previousSecretCiphertext: null, + previousSecretIv: null, + previousSecretTag: null, + previousSecretExpiresAt: null, + failingSince: null, + createdAt: now, + updatedAt: now, + ...overrides, + }; + record.update = vi.fn(async (values: Record) => Object.assign(record, values)); + record.destroy = vi.fn(); + return record; +} + +function buildDelivery(overrides: Record = {}) { + const record: any = { + id: deliveryId, + endpointId, + eventType: 'user.created', + authEventSeq: '10', + payload: JSON.stringify({ + id: deliveryId, + type: 'user.created', + version: 1, + timestamp: now.toISOString(), + data: { userId: 'u', email: null, phone: null }, + }), + status: 'dead', + attempts: 8, + nextAttemptAt: null, + lastAttemptAt: now, + lastStatusCode: 500, + lastFailure: 'http_status', + createdAt: now, + ...overrides, + }; + record.update = vi.fn(async (values: Record) => Object.assign(record, values)); + return record; +} + +beforeAll(async () => { + app = await createApp(); +}); + +beforeEach(() => { + vi.clearAllMocks(); + (Session.findOne as any).mockResolvedValue(buildFreshStepUpSession()); +}); + +describe('webhook endpoints', () => { + it('lists endpoints without their secrets', async () => { + vi.mocked(WebhookEndpoint.findAll).mockResolvedValue([buildEndpoint()]); + + const res = await request(app).get('/admin/webhooks'); + + expect(res.status).toBe(200); + expect(res.body.endpoints[0]).toMatchObject({ id: endpointId, version: 1 }); + expect(JSON.stringify(res.body)).not.toMatch(/secret(Ciphertext|Iv|Tag)|whsec_/); + }); + + it('creates an endpoint, returns the secret once and audits it', async () => { + vi.mocked(WebhookEndpoint.create).mockImplementation(async (values: any) => + buildEndpoint(values), + ); + + const res = await request(app) + .post('/admin/webhooks') + .send({ url: 'https://hooks.example.com/a?token=abc', eventTypes: ['user.created'] }); + + expect(res.status).toBe(201); + expect(res.body.secret).toMatch(/^whsec_/); + // The audit log is permanent, so a token in the query string must not reach it. + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'admin_webhook_created', + metadata: expect.objectContaining({ url: 'https://hooks.example.com/a' }), + }), + ); + }); + + it('refuses a URL pointing at the cloud metadata address', async () => { + const res = await request(app) + .post('/admin/webhooks') + .send({ url: 'http://169.254.169.254/latest', eventTypes: ['user.created'] }); + + expect(res.status).toBe(400); + expect(res.body.error).toContain('never reachable'); + expect(WebhookEndpoint.create).not.toHaveBeenCalled(); + }); + + it('refuses an unknown event type and the test type', async () => { + for (const eventTypes of [['user.renamed'], ['webhook.test']]) { + const res = await request(app) + .post('/admin/webhooks') + .send({ url: 'https://hooks.example.com/a', eventTypes }); + expect(res.status).toBe(400); + } + }); + + it('reads, updates and deletes an endpoint, auditing each write', async () => { + const record = buildEndpoint(); + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(record); + + expect((await request(app).get(`/admin/webhooks/${endpointId}`)).status).toBe(200); + + const updated = await request(app) + .patch(`/admin/webhooks/${endpointId}`) + .send({ enabled: false }); + expect(updated.status).toBe(200); + expect(updated.body.endpoint).toMatchObject({ enabled: false, disabledReason: 'manual' }); + + const deleted = await request(app).delete(`/admin/webhooks/${endpointId}`); + expect(deleted.status).toBe(200); + expect(record.destroy).toHaveBeenCalled(); + + const types = vi.mocked(AuthEventService.log).mock.calls.map(([options]) => options.type); + expect(types).toEqual(['admin_webhook_updated', 'admin_webhook_deleted']); + }); + + it('answers 404 for an endpoint that does not exist', async () => { + for (const send of [ + () => request(app).get(`/admin/webhooks/${endpointId}`), + () => request(app).patch(`/admin/webhooks/${endpointId}`).send({ enabled: true }), + () => request(app).delete(`/admin/webhooks/${endpointId}`), + () => request(app).post(`/admin/webhooks/${endpointId}/secret`), + () => request(app).post(`/admin/webhooks/${endpointId}/test`), + ]) { + expect((await send()).status).toBe(404); + } + }); + + it('rotates the secret and returns the new one', async () => { + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(buildEndpoint()); + + const res = await request(app).post(`/admin/webhooks/${endpointId}/secret`); + + expect(res.status).toBe(200); + expect(res.body.secret).toMatch(/^whsec_/); + expect(res.body.previousSecretExpiresAt).toBeDefined(); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ type: 'admin_webhook_secret_rotated' }), + ); + }); + + it('sends a test event and reports the result', async () => { + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(buildEndpoint()); + vi.mocked(WebhookDelivery.create).mockImplementation(async (values: any) => + buildDelivery(values), + ); + vi.mocked(calloutRequest).mockResolvedValue({ + status: 200, + headers: {}, + body: Buffer.alloc(0), + }); + + const res = await request(app).post(`/admin/webhooks/${endpointId}/test`); + + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ ok: true, failure: null, statusCode: 200 }); + }); +}); + +describe('webhook deliveries', () => { + it('lists deliveries, filtered to dead letters', async () => { + vi.mocked(WebhookDelivery.findAll).mockResolvedValue([buildDelivery()]); + + const res = await request(app).get('/admin/webhook-deliveries?status=dead'); + + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ deliveries: [{ id: deliveryId }], nextCursor: null }); + }); + + it('refuses a cursor it did not issue', async () => { + const res = await request(app).get('/admin/webhook-deliveries?cursor=nope'); + + expect(res.status).toBe(400); + }); + + it('shows a delivery with its event', async () => { + vi.mocked(WebhookDelivery.findByPk).mockResolvedValue(buildDelivery()); + + const res = await request(app).get(`/admin/webhook-deliveries/${deliveryId}`); + + expect(res.status).toBe(200); + expect(res.body.delivery.event).toMatchObject({ type: 'user.created', id: deliveryId }); + }); + + it('redelivers and audits it', async () => { + const record = buildDelivery(); + vi.mocked(WebhookDelivery.findByPk).mockResolvedValue(record); + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(buildEndpoint()); + vi.mocked(calloutRequest).mockResolvedValue({ + status: 202, + headers: {}, + body: Buffer.alloc(0), + }); + + const res = await request(app).post(`/admin/webhook-deliveries/${deliveryId}/redeliver`); + + expect(res.status).toBe(200); + expect(res.body.delivery).toMatchObject({ status: 'succeeded', attempts: 9 }); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ type: 'admin_webhook_redelivered' }), + ); + }); + + it('answers 404 for a delivery that does not exist', async () => { + expect((await request(app).get(`/admin/webhook-deliveries/${deliveryId}`)).status).toBe(404); + expect( + (await request(app).post(`/admin/webhook-deliveries/${deliveryId}/redeliver`)).status, + ).toBe(404); + }); + + it('rethrows an unexpected error', async () => { + vi.mocked(WebhookDelivery.findAll).mockRejectedValue(new Error('database down')); + + expect((await request(app).get('/admin/webhook-deliveries')).status).toBe(500); + }); +}); diff --git a/tests/integration/organizations/organizationRoleSecurity.spec.ts b/tests/integration/organizations/organizationRoleSecurity.spec.ts index c0ec26d8..bfa8aebb 100644 --- a/tests/integration/organizations/organizationRoleSecurity.spec.ts +++ b/tests/integration/organizations/organizationRoleSecurity.spec.ts @@ -209,6 +209,7 @@ describe('organization membership audit', () => { userId: memberId, metadata: { organizationId: testOrganizationId, + roles: ['admin'], rolesAdded: ['admin'], rolesRemoved: ['member'], }, diff --git a/tests/postgres/webhooks.spec.ts b/tests/postgres/webhooks.spec.ts new file mode 100644 index 00000000..969d7a36 --- /dev/null +++ b/tests/postgres/webhooks.spec.ts @@ -0,0 +1,143 @@ +import { createServer, type IncomingHttpHeaders, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import { getSequelize, initializeModels } from '../../src/models/index.js'; +import { WebhookDelivery } from '../../src/models/webhookDeliveries.js'; +import { WebhookEndpoint } from '../../src/models/webhookEndpoints.js'; +import { AuthEventService } from '../../src/services/authEventService.js'; +import { createEndpoint, deliverDue, dispatchWebhooks } from '../../src/services/webhookService.js'; + +let server: Server; +let port: number; +const received: { headers: IncomingHttpHeaders; body: string }[] = []; +let answer = 200; + +beforeAll(async () => { + await initializeModels(); + + server = createServer((req, res) => { + let body = ''; + req.on('data', (chunk) => (body += chunk)); + req.on('end', () => { + received.push({ headers: req.headers, body }); + res.statusCode = answer; + res.end(); + }); + }); + await new Promise((done) => server.listen(0, '127.0.0.1', done)); + port = (server.address() as AddressInfo).port; +}); + +beforeEach(async () => { + received.length = 0; + answer = 200; + await getSequelize().query( + 'DELETE FROM webhook_deliveries; DELETE FROM webhook_endpoints; DELETE FROM event_dispatch_cursors;', + ); +}); + +afterAll(async () => { + server.closeAllConnections(); + await new Promise((done) => server.close(() => done())); + await getSequelize().close(); +}); + +async function logEvent(type: string, userId: string, metadata: Record = {}) { + await AuthEventService.logContext({ type: type as never, userId, metadata }); +} + +describe('webhook dispatch against the audit chain', () => { + it('starts after the newest event, then delivers each new one once, signed', async () => { + const { secret } = await createEndpoint( + { url: `http://127.0.0.1:${port}/hook`, eventTypes: ['user.deleted'] }, + null, + ); + + // Before the cursor exists: history is not replayed. + await logEvent('user_deleted', '11111111-1111-4111-8111-111111111111'); + expect(await dispatchWebhooks()).toBe(0); + + await logEvent('user_deleted', '22222222-2222-4222-8222-222222222222'); + await logEvent('login_failed', '22222222-2222-4222-8222-222222222222'); + expect(await dispatchWebhooks()).toBe(2); + // Running again finds nothing new and queues nothing twice. + expect(await dispatchWebhooks()).toBe(0); + + const deliveries = await WebhookDelivery.findAll(); + expect(deliveries).toHaveLength(1); + + expect(await deliverDue()).toBe(1); + expect(received).toHaveLength(1); + + const [{ headers, body }] = received; + expect(JSON.parse(body)).toMatchObject({ + id: deliveries[0].id, + type: 'user.deleted', + data: { userId: '22222222-2222-4222-8222-222222222222' }, + }); + expect(headers['webhook-id']).toBe(deliveries[0].id); + expect(headers['webhook-signature']).toMatch(/^v1,/); + expect(secret).toMatch(/^whsec_/); + + await deliveries[0].reload(); + expect(deliveries[0]).toMatchObject({ status: 'succeeded', attempts: 1 }); + }); + + it('cannot queue the same audit row twice for one endpoint', async () => { + const { endpoint } = await createEndpoint( + { url: `http://127.0.0.1:${port}/hook`, eventTypes: ['user.deleted'] }, + null, + ); + const insert = () => + getSequelize().query( + `INSERT INTO webhook_deliveries (id, "endpointId", "eventType", "authEventSeq", payload, + status, attempts, "createdAt", "updatedAt") + VALUES (gen_random_uuid(), :endpointId, 'user.deleted', 7, '{}', 'pending', 0, now(), now()) + ON CONFLICT ("endpointId", "authEventSeq") DO NOTHING`, + { replacements: { endpointId: endpoint.id } }, + ); + + await insert(); + await insert(); + + expect(await WebhookDelivery.count()).toBe(1); + }); + + it('schedules a retry after a failure and holds the lease from a second worker', async () => { + await createEndpoint( + { url: `http://127.0.0.1:${port}/hook`, eventTypes: ['user.deleted'] }, + null, + ); + await dispatchWebhooks(); + await logEvent('user_deleted', '33333333-3333-4333-8333-333333333333'); + await dispatchWebhooks(); + + answer = 503; + expect(await deliverDue()).toBe(1); + // Not due again until the schedule says so. + expect(await deliverDue()).toBe(0); + + const [delivery] = await WebhookDelivery.findAll(); + expect(delivery).toMatchObject({ status: 'failed', attempts: 1, lastStatusCode: 503 }); + expect(delivery.nextAttemptAt!.getTime()).toBeGreaterThan(Date.now()); + + const [endpoint] = await WebhookEndpoint.findAll(); + expect(endpoint.failingSince).not.toBeNull(); + }); + + it('deletes an endpoint with its deliveries', async () => { + const { endpoint } = await createEndpoint( + { url: `http://127.0.0.1:${port}/hook`, eventTypes: ['user.deleted'] }, + null, + ); + await dispatchWebhooks(); + await logEvent('user_deleted', '44444444-4444-4444-8444-444444444444'); + await dispatchWebhooks(); + + await endpoint.destroy(); + + expect(await WebhookDelivery.count()).toBe(0); + }); +}); diff --git a/tests/setup/mocks.ts b/tests/setup/mocks.ts index f19ca2b8..23b647e2 100644 --- a/tests/setup/mocks.ts +++ b/tests/setup/mocks.ts @@ -193,6 +193,25 @@ vi.mock('../../src/models/permissions.js', () => ({ }, })); +vi.mock('../../src/models/webhookEndpoints.js', () => ({ + WebhookEndpoint: { + create: vi.fn(), + findAll: vi.fn(async () => []), + findByPk: vi.fn(async () => null), + count: vi.fn(async () => 0), + }, +})); + +vi.mock('../../src/models/webhookDeliveries.js', () => ({ + WebhookDelivery: { + create: vi.fn(), + findAll: vi.fn(async () => []), + findByPk: vi.fn(async () => null), + update: vi.fn(), + destroy: vi.fn(async () => 0), + }, +})); + vi.mock('../../src/models/rolePermissions.js', () => ({ RolePermission: { sequelize: { @@ -359,6 +378,7 @@ vi.mock('bcrypt-ts', () => ({ vi.mock('../../src/services/authEventService.js', () => ({ AuthEventService: { log: vi.fn(), + logContext: vi.fn(), notificationSent: vi.fn(), refreshTokenFailed: vi.fn(), requestSuspicious: vi.fn(), diff --git a/tests/unit/config/authSecrets.spec.ts b/tests/unit/config/authSecrets.spec.ts index b439ade4..ee3a7465 100644 --- a/tests/unit/config/authSecrets.spec.ts +++ b/tests/unit/config/authSecrets.spec.ts @@ -28,6 +28,7 @@ describe('authSecret', () => { ); expect(authSecret('TOTP_SECRET_ENCRYPTION_KEY', {})).toBe('dev-totp-secret:local:local'); expect(authSecret('OAUTH_STATE_SECRET', {})).toBe('dev-oauth-state:local'); + expect(authSecret('CALLOUT_SECRET_ENCRYPTION_KEY', {})).toBe('dev-callout-secret:local:local'); expect(authSecret('DECOY_SUBJECT_SECRET', {})).toBe('dev-decoy-subject:local'); }); }); @@ -51,6 +52,48 @@ describe('authSecretsRequiredBy', () => { }); }); +describe('the callout secret key', () => { + it('is needed once a webhook or login hook stores a signing secret', () => { + expect( + authSecretsRequiredBy( + { oauth_providers: [] }, + { totpCredentialsExist: false, calloutSecretsExist: true }, + ), + ).toContain('CALLOUT_SECRET_ENCRYPTION_KEY'); + expect( + authSecretsRequiredBy({ oauth_providers: [] }, { totpCredentialsExist: false }), + ).not.toContain('CALLOUT_SECRET_ENCRYPTION_KEY'); + }); +}); + +describe('assertAuthSecrets for the callout key', () => { + const production = { + NODE_ENV: 'production', + REFRESH_TOKEN_LOOKUP_SECRET: 'a', + DECOY_SUBJECT_SECRET: 'b', + }; + + it('refuses to start without it once webhooks exist, and does not suggest the service token', () => { + expect(() => + assertAuthSecrets( + { oauth_providers: [] }, + { totpCredentialsExist: false, calloutSecretsExist: true }, + production, + ), + ).toThrow(/Restore the value they were created with/); + }); + + it('starts with it set', () => { + expect(() => + assertAuthSecrets( + { oauth_providers: [] }, + { totpCredentialsExist: false, calloutSecretsExist: true }, + { ...production, CALLOUT_SECRET_ENCRYPTION_KEY: 'c' }, + ), + ).not.toThrow(); + }); +}); + describe('productionSecretMissing', () => { it('is true only in production without the secret', () => { expect(productionSecretMissing('OAUTH_STATE_SECRET', production)).toBe(true); @@ -63,28 +106,44 @@ describe('productionSecretMissing', () => { describe('assertAuthSecrets', () => { it('passes outside production and when everything needed is set', () => { - expect(() => assertAuthSecrets({ oauth_providers: [provider] }, true, {})).not.toThrow(); expect(() => - assertAuthSecrets({ oauth_providers: [] }, false, { - ...production, - REFRESH_TOKEN_LOOKUP_SECRET: 'a', - DECOY_SUBJECT_SECRET: 'b', - }), + assertAuthSecrets({ oauth_providers: [provider] }, { totpCredentialsExist: true }, {}), + ).not.toThrow(); + expect(() => + assertAuthSecrets( + { oauth_providers: [] }, + { totpCredentialsExist: false }, + { + ...production, + REFRESH_TOKEN_LOOKUP_SECRET: 'a', + DECOY_SUBJECT_SECRET: 'b', + }, + ), ).not.toThrow(); }); it('names every missing secret and how to keep existing data valid', () => { - expect(() => assertAuthSecrets({ oauth_providers: [provider] }, true, production)).toThrow( + expect(() => + assertAuthSecrets( + { oauth_providers: [provider] }, + { totpCredentialsExist: true }, + production, + ), + ).toThrow( /REFRESH_TOKEN_LOOKUP_SECRET, DECOY_SUBJECT_SECRET, TOTP_SECRET_ENCRYPTION_KEY, OAUTH_STATE_SECRET are not set[\s\S]*current SEAMLESS_SERVICE_TOKEN value/, ); }); it('uses the singular for one missing secret', () => { expect(() => - assertAuthSecrets({ oauth_providers: [] }, false, { - ...production, - REFRESH_TOKEN_LOOKUP_SECRET: 'a', - }), + assertAuthSecrets( + { oauth_providers: [] }, + { totpCredentialsExist: false }, + { + ...production, + REFRESH_TOKEN_LOOKUP_SECRET: 'a', + }, + ), ).toThrow('DECOY_SUBJECT_SECRET is not set'); }); }); diff --git a/tests/unit/lib/calloutSigning.spec.ts b/tests/unit/lib/calloutSigning.spec.ts new file mode 100644 index 00000000..98da1ab0 --- /dev/null +++ b/tests/unit/lib/calloutSigning.spec.ts @@ -0,0 +1,115 @@ +import { createHmac, timingSafeEqual } from 'node:crypto'; + +import { CalloutSecretSchema } from '@seamless-auth/types'; +import { describe, expect, it, vi } from 'vitest'; + +import { + calloutSignature, + decryptCalloutSecret, + encryptCalloutSecret, + generateCalloutSecret, + signedCalloutHeaders, +} from '../../../src/lib/calloutSigning.js'; + +// The shared setup makes randomBytes constant, and these tests need distinct secrets. +vi.unmock('crypto'); + +/** A receiver's check, written from the Standard Webhooks spec rather than from our signer. */ +function verifies(secret: string, id: string, timestamp: string, body: string, header: string) { + const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64'); + const expected = createHmac('sha256', key).update(`${id}.${timestamp}.${body}`).digest(); + + return header.split(' ').some((entry) => { + const [version, signature] = entry.split(','); + const given = Buffer.from(signature ?? '', 'base64'); + return version === 'v1' && given.length === expected.length && timingSafeEqual(given, expected); + }); +} + +describe('callout secrets', () => { + it('generates a whsec_ secret of 32 random bytes', () => { + const secret = generateCalloutSecret(); + + expect(CalloutSecretSchema.safeParse(secret).success).toBe(true); + expect(generateCalloutSecret()).not.toBe(secret); + }); + + it('round-trips through encryption at rest', () => { + const secret = generateCalloutSecret(); + const sealed = encryptCalloutSecret(secret); + + expect(sealed.ciphertext).not.toContain(secret.slice(6)); + expect(decryptCalloutSecret(sealed)).toBe(secret); + }); + + it('refuses a ciphertext that was tampered with', () => { + const sealed = encryptCalloutSecret(generateCalloutSecret()); + const flipped = Buffer.from(sealed.ciphertext, 'base64'); + flipped[0] ^= 1; + + expect(() => + decryptCalloutSecret({ ...sealed, ciphertext: flipped.toString('base64') }), + ).toThrow(); + }); + + it('cannot be read under another key', () => { + const sealed = encryptCalloutSecret(generateCalloutSecret()); + vi.stubEnv('CALLOUT_SECRET_ENCRYPTION_KEY', 'a different key'); + + expect(() => decryptCalloutSecret(sealed)).toThrow(); + }); +}); + +describe('signedCalloutHeaders', () => { + const body = '{"type":"user.created"}'; + const at = new Date('2026-11-07T12:00:00.000Z'); + + it('signs id, timestamp and body the way a Standard Webhooks receiver checks them', () => { + const secret = generateCalloutSecret(); + const headers = signedCalloutHeaders('msg_1', body, [secret], at); + + expect(headers['content-type']).toBe('application/json'); + expect(headers['webhook-id']).toBe('msg_1'); + expect(headers['webhook-timestamp']).toBe(String(at.getTime() / 1000)); + expect( + verifies(secret, 'msg_1', headers['webhook-timestamp'], body, headers['webhook-signature']), + ).toBe(true); + }); + + it('does not verify a changed body, id or timestamp', () => { + const secret = generateCalloutSecret(); + const headers = signedCalloutHeaders('msg_1', body, [secret], at); + const ts = headers['webhook-timestamp']; + const signature = headers['webhook-signature']; + + expect(verifies(secret, 'msg_1', ts, `${body} `, signature)).toBe(false); + expect(verifies(secret, 'msg_2', ts, body, signature)).toBe(false); + expect(verifies(secret, 'msg_1', String(Number(ts) + 1), body, signature)).toBe(false); + expect(verifies(generateCalloutSecret(), 'msg_1', ts, body, signature)).toBe(false); + }); + + it('signs with both secrets while one rotates, so either verifies', () => { + const current = generateCalloutSecret(); + const previous = generateCalloutSecret(); + const headers = signedCalloutHeaders('msg_1', body, [current, previous], at); + const ts = headers['webhook-timestamp']; + + expect(headers['webhook-signature'].split(' ')).toHaveLength(2); + expect(verifies(current, 'msg_1', ts, body, headers['webhook-signature'])).toBe(true); + expect(verifies(previous, 'msg_1', ts, body, headers['webhook-signature'])).toBe(true); + }); + + it('defaults the timestamp to now', () => { + vi.useFakeTimers({ now: at }); + try { + const headers = signedCalloutHeaders('msg_1', body, [generateCalloutSecret()]); + expect(headers['webhook-timestamp']).toBe(String(at.getTime() / 1000)); + } finally { + vi.useRealTimers(); + } + }); + + it('formats one signature as v1 and base64', () => { + expect(calloutSignature('a', 1, 'b', generateCalloutSecret())).toMatch(/^v1,[A-Za-z0-9+/]+=*$/); + }); +}); diff --git a/tests/unit/lib/calloutTransport.spec.ts b/tests/unit/lib/calloutTransport.spec.ts new file mode 100644 index 00000000..a2f35574 --- /dev/null +++ b/tests/unit/lib/calloutTransport.spec.ts @@ -0,0 +1,311 @@ +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { + CALLOUT_PRIVATE_HOSTS_ENV, + CalloutError, + calloutHostProblem, + calloutLookup, + calloutRequest, + calloutUrlProblem, +} from '../../../src/lib/calloutTransport.js'; + +const production = { NODE_ENV: 'production', ISSUER: 'https://auth.example.com' }; +const development = { NODE_ENV: 'development', ISSUER: 'http://localhost:5312' }; + +let server: Server | null = null; + +async function serve(handler: Parameters[1]) { + server = createServer(handler); + await new Promise((done) => server!.listen(0, '127.0.0.1', done)); + return (server.address() as AddressInfo).port; +} + +afterEach(async () => { + if (server) { + server.closeAllConnections(); + await new Promise((done) => server!.close(() => done())); + server = null; + } +}); + +async function failureOf(promise: Promise) { + try { + await promise; + } catch (error) { + expect(error).toBeInstanceOf(CalloutError); + return (error as CalloutError).failure; + } + throw new Error('expected the callout to fail'); +} + +describe('calloutUrlProblem', () => { + it.each([ + ['not a url', 'is not a valid URL'], + ['ftp://hooks.example.com/', 'must use https'], + ['http://hooks.example.com/', 'must use https'], + ['https://user:pass@hooks.example.com/', 'must not carry a username or password'], + ['https://auth.example.com/hooks', 'must not point at this server'], + ['https://127.0.0.1/hook', `list the host in ${CALLOUT_PRIVATE_HOSTS_ENV}`], + ['https://10.0.0.5/hook', `list the host in ${CALLOUT_PRIVATE_HOSTS_ENV}`], + ['https://[::1]/hook', `list the host in ${CALLOUT_PRIVATE_HOSTS_ENV}`], + ['https://169.254.169.254/latest/meta-data', 'never reachable'], + // NAT64 for 169.254.169.254: a gateway would turn it back into the metadata address. + ['https://[64:ff9b::a9fe:a9fe]/', 'never reachable'], + ['https://[::ffff:169.254.169.254]/', 'never reachable'], + ['https://224.0.0.1/', 'never reachable'], + ['https://0.0.0.0/', 'never reachable'], + ])('refuses %j in production', (url, problem) => { + expect(calloutUrlProblem(url, production)).toContain(problem); + }); + + it('accepts a public https URL in production', () => { + expect(calloutUrlProblem('https://hooks.example.com/seamless', production)).toBeNull(); + }); + + it('admits a private host only when the operator lists it', () => { + const env = { ...production, [CALLOUT_PRIVATE_HOSTS_ENV]: 'hooks.internal, 10.0.0.5' }; + + expect(calloutUrlProblem('https://10.0.0.5/hook', env)).toBeNull(); + expect(calloutUrlProblem('https://10.0.0.6/hook', env)).toContain('non-public'); + }); + + it('never admits the metadata address, even when the operator lists it', () => { + const env = { ...production, [CALLOUT_PRIVATE_HOSTS_ENV]: '169.254.169.254' }; + + expect(calloutUrlProblem('https://169.254.169.254/', env)).toContain('never reachable'); + }); + + it('allows http and private hosts outside production, but never link-local', () => { + expect(calloutUrlProblem('http://127.0.0.1:9000/hook', development)).toBeNull(); + expect(calloutUrlProblem('http://169.254.169.254/', development)).toContain('never reachable'); + }); + + it('refuses a missing host', () => { + expect(calloutHostProblem('', production)).toBe('has no host'); + }); + + it('ignores an issuer it cannot parse', () => { + expect(calloutHostProblem('hooks.example.com', { ISSUER: 'not a url' })).toBeNull(); + }); +}); + +describe('calloutLookup', () => { + function resolve(hostname: string, env: Record, all = false) { + return new Promise<{ error: Error | null; address: unknown }>((done) => + (calloutLookup(env) as any)(hostname, { all }, (error: Error | null, address: unknown) => + done({ error, address }), + ), + ); + } + + // A name is checked at connect time, so DNS that answers with a private address is refused + // even though the URL looked public when it was written. + it('refuses a name that resolves to loopback in production', async () => { + const { error } = await resolve('localhost', production); + + expect(error).toBeInstanceOf(CalloutError); + expect((error as CalloutError).failure).toBe('refused'); + }); + + it('admits a listed name in production', async () => { + const { error, address } = await resolve('localhost', { + ...production, + [CALLOUT_PRIVATE_HOSTS_ENV]: 'localhost', + }); + + expect(error).toBeNull(); + expect(typeof address).toBe('string'); + }); + + it('returns every address when asked for all of them', async () => { + const { error, address } = await resolve('localhost', development, true); + + expect(error).toBeNull(); + expect(Array.isArray(address)).toBe(true); + }); + + it.each([ + [4, 'IPv4'], + [6, 'IPv6'], + ])('honors a requested family (%s)', async (family) => { + const result = await new Promise<{ error: Error | null }>((done) => + (calloutLookup(development) as any)('localhost', { family }, (error: Error | null) => + done({ error }), + ), + ); + // Either family may be absent on the host; what matters is that the lookup ran. + expect(result.error === null || result.error instanceof Error).toBe(true); + }); + + it('passes a DNS failure through', async () => { + const { error } = await resolve('does-not-exist.invalid', development); + + expect(error).toBeInstanceOf(Error); + expect(error).not.toBeInstanceOf(CalloutError); + }); +}); + +describe('calloutRequest', () => { + const base = { timeoutMs: 2000, maxResponseBytes: 1024 }; + + it('posts the body and returns the status, headers and body', async () => { + let received = ''; + const port = await serve((req, res) => { + req.on('data', (chunk) => (received += chunk)); + req.on('end', () => { + res.setHeader('retry-after', '5'); + res.end('ok'); + }); + }); + + const response = await calloutRequest( + `http://127.0.0.1:${port}/hook`, + { ...base, body: '{"a":1}', headers: { 'x-test': '1' } }, + development, + ); + + expect(received).toBe('{"a":1}'); + expect(response.status).toBe(200); + expect(response.headers['retry-after']).toBe('5'); + expect(response.body.toString()).toBe('ok'); + }); + + it('sends a GET without a body', async () => { + const port = await serve((req, res) => res.end(req.method)); + + const response = await calloutRequest( + `http://127.0.0.1:${port}/`, + { ...base, method: 'GET' }, + development, + ); + + expect(response.body.toString()).toBe('GET'); + }); + + it('does not follow a redirect', async () => { + let hits = 0; + const port = await serve((req, res) => { + hits += 1; + res.statusCode = 307; + res.setHeader('location', 'http://169.254.169.254/latest/meta-data'); + res.end(); + }); + + const response = await calloutRequest(`http://127.0.0.1:${port}/`, base, development); + + expect(response.status).toBe(307); + expect(hits).toBe(1); + }); + + it('refuses loopback in production before connecting', async () => { + let hits = 0; + const port = await serve((_req, res) => { + hits += 1; + res.end(); + }); + + expect(await failureOf(calloutRequest(`https://127.0.0.1:${port}/`, base, production))).toBe( + 'refused', + ); + expect(hits).toBe(0); + }); + + it('refuses a name that resolves to loopback in production', async () => { + const port = await serve((_req, res) => res.end()); + + expect(await failureOf(calloutRequest(`https://localhost:${port}/`, base, production))).toBe( + 'refused', + ); + }); + + it('times out a destination that never answers', async () => { + const port = await serve(() => { + // Never responds. + }); + + expect( + await failureOf( + calloutRequest(`http://127.0.0.1:${port}/`, { ...base, timeoutMs: 100 }, development), + ), + ).toBe('timed_out'); + }); + + it('stops reading a response that is too large', async () => { + const port = await serve((_req, res) => res.end('x'.repeat(4096))); + + expect( + await failureOf( + calloutRequest( + `http://127.0.0.1:${port}/`, + { ...base, maxResponseBytes: 100 }, + development, + ), + ), + ).toBe('too_large'); + }); + + it('reports a refused connection without the socket error', async () => { + const port = await serve((_req, res) => res.end()); + server!.close(); + server = null; + + const failure = calloutRequest(`http://127.0.0.1:${port}/`, base, development); + + await expect(failure).rejects.toMatchObject({ + failure: 'connection_failed', + message: 'Callout connection failed', + }); + }); + + it('reports a response that breaks off mid-body', async () => { + const port = await serve((_req, res) => { + res.writeHead(200, { 'content-length': '100' }); + res.write('partial'); + setTimeout(() => res.socket?.destroy(), 10); + }); + + expect(await failureOf(calloutRequest(`http://127.0.0.1:${port}/`, base, development))).toBe( + 'connection_failed', + ); + }); +}); + +describe('calloutRequest status fallback', () => { + beforeEach(() => { + vi.resetModules(); + }); + + it('treats a missing status code as a bad gateway', async () => { + vi.doMock('node:http', async (importOriginal) => { + const actual = await importOriginal(); + const { EventEmitter } = await import('node:events'); + return { + ...actual, + request: (_url: unknown, _options: unknown, onResponse: (r: unknown) => void) => { + const request = new EventEmitter() as any; + request.destroy = () => {}; + request.end = () => { + const response = new EventEmitter() as any; + response.headers = {}; + onResponse(response); + response.emit('end'); + }; + return request; + }, + }; + }); + + const { calloutRequest: isolated } = await import('../../../src/lib/calloutTransport.js'); + const response = await isolated('http://127.0.0.1:1/', base(), development); + + expect(response.status).toBe(502); + vi.doUnmock('node:http'); + }); + + function base() { + return { timeoutMs: 1000, maxResponseBytes: 1024 }; + } +}); diff --git a/tests/unit/models/models.spec.ts b/tests/unit/models/models.spec.ts index 409e8fc8..8d90dbc3 100644 --- a/tests/unit/models/models.spec.ts +++ b/tests/unit/models/models.spec.ts @@ -16,6 +16,8 @@ vi.unmock('../../../src/models/organizationMemberships.js'); vi.unmock('../../../src/models/organizationRoles.js'); vi.unmock('../../../src/models/permissions.js'); vi.unmock('../../../src/models/rolePermissions.js'); +vi.unmock('../../../src/models/webhookDeliveries.js'); +vi.unmock('../../../src/models/webhookEndpoints.js'); vi.unmock('../../../src/models/webauthnChallenges.js'); vi.unmock('../../../src/models/userExternalIds.js'); vi.unmock('../../../src/models/policyVersions.js'); diff --git a/tests/unit/services/sessionIssueService.spec.ts b/tests/unit/services/sessionIssueService.spec.ts index fbaf45e6..ca14ed71 100644 --- a/tests/unit/services/sessionIssueService.spec.ts +++ b/tests/unit/services/sessionIssueService.spec.ts @@ -38,6 +38,7 @@ vi.mock('../../../src/utils/utils.js', () => ({ import { getSystemConfig } from '../../../src/config/getSystemConfig.js'; import { Credential } from '../../../src/models/credentials.js'; +import { AuthEventService } from '../../../src/services/authEventService.js'; import { createRefreshTokenLookup, generateRefreshToken, @@ -129,6 +130,39 @@ describe('issueSessionAndRespond', () => { }); }); + // The one record that a sign-in completed, which the user.signed_in webhook is built from. + it('records that a session was created, with the method and organization', async () => { + const req = mockReq(); + + await issueSessionAndRespond({ user: mockUser, req, res: mockRes(), method: 'email_otp' }); + + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + userId: mockUser.id, + sessionId: 'session-1', + type: 'session_created', + metadata: { method: 'email_otp', organizationId: null }, + }), + ); + }); + + it('marks a recovery session in the record', async () => { + await issueSessionAndRespond({ + user: mockUser, + req: mockReq(), + res: mockRes(), + method: 'account_recovery', + recovery: true, + }); + + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'session_created', + metadata: expect.objectContaining({ recovery: true }), + }), + ); + }); + it('records the sign-in method and time for the provider auth context', async () => { await issueSessionAndRespond({ user: mockUser, diff --git a/tests/unit/services/webhookCatalog.spec.ts b/tests/unit/services/webhookCatalog.spec.ts new file mode 100644 index 00000000..197e9d84 --- /dev/null +++ b/tests/unit/services/webhookCatalog.spec.ts @@ -0,0 +1,196 @@ +import { WEBHOOK_EVENT_TYPES, WebhookEventSchema } from '@seamless-auth/types'; +import { describe, expect, it } from 'vitest'; + +import { AUTH_EVENT_TYPES } from '../../../src/schemas/authEvent.types.js'; +import { + type DispatchableAuthEvent, + WEBHOOK_SOURCE_TYPES, + webhookEventFor, +} from '../../../src/services/webhookCatalog.js'; + +function row(type: string, overrides: Partial = {}): DispatchableAuthEvent { + return { + seq: '10', + type, + user_id: 'user-1', + session_id: 'session-1', + metadata: null, + created_at: new Date('2026-11-07T12:00:00.000Z'), + ...overrides, + }; +} + +function parses(built: ReturnType) { + expect(built).not.toBeNull(); + return WebhookEventSchema.parse({ + id: 'delivery-1', + version: 1, + timestamp: '2026-11-07T12:00:00.000Z', + ...built, + }); +} + +describe('webhook catalog', () => { + // The catalog is a public contract. Adding an audit type must not change what receivers get + // unless this table changes with it. + it('pins which audit types become which webhook', () => { + expect(WEBHOOK_SOURCE_TYPES).toEqual({ + user_created: 'user.created', + user_deleted: 'user.deleted', + session_created: 'user.signed_in', + account_recovery_completed: 'user.recovered', + logout_success: 'session.revoked', + admin_session_revoked: 'session.revoked', + session_evicted: 'session.revoked', + oidc_session_revoked: 'session.revoked', + registration_success: 'credential.added', + totp_enrollment_success: 'credential.added', + recovery_codes_generated: 'credential.added', + credentials_deleted: 'credential.removed', + totp_disabled: 'credential.removed', + organization_member_added: 'organization.member_added', + organization_member_updated: 'organization.member_updated', + organization_member_removed: 'organization.member_removed', + }); + }); + + it('maps only audit types that exist, and reaches every catalog type', () => { + for (const source of Object.keys(WEBHOOK_SOURCE_TYPES)) { + expect(AUTH_EVENT_TYPES).toContain(source); + } + expect([...new Set(Object.values(WEBHOOK_SOURCE_TYPES))].sort()).toEqual( + [...WEBHOOK_EVENT_TYPES].sort(), + ); + }); + + it('ignores audit types outside the catalog', () => { + expect(webhookEventFor(row('login_success'), null)).toBeNull(); + expect(webhookEventFor(row('login_failed'), null)).toBeNull(); + }); + + it('builds user.created with the address the account was made with', () => { + const event = parses( + webhookEventFor(row('user_created'), { email: 'a@example.com', phone: null }), + ); + expect(event.data).toEqual({ userId: 'user-1', email: 'a@example.com', phone: null }); + }); + + it('builds user.created without an address when the user is already gone', () => { + expect(parses(webhookEventFor(row('user_created'), null)).data).toEqual({ + userId: 'user-1', + email: null, + phone: null, + }); + }); + + it.each(['user_created', 'user_deleted', 'account_recovery_completed', 'session_created'])( + 'drops %s without a user', + (type) => { + expect(webhookEventFor(row(type, { user_id: null }), null)).toBeNull(); + }, + ); + + it('builds user.deleted and user.recovered', () => { + expect(parses(webhookEventFor(row('user_deleted'), null)).type).toBe('user.deleted'); + expect(parses(webhookEventFor(row('account_recovery_completed'), null)).type).toBe( + 'user.recovered', + ); + }); + + it('builds user.signed_in from session_created, with no network detail', () => { + const event = parses( + webhookEventFor( + row('session_created', { metadata: { method: 'passkey', organizationId: 'org-1' } }), + null, + ), + ); + + expect(event.data).toEqual({ + userId: 'user-1', + sessionId: 'session-1', + method: 'passkey', + organizationId: 'org-1', + }); + }); + + it.each([ + ['logout_success', { scope: 'current_session' }, 'session-1', 'logout'], + ['logout_success', { scope: 'all_sessions' }, null, 'logout'], + // The request's own session is the administrator's, never the one revoked. + ['admin_session_revoked', { sessionId: 'target' }, 'target', 'admin'], + ['admin_session_revoked', { targetUser: 'user-1' }, null, 'admin'], + ['session_evicted', { sessionId: 'old' }, 'old', 'evicted'], + ['oidc_session_revoked', { reason: 'logout' }, 'session-1', 'provider'], + ])('builds session.revoked from %s %j', (type, metadata, sessionId, reason) => { + const event = parses(webhookEventFor(row(type, { metadata }), null)); + expect(event.data).toEqual({ userId: 'user-1', sessionId, reason }); + }); + + it.each([ + [ + 'registration_success', + { credential: 'passkey', credentialId: 'cred-1' }, + 'passkey', + 'cred-1', + ], + ['totp_enrollment_success', null, 'totp', null], + ['recovery_codes_generated', null, 'recovery_codes', null], + ])('builds credential.added from %s', (type, metadata, kind, credentialId) => { + const event = parses(webhookEventFor(row(type, { metadata }), null)); + expect(event).toMatchObject({ type: 'credential.added', data: { kind, credentialId } }); + }); + + it.each([ + ['credentials_deleted', { credential: 'passkey', credentialId: 'cred-1' }, 'passkey'], + ['totp_disabled', null, 'totp'], + ])('builds credential.removed from %s', (type, metadata, kind) => { + expect(parses(webhookEventFor(row(type, { metadata }), null))).toMatchObject({ + type: 'credential.removed', + data: { kind }, + }); + }); + + // Account registration and account deletion write the same audit types without naming a passkey. + it('drops registration_success and credentials_deleted that are not about a passkey', () => { + expect(webhookEventFor(row('registration_success', { metadata: {} }), null)).toBeNull(); + expect( + webhookEventFor( + row('credentials_deleted', { metadata: { reason: 'User deleted account' } }), + null, + ), + ).toBeNull(); + expect(webhookEventFor(row('totp_disabled', { user_id: null }), null)).toBeNull(); + }); + + it.each([ + ['organization_member_added', ['member'], ['member']], + ['organization_member_updated', ['admin', 7], ['admin']], + ['organization_member_removed', ['admin'], []], + ])('builds the organization event from %s', (type, roles, expected) => { + const event = parses( + webhookEventFor(row(type, { metadata: { organizationId: 'org-1', roles } }), null), + ); + expect(event.data).toEqual({ organizationId: 'org-1', userId: 'user-1', roles: expected }); + }); + + it('builds roles as empty when the row carries none', () => { + expect( + parses( + webhookEventFor( + row('organization_member_added', { metadata: { organizationId: 'o' } }), + null, + ), + ).data, + ).toMatchObject({ roles: [] }); + }); + + it('drops an organization event without an organization or user', () => { + expect(webhookEventFor(row('organization_member_added', { metadata: {} }), null)).toBeNull(); + expect( + webhookEventFor( + row('organization_member_added', { user_id: null, metadata: { organizationId: 'o' } }), + null, + ), + ).toBeNull(); + }); +}); diff --git a/tests/unit/services/webhookService.spec.ts b/tests/unit/services/webhookService.spec.ts new file mode 100644 index 00000000..28a43630 --- /dev/null +++ b/tests/unit/services/webhookService.spec.ts @@ -0,0 +1,772 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const { query, transaction } = vi.hoisted(() => { + const query = vi.fn(); + const transaction = vi.fn(async (fn: (t: unknown) => unknown) => fn({ id: 'tx' })); + return { query, transaction }; +}); + +vi.mock('../../../src/models/index.js', () => ({ + getSequelize: () => ({ query, transaction }), +})); + +vi.mock('../../../src/models/webhookEndpoints.js', () => ({ + WebhookEndpoint: { + findAll: vi.fn(), + findByPk: vi.fn(), + create: vi.fn(), + }, +})); + +vi.mock('../../../src/models/webhookDeliveries.js', () => ({ + WebhookDelivery: { + findAll: vi.fn(), + findByPk: vi.fn(), + create: vi.fn(), + update: vi.fn(), + destroy: vi.fn(), + }, +})); + +vi.mock('../../../src/lib/calloutTransport.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, calloutRequest: vi.fn() }; +}); + +import { CalloutError, calloutRequest } from '../../../src/lib/calloutTransport.js'; +import { encryptCalloutSecret, generateCalloutSecret } from '../../../src/lib/calloutSigning.js'; +import { User } from '../../../src/models/users.js'; +import { WebhookDelivery } from '../../../src/models/webhookDeliveries.js'; +import { WebhookEndpoint } from '../../../src/models/webhookEndpoints.js'; +import { AuthEventService } from '../../../src/services/authEventService.js'; +import { + attemptDelivery, + createEndpoint, + deleteEndpoint, + deliverDue, + dispatchWebhooks, + getDelivery, + getEndpoint, + listDeliveries, + listEndpoints, + nextAttemptAt, + pruneDeliveries, + redeliver, + rotateEndpointSecret, + runWebhookTick, + sendSigned, + sendTestEvent, + serializeDelivery, + serializeEndpoint, + signingSecrets, + startWebhookDelivery, + updateEndpoint, + WebhookError, +} from '../../../src/services/webhookService.js'; + +const at = new Date('2026-11-07T12:00:00.000Z'); +const secret = 'whsec_' + Buffer.alloc(32, 1).toString('base64'); + +function endpoint(overrides: Record = {}) { + const sealed = encryptCalloutSecret(secret); + const record: any = { + id: 'endpoint-1', + url: 'https://hooks.example.com/seamless', + description: null, + eventTypes: ['user.created'], + enabled: true, + disabledReason: null, + version: 1, + secretCiphertext: sealed.ciphertext, + secretIv: sealed.iv, + secretTag: sealed.tag, + previousSecretCiphertext: null, + previousSecretIv: null, + previousSecretTag: null, + previousSecretExpiresAt: null, + failingSince: null, + createdAt: at, + updatedAt: at, + ...overrides, + }; + record.update = vi.fn(async (changes: Record) => Object.assign(record, changes)); + record.destroy = vi.fn(); + return record; +} + +function delivery(overrides: Record = {}) { + const record: any = { + id: 'delivery-1', + endpointId: 'endpoint-1', + eventType: 'user.created', + authEventSeq: '10', + payload: '{"type":"user.created"}', + status: 'pending', + attempts: 0, + nextAttemptAt: at, + lastAttemptAt: null, + lastStatusCode: null, + lastFailure: null, + createdAt: at, + ...overrides, + }; + record.update = vi.fn(async (changes: Record) => Object.assign(record, changes)); + return record; +} + +function responds(status: number, headers: Record = {}) { + vi.mocked(calloutRequest).mockResolvedValue({ status, headers, body: Buffer.alloc(0) }); +} + +beforeEach(() => { + transaction.mockImplementation(async (fn: (t: unknown) => unknown) => fn({ id: 'tx' })); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('endpoints', () => { + it('creates an endpoint with an encrypted secret and returns the secret once', async () => { + vi.mocked(WebhookEndpoint.create).mockImplementation(async (values: any) => endpoint(values)); + + const { endpoint: created, secret: issued } = await createEndpoint( + { url: 'https://hooks.example.com/a', eventTypes: ['user.created'] }, + 'admin-1', + ); + + const stored = vi.mocked(WebhookEndpoint.create).mock.calls[0][0] as any; + expect(issued).toMatch(/^whsec_/); + expect(stored.secretCiphertext).toBeDefined(); + expect(JSON.stringify(stored)).not.toContain(issued.slice(6)); + expect(stored).toMatchObject({ enabled: true, description: null, createdBy: 'admin-1' }); + expect(created.url).toBe('https://hooks.example.com/a'); + }); + + it('keeps an explicit description and enabled flag', async () => { + vi.mocked(WebhookEndpoint.create).mockImplementation(async (values: any) => endpoint(values)); + + await createEndpoint( + { + url: 'https://hooks.example.com/a', + eventTypes: ['user.created'], + description: 'CRM', + enabled: false, + }, + null, + ); + + expect(vi.mocked(WebhookEndpoint.create).mock.calls[0][0]).toMatchObject({ + description: 'CRM', + enabled: false, + }); + }); + + it('refuses a URL no callout may reach', async () => { + await expect( + createEndpoint({ url: 'http://169.254.169.254/', eventTypes: ['user.created'] }, null), + ).rejects.toMatchObject({ status: 400 }); + expect(WebhookEndpoint.create).not.toHaveBeenCalled(); + }); + + it('refuses to store a secret in production without the encryption key', async () => { + vi.stubEnv('NODE_ENV', 'production'); + vi.stubEnv('CALLOUT_SECRET_ENCRYPTION_KEY', ''); + + await expect( + createEndpoint({ url: 'https://hooks.example.com/a', eventTypes: ['user.created'] }, null), + ).rejects.toMatchObject({ status: 409 }); + }); + + it('lists, reads and deletes', async () => { + const record = endpoint(); + vi.mocked(WebhookEndpoint.findAll).mockResolvedValue([record]); + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(record); + + expect(await listEndpoints()).toEqual([record]); + expect(await getEndpoint('endpoint-1')).toBe(record); + expect(await deleteEndpoint('endpoint-1')).toBe(record); + expect(record.destroy).toHaveBeenCalled(); + }); + + it('answers 404 for a missing endpoint', async () => { + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(null); + + await expect(getEndpoint('missing')).rejects.toBeInstanceOf(WebhookError); + }); + + it('updates fields, and turning an endpoint on clears why it was off', async () => { + const record = endpoint({ enabled: false, disabledReason: 'failing', failingSince: at }); + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(record); + + await updateEndpoint('endpoint-1', { + url: 'https://hooks.example.com/b', + description: null, + eventTypes: ['user.deleted'], + enabled: true, + }); + + expect(record).toMatchObject({ + url: 'https://hooks.example.com/b', + eventTypes: ['user.deleted'], + enabled: true, + disabledReason: null, + failingSince: null, + }); + }); + + it('records a manual disable', async () => { + const record = endpoint(); + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(record); + + await updateEndpoint('endpoint-1', { enabled: false }); + + expect(record.disabledReason).toBe('manual'); + }); + + it('refuses an update to a URL no callout may reach', async () => { + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(endpoint()); + + await expect( + updateEndpoint('endpoint-1', { url: 'https://user:pw@hooks.example.com/' }), + ).rejects.toMatchObject({ status: 400 }); + }); + + it('rotates the secret, keeping the old one signing for a day', async () => { + vi.useFakeTimers({ now: at }); + const record = endpoint(); + const oldCiphertext = record.secretCiphertext; + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(record); + + const { secret: issued, previousSecretExpiresAt } = await rotateEndpointSecret('endpoint-1'); + + expect(record.previousSecretCiphertext).toBe(oldCiphertext); + expect(previousSecretExpiresAt.toISOString()).toBe('2026-11-08T12:00:00.000Z'); + expect(signingSecrets(record)).toEqual([issued, secret]); + }); + + it('stops signing with the previous secret once its overlap ends', () => { + const sealed = encryptCalloutSecret(generateCalloutSecret()); + const record = endpoint({ + previousSecretCiphertext: sealed.ciphertext, + previousSecretIv: sealed.iv, + previousSecretTag: sealed.tag, + previousSecretExpiresAt: new Date(at.getTime() - 1), + }); + + expect(signingSecrets(record, at)).toEqual([secret]); + expect(serializeEndpoint(record).previousSecretExpiresAt).toBeNull(); + }); + + it('serializes an endpoint mid-rotation', () => { + const future = new Date(Date.now() + 60_000); + expect(serializeEndpoint(endpoint({ previousSecretExpiresAt: future }))).toMatchObject({ + previousSecretExpiresAt: future.toISOString(), + version: 1, + }); + }); +}); + +describe('sendSigned', () => { + it('signs the request and treats a 2xx as delivered', async () => { + responds(204); + + const attempt = await sendSigned('https://hooks.example.com/', 'id-1', '{}', [secret]); + + const [, request] = vi.mocked(calloutRequest).mock.calls[0]; + expect(request.headers?.['webhook-id']).toBe('id-1'); + expect(request.headers?.['webhook-signature']).toMatch(/^v1,/); + expect(attempt).toMatchObject({ ok: true, statusCode: 204, failure: null }); + }); + + it.each([ + [301, 'a redirect, which is not followed'], + [500, 'a server error'], + ])('treats %s as a failure (%s)', async (status) => { + responds(status); + + expect(await sendSigned('https://hooks.example.com/', 'id', '{}', [secret])).toMatchObject({ + ok: false, + statusCode: status, + failure: 'http_status', + }); + }); + + it.each([ + ['120', 120], + ['Sat, 07 Nov 2026 12:10:00 GMT', 600], + ['soon', null], + ])('reads Retry-After %j', async (header, seconds) => { + vi.useFakeTimers({ now: at }); + responds(429, { 'retry-after': header }); + + const attempt = await sendSigned('https://hooks.example.com/', 'id', '{}', [secret]); + + expect(attempt.retryAfterSeconds).toBe(seconds); + }); + + it('reads the first of repeated Retry-After headers', async () => { + vi.mocked(calloutRequest).mockResolvedValue({ + status: 503, + headers: { 'retry-after': ['30', '60'] }, + body: Buffer.alloc(0), + }); + + expect( + (await sendSigned('https://hooks.example.com/', 'id', '{}', [secret])).retryAfterSeconds, + ).toBe(30); + }); + + it('reports a transport failure by its coarse reason', async () => { + vi.mocked(calloutRequest).mockRejectedValue(new CalloutError('refused', 'internal detail')); + + expect(await sendSigned('https://hooks.example.com/', 'id', '{}', [secret])).toMatchObject({ + ok: false, + failure: 'refused', + statusCode: null, + }); + }); + + it('reports an unexpected error as a failed connection', async () => { + vi.mocked(calloutRequest).mockRejectedValue(new Error('boom')); + + expect((await sendSigned('https://hooks.example.com/', 'id', '{}', [secret])).failure).toBe( + 'connection_failed', + ); + }); +}); + +describe('nextAttemptAt', () => { + beforeEach(() => { + vi.spyOn(Math, 'random').mockReturnValue(0); + }); + + it('follows the schedule, then stops', () => { + expect(nextAttemptAt(1, at, null)?.toISOString()).toBe('2026-11-07T12:00:05.000Z'); + expect(nextAttemptAt(7, at, null)?.toISOString()).toBe('2026-11-08T12:00:00.000Z'); + expect(nextAttemptAt(8, at, null)).toBeNull(); + }); + + it('honors a longer Retry-After, up to the longest step', () => { + expect(nextAttemptAt(1, at, 600)?.toISOString()).toBe('2026-11-07T12:10:00.000Z'); + expect(nextAttemptAt(1, at, 10 * 86400)?.toISOString()).toBe('2026-11-08T12:00:00.000Z'); + expect(nextAttemptAt(3, at, 1)?.toISOString()).toBe('2026-11-07T12:30:00.000Z'); + }); +}); + +describe('attemptDelivery', () => { + beforeEach(() => { + vi.spyOn(Math, 'random').mockReturnValue(0); + vi.useFakeTimers({ now: at }); + }); + + it('marks a delivered event and clears a failing streak', async () => { + responds(200); + const record = delivery(); + const target = endpoint({ failingSince: new Date(at.getTime() - 1000) }); + + await attemptDelivery(record, target); + + expect(record).toMatchObject({ status: 'succeeded', attempts: 1, nextAttemptAt: null }); + expect(target.failingSince).toBeNull(); + }); + + it('leaves a healthy endpoint alone on success', async () => { + responds(200); + const target = endpoint(); + + await attemptDelivery(delivery(), target); + + expect(target.update).not.toHaveBeenCalled(); + }); + + it('schedules a retry and starts the failing streak', async () => { + responds(500); + const record = delivery(); + const target = endpoint(); + + await attemptDelivery(record, target); + + expect(record).toMatchObject({ + status: 'failed', + attempts: 1, + lastStatusCode: 500, + lastFailure: 'http_status', + }); + expect(record.nextAttemptAt.toISOString()).toBe('2026-11-07T12:00:05.000Z'); + expect(target.failingSince).toEqual(at); + }); + + it('dead-letters a delivery after the last scheduled attempt', async () => { + responds(500); + const record = delivery({ attempts: 7 }); + + await attemptDelivery(record, endpoint({ failingSince: at })); + + expect(record).toMatchObject({ status: 'dead', attempts: 8, nextAttemptAt: null }); + }); + + it('disables an endpoint that answers 410, and audits it', async () => { + responds(410); + const target = endpoint(); + + await attemptDelivery(delivery(), target); + + expect(target).toMatchObject({ enabled: false, disabledReason: 'gone' }); + expect(AuthEventService.logContext).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'webhook_endpoint_disabled', + metadata: { endpointId: 'endpoint-1', reason: 'gone' }, + }), + ); + }); + + it('disables an endpoint whose deliveries have all failed for three days', async () => { + responds(503); + const target = endpoint({ failingSince: new Date(at.getTime() - 3 * 86400 * 1000) }); + + await attemptDelivery(delivery(), target); + + expect(target).toMatchObject({ enabled: false, disabledReason: 'failing' }); + }); + + it('keeps the start of a failing streak', async () => { + responds(503); + const since = new Date(at.getTime() - 3600 * 1000); + const target = endpoint({ failingSince: since }); + + await attemptDelivery(delivery(), target); + + expect(target.failingSince).toBe(since); + expect(target.update).not.toHaveBeenCalled(); + }); + + it('does not disable an endpoint twice', async () => { + responds(410); + const target = endpoint({ enabled: false, disabledReason: 'manual' }); + + await attemptDelivery(delivery(), target); + + expect(target.disabledReason).toBe('manual'); + expect(AuthEventService.logContext).not.toHaveBeenCalled(); + }); +}); + +describe('test events and redelivery', () => { + it('sends webhook.test once and logs it, without touching the endpoint', async () => { + responds(500); + const target = endpoint(); + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(target); + vi.mocked(WebhookDelivery.create).mockImplementation(async (values: any) => delivery(values)); + + const result = await sendTestEvent('endpoint-1'); + + const created = vi.mocked(WebhookDelivery.create).mock.calls[0][0] as any; + expect(JSON.parse(created.payload)).toMatchObject({ + type: 'webhook.test', + version: 1, + data: { endpointId: 'endpoint-1' }, + }); + expect(result).toMatchObject({ ok: false, failure: 'http_status', statusCode: 500 }); + expect(target.update).not.toHaveBeenCalled(); + }); + + it('reports a passing test', async () => { + responds(200); + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(endpoint()); + const record = delivery({ eventType: 'webhook.test' }); + vi.mocked(WebhookDelivery.create).mockResolvedValue(record); + + expect((await sendTestEvent('endpoint-1')).ok).toBe(true); + expect(record.status).toBe('succeeded'); + }); + + it('redelivers with the same id and body', async () => { + responds(200); + const record = delivery({ status: 'dead', attempts: 8 }); + vi.mocked(WebhookDelivery.findByPk).mockResolvedValue(record); + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(endpoint()); + + await redeliver('delivery-1'); + + const [, request] = vi.mocked(calloutRequest).mock.calls[0]; + expect(request.headers?.['webhook-id']).toBe('delivery-1'); + expect(request.body).toBe(record.payload); + expect(record.status).toBe('succeeded'); + }); + + it('answers 404 for a missing delivery', async () => { + vi.mocked(WebhookDelivery.findByPk).mockResolvedValue(null); + + await expect(getDelivery('missing')).rejects.toMatchObject({ status: 404 }); + }); +}); + +describe('listDeliveries', () => { + it('pages newest first with an opaque cursor', async () => { + const rows = [ + delivery({ id: 'c', createdAt: new Date(at.getTime() + 2) }), + delivery({ id: 'b', createdAt: new Date(at.getTime() + 1) }), + delivery({ id: 'a', createdAt: at }), + ]; + vi.mocked(WebhookDelivery.findAll).mockResolvedValue(rows); + + const page = await listDeliveries({ + limit: 2, + endpointId: '11111111-1111-4111-8111-111111111111', + status: 'dead', + eventType: 'user.created', + }); + + expect(page.deliveries.map((d: any) => d.id)).toEqual(['c', 'b']); + expect(page.nextCursor).not.toBeNull(); + + vi.mocked(WebhookDelivery.findAll).mockResolvedValue([rows[2]]); + const next = await listDeliveries({ limit: 2, cursor: page.nextCursor! }); + + expect(next).toMatchObject({ nextCursor: null }); + expect(vi.mocked(WebhookDelivery.findAll).mock.calls[1][0]).toMatchObject({ limit: 3 }); + }); + + it('lists with no filters', async () => { + vi.mocked(WebhookDelivery.findAll).mockResolvedValue([]); + + expect(await listDeliveries({ limit: 50 })).toEqual({ deliveries: [], nextCursor: null }); + }); + + it('refuses a cursor it did not issue', async () => { + await expect(listDeliveries({ limit: 10, cursor: 'garbage' })).rejects.toMatchObject({ + status: 400, + }); + }); + + it('serializes a delivery', () => { + expect(serializeDelivery(delivery({ nextAttemptAt: null }))).toEqual({ + id: 'delivery-1', + endpointId: 'endpoint-1', + eventType: 'user.created', + status: 'pending', + attempts: 0, + nextAttemptAt: null, + lastAttemptAt: null, + lastStatusCode: null, + lastFailure: null, + createdAt: at.toISOString(), + }); + }); +}); + +describe('dispatchWebhooks', () => { + function queries(...answers: unknown[]) { + for (const answer of answers) query.mockResolvedValueOnce(answer); + } + + it('does nothing while another replica holds the lock', async () => { + queries([{ locked: false }]); + + expect(await dispatchWebhooks()).toBe(0); + expect(query).toHaveBeenCalledTimes(1); + }); + + it('starts the cursor at the newest row instead of replaying history', async () => { + queries([{ locked: true }], [], [{ head: '42' }], undefined); + + expect(await dispatchWebhooks()).toBe(0); + expect(query.mock.calls[3][0]).toContain('INSERT INTO public.event_dispatch_cursors'); + expect(query.mock.calls[3][1].replacements).toMatchObject({ head: '42' }); + }); + + it('returns at once when no row is past the cursor', async () => { + queries([{ locked: true }], [{ lastSeq: '42' }], []); + + expect(await dispatchWebhooks()).toBe(0); + expect(WebhookEndpoint.findAll).not.toHaveBeenCalled(); + }); + + it('queues one delivery per subscribed endpoint and advances the cursor', async () => { + const created = new Date('2026-11-07T11:59:00.000Z'); + queries( + [{ locked: true }], + [{ lastSeq: '9' }], + [ + { + seq: '10', + type: 'user_created', + user_id: 'user-1', + session_id: null, + metadata: null, + created_at: created, + }, + // Nobody subscribes to sign-ins here. + { + seq: '11', + type: 'session_created', + user_id: 'user-1', + session_id: 's', + metadata: { method: 'passkey' }, + created_at: created, + }, + // Subscribed, but this row is about an account rather than a passkey. + { + seq: '12', + type: 'registration_success', + user_id: 'user-1', + session_id: null, + metadata: {}, + created_at: created, + }, + ], + ); + query.mockResolvedValue(undefined); + vi.mocked(WebhookEndpoint.findAll).mockResolvedValue([ + endpoint({ id: 'a', eventTypes: ['user.created', 'credential.added'] }), + endpoint({ id: 'b', eventTypes: ['user.created'] }), + ]); + vi.mocked(User.findByPk).mockResolvedValue({ email: 'a@example.com', phone: null } as any); + + expect(await dispatchWebhooks()).toBe(3); + + const inserts = query.mock.calls.filter(([sql]) => + sql.includes('INSERT INTO public.webhook_deliveries'), + ); + expect(inserts).toHaveLength(2); + expect(inserts.map(([, options]) => options.replacements.endpointId)).toEqual(['a', 'b']); + const payload = JSON.parse(inserts[0][1].replacements.payload); + expect(payload).toEqual({ + id: inserts[0][1].replacements.id, + type: 'user.created', + version: 1, + timestamp: created.toISOString(), + data: { userId: 'user-1', email: 'a@example.com', phone: null }, + }); + expect(inserts[0][0]).toContain('ON CONFLICT ("endpointId", "authEventSeq") DO NOTHING'); + + const advance = query.mock.calls.at(-1)!; + expect(advance[0]).toContain('UPDATE public.event_dispatch_cursors'); + expect(advance[1].replacements).toMatchObject({ seq: '12' }); + }); + + it('builds user.created without an address once the user is gone', async () => { + queries( + [{ locked: true }], + [{ lastSeq: '9' }], + [ + { + seq: '10', + type: 'user_created', + user_id: 'u', + session_id: null, + metadata: null, + created_at: at, + }, + ], + ); + query.mockResolvedValue(undefined); + vi.mocked(WebhookEndpoint.findAll).mockResolvedValue([endpoint()]); + vi.mocked(User.findByPk).mockResolvedValue(null); + + await dispatchWebhooks(); + + const insert = query.mock.calls.find(([sql]) => sql.includes('webhook_deliveries'))!; + expect(JSON.parse(insert[1].replacements.payload).data.email).toBeNull(); + }); + + it('reads no user for an event that does not carry an address', async () => { + queries( + [{ locked: true }], + [{ lastSeq: '9' }], + [ + { + seq: '10', + type: 'user_deleted', + user_id: 'u', + session_id: null, + metadata: null, + created_at: at, + }, + ], + ); + query.mockResolvedValue(undefined); + vi.mocked(WebhookEndpoint.findAll).mockResolvedValue([ + endpoint({ eventTypes: ['user.deleted'] }), + ]); + + await dispatchWebhooks(); + + expect(User.findByPk).not.toHaveBeenCalled(); + }); +}); + +describe('deliverDue', () => { + it('returns at once when nothing is due', async () => { + query.mockResolvedValueOnce([]); + + expect(await deliverDue()).toBe(0); + expect(WebhookDelivery.update).not.toHaveBeenCalled(); + }); + + it('leases the claimed rows, then sends each to its endpoint', async () => { + responds(200); + query.mockResolvedValueOnce([{ id: 'd1' }, { id: 'd2' }]); + const first = delivery({ id: 'd1' }); + const second = delivery({ id: 'd2', endpointId: 'gone' }); + vi.mocked(WebhookDelivery.findAll).mockResolvedValue([first, second]); + vi.mocked(WebhookEndpoint.findAll).mockResolvedValue([endpoint()]); + + expect(await deliverDue()).toBe(2); + + expect(query.mock.calls[0][0]).toContain('FOR UPDATE SKIP LOCKED'); + expect(vi.mocked(WebhookDelivery.update).mock.calls[0][0]).toHaveProperty('nextAttemptAt'); + expect(first.status).toBe('succeeded'); + // Its endpoint was deleted or disabled after it was queued: held, not sent. + expect(second.nextAttemptAt).toBeNull(); + expect(calloutRequest).toHaveBeenCalledTimes(1); + }); +}); + +describe('the delivery loop', () => { + it('prunes deliveries older than 30 days', async () => { + vi.mocked(WebhookDelivery.destroy).mockResolvedValue(3 as never); + + expect(await pruneDeliveries(at)).toBe(3); + const where = vi.mocked(WebhookDelivery.destroy).mock.calls[0][0] as any; + const [op] = Object.getOwnPropertySymbols(where.where.createdAt); + const cutoff = where.where.createdAt[op] as Date; + expect(cutoff.toISOString()).toBe('2026-10-08T12:00:00.000Z'); + }); + + it('runs dispatch and delivery until each comes back short, and prunes on the hour', async () => { + query.mockImplementation(async (sql: string) => + sql.includes('pg_try_advisory_xact_lock') ? [{ locked: false }] : [], + ); + vi.mocked(WebhookDelivery.destroy).mockResolvedValue(0 as never); + + await runWebhookTick(0); + expect(WebhookDelivery.destroy).toHaveBeenCalledTimes(1); + + await runWebhookTick(1); + expect(WebhookDelivery.destroy).toHaveBeenCalledTimes(1); + }); + + it('keeps going after a failed tick', async () => { + transaction.mockRejectedValue(new Error('database down')); + + await expect(runWebhookTick(1)).resolves.toBeUndefined(); + }); + + it('polls once a second and skips a tick while one is running', async () => { + vi.useFakeTimers(); + let release: () => void = () => {}; + transaction.mockImplementation( + () => new Promise((resolve) => (release = () => resolve(0))) as never, + ); + + const timer = startWebhookDelivery(); + await vi.advanceTimersByTimeAsync(1000); + await vi.advanceTimersByTimeAsync(1000); + expect(transaction).toHaveBeenCalledTimes(1); + + release(); + clearInterval(timer); + }); +}); From 1866332087c37a2523fc6226cc005eaff1a623f9 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Sat, 7 Nov 2026 19:37:16 -0500 Subject: [PATCH 3/9] fix(deps): use @seamless-auth/types 0.39.0 --- package-lock.json | 8 ++++---- package.json | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package-lock.json b/package-lock.json index 7004eecb..ee7068da 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,7 +13,7 @@ "@seamless-auth/messaging": "^0.3.1", "@seamless-auth/messaging-aws": "^0.3.1", "@seamless-auth/messaging-twilio": "^0.3.1", - "@seamless-auth/types": "^0.38.0", + "@seamless-auth/types": "^0.39.0", "@simplewebauthn/server": "^14.0.3", "base64url": "^3.0.1", "bcrypt-ts": "^9.0.2", @@ -2927,9 +2927,9 @@ } }, "node_modules/@seamless-auth/types": { - "version": "0.38.0", - "resolved": "https://registry.npmjs.org/@seamless-auth/types/-/types-0.38.0.tgz", - "integrity": "sha512-qALF5GFQEv+9yucQdn179cpTdEMMH/PjtZWAHatWk1qUEOzb1ElOqoBZgC4/THAk6u4aLgDyuDt/dCD/BzloqA==", + "version": "0.39.0", + "resolved": "https://registry.npmjs.org/@seamless-auth/types/-/types-0.39.0.tgz", + "integrity": "sha512-xoJLkpgkisvVvSh3aBxByC5GfWm6LaIulusf+6A2ghok/l5FP6r2V8lwLEqbXO6dy/g01RNWxfTupjWAp42b0A==", "license": "Apache-2.0", "dependencies": { "zod": "^4.5.0" diff --git a/package.json b/package.json index 855c3341..c552a569 100644 --- a/package.json +++ b/package.json @@ -52,7 +52,7 @@ "@seamless-auth/messaging": "^0.3.1", "@seamless-auth/messaging-aws": "^0.3.1", "@seamless-auth/messaging-twilio": "^0.3.1", - "@seamless-auth/types": "^0.38.0", + "@seamless-auth/types": "^0.39.0", "@simplewebauthn/server": "^14.0.3", "base64url": "^3.0.1", "bcrypt-ts": "^9.0.2", From f16097668e15f5fbae7a01c3d9df9686d6087818 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Sat, 7 Nov 2026 19:37:30 -0500 Subject: [PATCH 4/9] feat(audit): stream audit events to OTLP and syslog sinks Adds audit sinks behind an audited admin API under /admin/audit-sinks, with step-up on every write. A sink streams committed audit rows past its own cursor to an OTLP/HTTP JSON collector at /v1/logs, or to a syslog collector as RFC 5424 over TLS with octet counting. Plain TCP is refused in production. Every record carries the event's seamless-auth-events/1 export line, so the hash chain verifies downstream as an export does. The cursor moves only when the collector takes the whole batch, and a failing sink retries with backoff capped at a minute, with no dead letter. Status reports the lag behind the chain head. A test record is sent outside the chain and moves nothing. Destinations follow the callout reachability rules when written and at connect time, including the guarded DNS lookup for syslog sockets. Credentials are named as _AUDIT_SINK_SECRET env vars and read at send time; a missing one fails the send rather than sending it empty. Retention now stops at the oldest sink cursor, so a sink that falls behind never loses an event to the archive. Closes #420. --- .changeset/audit-sinks.md | 12 + adapter-manifest.json | 6 + docs/adr/0005-extensibility-callouts.md | 1 + docs/configuration.md | 39 +- openapi.json | 1622 ++++++++++++++++- src/controllers/auditSinks.ts | 132 ++ src/generated/api.ts | 1278 +++++++++++++ src/lib/auditSinkTransport.ts | 362 ++++ .../20261107140000-add-audit-sinks.cjs | 45 + src/models/auditSinks.ts | 93 + src/routes/auditSinks.routes.ts | 130 ++ src/schemas/auditSink.schemas.ts | 14 + src/schemas/authEvent.types.ts | 3 + src/server.ts | 2 + src/services/auditExport.ts | 7 +- src/services/auditRetention.ts | 28 +- src/services/auditSinkService.ts | 284 +++ tests/fixtures/auditSinkTls/ca.pem | 10 + tests/fixtures/auditSinkTls/client.key | 5 + tests/fixtures/auditSinkTls/client.pem | 10 + tests/fixtures/auditSinkTls/server.key | 5 + tests/fixtures/auditSinkTls/server.pem | 10 + tests/integration/admin/adminStepUp.spec.ts | 4 + tests/integration/admin/auditSinks.spec.ts | 215 +++ tests/postgres/auditSinks.spec.ts | 271 +++ tests/setup/mocks.ts | 8 + tests/unit/lib/auditSinkTransport.spec.ts | 569 ++++++ tests/unit/models/models.spec.ts | 1 + tests/unit/services/auditRetention.spec.ts | 38 + tests/unit/services/auditSinkService.spec.ts | 441 +++++ 30 files changed, 5627 insertions(+), 18 deletions(-) create mode 100644 .changeset/audit-sinks.md create mode 100644 src/controllers/auditSinks.ts create mode 100644 src/lib/auditSinkTransport.ts create mode 100644 src/migrations/20261107140000-add-audit-sinks.cjs create mode 100644 src/models/auditSinks.ts create mode 100644 src/routes/auditSinks.routes.ts create mode 100644 src/schemas/auditSink.schemas.ts create mode 100644 src/services/auditSinkService.ts create mode 100644 tests/fixtures/auditSinkTls/ca.pem create mode 100644 tests/fixtures/auditSinkTls/client.key create mode 100644 tests/fixtures/auditSinkTls/client.pem create mode 100644 tests/fixtures/auditSinkTls/server.key create mode 100644 tests/fixtures/auditSinkTls/server.pem create mode 100644 tests/integration/admin/auditSinks.spec.ts create mode 100644 tests/postgres/auditSinks.spec.ts create mode 100644 tests/unit/lib/auditSinkTransport.spec.ts create mode 100644 tests/unit/services/auditSinkService.spec.ts diff --git a/.changeset/audit-sinks.md b/.changeset/audit-sinks.md new file mode 100644 index 00000000..693d5682 --- /dev/null +++ b/.changeset/audit-sinks.md @@ -0,0 +1,12 @@ +--- +'seamless-auth-api': minor +--- + +Stream audit events to a SIEM (ADR 0005, #420). + +- Admin API under `/admin/audit-sinks`: create, update, disable and delete sinks, and send a test record. Every write takes step-up and is audited as `admin_audit_sink_created`, `admin_audit_sink_updated` or `admin_audit_sink_deleted`. +- OTLP/HTTP with JSON encoding to `/v1/logs`, and syslog (RFC 5424) over TLS with octet counting. Plain TCP syslog is refused in production. +- Every record carries the event's `seamless-auth-events/1` export line, so the hash chain verifies downstream as an export does. +- Each sink has its own cursor and retries until its collector takes the events, backing off to one minute. There is no dead letter: a sink reports how far behind the chain head it is. +- Credentials are never stored. A sink names env vars ending `_AUDIT_SINK_SECRET`, read at send time. +- Audit retention no longer deletes events a sink has yet to deliver. diff --git a/adapter-manifest.json b/adapter-manifest.json index 923aa4d6..2ece2de1 100644 --- a/adapter-manifest.json +++ b/adapter-manifest.json @@ -29,6 +29,12 @@ { "method": "GET", "path": "/admin/applications/{id}/resources", "credential": "access" }, { "method": "PUT", "path": "/admin/applications/{id}/resources", "credential": "access" }, { "method": "POST", "path": "/admin/applications/{id}/secret", "credential": "access" }, + { "method": "GET", "path": "/admin/audit-sinks", "credential": "access" }, + { "method": "POST", "path": "/admin/audit-sinks", "credential": "access" }, + { "method": "DELETE", "path": "/admin/audit-sinks/{id}", "credential": "access" }, + { "method": "GET", "path": "/admin/audit-sinks/{id}", "credential": "access" }, + { "method": "PATCH", "path": "/admin/audit-sinks/{id}", "credential": "access" }, + { "method": "POST", "path": "/admin/audit-sinks/{id}/test", "credential": "access" }, { "method": "GET", "path": "/admin/auth-events", "credential": "access" }, { "method": "GET", "path": "/admin/auth-events/export", "credential": "access" }, { "method": "GET", "path": "/admin/auth-events/integrity", "credential": "access" }, diff --git a/docs/adr/0005-extensibility-callouts.md b/docs/adr/0005-extensibility-callouts.md index 11718d7d..84aaa64e 100644 --- a/docs/adr/0005-extensibility-callouts.md +++ b/docs/adr/0005-extensibility-callouts.md @@ -112,6 +112,7 @@ They must be read back to sign, so they cannot be hashed. They are AES-256-GCM e - `login_success` is written when `/login` resolves which methods an identifier may use, before any factor is proven, so it cannot be the source of `user.signed_in`. No event recorded that a session was created. `issueSessionAndRespond` now writes `session_created`, with the method and organization. - Deleting a passkey (`DELETE /users/credentials`) wrote no audit event. It now writes `credentials_deleted` naming the passkey. Reproducing test first. - Passkey registration and account registration both write `registration_success`. The passkey path now names the credential in metadata, which is how the catalog tells them apart. +- Audit retention deleted by age alone, so a sink that fell behind for longer than the retention period would have lost events it never sent. Retention now stops at the oldest sink cursor, and a sink cannot be created to replay from before the oldest event still held. - `organization_member_updated` recorded only what was added and removed. It now records the roles after the change too, which the webhook carries. ## Consequences diff --git a/docs/configuration.md b/docs/configuration.md index 0f81d507..85b96ee8 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -112,19 +112,36 @@ then daily, and each run also logs the audit chain head as an external anchor. S | `AUDIT_ARCHIVE_DIR` | With retention | - | Where expired events are written before they are deleted, as `auth-events--.ndjson` with a `.sha256` file beside each. Use durable storage, such as a mounted volume, since a file here is the only copy once its rows are gone. | | `AUDIT_RETENTION_DATABASE_URL` | No | `DATABASE_URL` | A connection for the retention job alone, so it can run as a role that holds DELETE on `auth_events` while the application role does not. | +Retention never deletes an event an [audit sink](#siem-streaming) has yet to deliver, so a sink +that has fallen behind, or is turned off, holds retention back until it catches up or is +deleted. Retention logs a warning while it is held. + +### SIEM streaming + +Audit sinks under `/admin/audit-sinks` stream every audit event to a collector, over OTLP/HTTP +(JSON, to `/v1/logs`) or syslog (RFC 5424 over TLS, octet counted). Each record carries +the event's `seamless-auth-events/1` export line, so the hash chain verifies downstream as an +export does. A sink retries until its collector takes the events, backing off to one minute, and +reports how far behind the chain head it is. Destinations follow the same rules as webhooks, +including `CALLOUT_PRIVATE_HOSTS`, and plain TCP syslog is refused in production. + +| Variable | Required | Default | Notes | +| -------------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `_AUDIT_SINK_SECRET` | No | - | Credentials a sink names rather than stores: an OTLP header value (`headersFromEnv`), or a PEM CA, client certificate or client key for syslog TLS. Names must end in `_AUDIT_SINK_SECRET`. Read at send time; a sink whose variable is unset fails with `refused` and sends nothing. | + ### Service tokens and secrets -| Variable | Required | Default | Notes | -| ------------------------------- | ------------------------------------ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `SEAMLESS_SERVICE_TOKEN` | Yes | - | Trusted server-adapter and internal bearer secret. No other secret falls back to it. | -| `API_SERVICE_TOKEN` | No | - | Supported fallback name for `SEAMLESS_SERVICE_TOKEN`. Used only when `SEAMLESS_SERVICE_TOKEN` is unset, with an info notice at boot. Setting both to different values stops the server at boot. | -| `REFRESH_TOKEN_LOOKUP_SECRET` | Production | development-only value | HMAC key for indexed refresh-token lookup fingerprints. Always required in production. | -| `TOTP_SECRET_ENCRYPTION_KEY` | Production, once TOTP is used | development-only value | Encrypts stored TOTP secrets (hashed with SHA-256 to derive the key, so any high-entropy value works). Production refuses to start while any TOTP credential exists without it, and `POST /totp/enroll/start` answers `409 secret_required` until it is set. | -| `OAUTH_STATE_SECRET` | Production, once OAuth is configured | development-only value | Signs OAuth state. Production refuses to start with a provider configured and no value, and adding a provider answers `409 secret_required` until it is set. | -| `DECOY_SUBJECT_SECRET` | Production | development-only value | HMAC key the decoy pre-auth subjects on `POST /login` derive from. Always required in production. Rotating it re-maps which subject an unknown identifier gets, which is harmless: decoys are stateless and pre-auth tokens live five minutes. | -| `OAUTH_PROVIDER_PRIVATE_HOSTS` | No | - | Comma-separated OAuth provider hosts allowed to resolve to private or loopback addresses in production, for an on-premises IdP. Other provider hosts must resolve to public addresses. Link-local is always refused. | -| `CALLOUT_SECRET_ENCRYPTION_KEY` | Production, once a webhook exists | development-only value | Encrypts stored webhook signing secrets (hashed with SHA-256 to derive the key). Production refuses to start while any webhook exists without it, and creating one answers `409` until it is set. | -| `CALLOUT_PRIVATE_HOSTS` | No | - | Comma-separated webhook hosts allowed to resolve to private or loopback addresses in production, for a receiver inside your own network. Separate from `OAUTH_PROVIDER_PRIVATE_HOSTS`. Link-local, multicast and the unspecified address are always refused, and a webhook can never point at the API's own issuer host. | +| Variable | Required | Default | Notes | +| ------------------------------- | ------------------------------------ | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `SEAMLESS_SERVICE_TOKEN` | Yes | - | Trusted server-adapter and internal bearer secret. No other secret falls back to it. | +| `API_SERVICE_TOKEN` | No | - | Supported fallback name for `SEAMLESS_SERVICE_TOKEN`. Used only when `SEAMLESS_SERVICE_TOKEN` is unset, with an info notice at boot. Setting both to different values stops the server at boot. | +| `REFRESH_TOKEN_LOOKUP_SECRET` | Production | development-only value | HMAC key for indexed refresh-token lookup fingerprints. Always required in production. | +| `TOTP_SECRET_ENCRYPTION_KEY` | Production, once TOTP is used | development-only value | Encrypts stored TOTP secrets (hashed with SHA-256 to derive the key, so any high-entropy value works). Production refuses to start while any TOTP credential exists without it, and `POST /totp/enroll/start` answers `409 secret_required` until it is set. | +| `OAUTH_STATE_SECRET` | Production, once OAuth is configured | development-only value | Signs OAuth state. Production refuses to start with a provider configured and no value, and adding a provider answers `409 secret_required` until it is set. | +| `DECOY_SUBJECT_SECRET` | Production | development-only value | HMAC key the decoy pre-auth subjects on `POST /login` derive from. Always required in production. Rotating it re-maps which subject an unknown identifier gets, which is harmless: decoys are stateless and pre-auth tokens live five minutes. | +| `OAUTH_PROVIDER_PRIVATE_HOSTS` | No | - | Comma-separated OAuth provider hosts allowed to resolve to private or loopback addresses in production, for an on-premises IdP. Other provider hosts must resolve to public addresses. Link-local is always refused. | +| `CALLOUT_SECRET_ENCRYPTION_KEY` | Production, once a webhook exists | development-only value | Encrypts stored webhook signing secrets (hashed with SHA-256 to derive the key). Production refuses to start while any webhook exists without it, and creating one answers `409` until it is set. | +| `CALLOUT_PRIVATE_HOSTS` | No | - | Comma-separated webhook and audit sink hosts allowed to resolve to private or loopback addresses in production, for a receiver inside your own network. Separate from `OAUTH_PROVIDER_PRIVATE_HOSTS`. Link-local, multicast and the unspecified address are always refused, and a callout can never point at the API's own issuer host. | > None of these falls back to the service token. Development (any `NODE_ENV` other than > `production`) uses a fixed development-only value for each unset one, with a warning. See diff --git a/openapi.json b/openapi.json index 7bf24b7b..3468013c 100644 --- a/openapi.json +++ b/openapi.json @@ -7300,7 +7300,10 @@ "admin_webhook_secret_rotated", "admin_webhook_updated", "session_created", - "webhook_endpoint_disabled" + "webhook_endpoint_disabled", + "admin_audit_sink_created", + "admin_audit_sink_updated", + "admin_audit_sink_deleted" ] }, { "type": "string" }, @@ -7446,7 +7449,10 @@ "admin_webhook_secret_rotated", "admin_webhook_updated", "session_created", - "webhook_endpoint_disabled" + "webhook_endpoint_disabled", + "admin_audit_sink_created", + "admin_audit_sink_updated", + "admin_audit_sink_deleted" ] }, { "type": "string" } @@ -10149,6 +10155,1618 @@ } } }, + "/admin/audit-sinks": { + "get": { + "summary": "List audit sinks", + "description": "Each with its cursor and how many events it is behind the chain head.", + "tags": ["Admin", "Audit sinks"], + "security": [{ "bearerAuth": [] }], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { "sinks": [null] }, + "schema": { + "type": "object", + "properties": { + "sinks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { "type": "string" }, + "name": { "type": "string" }, + "enabled": { "type": "boolean" }, + "settings": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["otlp"] }, + "endpoint": { "type": "string", "maxLength": 2048 }, + "headersFromEnv": { + "type": "object", + "additionalProperties": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "default": {} + }, + "serviceName": { + "type": "string", + "minLength": 1, + "maxLength": 100, + "default": "seamless-auth" + } + }, + "required": ["kind", "endpoint"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["syslog"] }, + "host": { "type": "string", "minLength": 1, "maxLength": 253 }, + "port": { + "type": "integer", + "minimum": 1, + "maximum": 65535, + "default": 6514 + }, + "transport": { + "type": "string", + "enum": ["tls", "tcp"], + "default": "tls" + }, + "appName": { + "type": "string", + "pattern": "^[!-~]{1,48}$", + "default": "seamless-auth" + }, + "facility": { + "type": "integer", + "minimum": 0, + "maximum": 23, + "default": 10 + }, + "tlsCaEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "tlsClientCertEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "tlsClientKeyEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + } + }, + "required": ["kind", "host"] + } + ] + }, + "status": { + "type": "object", + "properties": { + "cursorSeq": { "type": "integer", "nullable": true }, + "lagEvents": { "type": "integer", "nullable": true, "minimum": 0 }, + "lastDeliveredAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "lastFailure": { + "type": "string", + "nullable": true, + "enum": [ + "refused", + "timed_out", + "connection_failed", + "http_status", + "invalid_response", + "too_large", + null + ] + }, + "lastFailureAt": { + "type": "string", + "nullable": true, + "format": "date-time" + } + }, + "required": [ + "cursorSeq", + "lagEvents", + "lastDeliveredAt", + "lastFailure", + "lastFailureAt" + ] + }, + "createdAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "updatedAt": { "type": "string", "nullable": true, "format": "date-time" } + }, + "required": [ + "id", + "name", + "enabled", + "settings", + "status", + "createdAt", + "updatedAt" + ] + } + } + }, + "required": ["sinks"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + }, + "post": { + "summary": "Create an audit sink", + "description": "Starts after the newest event unless `startAfterSeq` replays from an earlier one. Credentials are named as `_AUDIT_SINK_SECRET` env vars, never stored.", + "tags": ["Admin", "Audit sinks"], + "security": [{ "bearerAuth": [] }], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { "type": "string", "minLength": 1, "maxLength": 100 }, + "settings": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["otlp"] }, + "endpoint": { "type": "string", "maxLength": 2048 }, + "headersFromEnv": { + "type": "object", + "additionalProperties": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "default": {} + }, + "serviceName": { + "type": "string", + "minLength": 1, + "maxLength": 100, + "default": "seamless-auth" + } + }, + "required": ["kind", "endpoint"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["syslog"] }, + "host": { "type": "string", "minLength": 1, "maxLength": 253 }, + "port": { + "type": "integer", + "minimum": 1, + "maximum": 65535, + "default": 6514 + }, + "transport": { + "type": "string", + "enum": ["tls", "tcp"], + "default": "tls" + }, + "appName": { + "type": "string", + "pattern": "^[!-~]{1,48}$", + "default": "seamless-auth" + }, + "facility": { + "type": "integer", + "minimum": 0, + "maximum": 23, + "default": 10 + }, + "tlsCaEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "tlsClientCertEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "tlsClientKeyEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + } + }, + "required": ["kind", "host"] + } + ] + }, + "enabled": { "type": "boolean", "default": true }, + "startAfterSeq": { "type": "integer", "minimum": 0 } + }, + "required": ["name", "settings"] + } + } + } + }, + "responses": { + "201": { + "description": "HTTP 201", + "content": { + "application/json": { + "example": { + "sink": { + "id": "string", + "name": "string", + "enabled": true, + "settings": null, + "status": { + "cursorSeq": 0, + "lagEvents": 0, + "lastDeliveredAt": null, + "lastFailure": null, + "lastFailureAt": null + }, + "createdAt": null, + "updatedAt": null + } + }, + "schema": { + "type": "object", + "properties": { + "sink": { + "type": "object", + "properties": { + "id": { "type": "string" }, + "name": { "type": "string" }, + "enabled": { "type": "boolean" }, + "settings": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["otlp"] }, + "endpoint": { "type": "string", "maxLength": 2048 }, + "headersFromEnv": { + "type": "object", + "additionalProperties": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "default": {} + }, + "serviceName": { + "type": "string", + "minLength": 1, + "maxLength": 100, + "default": "seamless-auth" + } + }, + "required": ["kind", "endpoint"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["syslog"] }, + "host": { "type": "string", "minLength": 1, "maxLength": 253 }, + "port": { + "type": "integer", + "minimum": 1, + "maximum": 65535, + "default": 6514 + }, + "transport": { + "type": "string", + "enum": ["tls", "tcp"], + "default": "tls" + }, + "appName": { + "type": "string", + "pattern": "^[!-~]{1,48}$", + "default": "seamless-auth" + }, + "facility": { + "type": "integer", + "minimum": 0, + "maximum": 23, + "default": 10 + }, + "tlsCaEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "tlsClientCertEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "tlsClientKeyEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + } + }, + "required": ["kind", "host"] + } + ] + }, + "status": { + "type": "object", + "properties": { + "cursorSeq": { "type": "integer", "nullable": true }, + "lagEvents": { "type": "integer", "nullable": true, "minimum": 0 }, + "lastDeliveredAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "lastFailure": { + "type": "string", + "nullable": true, + "enum": [ + "refused", + "timed_out", + "connection_failed", + "http_status", + "invalid_response", + "too_large", + null + ] + }, + "lastFailureAt": { + "type": "string", + "nullable": true, + "format": "date-time" + } + }, + "required": [ + "cursorSeq", + "lagEvents", + "lastDeliveredAt", + "lastFailure", + "lastFailureAt" + ] + }, + "createdAt": { "type": "string", "nullable": true, "format": "date-time" }, + "updatedAt": { "type": "string", "nullable": true, "format": "date-time" } + }, + "required": [ + "id", + "name", + "enabled", + "settings", + "status", + "createdAt", + "updatedAt" + ] + } + }, + "required": ["sink"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } + }, + "/admin/audit-sinks/{id}": { + "get": { + "summary": "Get an audit sink", + "tags": ["Admin", "Audit sinks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { + "sink": { + "id": "string", + "name": "string", + "enabled": true, + "settings": null, + "status": { + "cursorSeq": 0, + "lagEvents": 0, + "lastDeliveredAt": null, + "lastFailure": null, + "lastFailureAt": null + }, + "createdAt": null, + "updatedAt": null + } + }, + "schema": { + "type": "object", + "properties": { + "sink": { + "type": "object", + "properties": { + "id": { "type": "string" }, + "name": { "type": "string" }, + "enabled": { "type": "boolean" }, + "settings": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["otlp"] }, + "endpoint": { "type": "string", "maxLength": 2048 }, + "headersFromEnv": { + "type": "object", + "additionalProperties": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "default": {} + }, + "serviceName": { + "type": "string", + "minLength": 1, + "maxLength": 100, + "default": "seamless-auth" + } + }, + "required": ["kind", "endpoint"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["syslog"] }, + "host": { "type": "string", "minLength": 1, "maxLength": 253 }, + "port": { + "type": "integer", + "minimum": 1, + "maximum": 65535, + "default": 6514 + }, + "transport": { + "type": "string", + "enum": ["tls", "tcp"], + "default": "tls" + }, + "appName": { + "type": "string", + "pattern": "^[!-~]{1,48}$", + "default": "seamless-auth" + }, + "facility": { + "type": "integer", + "minimum": 0, + "maximum": 23, + "default": 10 + }, + "tlsCaEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "tlsClientCertEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "tlsClientKeyEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + } + }, + "required": ["kind", "host"] + } + ] + }, + "status": { + "type": "object", + "properties": { + "cursorSeq": { "type": "integer", "nullable": true }, + "lagEvents": { "type": "integer", "nullable": true, "minimum": 0 }, + "lastDeliveredAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "lastFailure": { + "type": "string", + "nullable": true, + "enum": [ + "refused", + "timed_out", + "connection_failed", + "http_status", + "invalid_response", + "too_large", + null + ] + }, + "lastFailureAt": { + "type": "string", + "nullable": true, + "format": "date-time" + } + }, + "required": [ + "cursorSeq", + "lagEvents", + "lastDeliveredAt", + "lastFailure", + "lastFailureAt" + ] + }, + "createdAt": { "type": "string", "nullable": true, "format": "date-time" }, + "updatedAt": { "type": "string", "nullable": true, "format": "date-time" } + }, + "required": [ + "id", + "name", + "enabled", + "settings", + "status", + "createdAt", + "updatedAt" + ] + } + }, + "required": ["sink"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + }, + "patch": { + "summary": "Update an audit sink", + "description": "The cursor is kept, so a sink turned back on resumes where it stopped.", + "tags": ["Admin", "Audit sinks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "id", + "in": "path" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "name": { "type": "string", "minLength": 1, "maxLength": 100 }, + "settings": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["otlp"] }, + "endpoint": { "type": "string", "maxLength": 2048 }, + "headersFromEnv": { + "type": "object", + "additionalProperties": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "default": {} + }, + "serviceName": { + "type": "string", + "minLength": 1, + "maxLength": 100, + "default": "seamless-auth" + } + }, + "required": ["kind", "endpoint"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["syslog"] }, + "host": { "type": "string", "minLength": 1, "maxLength": 253 }, + "port": { + "type": "integer", + "minimum": 1, + "maximum": 65535, + "default": 6514 + }, + "transport": { + "type": "string", + "enum": ["tls", "tcp"], + "default": "tls" + }, + "appName": { + "type": "string", + "pattern": "^[!-~]{1,48}$", + "default": "seamless-auth" + }, + "facility": { + "type": "integer", + "minimum": 0, + "maximum": 23, + "default": 10 + }, + "tlsCaEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "tlsClientCertEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "tlsClientKeyEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + } + }, + "required": ["kind", "host"] + } + ] + }, + "enabled": { "type": "boolean" } + } + } + } + } + }, + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { + "sink": { + "id": "string", + "name": "string", + "enabled": true, + "settings": null, + "status": { + "cursorSeq": 0, + "lagEvents": 0, + "lastDeliveredAt": null, + "lastFailure": null, + "lastFailureAt": null + }, + "createdAt": null, + "updatedAt": null + } + }, + "schema": { + "type": "object", + "properties": { + "sink": { + "type": "object", + "properties": { + "id": { "type": "string" }, + "name": { "type": "string" }, + "enabled": { "type": "boolean" }, + "settings": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["otlp"] }, + "endpoint": { "type": "string", "maxLength": 2048 }, + "headersFromEnv": { + "type": "object", + "additionalProperties": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "default": {} + }, + "serviceName": { + "type": "string", + "minLength": 1, + "maxLength": 100, + "default": "seamless-auth" + } + }, + "required": ["kind", "endpoint"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["syslog"] }, + "host": { "type": "string", "minLength": 1, "maxLength": 253 }, + "port": { + "type": "integer", + "minimum": 1, + "maximum": 65535, + "default": 6514 + }, + "transport": { + "type": "string", + "enum": ["tls", "tcp"], + "default": "tls" + }, + "appName": { + "type": "string", + "pattern": "^[!-~]{1,48}$", + "default": "seamless-auth" + }, + "facility": { + "type": "integer", + "minimum": 0, + "maximum": 23, + "default": 10 + }, + "tlsCaEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "tlsClientCertEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + }, + "tlsClientKeyEnv": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,59}_AUDIT_SINK_SECRET$" + } + }, + "required": ["kind", "host"] + } + ] + }, + "status": { + "type": "object", + "properties": { + "cursorSeq": { "type": "integer", "nullable": true }, + "lagEvents": { "type": "integer", "nullable": true, "minimum": 0 }, + "lastDeliveredAt": { + "type": "string", + "nullable": true, + "format": "date-time" + }, + "lastFailure": { + "type": "string", + "nullable": true, + "enum": [ + "refused", + "timed_out", + "connection_failed", + "http_status", + "invalid_response", + "too_large", + null + ] + }, + "lastFailureAt": { + "type": "string", + "nullable": true, + "format": "date-time" + } + }, + "required": [ + "cursorSeq", + "lagEvents", + "lastDeliveredAt", + "lastFailure", + "lastFailureAt" + ] + }, + "createdAt": { "type": "string", "nullable": true, "format": "date-time" }, + "updatedAt": { "type": "string", "nullable": true, "format": "date-time" } + }, + "required": [ + "id", + "name", + "enabled", + "settings", + "status", + "createdAt", + "updatedAt" + ] + } + }, + "required": ["sink"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + }, + "delete": { + "summary": "Delete an audit sink", + "tags": ["Admin", "Audit sinks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { "message": "string", "token": "string", "delivery": null }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "token": { "type": "string" }, + "delivery": { + "oneOf": [ + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["otp_email"] }, + "to": { "type": "string" }, + "token": { "type": "string" }, + "purpose": { "type": "string", "enum": ["account_recovery"] } + }, + "required": ["kind", "to", "token"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["otp_sms"] }, + "to": { "type": "string" }, + "token": { "anyOf": [{ "type": "string" }, { "type": "number" }] }, + "purpose": { "type": "string", "enum": ["account_recovery"] } + }, + "required": ["kind", "to", "token"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["magic_link_email"] }, + "to": { "type": "string" }, + "token": { "type": "string" }, + "magicLinkUrl": { "type": "string" } + }, + "required": ["kind", "to", "magicLinkUrl"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["enrollment_invite_email"] }, + "to": { "type": "string" }, + "signInUrl": { "type": "string" } + }, + "required": ["kind", "to", "signInUrl"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["account_notice_email"] }, + "notice": { + "type": "string", + "enum": [ + "account_recovery_opened", + "account_recovery_completed", + "recovery_code_used", + "identity_changed", + "application_notice" + ] + }, + "to": { "type": "string" }, + "subject": { "type": "string" }, + "text": { "type": "string" }, + "cancelUrl": { "type": "string" }, + "application": { + "type": "object", + "properties": { + "clientId": { "type": "string" }, + "name": { "type": "string" } + }, + "required": ["clientId", "name"] + } + }, + "required": ["kind", "notice", "to", "subject", "text"] + }, + { + "type": "object", + "properties": { + "kind": { "type": "string", "enum": ["account_notice_sms"] }, + "notice": { + "type": "string", + "enum": [ + "account_recovery_opened", + "account_recovery_completed", + "recovery_code_used", + "identity_changed", + "application_notice" + ] + }, + "to": { "type": "string" }, + "text": { "type": "string" }, + "cancelUrl": { "type": "string" }, + "application": { + "type": "object", + "properties": { + "clientId": { "type": "string" }, + "name": { "type": "string" } + }, + "required": ["clientId", "name"] + } + }, + "required": ["kind", "notice", "to", "text"] + } + ] + } + }, + "required": ["message"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } + }, + "/admin/audit-sinks/{id}/test": { + "post": { + "summary": "Send a test record", + "description": "Sends one record marked as a test, now. It is not part of the chain and does not move the cursor.", + "tags": ["Admin", "Audit sinks"], + "security": [{ "bearerAuth": [] }], + "parameters": [ + { + "schema": { "type": "string", "format": "uuid" }, + "required": true, + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "HTTP 200", + "content": { + "application/json": { + "example": { "ok": true, "failure": null, "statusCode": 0, "durationMs": 0 }, + "schema": { + "type": "object", + "properties": { + "ok": { "type": "boolean" }, + "failure": { + "type": "string", + "nullable": true, + "enum": [ + "refused", + "timed_out", + "connection_failed", + "http_status", + "invalid_response", + "too_large", + null + ] + }, + "statusCode": { "type": "integer", "nullable": true }, + "durationMs": { "type": "integer", "minimum": 0 } + }, + "required": ["ok", "failure", "statusCode", "durationMs"] + } + } + } + }, + "400": { + "description": "HTTP 400", + "content": { + "application/json": { + "example": { + "error": "string", + "message": "string", + "details": { "issues": [null] } + }, + "schema": { + "type": "object", + "properties": { + "error": { "type": "string" }, + "message": { "type": "string" }, + "details": { + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "array", + "items": { "anyOf": [{ "type": "string" }, { "type": "number" }] } + }, + "code": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["path", "code", "message"] + } + } + }, + "required": ["issues"] + } + }, + "required": ["error"] + } + } + } + }, + "403": { + "description": "HTTP 403", + "content": { + "application/json": { + "example": { + "message": "string", + "error": "string", + "fresh": true, + "method": null, + "verifiedAt": "string", + "expiresAt": "string", + "maxAgeSeconds": 0 + }, + "schema": { + "type": "object", + "properties": { + "message": { "type": "string" }, + "error": { "type": "string" }, + "fresh": { "type": "boolean" }, + "method": { + "type": "string", + "nullable": true, + "enum": ["webauthn", "totp", null] + }, + "verifiedAt": { "type": "string", "nullable": true }, + "expiresAt": { "type": "string", "nullable": true }, + "maxAgeSeconds": { "type": "number" } + }, + "required": ["error"] + } + } + } + }, + "404": { + "description": "HTTP 404", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "429": { + "description": "HTTP 429", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, + "500": { + "description": "HTTP 500", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + } + } + } + }, "/login": { "post": { "summary": "Login using identifier (email or phone)", diff --git a/src/controllers/auditSinks.ts b/src/controllers/auditSinks.ts new file mode 100644 index 00000000..9182da8a --- /dev/null +++ b/src/controllers/auditSinks.ts @@ -0,0 +1,132 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import type { AuditSinkSettings } from '@seamless-auth/types'; +import { Request, Response } from 'express'; + +import { + AuditSinkError, + chainHead, + createSink, + deleteSink, + getSink, + listSinks, + sendSinkTest, + serializeSink, + updateSink, +} from '../services/auditSinkService.js'; +import { AuthEventService } from '../services/authEventService.js'; +import { AuthenticatedRequest, RouteRequest } from '../types/types.js'; + +function actorUserId(req: Request) { + return (req as AuthenticatedRequest).user?.id ?? null; +} + +/** Where a sink sends, for the audit log. A URL is recorded without its query string. */ +function destination(settings: AuditSinkSettings) { + if (settings.kind === 'otlp') { + const url = new URL(settings.endpoint); + return `${url.origin}${url.pathname}`; + } + return `${settings.transport}://${settings.host}:${settings.port}`; +} + +function sendError(res: Response, error: unknown) { + if (error instanceof AuditSinkError) { + return res.status(error.status).json({ error: error.message }); + } + + throw error; +} + +export async function listAuditSinks(_req: Request, res: Response) { + const [sinks, head] = await Promise.all([listSinks(), chainHead()]); + return res.json({ sinks: sinks.map((sink) => serializeSink(sink, head)) }); +} + +export async function getAuditSink(req: RouteRequest, res: Response) { + try { + const sink = await getSink(req.params.id); + return res.json({ sink: serializeSink(sink, await chainHead()) }); + } catch (error) { + return sendError(res, error); + } +} + +export async function createAuditSink(req: Request, res: Response) { + try { + const sink = await createSink(req.body, actorUserId(req)); + + await AuthEventService.log({ + actorUserId: actorUserId(req), + type: 'admin_audit_sink_created', + req, + metadata: { + sinkId: sink.id, + kind: sink.kind, + destination: destination(sink.settings), + enabled: sink.enabled, + cursorSeq: Number(sink.cursorSeq), + }, + }); + + return res.status(201).json({ sink: serializeSink(sink, await chainHead()) }); + } catch (error) { + return sendError(res, error); + } +} + +export async function updateAuditSink(req: RouteRequest, res: Response) { + try { + const sink = await updateSink(req.params.id, req.body); + + await AuthEventService.log({ + actorUserId: actorUserId(req), + type: 'admin_audit_sink_updated', + req, + metadata: { + sinkId: sink.id, + changed: Object.keys(req.body), + destination: destination(sink.settings), + enabled: sink.enabled, + }, + }); + + return res.json({ sink: serializeSink(sink, await chainHead()) }); + } catch (error) { + return sendError(res, error); + } +} + +export async function deleteAuditSink(req: RouteRequest, res: Response) { + try { + const sink = await deleteSink(req.params.id); + + await AuthEventService.log({ + actorUserId: actorUserId(req), + type: 'admin_audit_sink_deleted', + req, + metadata: { + sinkId: sink.id, + kind: sink.kind, + destination: destination(sink.settings), + cursorSeq: Number(sink.cursorSeq), + }, + }); + + return res.json({ message: 'Audit sink deleted' }); + } catch (error) { + return sendError(res, error); + } +} + +export async function testAuditSink(req: RouteRequest, res: Response) { + try { + return res.json(await sendSinkTest(req.params.id)); + } catch (error) { + return sendError(res, error); + } +} diff --git a/src/generated/api.ts b/src/generated/api.ts index c5c25921..5441de1e 100644 --- a/src/generated/api.ts +++ b/src/generated/api.ts @@ -6907,6 +6907,9 @@ export interface paths { | 'admin_webhook_updated' | 'session_created' | 'webhook_endpoint_disabled' + | 'admin_audit_sink_created' + | 'admin_audit_sink_updated' + | 'admin_audit_sink_deleted' ) | string | ( @@ -7047,6 +7050,9 @@ export interface paths { | 'admin_webhook_updated' | 'session_created' | 'webhook_endpoint_disabled' + | 'admin_audit_sink_created' + | 'admin_audit_sink_updated' + | 'admin_audit_sink_deleted' ) | string )[]; @@ -9647,6 +9653,1278 @@ export interface paths { patch?: never; trace?: never; }; + '/admin/audit-sinks': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List audit sinks + * @description Each with its cursor and how many events it is behind the chain head. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "sinks": [ + * null + * ] + * } + */ + 'application/json': { + sinks: { + id: string; + name: string; + enabled: boolean; + settings: + | { + /** @enum {string} */ + kind: 'otlp'; + endpoint: string; + /** @default {} */ + headersFromEnv: { + [key: string]: string; + }; + /** @default seamless-auth */ + serviceName: string; + } + | { + /** @enum {string} */ + kind: 'syslog'; + host: string; + /** @default 6514 */ + port: number; + /** + * @default tls + * @enum {string} + */ + transport: 'tls' | 'tcp'; + /** @default seamless-auth */ + appName: string; + /** @default 10 */ + facility: number; + tlsCaEnv?: string; + tlsClientCertEnv?: string; + tlsClientKeyEnv?: string; + }; + status: { + cursorSeq: number | null; + lagEvents: number | null; + /** Format: date-time */ + lastDeliveredAt: string | null; + /** @enum {string|null} */ + lastFailure: + | 'refused' + | 'timed_out' + | 'connection_failed' + | 'http_status' + | 'invalid_response' + | 'too_large' + | null; + /** Format: date-time */ + lastFailureAt: string | null; + }; + /** Format: date-time */ + createdAt: string | null; + /** Format: date-time */ + updatedAt: string | null; + }[]; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + put?: never; + /** + * Create an audit sink + * @description Starts after the newest event unless `startAfterSeq` replays from an earlier one. Credentials are named as `_AUDIT_SINK_SECRET` env vars, never stored. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + 'application/json': { + name: string; + settings: + | { + /** @enum {string} */ + kind: 'otlp'; + endpoint: string; + /** @default {} */ + headersFromEnv?: { + [key: string]: string; + }; + /** @default seamless-auth */ + serviceName?: string; + } + | { + /** @enum {string} */ + kind: 'syslog'; + host: string; + /** @default 6514 */ + port?: number; + /** + * @default tls + * @enum {string} + */ + transport?: 'tls' | 'tcp'; + /** @default seamless-auth */ + appName?: string; + /** @default 10 */ + facility?: number; + tlsCaEnv?: string; + tlsClientCertEnv?: string; + tlsClientKeyEnv?: string; + }; + /** @default true */ + enabled?: boolean; + startAfterSeq?: number; + }; + }; + }; + responses: { + /** @description HTTP 201 */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "sink": { + * "id": "string", + * "name": "string", + * "enabled": true, + * "settings": null, + * "status": { + * "cursorSeq": 0, + * "lagEvents": 0, + * "lastDeliveredAt": null, + * "lastFailure": null, + * "lastFailureAt": null + * }, + * "createdAt": null, + * "updatedAt": null + * } + * } + */ + 'application/json': { + sink: { + id: string; + name: string; + enabled: boolean; + settings: + | { + /** @enum {string} */ + kind: 'otlp'; + endpoint: string; + /** @default {} */ + headersFromEnv: { + [key: string]: string; + }; + /** @default seamless-auth */ + serviceName: string; + } + | { + /** @enum {string} */ + kind: 'syslog'; + host: string; + /** @default 6514 */ + port: number; + /** + * @default tls + * @enum {string} + */ + transport: 'tls' | 'tcp'; + /** @default seamless-auth */ + appName: string; + /** @default 10 */ + facility: number; + tlsCaEnv?: string; + tlsClientCertEnv?: string; + tlsClientKeyEnv?: string; + }; + status: { + cursorSeq: number | null; + lagEvents: number | null; + /** Format: date-time */ + lastDeliveredAt: string | null; + /** @enum {string|null} */ + lastFailure: + | 'refused' + | 'timed_out' + | 'connection_failed' + | 'http_status' + | 'invalid_response' + | 'too_large' + | null; + /** Format: date-time */ + lastFailureAt: string | null; + }; + /** Format: date-time */ + createdAt: string | null; + /** Format: date-time */ + updatedAt: string | null; + }; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + '/admin/audit-sinks/{id}': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Get an audit sink */ + get: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "sink": { + * "id": "string", + * "name": "string", + * "enabled": true, + * "settings": null, + * "status": { + * "cursorSeq": 0, + * "lagEvents": 0, + * "lastDeliveredAt": null, + * "lastFailure": null, + * "lastFailureAt": null + * }, + * "createdAt": null, + * "updatedAt": null + * } + * } + */ + 'application/json': { + sink: { + id: string; + name: string; + enabled: boolean; + settings: + | { + /** @enum {string} */ + kind: 'otlp'; + endpoint: string; + /** @default {} */ + headersFromEnv: { + [key: string]: string; + }; + /** @default seamless-auth */ + serviceName: string; + } + | { + /** @enum {string} */ + kind: 'syslog'; + host: string; + /** @default 6514 */ + port: number; + /** + * @default tls + * @enum {string} + */ + transport: 'tls' | 'tcp'; + /** @default seamless-auth */ + appName: string; + /** @default 10 */ + facility: number; + tlsCaEnv?: string; + tlsClientCertEnv?: string; + tlsClientKeyEnv?: string; + }; + status: { + cursorSeq: number | null; + lagEvents: number | null; + /** Format: date-time */ + lastDeliveredAt: string | null; + /** @enum {string|null} */ + lastFailure: + | 'refused' + | 'timed_out' + | 'connection_failed' + | 'http_status' + | 'invalid_response' + | 'too_large' + | null; + /** Format: date-time */ + lastFailureAt: string | null; + }; + /** Format: date-time */ + createdAt: string | null; + /** Format: date-time */ + updatedAt: string | null; + }; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + put?: never; + post?: never; + /** Delete an audit sink */ + delete: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "token": "string", + * "delivery": null + * } + */ + 'application/json': { + message: string; + token?: string; + delivery?: + | { + /** @enum {string} */ + kind: 'otp_email'; + to: string; + token: string; + /** @enum {string} */ + purpose?: 'account_recovery'; + } + | { + /** @enum {string} */ + kind: 'otp_sms'; + to: string; + token: string | number; + /** @enum {string} */ + purpose?: 'account_recovery'; + } + | { + /** @enum {string} */ + kind: 'magic_link_email'; + to: string; + token?: string; + magicLinkUrl: string; + } + | { + /** @enum {string} */ + kind: 'enrollment_invite_email'; + to: string; + signInUrl: string; + } + | { + /** @enum {string} */ + kind: 'account_notice_email'; + /** @enum {string} */ + notice: + | 'account_recovery_opened' + | 'account_recovery_completed' + | 'recovery_code_used' + | 'identity_changed' + | 'application_notice'; + to: string; + subject: string; + text: string; + cancelUrl?: string; + application?: { + clientId: string; + name: string; + }; + } + | { + /** @enum {string} */ + kind: 'account_notice_sms'; + /** @enum {string} */ + notice: + | 'account_recovery_opened' + | 'account_recovery_completed' + | 'recovery_code_used' + | 'identity_changed' + | 'application_notice'; + to: string; + text: string; + cancelUrl?: string; + application?: { + clientId: string; + name: string; + }; + }; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + options?: never; + head?: never; + /** + * Update an audit sink + * @description The cursor is kept, so a sink turned back on resumes where it stopped. + */ + patch: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + 'application/json': { + name?: string; + settings?: + | { + /** @enum {string} */ + kind: 'otlp'; + endpoint: string; + /** @default {} */ + headersFromEnv?: { + [key: string]: string; + }; + /** @default seamless-auth */ + serviceName?: string; + } + | { + /** @enum {string} */ + kind: 'syslog'; + host: string; + /** @default 6514 */ + port?: number; + /** + * @default tls + * @enum {string} + */ + transport?: 'tls' | 'tcp'; + /** @default seamless-auth */ + appName?: string; + /** @default 10 */ + facility?: number; + tlsCaEnv?: string; + tlsClientCertEnv?: string; + tlsClientKeyEnv?: string; + }; + enabled?: boolean; + }; + }; + }; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "sink": { + * "id": "string", + * "name": "string", + * "enabled": true, + * "settings": null, + * "status": { + * "cursorSeq": 0, + * "lagEvents": 0, + * "lastDeliveredAt": null, + * "lastFailure": null, + * "lastFailureAt": null + * }, + * "createdAt": null, + * "updatedAt": null + * } + * } + */ + 'application/json': { + sink: { + id: string; + name: string; + enabled: boolean; + settings: + | { + /** @enum {string} */ + kind: 'otlp'; + endpoint: string; + /** @default {} */ + headersFromEnv: { + [key: string]: string; + }; + /** @default seamless-auth */ + serviceName: string; + } + | { + /** @enum {string} */ + kind: 'syslog'; + host: string; + /** @default 6514 */ + port: number; + /** + * @default tls + * @enum {string} + */ + transport: 'tls' | 'tcp'; + /** @default seamless-auth */ + appName: string; + /** @default 10 */ + facility: number; + tlsCaEnv?: string; + tlsClientCertEnv?: string; + tlsClientKeyEnv?: string; + }; + status: { + cursorSeq: number | null; + lagEvents: number | null; + /** Format: date-time */ + lastDeliveredAt: string | null; + /** @enum {string|null} */ + lastFailure: + | 'refused' + | 'timed_out' + | 'connection_failed' + | 'http_status' + | 'invalid_response' + | 'too_large' + | null; + /** Format: date-time */ + lastFailureAt: string | null; + }; + /** Format: date-time */ + createdAt: string | null; + /** Format: date-time */ + updatedAt: string | null; + }; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + trace?: never; + }; + '/admin/audit-sinks/{id}/test': { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Send a test record + * @description Sends one record marked as a test, now. It is not part of the chain and does not move the cursor. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTTP 200 */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "ok": true, + * "failure": null, + * "statusCode": 0, + * "durationMs": 0 + * } + */ + 'application/json': { + ok: boolean; + /** @enum {string|null} */ + failure: + | 'refused' + | 'timed_out' + | 'connection_failed' + | 'http_status' + | 'invalid_response' + | 'too_large' + | null; + statusCode: number | null; + durationMs: number; + }; + }; + }; + /** @description HTTP 400 */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "string", + * "message": "string", + * "details": { + * "issues": [ + * null + * ] + * } + * } + */ + 'application/json': { + error: string; + message?: string; + details?: { + issues: { + path: (string | number)[]; + code: string; + message: string; + }[]; + }; + }; + }; + }; + /** @description HTTP 403 */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string", + * "fresh": true, + * "method": null, + * "verifiedAt": "string", + * "expiresAt": "string", + * "maxAgeSeconds": 0 + * } + */ + 'application/json': { + message?: string; + error: string; + fresh?: boolean; + /** @enum {string|null} */ + method?: 'webauthn' | 'totp' | null; + verifiedAt?: string | null; + expiresAt?: string | null; + maxAgeSeconds?: number; + }; + }; + }; + /** @description HTTP 404 */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 429 */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + /** @description HTTP 500 */ + 500: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; '/login': { parameters: { query?: never; diff --git a/src/lib/auditSinkTransport.ts b/src/lib/auditSinkTransport.ts new file mode 100644 index 00000000..0f747c48 --- /dev/null +++ b/src/lib/auditSinkTransport.ts @@ -0,0 +1,362 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import { connect as netConnect, isIP, type Socket } from 'node:net'; +import { hostname as osHostname } from 'node:os'; +import { connect as tlsConnect } from 'node:tls'; + +import type { + CalloutFailure, + CalloutTestResponse, + OtlpSinkSettings, + SyslogSinkSettings, +} from '@seamless-auth/types'; +import { AUDIT_SINK_SECRET_ENV_PATTERN } from '@seamless-auth/types'; + +import { type ExportedAuthEvent, exportLine } from '../services/auditExport.js'; +import { authEventOutcome } from './authEventCategories.js'; +import { + CalloutError, + calloutHostProblem, + calloutLookup, + calloutRequest, + calloutUrlProblem, +} from './calloutTransport.js'; + +type EnvSource = Record; + +export const AUDIT_SINK_TIMEOUT_MS = 10_000; +const MAX_RESPONSE_BYTES = 64 * 1024; + +/** + * The structured data element carrying `seq` and `hash` in each syslog record. RFC 5424 needs + * a private SD-ID to be `name@`. 32473 is the number RFC 5612 reserves + * for documentation, a placeholder until Fells Code has its own. + */ +export const SYSLOG_SD_ID = 'seamless@32473'; + +export const AUDIT_SINK_SCOPE = 'seamless-auth.audit'; + +/** + * One record for a sink. `event` is null for a test record, which is not part of the chain and + * carries no `seq` or `hash`, so nothing downstream can mistake it for an event. + */ +export type SinkRecord = { line: string; at: Date; event: ExportedAuthEvent | null }; + +export type SinkAttempt = CalloutTestResponse; + +export function eventRecord(event: ExportedAuthEvent): SinkRecord { + return { line: exportLine(event), at: new Date(event.createdAt), event }; +} + +export function testRecord(sinkId: string, at: Date = new Date()): SinkRecord { + return { + line: JSON.stringify({ type: 'test', test: true, sinkId, generatedAt: at.toISOString() }), + at, + event: null, + }; +} + +/** Thrown before any connection for a sink whose settings or env cannot be used. */ +class SinkRefused extends CalloutError { + constructor(message: string) { + super('refused', message); + } +} + +function isProduction(env: EnvSource) { + return env.NODE_ENV === 'production'; +} + +const HOST_NAME = + /^(?=.{1,253}$)[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i; + +/** What is wrong with a sink's destination, checked when written and again before each send. */ +export function sinkDestinationProblem( + settings: OtlpSinkSettings | SyslogSinkSettings, + env: EnvSource = process.env, +): string | null { + if (settings.kind === 'otlp') { + const problem = calloutUrlProblem(settings.endpoint, env); + return problem ? `endpoint ${problem}` : null; + } + + if (!isIP(settings.host) && !HOST_NAME.test(settings.host)) return 'host is not a host name'; + if (settings.transport === 'tcp' && isProduction(env)) { + return 'transport must be tls in production'; + } + if (Boolean(settings.tlsClientCertEnv) !== Boolean(settings.tlsClientKeyEnv)) { + return 'tlsClientCertEnv and tlsClientKeyEnv must be set together'; + } + + const problem = calloutHostProblem(settings.host, env); + return problem ? `host ${problem}` : null; +} + +function secretFromEnv(name: string, env: EnvSource): string { + // The schema already holds names to the pattern; checked again so nothing that bypasses it + // can read a secret the server keeps for something else. + if (!AUDIT_SINK_SECRET_ENV_PATTERN.test(name)) throw new SinkRefused(`${name} is not allowed`); + const value = env[name]; + if (!value) throw new SinkRefused(`${name} is not set`); + return value; +} + +// The characters Node accepts in a header value. Anything else would throw inside the request. +const HEADER_VALUE = /^[\t\x20-\x7e\x80-\xff]+$/; + +function otlpHeaders(settings: OtlpSinkSettings, env: EnvSource) { + const headers: Record = { 'content-type': 'application/json' }; + for (const [name, envName] of Object.entries(settings.headersFromEnv)) { + const value = secretFromEnv(envName, env); + if (!HEADER_VALUE.test(value)) throw new SinkRefused(`${envName} is not a header value`); + headers[name] = value; + } + return headers; +} + +export function otlpLogsUrl(endpoint: string): string { + const url = new URL(endpoint); + url.pathname = `${url.pathname.replace(/\/+$/, '')}/v1/logs`; + return url.toString(); +} + +type OtlpValue = { stringValue: string } | { intValue: string } | { boolValue: boolean }; + +function attribute( + key: string, + value: string | number | boolean, +): { key: string; value: OtlpValue } { + if (typeof value === 'boolean') return { key, value: { boolValue: value } }; + if (typeof value === 'number') return { key, value: { intValue: String(value) } }; + return { key, value: { stringValue: value } }; +} + +function suspicious(record: SinkRecord) { + return record.event !== null && authEventOutcome(record.event.type) === 'suspicious'; +} + +function otlpAttributes(record: SinkRecord) { + const { event } = record; + if (!event) return [attribute('seamless.audit.test', true)]; + + const attributes = [ + attribute('seamless.audit.seq', event.seq), + attribute('seamless.audit.id', event.id), + attribute('seamless.audit.type', event.type), + attribute('seamless.audit.hash', event.hash), + ]; + if (event.prevHash) attributes.push(attribute('seamless.audit.prev_hash', event.prevHash)); + if (event.userId) attributes.push(attribute('user.id', event.userId)); + if (event.actorUserId) + attributes.push(attribute('seamless.audit.actor_user_id', event.actorUserId)); + if (event.sessionId) attributes.push(attribute('session.id', event.sessionId)); + return attributes; +} + +function unixNano(at: Date) { + return `${BigInt(at.getTime()) * 1_000_000n}`; +} + +/** An OTLP/HTTP JSON `ExportLogsServiceRequest`, one log record per audit event. */ +export function otlpLogsBody(records: SinkRecord[], serviceName: string, observed = new Date()) { + return JSON.stringify({ + resourceLogs: [ + { + resource: { attributes: [attribute('service.name', serviceName)] }, + scopeLogs: [ + { + scope: { name: AUDIT_SINK_SCOPE }, + logRecords: records.map((record) => ({ + timeUnixNano: unixNano(record.at), + observedTimeUnixNano: unixNano(observed), + severityNumber: suspicious(record) ? 13 : 9, + severityText: suspicious(record) ? 'WARN' : 'INFO', + body: { stringValue: record.line }, + attributes: otlpAttributes(record), + })), + }, + ], + }, + ], + }); +} + +function sdValue(value: string) { + return value.replace(/["\\\]]/g, (char) => `\\${char}`); +} + +function syslogHostname() { + const name = osHostname() + .replace(/[^!-~]/g, '') + .slice(0, 255); + return name || '-'; +} + +/** + * One RFC 5424 message. MSG is the export line with no BOM: RFC 5424 allows MSG as any octets + * (MSG-ANY), and a BOM would make the line fail to parse as JSON in most consumers. + */ +export function syslogMessage( + record: SinkRecord, + settings: SyslogSinkSettings, + hostname: string = syslogHostname(), +): string { + // Informational, or warning for a suspicious event. + const severity = suspicious(record) ? 4 : 6; + const pri = settings.facility * 8 + severity; + const sd = record.event + ? `[${SYSLOG_SD_ID} seq="${record.event.seq}" hash="${sdValue(record.event.hash)}"]` + : `[${SYSLOG_SD_ID} test="true"]`; + const msgId = record.event ? 'audit' : 'test'; + + return `<${pri}>1 ${record.at.toISOString()} ${hostname} ${settings.appName} - ${msgId} ${sd} ${record.line}`; +} + +/** Octet-counting framing (RFC 6587, 3.4.1), the framing RFC 5425 requires over TLS. */ +export function octetFrame(message: string): string { + return `${Buffer.byteLength(message, 'utf8')} ${message}`; +} + +function failureOf(error: unknown): CalloutFailure { + return error instanceof CalloutError ? error.failure : 'connection_failed'; +} + +function tlsMaterial(settings: SyslogSinkSettings, env: EnvSource) { + return { + ...(settings.tlsCaEnv ? { ca: secretFromEnv(settings.tlsCaEnv, env) } : {}), + ...(settings.tlsClientCertEnv ? { cert: secretFromEnv(settings.tlsClientCertEnv, env) } : {}), + ...(settings.tlsClientKeyEnv ? { key: secretFromEnv(settings.tlsClientKeyEnv, env) } : {}), + }; +} + +/** + * Writes every frame on one connection, ends it, and resolves once the collector closes its + * side. Syslog has no acknowledgement, so that is as much as a sender can know. + */ +function writeSyslog( + settings: SyslogSinkSettings, + payload: string, + env: EnvSource, + timeoutMs: number, +): Promise { + const problem = sinkDestinationProblem(settings, env); + if (problem) return Promise.reject(new SinkRefused(`Audit sink ${problem}`)); + + let material: ReturnType; + try { + material = tlsMaterial(settings, env); + } catch (error) { + return Promise.reject(error); + } + + return new Promise((resolve, reject) => { + let settled = false; + const finish = (error: CalloutError | null) => { + if (settled) return; + settled = true; + clearTimeout(timer); + socket.destroy(); + if (error) reject(error); + else resolve(); + }; + + const send = () => socket.end(payload); + const lookup = calloutLookup(env); + const socket: Socket = + settings.transport === 'tls' + ? tlsConnect( + { + host: settings.host, + port: settings.port, + lookup, + minVersion: 'TLSv1.2', + ...(isIP(settings.host) ? {} : { servername: settings.host }), + ...material, + }, + send, + ) + : netConnect({ host: settings.host, port: settings.port, lookup }, send); + + const timer = setTimeout( + () => finish(new CalloutError('timed_out', 'Audit sink timed out')), + timeoutMs, + ); + timer.unref(); + + // Success is the collector closing its side after reading to our end of stream, which + // also catches a TLS 1.3 client certificate refused after the client thinks it is done. + // Anything it sends is discarded, so that close is seen. + let flushed = false; + socket.resume(); + socket.on('finish', () => (flushed = true)); + socket.on('close', () => + finish( + flushed ? null : new CalloutError('connection_failed', 'Audit sink connection closed'), + ), + ); + socket.on('error', (error: Error) => + finish( + error instanceof CalloutError + ? error + : new CalloutError('connection_failed', 'Audit sink connection failed'), + ), + ); + }); +} + +async function sendOtlp( + settings: OtlpSinkSettings, + records: SinkRecord[], + env: EnvSource, + timeoutMs: number, +): Promise<{ statusCode: number | null; ok: boolean }> { + const headers = otlpHeaders(settings, env); + const response = await calloutRequest( + otlpLogsUrl(settings.endpoint), + { + method: 'POST', + headers, + body: otlpLogsBody(records, settings.serviceName), + timeoutMs, + maxResponseBytes: MAX_RESPONSE_BYTES, + }, + env, + ); + return { statusCode: response.status, ok: response.status >= 200 && response.status < 300 }; +} + +/** + * Sends records to a sink in order. For OTLP anything but a 2xx is a failure, including a + * redirect, which is not followed. + */ +export async function sendToSink( + settings: OtlpSinkSettings | SyslogSinkSettings, + records: SinkRecord[], + env: EnvSource = process.env, + timeoutMs: number = AUDIT_SINK_TIMEOUT_MS, +): Promise { + const started = Date.now(); + const durationMs = () => Date.now() - started; + + try { + if (settings.kind === 'otlp') { + const { statusCode, ok } = await sendOtlp(settings, records, env, timeoutMs); + return { ok, statusCode, failure: ok ? null : 'http_status', durationMs: durationMs() }; + } + + const hostname = syslogHostname(); + await writeSyslog( + settings, + records.map((record) => octetFrame(syslogMessage(record, settings, hostname))).join(''), + env, + timeoutMs, + ); + return { ok: true, statusCode: null, failure: null, durationMs: durationMs() }; + } catch (error) { + return { ok: false, statusCode: null, failure: failureOf(error), durationMs: durationMs() }; + } +} diff --git a/src/migrations/20261107140000-add-audit-sinks.cjs b/src/migrations/20261107140000-add-audit-sinks.cjs new file mode 100644 index 00000000..6967d3b3 --- /dev/null +++ b/src/migrations/20261107140000-add-audit-sinks.cjs @@ -0,0 +1,45 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +'use strict'; + +/** + * Audit sinks stream the audit log to a SIEM (ADR 0005, E7). Each sink keeps its own cursor, + * the `seq` of the last event its destination accepted, and only moves it on success, so a + * sink that cannot deliver falls behind rather than dropping events. `settings` never holds a + * credential: it names env vars instead. + * + * @type {import('sequelize-cli').Migration} + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query(` + CREATE TABLE IF NOT EXISTS public.audit_sinks ( + id uuid NOT NULL, + name character varying(100) NOT NULL, + kind character varying(16) NOT NULL, + enabled boolean NOT NULL DEFAULT true, + settings jsonb NOT NULL, + "cursorSeq" bigint NOT NULL, + "failureCount" integer NOT NULL DEFAULT 0, + "nextAttemptAt" timestamp with time zone, + "lastDeliveredAt" timestamp with time zone, + "lastFailure" character varying(32), + "lastFailureAt" timestamp with time zone, + "createdBy" uuid, + "createdAt" timestamp with time zone NOT NULL, + "updatedAt" timestamp with time zone NOT NULL, + CONSTRAINT audit_sinks_pkey PRIMARY KEY (id), + CONSTRAINT audit_sinks_kind CHECK (kind IN ('otlp', 'syslog')), + CONSTRAINT audit_sinks_cursor CHECK ("cursorSeq" >= 0) + ); + `); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query('DROP TABLE IF EXISTS public.audit_sinks;'); + }, +}; diff --git a/src/models/auditSinks.ts b/src/models/auditSinks.ts new file mode 100644 index 00000000..6614a282 --- /dev/null +++ b/src/models/auditSinks.ts @@ -0,0 +1,93 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import type { AuditSinkSettings, CalloutFailure } from '@seamless-auth/types'; +import { DataTypes, Model, Optional, Sequelize } from 'sequelize'; + +export interface AuditSinkAttributes { + id: string; + name: string; + kind: AuditSinkSettings['kind']; + enabled: boolean; + settings: AuditSinkSettings; + /** The `seq` of the last event the destination accepted. A bigint, so Postgres returns a string. */ + cursorSeq: string; + /** Failed sends in a row, for the backoff. Cleared by any success. */ + failureCount: number; + nextAttemptAt: Date | null; + lastDeliveredAt: Date | null; + lastFailure: CalloutFailure | null; + lastFailureAt: Date | null; + createdBy: string | null; + createdAt?: Date; + updatedAt?: Date; +} + +type AuditSinkCreationAttributes = Optional< + AuditSinkAttributes, + | 'id' + | 'enabled' + | 'failureCount' + | 'nextAttemptAt' + | 'lastDeliveredAt' + | 'lastFailure' + | 'lastFailureAt' + | 'createdBy' + | 'createdAt' + | 'updatedAt' +>; + +export class AuditSink + extends Model + implements AuditSinkAttributes +{ + declare id: string; + declare name: string; + declare kind: AuditSinkSettings['kind']; + declare enabled: boolean; + declare settings: AuditSinkSettings; + declare cursorSeq: string; + declare failureCount: number; + declare nextAttemptAt: Date | null; + declare lastDeliveredAt: Date | null; + declare lastFailure: CalloutFailure | null; + declare lastFailureAt: Date | null; + declare createdBy: string | null; + declare readonly createdAt: Date; + declare readonly updatedAt: Date; +} + +const initializeAuditSinkModel = (sequelize: Sequelize) => { + AuditSink.init( + { + id: { + type: DataTypes.UUID, + primaryKey: true, + defaultValue: DataTypes.UUIDV4, + allowNull: false, + }, + name: { type: DataTypes.STRING(100), allowNull: false }, + kind: { type: DataTypes.STRING(16), allowNull: false }, + enabled: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true }, + settings: { type: DataTypes.JSONB, allowNull: false }, + cursorSeq: { type: DataTypes.BIGINT, allowNull: false }, + failureCount: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 }, + nextAttemptAt: { type: DataTypes.DATE, allowNull: true }, + lastDeliveredAt: { type: DataTypes.DATE, allowNull: true }, + lastFailure: { type: DataTypes.STRING(32), allowNull: true }, + lastFailureAt: { type: DataTypes.DATE, allowNull: true }, + createdBy: { type: DataTypes.UUID, allowNull: true }, + }, + { + sequelize, + tableName: 'audit_sinks', + modelName: 'AuditSink', + }, + ); + return AuditSink; +}; + +export default initializeAuditSinkModel; diff --git a/src/routes/auditSinks.routes.ts b/src/routes/auditSinks.routes.ts new file mode 100644 index 00000000..f8dea86e --- /dev/null +++ b/src/routes/auditSinks.routes.ts @@ -0,0 +1,130 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import { + createAuditSink, + deleteAuditSink, + getAuditSink, + listAuditSinks, + testAuditSink, + updateAuditSink, +} from '../controllers/auditSinks.js'; +import { createRouter } from '../lib/createRouter.js'; +import { requireAdmin } from '../middleware/requireAdmin.js'; +import { requireStepUp } from '../middleware/requireStepUp.js'; +import { + AuditSinkIdParamSchema, + AuditSinkListResponseSchema, + AuditSinkResponseSchema, + CalloutTestResponseSchema, + CreateAuditSinkRequestSchema, + UpdateAuditSinkRequestSchema, +} from '../schemas/auditSink.schemas.js'; +import { ErrorSchema, MessageSchema } from '../schemas/generic.responses.js'; +import { StepUpRequiredErrorSchema } from '../schemas/stepUp.responses.js'; + +/** + * Streaming the audit log to a SIEM (ADR 0005, E7). Sending a test record is a write: it + * connects to a destination an administrator chose, so it takes step-up like the rest. + */ +const router = createRouter('/admin'); + +const tags = ['Admin', 'Audit sinks']; +const read = { auth: 'access', tags, middleware: [requireAdmin('read')] }; +const write = { auth: 'access', tags, middleware: [requireAdmin('write'), requireStepUp()] }; + +router.get( + '/audit-sinks', + { + ...read, + summary: 'List audit sinks', + description: 'Each with its cursor and how many events it is behind the chain head.', + schemas: { response: { 200: AuditSinkListResponseSchema } }, + }, + listAuditSinks, +); + +router.post( + '/audit-sinks', + { + ...write, + summary: 'Create an audit sink', + description: + 'Starts after the newest event unless `startAfterSeq` replays from an earlier one. Credentials are named as `_AUDIT_SINK_SECRET` env vars, never stored.', + schemas: { + body: CreateAuditSinkRequestSchema, + response: { 201: AuditSinkResponseSchema, 400: ErrorSchema, 403: StepUpRequiredErrorSchema }, + }, + }, + createAuditSink, +); + +router.get( + '/audit-sinks/:id', + { + ...read, + summary: 'Get an audit sink', + schemas: { + params: AuditSinkIdParamSchema, + response: { 200: AuditSinkResponseSchema, 404: ErrorSchema }, + }, + }, + getAuditSink, +); + +router.patch( + '/audit-sinks/:id', + { + ...write, + summary: 'Update an audit sink', + description: 'The cursor is kept, so a sink turned back on resumes where it stopped.', + schemas: { + params: AuditSinkIdParamSchema, + body: UpdateAuditSinkRequestSchema, + response: { + 200: AuditSinkResponseSchema, + 400: ErrorSchema, + 403: StepUpRequiredErrorSchema, + 404: ErrorSchema, + }, + }, + }, + updateAuditSink, +); + +router.delete( + '/audit-sinks/:id', + { + ...write, + summary: 'Delete an audit sink', + schemas: { + params: AuditSinkIdParamSchema, + response: { 200: MessageSchema, 403: StepUpRequiredErrorSchema, 404: ErrorSchema }, + }, + }, + deleteAuditSink, +); + +router.post( + '/audit-sinks/:id/test', + { + ...write, + summary: 'Send a test record', + description: + 'Sends one record marked as a test, now. It is not part of the chain and does not move the cursor.', + schemas: { + params: AuditSinkIdParamSchema, + response: { + 200: CalloutTestResponseSchema, + 403: StepUpRequiredErrorSchema, + 404: ErrorSchema, + }, + }, + }, + testAuditSink, +); + +export default router.router; diff --git a/src/schemas/auditSink.schemas.ts b/src/schemas/auditSink.schemas.ts new file mode 100644 index 00000000..6bcd92fc --- /dev/null +++ b/src/schemas/auditSink.schemas.ts @@ -0,0 +1,14 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +export { + AuditSinkIdParamSchema, + AuditSinkListResponseSchema, + AuditSinkResponseSchema, + CalloutTestResponseSchema, + CreateAuditSinkRequestSchema, + UpdateAuditSinkRequestSchema, +} from '@seamless-auth/types'; diff --git a/src/schemas/authEvent.types.ts b/src/schemas/authEvent.types.ts index 7fdd5568..9529d468 100644 --- a/src/schemas/authEvent.types.ts +++ b/src/schemas/authEvent.types.ts @@ -144,6 +144,9 @@ export const AUTH_EVENT_TYPES = [ 'admin_webhook_updated', 'session_created', 'webhook_endpoint_disabled', + 'admin_audit_sink_created', + 'admin_audit_sink_updated', + 'admin_audit_sink_deleted', ] as const; export const AuthEventTypeEnum = z.enum(AUTH_EVENT_TYPES); diff --git a/src/server.ts b/src/server.ts index 326fb403..912a6426 100644 --- a/src/server.ts +++ b/src/server.ts @@ -17,6 +17,7 @@ import { initializeModels } from './models/index.js'; import { TotpCredential } from './models/totpCredentials.js'; import { WebhookEndpoint } from './models/webhookEndpoints.js'; import { startAuditMaintenance } from './services/auditRetention.js'; +import { startAuditSinkDelivery } from './services/auditSinkService.js'; import { warnOnBreakGlassMisconfiguration } from './services/breakGlassService.js'; import { initializeMetadataService } from './services/metadataServiceBootstrap.js'; import { warnIfUnboundOAuthStateSet } from './services/oauthService.js'; @@ -73,6 +74,7 @@ async function startServer() { startOidcPayloadPurge(); startBackchannelLogoutSweep(); startWebhookDelivery(); + startAuditSinkDelivery(); } catch (err) { logger.error('Failed to start server:', err); process.exit(1); diff --git a/src/services/auditExport.ts b/src/services/auditExport.ts index 61aeb1b4..82d4b0ca 100644 --- a/src/services/auditExport.ts +++ b/src/services/auditExport.ts @@ -86,6 +86,11 @@ export const EXPORT_COLUMNS = ` public.auth_event_payload(e.*) AS payload `; +/** One event as a `seamless-auth-events/1` line, without the trailing newline. */ +export function exportLine(event: ExportedAuthEvent): string { + return JSON.stringify(event); +} + export function toExportedEvent(row: ExportRow): ExportedAuthEvent { return { seq: Number(row.seq), @@ -201,7 +206,7 @@ export async function streamAuthEventExport(params: { firstSeq = event.seq; anchorHash = event.prevHash; } - await write(`${JSON.stringify(event)}\n`); + await write(`${exportLine(event)}\n`); lastSeq = event.seq; lastHash = event.hash; count += 1; diff --git a/src/services/auditRetention.ts b/src/services/auditRetention.ts index 21f36b99..4b92dcfa 100644 --- a/src/services/auditRetention.ts +++ b/src/services/auditRetention.ts @@ -12,7 +12,7 @@ import { QueryTypes, Sequelize } from 'sequelize'; import { resolveSslOptions, withoutSslMode } from '../config/database.cjs'; import { getSequelize } from '../models/index.js'; import getLogger from '../utils/logger.js'; -import { buildManifest, ExportedAuthEvent, readExportBatch } from './auditExport.js'; +import { buildManifest, ExportedAuthEvent, exportLine, readExportBatch } from './auditExport.js'; const logger = getLogger('audit-retention'); @@ -76,6 +76,20 @@ function getRetentionSequelize(env = process.env): Sequelize { return retentionSequelize; } +/** + * The newest event every audit sink has delivered, or null without sinks. Retention never + * deletes past it, so a sink that has fallen behind still finds every event it has yet to send + * (ADR 0005, E7). Read through the application's connection, since the retention role need not + * see `audit_sinks`. + */ +async function auditSinkHold(): Promise { + const [row] = await getSequelize().query<{ held: string | null }>( + 'SELECT min("cursorSeq") AS held FROM public.audit_sinks', + { type: QueryTypes.SELECT }, + ); + return row?.held == null ? null : Number(row.held); +} + async function writeArchiveFile(archiveDir: string, events: ExportedAuthEvent[]) { const first = events[0]; const last = events[events.length - 1]; @@ -92,8 +106,7 @@ async function writeArchiveFile(archiveDir: string, events: ExportedAuthEvent[]) lastHash: last.hash, }); - const body = - events.map((event) => JSON.stringify(event)).join('\n') + `\n${JSON.stringify(manifest)}\n`; + const body = events.map(exportLine).join('\n') + `\n${JSON.stringify(manifest)}\n`; // Written under a temporary name, flushed to disk, then renamed, so a file under its // final name is always complete. The rows are only deleted after this returns. @@ -151,6 +164,7 @@ export async function runAuditRetention( let archived = 0; for (;;) { + const heldFor = await auditSinkHold(); const outcome = await sequelize.transaction(async (transaction) => { const [{ locked }] = await sequelize.query<{ locked: boolean }>( 'SELECT pg_try_advisory_xact_lock(:key) AS locked', @@ -175,9 +189,15 @@ export async function runAuditRetention( if (maxSeq === null || Number(maxSeq) < 1) return 'finished' as const; + const deletable = heldFor === null ? Number(maxSeq) : Math.min(Number(maxSeq), heldFor); + if (deletable < Number(maxSeq)) { + logger.warn(`Audit retention is held at seq ${deletable} by an audit sink that is behind`); + } + if (deletable < 1) return 'finished' as const; + const batch = await readExportBatch({ afterSeq: 0, - maxSeq: Number(maxSeq), + maxSeq: deletable, limit: ARCHIVE_BATCH_SIZE, sequelize, transaction, diff --git a/src/services/auditSinkService.ts b/src/services/auditSinkService.ts new file mode 100644 index 00000000..88f88636 --- /dev/null +++ b/src/services/auditSinkService.ts @@ -0,0 +1,284 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import type { + AuditSinkSettings, + CalloutTestResponse, + CreateAuditSinkRequest, + UpdateAuditSinkRequest, +} from '@seamless-auth/types'; +import { Op, QueryTypes } from 'sequelize'; + +import { + eventRecord, + sendToSink, + sinkDestinationProblem, + testRecord, +} from '../lib/auditSinkTransport.js'; +import { AuditSink } from '../models/auditSinks.js'; +import { getSequelize } from '../models/index.js'; +import getLogger from '../utils/logger.js'; +import { readExportBatch } from './auditExport.js'; + +const logger = getLogger('audit-sinks'); + +export class AuditSinkError extends Error { + constructor( + readonly status: number, + message: string, + ) { + super(message); + this.name = 'AuditSinkError'; + } +} + +export const SINK_BATCH = 100; +const MAX_BACKOFF_MS = 60_000; +// Taken with each sink's id as the second key, so replicas take turns per sink and two sinks +// never wait on each other. The two-key form is a separate space from the single-key locks the +// webhook dispatcher and audit maintenance take. +const SINK_LOCK_CLASS = 72_641_003; + +function now() { + return new Date(); +} + +type ChainBounds = { head: number; oldest: number | null }; + +async function chainBounds(): Promise { + const [row] = await getSequelize().query<{ head: string | null; oldest: string | null }>( + `SELECT (SELECT seq FROM public.auth_event_chain_head WHERE id = 1) AS head, + (SELECT min(seq) FROM public.auth_events) AS oldest`, + { type: QueryTypes.SELECT }, + ); + return { + head: row?.head == null ? 0 : Number(row.head), + oldest: row?.oldest == null ? null : Number(row.oldest), + }; +} + +export async function chainHead(): Promise { + return (await chainBounds()).head; +} + +export function serializeSink(sink: AuditSink, head: number) { + const cursorSeq = Number(sink.cursorSeq); + return { + id: sink.id, + name: sink.name, + enabled: sink.enabled, + settings: sink.settings, + status: { + cursorSeq, + lagEvents: Math.max(0, head - cursorSeq), + lastDeliveredAt: sink.lastDeliveredAt?.toISOString() ?? null, + lastFailure: sink.lastFailure ?? null, + lastFailureAt: sink.lastFailureAt?.toISOString() ?? null, + }, + createdAt: sink.createdAt.toISOString(), + updatedAt: sink.updatedAt.toISOString(), + }; +} + +function assertSettings(settings: AuditSinkSettings) { + const problem = sinkDestinationProblem(settings); + if (problem) throw new AuditSinkError(400, problem); +} + +export async function listSinks() { + return AuditSink.findAll({ order: [['createdAt', 'ASC']] }); +} + +export async function getSink(id: string) { + const sink = await AuditSink.findByPk(id); + if (!sink) throw new AuditSinkError(404, 'Audit sink not found'); + return sink; +} + +/** + * Without `startAfterSeq` the sink starts after the newest event. A replay may not start before + * the oldest event still held, since what retention archived cannot be streamed. + */ +async function startingCursor(startAfterSeq: number | undefined) { + const { head, oldest } = await chainBounds(); + if (startAfterSeq === undefined) return head; + + if (startAfterSeq > head) { + throw new AuditSinkError(400, `startAfterSeq is past the newest event (${head})`); + } + if (oldest !== null && startAfterSeq < oldest - 1) { + throw new AuditSinkError( + 400, + `startAfterSeq is before the oldest event still held (${oldest}); older events are in the retention archive`, + ); + } + return startAfterSeq; +} + +export async function createSink(input: CreateAuditSinkRequest, actorUserId: string | null) { + assertSettings(input.settings); + const cursorSeq = await startingCursor(input.startAfterSeq); + + return AuditSink.create({ + name: input.name, + kind: input.settings.kind, + settings: input.settings, + enabled: input.enabled ?? true, + cursorSeq: String(cursorSeq), + createdBy: actorUserId, + }); +} + +/** A change of settings or a re-enable is tried at once rather than after the backoff. */ +export async function updateSink(id: string, input: UpdateAuditSinkRequest) { + const sink = await getSink(id); + if (input.settings !== undefined) assertSettings(input.settings); + + await sink.update({ + ...(input.name !== undefined ? { name: input.name } : {}), + ...(input.settings !== undefined + ? { settings: input.settings, kind: input.settings.kind } + : {}), + ...(input.enabled !== undefined ? { enabled: input.enabled } : {}), + failureCount: 0, + nextAttemptAt: null, + }); + + return sink; +} + +export async function deleteSink(id: string) { + const sink = await getSink(id); + await sink.destroy(); + return sink; +} + +/** One record marked as a test, outside the chain. It moves no cursor and records no failure. */ +export async function sendSinkTest(id: string): Promise { + const sink = await getSink(id); + return sendToSink(sink.settings, [testRecord(sink.id)]); +} + +/** Doubles from one second, capped at a minute, with up to 10% taken off so sinks spread out. */ +export function backoffMs(failures: number) { + const base = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.max(0, failures - 1)); + return Math.round(base * (1 - Math.random() * 0.1)); +} + +/** + * Sends the next batch past the sink's cursor and moves the cursor only when the destination + * took all of it, so an event is never skipped: a failure resends the same batch later. Rows are + * read by `seq` and committed rows form a gapless prefix of it (see `dispatchWebhooks`). + * + * The send happens inside the transaction holding the sink's lock, so a replica never sends a + * batch another is sending. If the commit fails after a send, the batch goes again: delivery is + * at least once, and `seq` lets the destination drop a repeat. + * + * Returns how many events were delivered. + */ +export async function deliverSink(id: string): Promise { + const sequelize = getSequelize(); + + return sequelize.transaction(async (transaction) => { + const [{ locked }] = await sequelize.query<{ locked: boolean }>( + 'SELECT pg_try_advisory_xact_lock(:lockClass, hashtext(:id)) AS locked', + { + replacements: { lockClass: SINK_LOCK_CLASS, id }, + type: QueryTypes.SELECT, + transaction, + }, + ); + if (!locked) return 0; + + const sink = await AuditSink.findByPk(id, { transaction }); + if (!sink || !sink.enabled) return 0; + if (sink.nextAttemptAt && sink.nextAttemptAt > now()) return 0; + + const events = await readExportBatch({ + afterSeq: Number(sink.cursorSeq), + maxSeq: Number.MAX_SAFE_INTEGER, + limit: SINK_BATCH, + sequelize, + transaction, + }); + if (events.length === 0) return 0; + + const attempt = await sendToSink(sink.settings, events.map(eventRecord)); + + if (attempt.ok) { + await sink.update( + { + cursorSeq: String(events[events.length - 1].seq), + lastDeliveredAt: now(), + failureCount: 0, + nextAttemptAt: null, + }, + { transaction }, + ); + return events.length; + } + + // Not audited: a sink that is down would write an event per retry into the very chain it + // streams. + const failureCount = sink.failureCount + 1; + await sink.update( + { + lastFailure: attempt.failure, + lastFailureAt: now(), + failureCount, + nextAttemptAt: new Date(Date.now() + backoffMs(failureCount)), + }, + { transaction }, + ); + return 0; + }); +} + +// Bounds one sink's catch-up within a tick to 5,000 events, so a long backlog does not hold +// the loop from sinks that become due meanwhile. +const MAX_BATCHES_PER_TICK = 50; + +async function drainSink(id: string) { + try { + for (let batch = 0; batch < MAX_BATCHES_PER_TICK; batch += 1) { + if ((await deliverSink(id)) < SINK_BATCH) return; + } + } catch (error) { + logger.error(`Audit sink ${id} failed: ${(error as Error).message}`); + } +} + +/** One pass over every enabled sink that is due. Errors are logged, not thrown. */ +export async function runAuditSinkTick() { + try { + const sinks = await AuditSink.findAll({ + attributes: ['id'], + where: { + enabled: true, + [Op.or]: [{ nextAttemptAt: null }, { nextAttemptAt: { [Op.lte]: now() } }], + }, + }); + await Promise.all(sinks.map((sink) => drainSink(sink.id))); + } catch (error) { + logger.error(`Audit sink tick failed: ${(error as Error).message}`); + } +} + +const TICK_MS = 1000; + +/** Polls once a second, like webhook delivery. Idle, it is one read of a small table. */ +export function startAuditSinkDelivery() { + let running = false; + const timer = setInterval(() => { + if (running) return; + running = true; + void runAuditSinkTick().finally(() => { + running = false; + }); + }, TICK_MS); + timer.unref(); + return timer; +} diff --git a/tests/fixtures/auditSinkTls/ca.pem b/tests/fixtures/auditSinkTls/ca.pem new file mode 100644 index 00000000..0b00471f --- /dev/null +++ b/tests/fixtures/auditSinkTls/ca.pem @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE----- +MIIBcjCCARegAwIBAgIJAKpqvJrKrQqbMAoGCCqGSM49BAMCMBsxGTAXBgNVBAMM +EHNlYW1sZXNzIHRlc3QgY2EwIBcNMjYxMTA4MDAyOTQzWhgPMjEyNjEwMTUwMDI5 +NDNaMBsxGTAXBgNVBAMMEHNlYW1sZXNzIHRlc3QgY2EwWTATBgcqhkjOPQIBBggq +hkjOPQMBBwNCAAR/emcWTXV+a6WY+B5bBroXTEovVOpogl0cpvLs4eqYh7sZfOw8 +jqshKDmszrmM9GUlg5NPMw0cez6XMVgn77Tqo0IwQDAPBgNVHRMBAf8EBTADAQH/ +MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUoXFdXVtWgbp7Rcl6BkKlA4+5PvQw +CgYIKoZIzj0EAwIDSQAwRgIhAOVnEq+ByGysSs+5X7GILhtrYtLFcsif24EnK2bx +CdB7AiEA6zygcHedrDhKgmUMvfzcUtC90CmysolM5JgQ+2S1mfU= +-----END CERTIFICATE----- diff --git a/tests/fixtures/auditSinkTls/client.key b/tests/fixtures/auditSinkTls/client.key new file mode 100644 index 00000000..96ea8358 --- /dev/null +++ b/tests/fixtures/auditSinkTls/client.key @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQggrW4kv8HzAf0fJAu +a/ux0RBpOi491Sv/fl23PPBtAyOhRANCAARyzxs5JHDEXtjLd79AQJqPYu+tZPPT +5pZbZb6GqYFmj1y6qF3lYjUPx1o8Ejq6nlSFS+rvG/ls3yKKHAm0gMy5 +-----END PRIVATE KEY----- diff --git a/tests/fixtures/auditSinkTls/client.pem b/tests/fixtures/auditSinkTls/client.pem new file mode 100644 index 00000000..4ae0195a --- /dev/null +++ b/tests/fixtures/auditSinkTls/client.pem @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE----- +MIIBUzCB+qADAgECAgkAhT5UNmDyl/4wCgYIKoZIzj0EAwIwGzEZMBcGA1UEAwwQ +c2VhbWxlc3MgdGVzdCBjYTAgFw0yNjExMDgwMDI5NDNaGA8yMTI2MTAxNTAwMjk0 +M1owETEPMA0GA1UEAwwGY2xpZW50MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE +cs8bOSRwxF7Yy3e/QECaj2LvrWTz0+aWW2W+hqmBZo9cuqhd5WI1D8daPBI6up5U +hUvq7xv5bN8iihwJtIDMuaMvMC0wCQYDVR0TBAIwADALBgNVHQ8EBAMCB4AwEwYD +VR0lBAwwCgYIKwYBBQUHAwIwCgYIKoZIzj0EAwIDSAAwRQIhAJzhfml8R12RdbEJ +4i1LcPk346nPJTkR/wMaYaaLonxuAiA25pTuxSkXKhtsliWlvYD9BNRONDqOSySZ +KT8h8/a1Ww== +-----END CERTIFICATE----- diff --git a/tests/fixtures/auditSinkTls/server.key b/tests/fixtures/auditSinkTls/server.key new file mode 100644 index 00000000..f9553e2c --- /dev/null +++ b/tests/fixtures/auditSinkTls/server.key @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgW1ygJcnt2yCyuJAF +2CyCrBvY5z1e24uZQpZScl/hqdOhRANCAASe0UE1PwVL/YH4lCNFzxUhSDGrodDG +k/Kgt7UXtgXOqcuUg3Lbbffq1CZR7GXMKWrOziswcbmSlH/3ixtZedk9 +-----END PRIVATE KEY----- diff --git a/tests/fixtures/auditSinkTls/server.pem b/tests/fixtures/auditSinkTls/server.pem new file mode 100644 index 00000000..f0f335da --- /dev/null +++ b/tests/fixtures/auditSinkTls/server.pem @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE----- +MIIBcDCCARagAwIBAgIJAIU+VDZg8pf9MAoGCCqGSM49BAMCMBsxGTAXBgNVBAMM +EHNlYW1sZXNzIHRlc3QgY2EwIBcNMjYxMTA4MDAyOTQzWhgPMjEyNjEwMTUwMDI5 +NDNaMBExDzANBgNVBAMMBnNlcnZlcjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA +BJ7RQTU/BUv9gfiUI0XPFSFIMauh0MaT8qC3tRe2Bc6py5SDcttt9+rUJlHsZcwp +as7OKzBxuZKUf/eLG1l52T2jSzBJMBoGA1UdEQQTMBGCCWxvY2FsaG9zdIcEfwAA +ATAJBgNVHRMEAjAAMAsGA1UdDwQEAwIFoDATBgNVHSUEDDAKBggrBgEFBQcDATAK +BggqhkjOPQQDAgNIADBFAiEAnYomvCYL2OAu6+fXy8DuFupR/+Hj9n5Qr5S1Ht5X +bb8CIA6Kec9l4YNotFF2jY50uYJvgHnrn24SdIxh8V+cGvTk +-----END CERTIFICATE----- diff --git a/tests/integration/admin/adminStepUp.spec.ts b/tests/integration/admin/adminStepUp.spec.ts index ad7dd745..c328985d 100644 --- a/tests/integration/admin/adminStepUp.spec.ts +++ b/tests/integration/admin/adminStepUp.spec.ts @@ -43,6 +43,10 @@ const GUARDED = [ 'PATCH /admin/permissions/{permissionName}', 'DELETE /admin/permissions/{permissionName}', 'PUT /admin/roles/{kind}/{roleName}/permissions', + 'POST /admin/audit-sinks', + 'PATCH /admin/audit-sinks/{id}', + 'DELETE /admin/audit-sinks/{id}', + 'POST /admin/audit-sinks/{id}/test', 'POST /admin/webhooks', 'PATCH /admin/webhooks/{id}', 'DELETE /admin/webhooks/{id}', diff --git a/tests/integration/admin/auditSinks.spec.ts b/tests/integration/admin/auditSinks.spec.ts new file mode 100644 index 00000000..ec1164f8 --- /dev/null +++ b/tests/integration/admin/auditSinks.spec.ts @@ -0,0 +1,215 @@ +import { Application } from 'express'; +import request from 'supertest'; +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +const { query } = vi.hoisted(() => ({ query: vi.fn() })); + +vi.mock('../../../src/models/index.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, getSequelize: () => ({ query }) }; +}); + +vi.mock('../../../src/lib/auditSinkTransport.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, sendToSink: vi.fn() }; +}); + +import { createApp } from '../../../src/app'; +import { sendToSink } from '../../../src/lib/auditSinkTransport.js'; +import { AuditSink } from '../../../src/models/auditSinks.js'; +import { Session } from '../../../src/models/sessions.js'; +import { AuthEventService } from '../../../src/services/authEventService.js'; +import { buildFreshStepUpSession } from '../../factories/sessionFactory'; + +let app: Application; + +const now = new Date('2026-11-07T12:00:00.000Z'); +const sinkId = '7d0c3e4f-5a6b-4c7d-8e9f-0a1b2c3d4e5f'; + +const otlp = { + kind: 'otlp', + endpoint: 'https://otel.example.com/ingest?token=abc', + headersFromEnv: { 'DD-API-KEY': 'DD_AUDIT_SINK_SECRET' }, + serviceName: 'seamless-auth', +}; + +function buildSink(overrides: Record = {}) { + const record: any = { + id: sinkId, + name: 'SIEM', + kind: 'otlp', + enabled: true, + settings: otlp, + cursorSeq: '40', + failureCount: 0, + nextAttemptAt: null, + lastDeliveredAt: null, + lastFailure: null, + lastFailureAt: null, + createdBy: null, + createdAt: now, + updatedAt: now, + ...overrides, + }; + record.update = vi.fn(async (values: Record) => Object.assign(record, values)); + record.destroy = vi.fn(); + return record; +} + +beforeAll(async () => { + app = await createApp(); +}); + +beforeEach(() => { + vi.clearAllMocks(); + (Session.findOne as any).mockResolvedValue(buildFreshStepUpSession()); + query.mockResolvedValue([{ head: '42', oldest: '1' }]); +}); + +describe('audit sinks', () => { + it('lists sinks with their lag behind the chain head', async () => { + vi.mocked(AuditSink.findAll).mockResolvedValue([buildSink()]); + + const res = await request(app).get('/admin/audit-sinks'); + + expect(res.status).toBe(200); + expect(res.body.sinks[0]).toMatchObject({ + id: sinkId, + settings: { kind: 'otlp' }, + status: { cursorSeq: 40, lagEvents: 2 }, + }); + }); + + it('creates a sink at the chain head and audits it without the query string', async () => { + vi.mocked(AuditSink.create).mockImplementation(async (values: any) => buildSink(values)); + + const res = await request(app) + .post('/admin/audit-sinks') + .send({ name: 'SIEM', settings: otlp }); + + expect(res.status).toBe(201); + expect(res.body.sink.status).toMatchObject({ cursorSeq: 42, lagEvents: 0 }); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'admin_audit_sink_created', + metadata: expect.objectContaining({ + destination: 'https://otel.example.com/ingest', + kind: 'otlp', + cursorSeq: 42, + }), + }), + ); + }); + + it('refuses a destination pointing at the cloud metadata address', async () => { + const res = await request(app) + .post('/admin/audit-sinks') + .send({ name: 'SIEM', settings: { ...otlp, endpoint: 'http://169.254.169.254/' } }); + + expect(res.status).toBe(400); + expect(res.body.error).toContain('never reachable'); + expect(AuditSink.create).not.toHaveBeenCalled(); + }); + + it('refuses plain TCP syslog in production', async () => { + vi.stubEnv('NODE_ENV', 'production'); + + const res = await request(app) + .post('/admin/audit-sinks') + .send({ + name: 'SIEM', + settings: { kind: 'syslog', host: 'collector.example.com', transport: 'tcp' }, + }); + + expect(res.status).toBe(400); + expect(res.body.error).toBe('transport must be tls in production'); + }); + + it('refuses a credential env var outside the _AUDIT_SINK_SECRET names', async () => { + const res = await request(app) + .post('/admin/audit-sinks') + .send({ + name: 'SIEM', + settings: { ...otlp, headersFromEnv: { Authorization: 'SEAMLESS_SERVICE_TOKEN' } }, + }); + + expect(res.status).toBe(400); + expect(AuditSink.create).not.toHaveBeenCalled(); + }); + + it('reads, updates and deletes a sink, auditing each write', async () => { + const record = buildSink(); + vi.mocked(AuditSink.findByPk).mockResolvedValue(record); + + expect((await request(app).get(`/admin/audit-sinks/${sinkId}`)).status).toBe(200); + + const updated = await request(app) + .patch(`/admin/audit-sinks/${sinkId}`) + .send({ + enabled: false, + settings: { kind: 'syslog', host: 'collector.example.com' }, + }); + expect(updated.status).toBe(200); + expect(updated.body.sink).toMatchObject({ + enabled: false, + settings: { kind: 'syslog', port: 6514, transport: 'tls', facility: 10 }, + }); + + const deleted = await request(app).delete(`/admin/audit-sinks/${sinkId}`); + expect(deleted.status).toBe(200); + expect(record.destroy).toHaveBeenCalled(); + + const calls = vi.mocked(AuthEventService.log).mock.calls.map(([options]) => options); + expect(calls.map((options) => options.type)).toEqual([ + 'admin_audit_sink_updated', + 'admin_audit_sink_deleted', + ]); + expect(calls[0].metadata).toMatchObject({ + changed: ['settings', 'enabled'], + destination: 'tls://collector.example.com:6514', + }); + }); + + it('passes an unexpected failure to the error handler', async () => { + vi.mocked(AuditSink.findByPk).mockRejectedValue(new Error('database unavailable')); + + const res = await request(app).get(`/admin/audit-sinks/${sinkId}`); + + expect(res.status).toBe(500); + }); + + it('refuses an empty update', async () => { + const res = await request(app).patch(`/admin/audit-sinks/${sinkId}`).send({}); + + expect(res.status).toBe(400); + }); + + it('answers 404 for a sink that does not exist', async () => { + for (const send of [ + () => request(app).get(`/admin/audit-sinks/${sinkId}`), + () => request(app).patch(`/admin/audit-sinks/${sinkId}`).send({ enabled: true }), + () => request(app).delete(`/admin/audit-sinks/${sinkId}`), + () => request(app).post(`/admin/audit-sinks/${sinkId}/test`), + ]) { + expect((await send()).status).toBe(404); + } + }); + + it('sends a test record and returns the outcome', async () => { + vi.mocked(AuditSink.findByPk).mockResolvedValue(buildSink()); + vi.mocked(sendToSink).mockResolvedValue({ + ok: false, + failure: 'refused', + statusCode: null, + durationMs: 3, + }); + + const res = await request(app).post(`/admin/audit-sinks/${sinkId}/test`); + + expect(res.status).toBe(200); + expect(res.body).toEqual({ ok: false, failure: 'refused', statusCode: null, durationMs: 3 }); + const [, records] = vi.mocked(sendToSink).mock.calls[0]; + expect(records).toHaveLength(1); + expect(records[0].event).toBeNull(); + }); +}); diff --git a/tests/postgres/auditSinks.spec.ts b/tests/postgres/auditSinks.spec.ts new file mode 100644 index 00000000..93f45287 --- /dev/null +++ b/tests/postgres/auditSinks.spec.ts @@ -0,0 +1,271 @@ +import { createHash } from 'node:crypto'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { createServer, type Server } from 'node:http'; +import { + type AddressInfo, + createServer as createTcpServer, + type Server as TcpServer, +} from 'node:net'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import { AuditSink } from '../../src/models/auditSinks.js'; +import { getSequelize, initializeModels } from '../../src/models/index.js'; +import { runAuditRetention } from '../../src/services/auditRetention.js'; +import { createSink, deliverSink } from '../../src/services/auditSinkService.js'; +import { AuthEventService } from '../../src/services/authEventService.js'; + +let http: Server; +let httpPort: number; +let tcp: TcpServer; +let tcpPort: number; +let otlpLines: string[] = []; +let syslogStreams: string[] = []; +let answer = 200; + +beforeAll(async () => { + await initializeModels(); + + http = createServer((req, res) => { + let body = ''; + req.on('data', (chunk) => (body += chunk)); + req.on('end', () => { + if (answer === 200) { + for (const record of JSON.parse(body).resourceLogs[0].scopeLogs[0].logRecords) { + otlpLines.push(record.body.stringValue); + } + } + res.statusCode = answer; + res.end(); + }); + }); + await new Promise((done) => http.listen(0, '127.0.0.1', done)); + httpPort = (http.address() as AddressInfo).port; + + tcp = createTcpServer((socket) => { + let stream = ''; + socket.setEncoding('utf8'); + socket.on('data', (chunk: string) => (stream += chunk)); + socket.on('end', () => { + syslogStreams.push(stream); + socket.end(); + }); + }); + await new Promise((done) => tcp.listen(0, '127.0.0.1', done)); + tcpPort = (tcp.address() as AddressInfo).port; +}); + +beforeEach(async () => { + otlpLines = []; + syslogStreams = []; + answer = 200; + await getSequelize().query('DELETE FROM audit_sinks;'); +}); + +afterAll(async () => { + // A sink left behind would hold retention back in the specs that follow. + await getSequelize().query('DELETE FROM audit_sinks;'); + http.closeAllConnections(); + await new Promise((done) => http.close(() => done())); + await new Promise((done) => tcp.close(() => done())); + await getSequelize().close(); +}); + +async function logEvents(count: number) { + for (let i = 0; i < count; i += 1) { + await AuthEventService.logContext({ + type: 'login_success' as never, + userId: '11111111-1111-4111-8111-111111111111', + userAgent: i === 0 ? 'Mozilla/5.0 (Ünïcødé)' : 'curl/8', + metadata: { i }, + }); + } +} + +function verifyRun(lines: string[]) { + const events = lines.map((line) => JSON.parse(line)); + for (let i = 0; i < events.length; i += 1) { + const { prevHash, payload, hash, seq } = events[i]; + expect( + createHash('sha256') + .update(`${prevHash ?? ''}${payload}`, 'utf8') + .digest('hex'), + ).toBe(hash); + if (i > 0) { + expect(prevHash).toBe(events[i - 1].hash); + expect(seq).toBe(events[i - 1].seq + 1); + } + } + return events; +} + +function messagesFrom(stream: string) { + const bytes = Buffer.from(stream, 'utf8'); + const messages: string[] = []; + let offset = 0; + while (offset < bytes.length) { + const space = bytes.indexOf(0x20, offset); + const length = Number(bytes.subarray(offset, space).toString('ascii')); + messages.push(bytes.subarray(space + 1, space + 1 + length).toString('utf8')); + offset = space + 1 + length; + } + return messages; +} + +describe('audit sinks against the chain', () => { + it('streams new events to an OTLP collector in order, and the chain verifies', async () => { + await logEvents(2); + const sink = await createSink( + { + name: 'collector', + enabled: true, + settings: { + kind: 'otlp', + endpoint: `http://127.0.0.1:${httpPort}`, + headersFromEnv: {}, + serviceName: 'seamless-auth', + }, + }, + null, + ); + const start = Number(sink.cursorSeq); + + // History before the sink existed is not sent. + expect(await deliverSink(sink.id)).toBe(0); + + await logEvents(3); + answer = 503; + expect(await deliverSink(sink.id)).toBe(0); + await sink.reload(); + expect(Number(sink.cursorSeq)).toBe(start); + expect(sink.lastFailure).toBe('http_status'); + + answer = 200; + await sink.update({ nextAttemptAt: null }); + expect(await deliverSink(sink.id)).toBe(3); + + const events = verifyRun(otlpLines); + expect(events.map((event) => event.seq)).toEqual([start + 1, start + 2, start + 3]); + + await sink.reload(); + expect(Number(sink.cursorSeq)).toBe(start + 3); + expect(sink).toMatchObject({ failureCount: 0, nextAttemptAt: null }); + expect(sink.lastDeliveredAt).toBeInstanceOf(Date); + expect(await deliverSink(sink.id)).toBe(0); + }); + + it('replays from startAfterSeq to a syslog collector', async () => { + await logEvents(3); + const [{ head }] = await getSequelize().query<{ head: string }>( + 'SELECT seq AS head FROM auth_event_chain_head WHERE id = 1', + { type: 'SELECT' as never }, + ); + const sink = await createSink( + { + name: 'syslog', + enabled: true, + startAfterSeq: Number(head) - 3, + settings: { + kind: 'syslog', + host: '127.0.0.1', + port: tcpPort, + transport: 'tcp', + appName: 'seamless-auth', + facility: 10, + }, + }, + null, + ); + + expect(await deliverSink(sink.id)).toBe(3); + + const messages = messagesFrom(syslogStreams[0]); + const lines = messages.map((message) => message.slice(message.indexOf('] ') + 2)); + const events = verifyRun(lines); + expect(events.map((event) => event.seq)).toEqual([ + Number(head) - 2, + Number(head) - 1, + Number(head), + ]); + expect(messages[0]).toContain(`seq="${Number(head) - 2}" hash="${events[0].hash}"`); + + await sink.reload(); + expect(Number(sink.cursorSeq)).toBe(Number(head)); + }); + + it('holds back a second replica while one sends', async () => { + await logEvents(1); + const sink = await createSink( + { + name: 'collector', + enabled: true, + settings: { + kind: 'otlp', + endpoint: `http://127.0.0.1:${httpPort}`, + headersFromEnv: {}, + serviceName: 'seamless-auth', + }, + }, + null, + ); + await logEvents(1); + + const sequelize = getSequelize(); + await sequelize.transaction(async (transaction) => { + await sequelize.query('SELECT pg_advisory_xact_lock(72641003, hashtext(:id))', { + replacements: { id: sink.id }, + transaction, + }); + expect(await deliverSink(sink.id)).toBe(0); + }); + + expect(await AuditSink.count()).toBe(1); + expect(otlpLines).toHaveLength(0); + }); + + it('keeps retention from deleting what a sink has yet to send', async () => { + await logEvents(4); + const sink = await createSink( + { + name: 'behind', + enabled: false, + settings: { + kind: 'otlp', + endpoint: `http://127.0.0.1:${httpPort}`, + headersFromEnv: {}, + serviceName: 'seamless-auth', + }, + }, + null, + ); + const cursor = Number(sink.cursorSeq) - 2; + await sink.update({ cursorSeq: String(cursor) }); + await logEvents(1); + const archiveDir = await mkdtemp(join(tmpdir(), 'audit-archive-')); + + try { + await runAuditRetention( + { retentionDays: 1, archiveDir }, + new Date(Date.now() + 10 * 24 * 60 * 60 * 1000), + ); + + const [{ oldest }] = await getSequelize().query<{ oldest: string }>( + 'SELECT min(seq) AS oldest FROM auth_events', + { type: 'SELECT' as never }, + ); + expect(Number(oldest)).toBe(cursor + 1); + } finally { + await rm(archiveDir, { recursive: true, force: true }); + } + + await sink.update({ enabled: true }); + expect(await deliverSink(sink.id)).toBe(3); + expect(verifyRun(otlpLines).map((event) => event.seq)).toEqual([ + cursor + 1, + cursor + 2, + cursor + 3, + ]); + }); +}); diff --git a/tests/setup/mocks.ts b/tests/setup/mocks.ts index 23b647e2..c0fe13a6 100644 --- a/tests/setup/mocks.ts +++ b/tests/setup/mocks.ts @@ -193,6 +193,14 @@ vi.mock('../../src/models/permissions.js', () => ({ }, })); +vi.mock('../../src/models/auditSinks.js', () => ({ + AuditSink: { + create: vi.fn(), + findAll: vi.fn(async () => []), + findByPk: vi.fn(async () => null), + }, +})); + vi.mock('../../src/models/webhookEndpoints.js', () => ({ WebhookEndpoint: { create: vi.fn(), diff --git a/tests/unit/lib/auditSinkTransport.spec.ts b/tests/unit/lib/auditSinkTransport.spec.ts new file mode 100644 index 00000000..c71180fb --- /dev/null +++ b/tests/unit/lib/auditSinkTransport.spec.ts @@ -0,0 +1,569 @@ +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { createServer as createHttpServer, type IncomingHttpHeaders, type Server } from 'node:http'; +import { + createServer as createTcpServer, + type AddressInfo, + type Server as TcpServer, +} from 'node:net'; +import { join } from 'node:path'; +import { createServer as createTlsServer, type TLSSocket } from 'node:tls'; + +import type { OtlpSinkSettings, SyslogSinkSettings } from '@seamless-auth/types'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { + eventRecord, + octetFrame, + otlpLogsBody, + otlpLogsUrl, + sendToSink, + sinkDestinationProblem, + SYSLOG_SD_ID, + syslogMessage, + testRecord, +} from '../../../src/lib/auditSinkTransport.js'; +import { exportLine, type ExportedAuthEvent } from '../../../src/services/auditExport.js'; + +const fixtures = join(__dirname, '../../fixtures/auditSinkTls'); +const pem = (name: string) => readFileSync(join(fixtures, name), 'utf8'); + +function sha256(text: string) { + return createHash('sha256').update(text, 'utf8').digest('hex'); +} + +/** A run of the chain built the way the database builds it. */ +function chain(count: number, firstSeq = 1, anchor: string | null = null): ExportedAuthEvent[] { + const events: ExportedAuthEvent[] = []; + let prevHash = anchor; + for (let i = 0; i < count; i += 1) { + const seq = firstSeq + i; + const createdAt = new Date(Date.UTC(2026, 10, 7, 12, 0, i)).toISOString(); + const type = i === 1 ? 'login_suspicious' : 'login_success'; + const userAgent = i === 2 ? 'Mozilla/5.0 (Ünïcødé ✓)' : 'curl/8'; + const payload = JSON.stringify([ + seq, + `id-${seq}`, + 'user-1', + null, + 'session-1', + type, + userAgent, + ]); + const hash = sha256((prevHash ?? '') + payload); + events.push({ + seq, + id: `id-${seq}`, + createdAt, + type, + userId: 'user-1', + actorUserId: i === 0 ? 'admin-1' : null, + sessionId: 'session-1', + attemptId: null, + ipAddress: '203.0.113.9', + userAgent, + deploymentId: null, + deviceClass: null, + mailProvider: null, + owner: null, + metadata: { method: 'passkey' }, + prevHash, + hash, + payload, + }); + prevHash = hash; + } + return events; +} + +/** What a downstream verifier does with the lines it received. */ +function verifies(lines: string[], anchor: string | null = null) { + let prev = anchor; + for (const line of lines) { + const event = JSON.parse(line) as ExportedAuthEvent; + if (event.prevHash !== prev) return false; + if (sha256((event.prevHash ?? '') + event.payload) !== event.hash) return false; + prev = event.hash; + } + return true; +} + +type Received = { url: string; method: string; headers: IncomingHttpHeaders; body: string }; + +let httpServer: Server; +let httpPort: number; +let received: Received[]; +let answer: { status: number; headers?: Record }; + +beforeEach(async () => { + received = []; + answer = { status: 200 }; + httpServer = createHttpServer((req, res) => { + let body = ''; + req.on('data', (chunk) => (body += chunk)); + req.on('end', () => { + received.push({ url: req.url ?? '', method: req.method ?? '', headers: req.headers, body }); + res.writeHead(answer.status, answer.headers ?? {}); + res.end('{}'); + }); + }); + await new Promise((done) => httpServer.listen(0, '127.0.0.1', done)); + httpPort = (httpServer.address() as AddressInfo).port; +}); + +afterEach(async () => { + httpServer.closeAllConnections(); + await new Promise((done) => httpServer.close(() => done())); +}); + +function otlp(overrides: Partial = {}): OtlpSinkSettings { + return { + kind: 'otlp', + endpoint: `http://127.0.0.1:${httpPort}/collector/`, + headersFromEnv: {}, + serviceName: 'seamless-auth', + ...overrides, + }; +} + +function syslog(port: number, overrides: Partial = {}): SyslogSinkSettings { + return { + kind: 'syslog', + host: '127.0.0.1', + port, + transport: 'tcp', + appName: 'seamless-auth', + facility: 10, + ...overrides, + }; +} + +describe('OTLP', () => { + it('posts one log record per event to /v1/logs, the export line as the body', async () => { + const events = chain(3); + + const attempt = await sendToSink( + otlp({ serviceName: 'auth-prod' }), + events.map(eventRecord), + {}, + ); + + expect(attempt).toMatchObject({ ok: true, statusCode: 200, failure: null }); + expect(received).toHaveLength(1); + const [request] = received; + expect(request.method).toBe('POST'); + expect(request.url).toBe('/collector/v1/logs'); + expect(request.headers['content-type']).toBe('application/json'); + + const body = JSON.parse(request.body); + const [resourceLogs] = body.resourceLogs; + expect(resourceLogs.resource.attributes).toEqual([ + { key: 'service.name', value: { stringValue: 'auth-prod' } }, + ]); + const [scopeLogs] = resourceLogs.scopeLogs; + expect(scopeLogs.scope.name).toBe('seamless-auth.audit'); + + const lines = scopeLogs.logRecords.map( + (record: { body: { stringValue: string } }) => record.body.stringValue, + ); + // Exactly the export's line, so the chain verifies from what the collector stored. + expect(lines).toEqual(events.map(exportLine)); + expect(verifies(lines)).toBe(true); + + const [first, second] = scopeLogs.logRecords; + expect(first.timeUnixNano).toBe(`${Date.parse(events[0].createdAt)}000000`); + expect(first.severityNumber).toBe(9); + expect(second.severityNumber).toBe(13); + expect(second.severityText).toBe('WARN'); + const attributes = Object.fromEntries( + first.attributes.map((entry: { key: string; value: unknown }) => [entry.key, entry.value]), + ); + expect(attributes).toEqual({ + 'seamless.audit.seq': { intValue: '1' }, + 'seamless.audit.id': { stringValue: 'id-1' }, + 'seamless.audit.type': { stringValue: 'login_success' }, + 'seamless.audit.hash': { stringValue: events[0].hash }, + 'user.id': { stringValue: 'user-1' }, + 'seamless.audit.actor_user_id': { stringValue: 'admin-1' }, + 'session.id': { stringValue: 'session-1' }, + }); + expect(second.attributes).toContainEqual({ + key: 'seamless.audit.prev_hash', + value: { stringValue: events[0].hash }, + }); + }); + + it('builds the logs URL without doubling slashes and keeps a query string', () => { + expect(otlpLogsUrl('https://otel.example.com')).toBe('https://otel.example.com/v1/logs'); + expect(otlpLogsUrl('https://otel.example.com/a//?tenant=1')).toBe( + 'https://otel.example.com/a/v1/logs?tenant=1', + ); + }); + + it('reads headers from their env vars at send time', async () => { + await sendToSink( + otlp({ headersFromEnv: { 'DD-API-KEY': 'DD_AUDIT_SINK_SECRET' } }), + chain(1).map(eventRecord), + { DD_AUDIT_SINK_SECRET: 'key-1' }, + ); + + expect(received[0].headers['dd-api-key']).toBe('key-1'); + }); + + it('refuses to send when a header env var is missing or empty, rather than send it empty', async () => { + const settings = otlp({ headersFromEnv: { Authorization: 'OTEL_AUDIT_SINK_SECRET' } }); + + for (const env of [{}, { OTEL_AUDIT_SINK_SECRET: '' }]) { + const attempt = await sendToSink(settings, chain(1).map(eventRecord), env); + expect(attempt).toMatchObject({ ok: false, failure: 'refused', statusCode: null }); + } + expect(received).toHaveLength(0); + }); + + it('refuses a header env var outside the _AUDIT_SINK_SECRET names', async () => { + const attempt = await sendToSink( + otlp({ headersFromEnv: { Authorization: 'SEAMLESS_SERVICE_TOKEN' } }), + chain(1).map(eventRecord), + { SEAMLESS_SERVICE_TOKEN: 'the-service-token' }, + ); + + expect(attempt.failure).toBe('refused'); + expect(received).toHaveLength(0); + }); + + it('refuses a header value that would split the request', async () => { + const attempt = await sendToSink( + otlp({ headersFromEnv: { Authorization: 'OTEL_AUDIT_SINK_SECRET' } }), + chain(1).map(eventRecord), + { OTEL_AUDIT_SINK_SECRET: 'a\r\nx-injected: 1' }, + ); + + expect(attempt.failure).toBe('refused'); + expect(received).toHaveLength(0); + }); + + it('treats a non-2xx, including a redirect, as a failure', async () => { + answer = { status: 503 }; + expect(await sendToSink(otlp(), chain(1).map(eventRecord), {})).toMatchObject({ + ok: false, + statusCode: 503, + failure: 'http_status', + }); + + answer = { status: 307, headers: { location: 'http://169.254.169.254/' } }; + expect(await sendToSink(otlp(), chain(1).map(eventRecord), {})).toMatchObject({ + ok: false, + statusCode: 307, + }); + expect(received).toHaveLength(2); + }); + + it('refuses a private destination in production unless the operator lists the host', async () => { + const env = { NODE_ENV: 'production' }; + const settings = otlp({ endpoint: `https://127.0.0.1:${httpPort}/` }); + + expect(sinkDestinationProblem(settings, env)).toContain('non-public'); + expect(await sendToSink(settings, chain(1).map(eventRecord), env)).toMatchObject({ + ok: false, + failure: 'refused', + }); + expect(sinkDestinationProblem(settings, { ...env, CALLOUT_PRIVATE_HOSTS: '127.0.0.1' })).toBe( + null, + ); + }); + + it('refuses plain http in production', () => { + expect( + sinkDestinationProblem(otlp({ endpoint: 'http://otel.example.com' }), { + NODE_ENV: 'production', + }), + ).toBe('endpoint must use https'); + }); + + it('never reaches a link-local address, in any mode', async () => { + const settings = otlp({ endpoint: 'http://169.254.169.254/' }); + + expect(sinkDestinationProblem(settings, {})).toContain('never reachable'); + expect((await sendToSink(settings, chain(1).map(eventRecord), {})).failure).toBe('refused'); + }); + + it('marks the test record and keeps it out of the chain', () => { + const body = JSON.parse(otlpLogsBody([testRecord('sink-1')], 'seamless-auth')); + const [record] = body.resourceLogs[0].scopeLogs[0].logRecords; + + expect(JSON.parse(record.body.stringValue)).toMatchObject({ type: 'test', test: true }); + expect(record.body.stringValue).not.toContain('"hash"'); + expect(record.attributes).toEqual([{ key: 'seamless.audit.test', value: { boolValue: true } }]); + }); +}); + +/** Splits an octet-counted stream into messages, failing on anything that is not a frame. */ +function unframe(stream: Buffer): string[] { + const messages: string[] = []; + let offset = 0; + while (offset < stream.length) { + const space = stream.indexOf(0x20, offset); + const length = Number(stream.subarray(offset, space).toString('ascii')); + if (!Number.isInteger(length) || length <= 0) throw new Error('not octet counted'); + messages.push(stream.subarray(space + 1, space + 1 + length).toString('utf8')); + offset = space + 1 + length; + } + return messages; +} + +const RFC5424 = + /^<(\d{1,3})>1 (\S+) (\S+) (\S+) - (\S+) (\[[^ ]+(?: [a-z]+="(?:[^"\\\]]|\\["\\\]])*")*\]) (.*)$/s; + +describe('syslog', () => { + let tcp: TcpServer; + let streams: Promise[]; + + function collect(socket: NodeJS.ReadableStream) { + streams.push( + new Promise((done) => { + const chunks: Buffer[] = []; + socket.on('data', (chunk: Buffer) => chunks.push(chunk)); + socket.on('end', () => done(Buffer.concat(chunks))); + }), + ); + } + + async function listen(server: TcpServer) { + await new Promise((done) => server.listen(0, '127.0.0.1', done)); + return (server.address() as AddressInfo).port; + } + + beforeEach(() => { + streams = []; + }); + + afterEach(async () => { + if (tcp?.listening) await new Promise((done) => tcp.close(() => done())); + }); + + it('frames RFC 5424 messages with octet counting, the export line as MSG', async () => { + tcp = createTcpServer((socket) => { + collect(socket); + socket.on('end', () => socket.end()); + }); + const port = await listen(tcp); + const events = chain(3); + + const attempt = await sendToSink(syslog(port), events.map(eventRecord), {}); + expect(attempt).toMatchObject({ ok: true, failure: null, statusCode: null }); + + const messages = unframe(await streams[0]); + expect(messages).toHaveLength(3); + + const parsed = messages.map((message) => { + const match = RFC5424.exec(message); + if (!match) throw new Error(`not RFC 5424: ${message}`); + const [, pri, timestamp, , appName, msgId, sd, msg] = match; + return { pri: Number(pri), timestamp, appName, msgId, sd, msg }; + }); + + // authpriv (10) * 8 + informational (6), and warning (4) for a suspicious event. + expect(parsed.map((entry) => entry.pri)).toEqual([86, 84, 86]); + expect(parsed[0]).toMatchObject({ + timestamp: events[0].createdAt, + appName: 'seamless-auth', + msgId: 'audit', + sd: `[${SYSLOG_SD_ID} seq="1" hash="${events[0].hash}"]`, + }); + const lines = parsed.map((entry) => entry.msg); + expect(lines).toEqual(events.map(exportLine)); + expect(verifies(lines)).toBe(true); + }); + + it('counts octets, not characters, so a non-ASCII line frames correctly', () => { + const message = syslogMessage(eventRecord(chain(3)[2]), syslog(1), 'host'); + const frame = octetFrame(message); + + expect(frame.startsWith(`${Buffer.byteLength(message, 'utf8')} `)).toBe(true); + expect(Buffer.byteLength(message, 'utf8')).toBeGreaterThan(message.length); + expect(unframe(Buffer.from(frame, 'utf8'))).toEqual([message]); + }); + + it('marks the test record with its own MSGID and no chain fields', () => { + const message = syslogMessage(testRecord('sink-1'), syslog(1), 'host'); + + expect(message).toMatch(/^<86>1 \S+ host seamless-auth - test \[seamless@32473 test="true"\] /); + expect(message).not.toContain('seq='); + }); + + it('refuses plain TCP in production, before connecting', async () => { + let connected = false; + tcp = createTcpServer(() => (connected = true)); + const port = await listen(tcp); + const env = { NODE_ENV: 'production', CALLOUT_PRIVATE_HOSTS: '127.0.0.1' }; + + expect(sinkDestinationProblem(syslog(port), env)).toBe('transport must be tls in production'); + expect((await sendToSink(syslog(port), chain(1).map(eventRecord), env)).failure).toBe( + 'refused', + ); + expect(connected).toBe(false); + }); + + it('refuses a private or link-local host in production', async () => { + const env = { NODE_ENV: 'production' }; + + expect(sinkDestinationProblem(syslog(6514, { transport: 'tls' }), env)).toContain('non-public'); + expect( + sinkDestinationProblem(syslog(6514, { host: '169.254.169.254', transport: 'tls' }), {}), + ).toContain('never reachable'); + expect( + ( + await sendToSink( + syslog(6514, { host: 'fe80::1', transport: 'tls' }), + chain(1).map(eventRecord), + {}, + ) + ).failure, + ).toBe('refused'); + }); + + it('refuses a host that is not a host name, and a client cert without its key', () => { + expect(sinkDestinationProblem(syslog(1, { host: 'collector.example.com:6514' }), {})).toBe( + 'host is not a host name', + ); + expect( + sinkDestinationProblem( + syslog(1, { host: 'collector.example.com', tlsClientCertEnv: 'CERT_AUDIT_SINK_SECRET' }), + {}, + ), + ).toBe('tlsClientCertEnv and tlsClientKeyEnv must be set together'); + }); + + it('checks DNS answers at connect time', async () => { + const attempt = await sendToSink( + syslog(6514, { host: 'localhost', transport: 'tls' }), + chain(1).map(eventRecord), + { NODE_ENV: 'production' }, + ); + + expect(attempt.failure).toBe('refused'); + }); + + it('fails a send the collector hangs up on before it is written', async () => { + tcp = createTcpServer((socket) => socket.destroy()); + const port = await listen(tcp); + + expect( + (await sendToSink(syslog(port, { transport: 'tls' }), chain(1).map(eventRecord), {})).failure, + ).toBe('connection_failed'); + }); + + it('reports a refused connection coarsely', async () => { + tcp = createTcpServer(); + const port = await listen(tcp); + await new Promise((done) => tcp.close(() => done())); + + expect((await sendToSink(syslog(port), chain(1).map(eventRecord), {})).failure).toBe( + 'connection_failed', + ); + }); + + describe('over TLS', () => { + const env = { + CA_AUDIT_SINK_SECRET: pem('ca.pem'), + CERT_AUDIT_SINK_SECRET: pem('client.pem'), + KEY_AUDIT_SINK_SECRET: pem('client.key'), + }; + + async function tlsServer(requestCert: boolean) { + const peers: (string | null)[] = []; + tcp = createTlsServer( + { + cert: pem('server.pem'), + key: pem('server.key'), + ca: pem('ca.pem'), + requestCert, + rejectUnauthorized: requestCert, + }, + (socket: TLSSocket) => { + peers.push(socket.getPeerCertificate()?.subject?.CN ?? null); + collect(socket); + socket.on('end', () => socket.end()); + }, + ); + const port = await listen(tcp); + return { port, peers }; + } + + it('verifies the collector against the configured CA and checks the name', async () => { + const { port } = await tlsServer(false); + const events = chain(2); + + const attempt = await sendToSink( + syslog(port, { host: 'localhost', transport: 'tls', tlsCaEnv: 'CA_AUDIT_SINK_SECRET' }), + events.map(eventRecord), + env, + ); + + expect(attempt).toMatchObject({ ok: true, failure: null }); + const lines = unframe(await streams[0]).map((message) => RFC5424.exec(message)?.[7]); + expect(lines).toEqual(events.map(exportLine)); + }); + + it('presents a client certificate from env vars', async () => { + const { port, peers } = await tlsServer(true); + + const attempt = await sendToSink( + syslog(port, { + host: 'localhost', + transport: 'tls', + tlsCaEnv: 'CA_AUDIT_SINK_SECRET', + tlsClientCertEnv: 'CERT_AUDIT_SINK_SECRET', + tlsClientKeyEnv: 'KEY_AUDIT_SINK_SECRET', + }), + chain(1).map(eventRecord), + env, + ); + + expect(attempt.ok).toBe(true); + await streams[0]; + expect(peers).toEqual(['client']); + }); + + it('fails a collector whose certificate is not trusted', async () => { + const { port } = await tlsServer(false); + + const attempt = await sendToSink( + syslog(port, { host: 'localhost', transport: 'tls' }), + chain(1).map(eventRecord), + {}, + ); + + expect(attempt).toMatchObject({ ok: false, failure: 'connection_failed' }); + }); + + it('refuses to connect when a named CA env var is unset', async () => { + const { port } = await tlsServer(false); + + const attempt = await sendToSink( + syslog(port, { host: 'localhost', transport: 'tls', tlsCaEnv: 'CA_AUDIT_SINK_SECRET' }), + chain(1).map(eventRecord), + {}, + ); + + expect(attempt.failure).toBe('refused'); + expect(streams).toHaveLength(0); + }); + + it('times out a collector that never completes the handshake', async () => { + tcp = createTcpServer(() => {}); + const port = await listen(tcp); + + const attempt = await sendToSink( + syslog(port, { transport: 'tls' }), + chain(1).map(eventRecord), + {}, + 200, + ); + + expect(attempt.failure).toBe('timed_out'); + tcp.close(); + await new Promise((done) => setImmediate(done)); + }); + }); +}); diff --git a/tests/unit/models/models.spec.ts b/tests/unit/models/models.spec.ts index 8d90dbc3..6140de18 100644 --- a/tests/unit/models/models.spec.ts +++ b/tests/unit/models/models.spec.ts @@ -1,5 +1,6 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; +vi.unmock('../../../src/models/auditSinks.js'); vi.unmock('../../../src/models/authEvents.js'); vi.unmock('../../../src/models/authFailures.js'); vi.unmock('../../../src/models/sessions.js'); diff --git a/tests/unit/services/auditRetention.spec.ts b/tests/unit/services/auditRetention.spec.ts index 12f49cd6..82e4eb6c 100644 --- a/tests/unit/services/auditRetention.spec.ts +++ b/tests/unit/services/auditRetention.spec.ts @@ -123,6 +123,36 @@ describe('runAuditRetention', () => { expect(query).not.toHaveBeenCalledWith(expect.stringContaining('DELETE'), expect.anything()); }); + it('never deletes past the oldest audit sink cursor', async () => { + respondTo({ + pg_try_advisory_xact_lock: [{ locked: true }], + 'AS max_seq': [{ max_seq: '3' }], + audit_sinks: [{ held: '2' }], + }); + vi.mocked(readExportBatch).mockResolvedValueOnce([event(1), event(2)]); + + await runAuditRetention({ retentionDays: 30, archiveDir }, new Date('2026-06-01T00:00:00Z')); + + expect(readExportBatch).toHaveBeenCalledWith(expect.objectContaining({ maxSeq: 2 })); + expect(query).toHaveBeenCalledWith('DELETE FROM public.auth_events WHERE seq <= :lastSeq', { + replacements: { lastSeq: 2 }, + transaction: expect.anything(), + }); + }); + + it('deletes nothing while a sink has sent no event at all', async () => { + respondTo({ + pg_try_advisory_xact_lock: [{ locked: true }], + 'AS max_seq': [{ max_seq: '3' }], + audit_sinks: [{ held: '0' }], + }); + + await runAuditRetention({ retentionDays: 30, archiveDir }, new Date('2026-06-01T00:00:00Z')); + + expect(readExportBatch).not.toHaveBeenCalled(); + expect(query).not.toHaveBeenCalledWith(expect.stringContaining('DELETE'), expect.anything()); + }); + it('archives a batch to disk, then deletes exactly that batch', async () => { respondTo({ pg_try_advisory_xact_lock: [{ locked: true }], @@ -257,10 +287,18 @@ describe('separate retention connection', () => { retentionQuery.mockImplementation(async (sql: string) => sql.includes('pg_try_advisory_xact_lock') ? [{ locked: true }] : [{ max_seq: null }], ); + query.mockResolvedValue([{ held: null }]); await runAuditRetention({ retentionDays: 30, archiveDir }); await runAuditRetention({ retentionDays: 30, archiveDir }); + // The sinks' hold is read as the application, since the retention role need not see them. + expect(query).toHaveBeenCalledWith(expect.stringContaining('audit_sinks'), expect.anything()); + expect(retentionQuery).not.toHaveBeenCalledWith( + expect.stringContaining('audit_sinks'), + expect.anything(), + ); + expect(SequelizeMock).toHaveBeenCalledTimes(1); expect(SequelizeMock).toHaveBeenCalledWith( 'postgres://retention:secret@db.internal:5432/seamless', diff --git a/tests/unit/services/auditSinkService.spec.ts b/tests/unit/services/auditSinkService.spec.ts new file mode 100644 index 00000000..818e6868 --- /dev/null +++ b/tests/unit/services/auditSinkService.spec.ts @@ -0,0 +1,441 @@ +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const { query, transaction } = vi.hoisted(() => { + const query = vi.fn(); + const transaction = vi.fn(async (fn: (t: unknown) => unknown) => fn({ id: 'tx' })); + return { query, transaction }; +}); + +vi.mock('../../../src/models/index.js', () => ({ + getSequelize: () => ({ query, transaction }), +})); + +vi.mock('../../../src/services/auditExport.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, readExportBatch: vi.fn() }; +}); + +import { AuditSink } from '../../../src/models/auditSinks.js'; +import { + AuditSinkError, + backoffMs, + chainHead, + createSink, + deleteSink, + deliverSink, + getSink, + listSinks, + runAuditSinkTick, + SINK_BATCH, + sendSinkTest, + serializeSink, + startAuditSinkDelivery, + updateSink, +} from '../../../src/services/auditSinkService.js'; +import { exportLine, readExportBatch } from '../../../src/services/auditExport.js'; + +const at = new Date('2026-11-07T12:00:00.000Z'); + +let server: Server; +let port: number; +let bodies: string[]; +let status: number; + +beforeEach(async () => { + bodies = []; + status = 200; + transaction.mockImplementation(async (fn: (t: unknown) => unknown) => fn({ id: 'tx' })); + server = createServer((req, res) => { + let body = ''; + req.on('data', (chunk) => (body += chunk)); + req.on('end', () => { + bodies.push(body); + res.statusCode = status; + res.end(); + }); + }); + await new Promise((done) => server.listen(0, '127.0.0.1', done)); + port = (server.address() as AddressInfo).port; +}); + +afterEach(async () => { + vi.useRealTimers(); + server.closeAllConnections(); + await new Promise((done) => server.close(() => done())); +}); + +function settings() { + return { + kind: 'otlp' as const, + endpoint: `http://127.0.0.1:${port}`, + headersFromEnv: {}, + serviceName: 'seamless-auth', + }; +} + +function sink(overrides: Record = {}) { + const record: any = { + id: 'sink-1', + name: 'SIEM', + kind: 'otlp', + enabled: true, + settings: settings(), + cursorSeq: '10', + failureCount: 0, + nextAttemptAt: null, + lastDeliveredAt: null, + lastFailure: null, + lastFailureAt: null, + createdBy: null, + createdAt: at, + updatedAt: at, + ...overrides, + }; + record.update = vi.fn(async (changes: Record) => Object.assign(record, changes)); + record.destroy = vi.fn(); + return record; +} + +function event(seq: number) { + return { + seq, + id: `id-${seq}`, + createdAt: at.toISOString(), + type: 'login_success', + userId: null, + actorUserId: null, + sessionId: null, + attemptId: null, + ipAddress: null, + userAgent: null, + deploymentId: null, + deviceClass: null, + mailProvider: null, + owner: null, + metadata: null, + prevHash: null, + hash: 'a'.repeat(64), + payload: `[${seq}]`, + }; +} + +function bounds(head: string | null, oldest: string | null) { + query.mockImplementation(async (sql: string) => + sql.includes('pg_try_advisory_xact_lock') ? [{ locked: true }] : [{ head, oldest }], + ); +} + +function sentLines() { + return bodies.flatMap((body) => + JSON.parse(body).resourceLogs[0].scopeLogs[0].logRecords.map( + (record: { body: { stringValue: string } }) => record.body.stringValue, + ), + ); +} + +describe('sinks', () => { + it('starts a new sink after the newest event', async () => { + bounds('42', '1'); + vi.mocked(AuditSink.create).mockImplementation(async (values: any) => sink(values)); + + const created = await createSink( + { name: 'SIEM', settings: settings(), enabled: true }, + 'admin-1', + ); + + expect(vi.mocked(AuditSink.create).mock.calls[0][0]).toMatchObject({ + kind: 'otlp', + cursorSeq: '42', + enabled: true, + createdBy: 'admin-1', + }); + expect(created.cursorSeq).toBe('42'); + }); + + it('replays from startAfterSeq, but not from before what retention kept or past the head', async () => { + bounds('42', '20'); + vi.mocked(AuditSink.create).mockImplementation(async (values: any) => sink(values)); + + await createSink( + { name: 'SIEM', settings: settings(), enabled: true, startAfterSeq: 19 }, + null, + ); + expect(vi.mocked(AuditSink.create).mock.calls[0][0]).toMatchObject({ cursorSeq: '19' }); + + await expect( + createSink({ name: 'SIEM', settings: settings(), enabled: true, startAfterSeq: 18 }, null), + ).rejects.toMatchObject({ status: 400, message: expect.stringContaining('retention') }); + await expect( + createSink({ name: 'SIEM', settings: settings(), enabled: true, startAfterSeq: 43 }, null), + ).rejects.toMatchObject({ status: 400 }); + }); + + it('treats an empty chain as starting at zero', async () => { + query.mockResolvedValue([{ head: null, oldest: null }]); + vi.mocked(AuditSink.create).mockImplementation(async (values: any) => sink(values)); + + await createSink({ name: 'SIEM', settings: settings(), startAfterSeq: 0 } as never, null); + + expect(vi.mocked(AuditSink.create).mock.calls[0][0]).toMatchObject({ + cursorSeq: '0', + enabled: true, + }); + expect(await chainHead()).toBe(0); + }); + + it('refuses a destination no callout may reach', async () => { + await expect( + createSink( + { name: 'SIEM', settings: { ...settings(), endpoint: 'http://169.254.169.254' } }, + null, + ), + ).rejects.toBeInstanceOf(AuditSinkError); + expect(AuditSink.create).not.toHaveBeenCalled(); + }); + + it('lists, reads and deletes, and answers 404 for a missing sink', async () => { + const record = sink(); + vi.mocked(AuditSink.findAll).mockResolvedValue([record]); + vi.mocked(AuditSink.findByPk).mockResolvedValueOnce(record).mockResolvedValueOnce(record); + + expect(await listSinks()).toEqual([record]); + expect(await getSink('sink-1')).toBe(record); + expect(await deleteSink('sink-1')).toBe(record); + expect(record.destroy).toHaveBeenCalled(); + + vi.mocked(AuditSink.findByPk).mockResolvedValue(null); + await expect(getSink('missing')).rejects.toMatchObject({ status: 404 }); + }); + + it('updates fields and clears the backoff, keeping the cursor', async () => { + const record = sink({ failureCount: 4, nextAttemptAt: new Date(Date.now() + 60_000) }); + vi.mocked(AuditSink.findByPk).mockResolvedValue(record); + + await updateSink('sink-1', { name: 'Renamed' }); + await updateSink('sink-1', { + settings: { + kind: 'syslog', + host: 'collector.example.com', + port: 6514, + transport: 'tls', + appName: 'seamless-auth', + facility: 10, + }, + enabled: false, + }); + + expect(record).toMatchObject({ + name: 'Renamed', + kind: 'syslog', + enabled: false, + cursorSeq: '10', + failureCount: 0, + nextAttemptAt: null, + }); + }); + + it('refuses an update to an unreachable destination', async () => { + vi.mocked(AuditSink.findByPk).mockResolvedValue(sink()); + + await expect( + updateSink('sink-1', { settings: { ...settings(), endpoint: 'http://[fe80::1]/' } }), + ).rejects.toMatchObject({ status: 400 }); + }); + + it('reports lag against the chain head', () => { + const serialized = serializeSink( + sink({ lastDeliveredAt: at, lastFailure: 'timed_out', lastFailureAt: at }), + 15, + ); + + expect(serialized.status).toEqual({ + cursorSeq: 10, + lagEvents: 5, + lastDeliveredAt: at.toISOString(), + lastFailure: 'timed_out', + lastFailureAt: at.toISOString(), + }); + expect(serializeSink(sink({ cursorSeq: '20' }), 15).status).toMatchObject({ + lagEvents: 0, + lastDeliveredAt: null, + lastFailure: null, + lastFailureAt: null, + }); + }); +}); + +describe('the test record', () => { + it('is sent once, outside the chain, and moves nothing', async () => { + const record = sink(); + vi.mocked(AuditSink.findByPk).mockResolvedValue(record); + + const result = await sendSinkTest('sink-1'); + + expect(result).toMatchObject({ ok: true, failure: null, statusCode: 200 }); + const [line] = sentLines(); + expect(JSON.parse(line)).toMatchObject({ type: 'test', test: true, sinkId: 'sink-1' }); + expect(record.update).not.toHaveBeenCalled(); + expect(record.cursorSeq).toBe('10'); + }); + + it('reports a failure without recording it on the sink', async () => { + status = 500; + const record = sink(); + vi.mocked(AuditSink.findByPk).mockResolvedValue(record); + + expect(await sendSinkTest('sink-1')).toMatchObject({ ok: false, failure: 'http_status' }); + expect(record.update).not.toHaveBeenCalled(); + }); +}); + +describe('delivery', () => { + function locked(value: boolean) { + query.mockResolvedValue([{ locked: value }]); + } + + it('sends the events past the cursor in order and advances the cursor on success', async () => { + locked(true); + const record = sink(); + vi.mocked(AuditSink.findByPk).mockResolvedValue(record); + vi.mocked(readExportBatch).mockResolvedValue([event(11), event(12), event(13)]); + + expect(await deliverSink('sink-1')).toBe(3); + + expect(readExportBatch).toHaveBeenCalledWith( + expect.objectContaining({ afterSeq: 10, limit: SINK_BATCH, transaction: { id: 'tx' } }), + ); + expect(sentLines()).toEqual([event(11), event(12), event(13)].map(exportLine)); + expect(record).toMatchObject({ cursorSeq: '13', failureCount: 0, nextAttemptAt: null }); + expect(record.lastDeliveredAt).toBeInstanceOf(Date); + expect(query).toHaveBeenCalledWith( + expect.stringContaining('pg_try_advisory_xact_lock(:lockClass, hashtext(:id))'), + expect.objectContaining({ replacements: expect.objectContaining({ id: 'sink-1' }) }), + ); + }); + + it('does not advance the cursor on failure and backs off', async () => { + locked(true); + status = 503; + const record = sink({ failureCount: 2 }); + vi.mocked(AuditSink.findByPk).mockResolvedValue(record); + vi.mocked(readExportBatch).mockResolvedValue([event(11)]); + + expect(await deliverSink('sink-1')).toBe(0); + + expect(bodies).toHaveLength(1); + expect(record.cursorSeq).toBe('10'); + expect(record).toMatchObject({ lastFailure: 'http_status', failureCount: 3 }); + expect(record.lastFailureAt).toBeInstanceOf(Date); + expect(record.nextAttemptAt.getTime()).toBeGreaterThan(Date.now()); + }); + + it('resends the same batch after a failure, so nothing is skipped', async () => { + locked(true); + const record = sink(); + vi.mocked(AuditSink.findByPk).mockResolvedValue(record); + vi.mocked(readExportBatch).mockImplementation(async ({ afterSeq }) => + [event(11), event(12)].filter((entry) => entry.seq > afterSeq), + ); + + status = 500; + await deliverSink('sink-1'); + record.nextAttemptAt = null; + status = 200; + await deliverSink('sink-1'); + + expect(sentLines()).toEqual([event(11), event(12), event(11), event(12)].map(exportLine)); + expect(record.cursorSeq).toBe('12'); + }); + + it('stands down when another replica holds the sink', async () => { + locked(false); + + expect(await deliverSink('sink-1')).toBe(0); + expect(AuditSink.findByPk).not.toHaveBeenCalled(); + }); + + it('skips a sink that is gone, disabled, backing off or caught up', async () => { + locked(true); + vi.mocked(readExportBatch).mockResolvedValue([]); + + for (const found of [ + null, + sink({ enabled: false }), + sink({ nextAttemptAt: new Date(Date.now() + 30_000) }), + sink(), + ]) { + vi.mocked(AuditSink.findByPk).mockResolvedValueOnce(found); + expect(await deliverSink('sink-1')).toBe(0); + } + expect(readExportBatch).toHaveBeenCalledTimes(1); + expect(bodies).toHaveLength(0); + }); + + it('backs off exponentially to a minute', () => { + vi.spyOn(Math, 'random').mockReturnValue(0); + expect([1, 2, 3, 7, 8, 50].map(backoffMs)).toEqual([1000, 2000, 4000, 60_000, 60_000, 60_000]); + vi.spyOn(Math, 'random').mockReturnValue(0.99); + expect(backoffMs(20)).toBeLessThanOrEqual(60_000); + expect(backoffMs(20)).toBeGreaterThan(53_000); + }); +}); + +describe('the loop', () => { + it('drains each due sink until a short batch', async () => { + vi.mocked(AuditSink.findAll).mockResolvedValue([{ id: 'sink-1' }] as never); + query.mockResolvedValue([{ locked: true }]); + const record = sink(); + vi.mocked(AuditSink.findByPk).mockResolvedValue(record); + const full = Array.from({ length: SINK_BATCH }, (_, index) => event(11 + index)); + vi.mocked(readExportBatch) + .mockResolvedValueOnce(full) + .mockResolvedValueOnce([event(111)]); + + await runAuditSinkTick(); + + expect(readExportBatch).toHaveBeenCalledTimes(2); + expect(record.cursorSeq).toBe('111'); + }); + + it('caps one sink at fifty batches a tick', async () => { + vi.mocked(AuditSink.findAll).mockResolvedValue([{ id: 'sink-1' }] as never); + query.mockResolvedValue([{ locked: true }]); + vi.mocked(AuditSink.findByPk).mockResolvedValue(sink()); + vi.mocked(readExportBatch).mockImplementation(async ({ afterSeq }) => + Array.from({ length: SINK_BATCH }, (_, index) => event(afterSeq + 1 + index)), + ); + + await runAuditSinkTick(); + + expect(readExportBatch).toHaveBeenCalledTimes(50); + }); + + it('logs rather than throws when a sink or the tick fails', async () => { + vi.mocked(AuditSink.findAll).mockResolvedValueOnce([{ id: 'sink-1' }] as never); + transaction.mockRejectedValueOnce(new Error('database unavailable')); + await expect(runAuditSinkTick()).resolves.toBeUndefined(); + + vi.mocked(AuditSink.findAll).mockRejectedValueOnce(new Error('database unavailable')); + await expect(runAuditSinkTick()).resolves.toBeUndefined(); + }); + + it('ticks once a second and never overlaps', async () => { + vi.useFakeTimers(); + let release: () => void = () => {}; + vi.mocked(AuditSink.findAll).mockImplementation( + () => new Promise((done) => (release = () => done([]))) as never, + ); + + const timer = startAuditSinkDelivery(); + await vi.advanceTimersByTimeAsync(3000); + expect(AuditSink.findAll).toHaveBeenCalledTimes(1); + + release(); + await vi.advanceTimersByTimeAsync(1000); + expect(AuditSink.findAll).toHaveBeenCalledTimes(2); + clearInterval(timer); + }); +}); From 68bedb3e39c30070bdd82801c9ce85ad5c54ab70 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Sat, 7 Nov 2026 21:13:57 -0500 Subject: [PATCH 5/9] feat(audit): name the sink holding retention and record sink decisions Retention's warning now names the audit sink holding it back and says to delete the sink to release it. A disabled sink keeps holding retention, since an audit event deleted before a SIEM receives it cannot be recovered. Records in ADR 0005 the decisions of 2026-11-07: disabled sinks hold retention, an OTLP 2xx with partialSuccess counts as delivered, and the syslog SD-ID stays a placeholder until Fells Code has an IANA enterprise number (#586). --- docs/adr/0005-extensibility-callouts.md | 5 +++- docs/configuration.md | 4 ++- src/lib/auditSinkTransport.ts | 1 + src/services/auditRetention.ts | 27 ++++++++++--------- tests/postgres/auditSinks.spec.ts | 2 +- tests/unit/services/auditRetention.spec.ts | 30 +++++++++++++++++++--- 6 files changed, 51 insertions(+), 18 deletions(-) diff --git a/docs/adr/0005-extensibility-callouts.md b/docs/adr/0005-extensibility-callouts.md index 84aaa64e..bb51ce71 100644 --- a/docs/adr/0005-extensibility-callouts.md +++ b/docs/adr/0005-extensibility-callouts.md @@ -90,6 +90,9 @@ All custom claims together get 1 KiB serialized, on top of ADR 0004's permission - Every record carries the event's `seamless-auth-events/1` line, with `seq`, `prevHash`, `hash` and `payload`, so the chain verifies downstream as an export does. - Each sink has its own cursor and retries until its destination takes the events, backing off to one minute. There is no dead letter: a sink falls behind and reports its lag. - Credentials are never stored. A sink names env vars ending `_AUDIT_SINK_SECRET`, the same pattern OAuth providers use. +- Retention never deletes past the oldest sink cursor, and a disabled sink holds it too (decided 2026-11-07). An audit event deleted before a SIEM receives it cannot be recovered, so a disabled sink holds retention until it is deleted. Retention logs a warning naming the holding sink and saying to delete it to release retention. +- An OTLP 2xx counts as delivered, including one whose `partialSuccess` reports rejected records (decided 2026-11-07). A collector rejects such records for their content, so retrying them would stall the sink forever. +- Syslog records carry `seq` and `hash` in the SD-ID `seamless@32473`. 32473 is the RFC 5612 documentation number, a placeholder until Fells Code has an IANA Private Enterprise Number (#586). A release must not ship with it. ### E8. Every callout follows the same reachability rules @@ -112,7 +115,7 @@ They must be read back to sign, so they cannot be hashed. They are AES-256-GCM e - `login_success` is written when `/login` resolves which methods an identifier may use, before any factor is proven, so it cannot be the source of `user.signed_in`. No event recorded that a session was created. `issueSessionAndRespond` now writes `session_created`, with the method and organization. - Deleting a passkey (`DELETE /users/credentials`) wrote no audit event. It now writes `credentials_deleted` naming the passkey. Reproducing test first. - Passkey registration and account registration both write `registration_success`. The passkey path now names the credential in metadata, which is how the catalog tells them apart. -- Audit retention deleted by age alone, so a sink that fell behind for longer than the retention period would have lost events it never sent. Retention now stops at the oldest sink cursor, and a sink cannot be created to replay from before the oldest event still held. +- Audit retention deleted by age alone, so a sink that fell behind for longer than the retention period would have lost events it never sent. Retention now stops at the oldest sink cursor, enabled or disabled, and a sink cannot be created to replay from before the oldest event still held. Decided 2026-11-07: an audit event deleted before a SIEM receives it cannot be recovered, so a disabled sink holds retention until it is deleted. - `organization_member_updated` recorded only what was added and removed. It now records the roles after the change too, which the webhook carries. ## Consequences diff --git a/docs/configuration.md b/docs/configuration.md index 85b96ee8..3f5f37e6 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -114,7 +114,9 @@ then daily, and each run also logs the audit chain head as an external anchor. S Retention never deletes an event an [audit sink](#siem-streaming) has yet to deliver, so a sink that has fallen behind, or is turned off, holds retention back until it catches up or is -deleted. Retention logs a warning while it is held. +deleted. An event deleted before a SIEM receives it cannot be recovered, so a disabled sink +holds retention until it is deleted. Retention logs a warning naming the holding sink while it +is held. ### SIEM streaming diff --git a/src/lib/auditSinkTransport.ts b/src/lib/auditSinkTransport.ts index 0f747c48..ce0eedcb 100644 --- a/src/lib/auditSinkTransport.ts +++ b/src/lib/auditSinkTransport.ts @@ -36,6 +36,7 @@ const MAX_RESPONSE_BYTES = 64 * 1024; * a private SD-ID to be `name@`. 32473 is the number RFC 5612 reserves * for documentation, a placeholder until Fells Code has its own. */ +// TODO(#586): replace 32473 with the Fells Code IANA enterprise number before release. export const SYSLOG_SD_ID = 'seamless@32473'; export const AUDIT_SINK_SCOPE = 'seamless-auth.audit'; diff --git a/src/services/auditRetention.ts b/src/services/auditRetention.ts index 4b92dcfa..a7fe11b4 100644 --- a/src/services/auditRetention.ts +++ b/src/services/auditRetention.ts @@ -77,17 +77,18 @@ function getRetentionSequelize(env = process.env): Sequelize { } /** - * The newest event every audit sink has delivered, or null without sinks. Retention never - * deletes past it, so a sink that has fallen behind still finds every event it has yet to send - * (ADR 0005, E7). Read through the application's connection, since the retention role need not - * see `audit_sinks`. + * The sink furthest behind, with the newest event it has delivered, or null without sinks. + * Retention never deletes past it, so a sink that has fallen behind still finds every event it + * has yet to send (ADR 0005, E7). A disabled sink holds it too: an event deleted before a SIEM + * receives it cannot be recovered, so only deleting the sink releases it. Read through the + * application's connection, since the retention role need not see `audit_sinks`. */ -async function auditSinkHold(): Promise { - const [row] = await getSequelize().query<{ held: string | null }>( - 'SELECT min("cursorSeq") AS held FROM public.audit_sinks', +async function auditSinkHold(): Promise<{ sinkId: string; seq: number } | null> { + const [row] = await getSequelize().query<{ id: string; cursorSeq: string }>( + 'SELECT id, "cursorSeq" FROM public.audit_sinks ORDER BY "cursorSeq", id LIMIT 1', { type: QueryTypes.SELECT }, ); - return row?.held == null ? null : Number(row.held); + return row ? { sinkId: row.id, seq: Number(row.cursorSeq) } : null; } async function writeArchiveFile(archiveDir: string, events: ExportedAuthEvent[]) { @@ -164,7 +165,7 @@ export async function runAuditRetention( let archived = 0; for (;;) { - const heldFor = await auditSinkHold(); + const held = await auditSinkHold(); const outcome = await sequelize.transaction(async (transaction) => { const [{ locked }] = await sequelize.query<{ locked: boolean }>( 'SELECT pg_try_advisory_xact_lock(:key) AS locked', @@ -189,9 +190,11 @@ export async function runAuditRetention( if (maxSeq === null || Number(maxSeq) < 1) return 'finished' as const; - const deletable = heldFor === null ? Number(maxSeq) : Math.min(Number(maxSeq), heldFor); - if (deletable < Number(maxSeq)) { - logger.warn(`Audit retention is held at seq ${deletable} by an audit sink that is behind`); + const deletable = held ? Math.min(Number(maxSeq), held.seq) : Number(maxSeq); + if (held && deletable < Number(maxSeq)) { + logger.warn( + `Audit retention is held at seq ${deletable} by audit sink ${held.sinkId}, which has not delivered the events after it; delete the sink to release it`, + ); } if (deletable < 1) return 'finished' as const; diff --git a/tests/postgres/auditSinks.spec.ts b/tests/postgres/auditSinks.spec.ts index 93f45287..a94f5c91 100644 --- a/tests/postgres/auditSinks.spec.ts +++ b/tests/postgres/auditSinks.spec.ts @@ -225,7 +225,7 @@ describe('audit sinks against the chain', () => { expect(otlpLines).toHaveLength(0); }); - it('keeps retention from deleting what a sink has yet to send', async () => { + it('keeps retention from deleting what a disabled sink has yet to send', async () => { await logEvents(4); const sink = await createSink( { diff --git a/tests/unit/services/auditRetention.spec.ts b/tests/unit/services/auditRetention.spec.ts index 82e4eb6c..6ede5670 100644 --- a/tests/unit/services/auditRetention.spec.ts +++ b/tests/unit/services/auditRetention.spec.ts @@ -16,6 +16,12 @@ vi.mock('../../../src/models/index.js', () => ({ getSequelize: vi.fn(), })); +const { warn } = vi.hoisted(() => ({ warn: vi.fn() })); + +vi.mock('../../../src/utils/logger.js', () => ({ + default: () => ({ error: vi.fn(), info: vi.fn(), warn, debug: vi.fn() }), +})); + const { retentionQuery, retentionTransaction, SequelizeMock } = vi.hoisted(() => { const retentionQuery = vi.fn(); const retentionTransaction = vi.fn(async (fn: (t: unknown) => unknown) => fn({ id: 'rtx' })); @@ -127,24 +133,42 @@ describe('runAuditRetention', () => { respondTo({ pg_try_advisory_xact_lock: [{ locked: true }], 'AS max_seq': [{ max_seq: '3' }], - audit_sinks: [{ held: '2' }], + audit_sinks: [{ id: 'sink-behind', cursorSeq: '2' }], }); vi.mocked(readExportBatch).mockResolvedValueOnce([event(1), event(2)]); await runAuditRetention({ retentionDays: 30, archiveDir }, new Date('2026-06-01T00:00:00Z')); expect(readExportBatch).toHaveBeenCalledWith(expect.objectContaining({ maxSeq: 2 })); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('held at seq 2 by audit sink sink-behind'), + ); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('delete the sink to release it')); expect(query).toHaveBeenCalledWith('DELETE FROM public.auth_events WHERE seq <= :lastSeq', { replacements: { lastSeq: 2 }, transaction: expect.anything(), }); }); + it('stays quiet when no sink is behind the retention cutoff', async () => { + respondTo({ + pg_try_advisory_xact_lock: [{ locked: true }], + 'AS max_seq': [{ max_seq: '3' }], + audit_sinks: [{ id: 'sink-current', cursorSeq: '9' }], + }); + vi.mocked(readExportBatch).mockResolvedValueOnce([event(1), event(2), event(3)]); + + await runAuditRetention({ retentionDays: 30, archiveDir }, new Date('2026-06-01T00:00:00Z')); + + expect(readExportBatch).toHaveBeenCalledWith(expect.objectContaining({ maxSeq: 3 })); + expect(warn).not.toHaveBeenCalled(); + }); + it('deletes nothing while a sink has sent no event at all', async () => { respondTo({ pg_try_advisory_xact_lock: [{ locked: true }], 'AS max_seq': [{ max_seq: '3' }], - audit_sinks: [{ held: '0' }], + audit_sinks: [{ id: 'sink-new', cursorSeq: '0' }], }); await runAuditRetention({ retentionDays: 30, archiveDir }, new Date('2026-06-01T00:00:00Z')); @@ -287,7 +311,7 @@ describe('separate retention connection', () => { retentionQuery.mockImplementation(async (sql: string) => sql.includes('pg_try_advisory_xact_lock') ? [{ locked: true }] : [{ max_seq: null }], ); - query.mockResolvedValue([{ held: null }]); + query.mockResolvedValue([]); await runAuditRetention({ retentionDays: 30, archiveDir }); await runAuditRetention({ retentionDays: 30, archiveDir }); From ba740fc490b41f8fd0c732a062fc534c5871ac08 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Sat, 7 Nov 2026 21:44:06 -0500 Subject: [PATCH 6/9] feat(webhooks): catch a re-enabled endpoint up on what it missed A disabled endpoint was given no deliveries, so events that happened while it was off were never sent, including after the API disabled it for a 410 or three days of failures. Its deliveries are now queued on hold, and turning it back on releases them, back as far as the 30 days deliveries are kept. The release uses the database clock, which the due check compares against. --- .changeset/signed-webhooks.md | 2 +- docs/adr/0005-extensibility-callouts.md | 3 +- src/controllers/webhooks.ts | 8 +++-- src/services/webhookService.ts | 34 ++++++++++++++++++---- tests/integration/admin/webhooks.spec.ts | 18 ++++++++++++ tests/postgres/webhooks.spec.ts | 34 +++++++++++++++++++++- tests/unit/services/webhookService.spec.ts | 31 +++++++++++++++++++- 7 files changed, 119 insertions(+), 11 deletions(-) diff --git a/.changeset/signed-webhooks.md b/.changeset/signed-webhooks.md index f38002cc..294a9700 100644 --- a/.changeset/signed-webhooks.md +++ b/.changeset/signed-webhooks.md @@ -6,7 +6,7 @@ Add signed, retried webhooks (ADR 0005, #418). - Admin API under `/admin/webhooks` and `/admin/webhook-deliveries`: create, update, disable and delete endpoints, rotate the signing secret (the old one signs beside the new one for 24 hours), send a test event, list deliveries with a dead letter filter, and redeliver. Every write takes step-up and is audited. - Payloads are signed with the Standard Webhooks scheme (`webhook-id`, `webhook-timestamp`, `webhook-signature`), so any Standard Webhooks verifier checks them. -- Events are built from committed audit rows, retried eight times over just under 42 hours, then dead-lettered. An endpoint that answers 410, or fails every delivery for three days, is disabled. +- Events are built from committed audit rows, retried eight times over just under 42 hours, then dead-lettered. An endpoint that answers 410, or fails every delivery for three days, is disabled. Deliveries for a disabled endpoint are held, and turning it back on sends what it missed, up to the 30 days deliveries are kept. - Every callout to an adopter URL refuses link-local, multicast and the API's own host, never follows redirects, and in production refuses private addresses unless the host is listed in the new `CALLOUT_PRIVATE_HOSTS`. - New env var `CALLOUT_SECRET_ENCRYPTION_KEY` encrypts stored signing secrets. Production requires it once a webhook exists. - New audit event `session_created`, written once per completed sign-in. Deleting a passkey is now audited as `credentials_deleted`, and passkey registration names the credential. diff --git a/docs/adr/0005-extensibility-callouts.md b/docs/adr/0005-extensibility-callouts.md index 11718d7d..ab8f8364 100644 --- a/docs/adr/0005-extensibility-callouts.md +++ b/docs/adr/0005-extensibility-callouts.md @@ -65,7 +65,8 @@ The chain trigger updates the chain head row on every insert and holds that lock - Attempts at 0 s, then 5 s, 5 min, 30 min, 2 h, 5 h, 10 h and 24 h after the previous one, with up to 10% jitter: eight attempts, dead just under 42 hours after the event. A longer `Retry-After` is honored, up to 24 hours. - `410 Gone` disables the endpoint. So do three days in which every delivery failed. Both write `webhook_endpoint_disabled`. - A delivery stores the exact body sent, so a retry or redelivery sends the same bytes. Responses are read for the status alone, and only the status and a coarse failure reason are kept. Deliveries are pruned after 30 days. -- Redeliver is one attempt now with the same `webhook-id` and body and a fresh timestamp and signature. A delivery whose endpoint was disabled after it was queued is held, and redeliver can still send it. +- Redeliver is one attempt now with the same `webhook-id` and body and a fresh timestamp and signature. +- A disabled endpoint still gets its deliveries, held with no attempt due, and a delivery already queued when its endpoint is disabled is held the same way. Turning the endpoint back on releases everything held, so it catches up on what happened while it was off instead of losing it. Deliveries are pruned after 30 days, so that is how far a catch-up reaches. A dead delivery stays dead; redeliver sends it. Decided by Brandon on 2026-11-07, after the webhooks guide found that events during a disable were never queued. ### E5. Login hooks diff --git a/src/controllers/webhooks.ts b/src/controllers/webhooks.ts index 2a2f5f9e..fd672f15 100644 --- a/src/controllers/webhooks.ts +++ b/src/controllers/webhooks.ts @@ -82,13 +82,17 @@ export async function createWebhook(req: Request, res: Response) { export async function updateWebhook(req: RouteRequest, res: Response) { try { - const endpoint = await updateEndpoint(req.params.id, req.body); + const { endpoint, released } = await updateEndpoint(req.params.id, req.body); await AuthEventService.log({ actorUserId: actorUserId(req), type: 'admin_webhook_updated', req, - metadata: { endpointId: endpoint.id, changed: Object.keys(req.body) }, + metadata: { + endpointId: endpoint.id, + changed: Object.keys(req.body), + ...(released ? { releasedDeliveries: released } : {}), + }, }); return res.json({ endpoint: serializeEndpoint(endpoint) }); diff --git a/src/services/webhookService.ts b/src/services/webhookService.ts index e6ddfcf4..37e77171 100644 --- a/src/services/webhookService.ts +++ b/src/services/webhookService.ts @@ -21,7 +21,7 @@ import { type WebhookDeliveryStatus, type WebhookEventType, } from '@seamless-auth/types'; -import { Op, QueryTypes, type Transaction, type WhereOptions } from 'sequelize'; +import { fn, Op, QueryTypes, type Transaction, type WhereOptions } from 'sequelize'; import { productionSecretMissing } from '../config/authSecrets.js'; import { @@ -188,6 +188,7 @@ export async function createEndpoint( export async function updateEndpoint(id: string, input: UpdateWebhookEndpointRequest) { const endpoint = await getEndpoint(id); if (input.url !== undefined) assertUrl(input.url); + const reenabling = input.enabled === true && !endpoint.enabled; await endpoint.update({ ...(input.url !== undefined ? { url: input.url } : {}), @@ -202,7 +203,26 @@ export async function updateEndpoint(id: string, input: UpdateWebhookEndpointReq : {}), }); - return endpoint; + // Releases what was held while it was off. Deliveries are pruned after 30 days, so that is how + // far back a catch-up reaches. A dead delivery stays dead; redeliver sends it. + const released = reenabling + ? ( + await WebhookDelivery.update( + // The database's clock, which the due check compares against, so a skewed app clock + // cannot leave released deliveries not yet due. + { nextAttemptAt: fn('now') as unknown as Date }, + { + where: { + endpointId: endpoint.id, + status: { [Op.in]: ['pending', 'failed'] }, + nextAttemptAt: null, + }, + }, + ) + )[0] + : 0; + + return { endpoint, released }; } export async function deleteEndpoint(id: string) { @@ -523,7 +543,9 @@ export async function dispatchWebhooks(): Promise { ); if (rows.length === 0) return 0; - const endpoints = await WebhookEndpoint.findAll({ where: { enabled: true }, transaction }); + // Disabled endpoints get their deliveries too, held with no attempt due, so turning one back + // on catches it up instead of losing what happened while it was off (ADR 0005, E4). + const endpoints = await WebhookEndpoint.findAll({ transaction }); for (const row of rows) { const subscribed = endpoints.filter((endpoint) => @@ -540,12 +562,14 @@ export async function dispatchWebhooks(): Promise { `INSERT INTO public.webhook_deliveries (id, "endpointId", "eventType", "authEventSeq", payload, status, attempts, "nextAttemptAt", "createdAt", "updatedAt") - VALUES (:id, :endpointId, :eventType, :seq, :payload, 'pending', 0, now(), now(), now()) + VALUES (:id, :endpointId, :eventType, :seq, :payload, 'pending', 0, + CASE WHEN :held THEN NULL ELSE now() END, now(), now()) ON CONFLICT ("endpointId", "authEventSeq") DO NOTHING`, { replacements: { id, endpointId: endpoint.id, + held: !endpoint.enabled, eventType: event.type, seq: row.seq, payload: body(id, event.type, new Date(row.created_at), event.data), @@ -607,7 +631,7 @@ export async function deliverDue(): Promise { await Promise.all( deliveries.map(async (delivery) => { const endpoint = endpoints.get(delivery.endpointId); - // Disabled after it was queued: hold the delivery, so redeliver can still send it. + // Disabled after it was queued: hold the delivery until the endpoint is turned back on. if (!endpoint || !endpoint.enabled) { await delivery.update({ nextAttemptAt: null }); return; diff --git a/tests/integration/admin/webhooks.spec.ts b/tests/integration/admin/webhooks.spec.ts index 789367b1..25c6272c 100644 --- a/tests/integration/admin/webhooks.spec.ts +++ b/tests/integration/admin/webhooks.spec.ts @@ -154,6 +154,24 @@ describe('webhook endpoints', () => { expect(types).toEqual(['admin_webhook_updated', 'admin_webhook_deleted']); }); + it('records how many held deliveries turning an endpoint back on released', async () => { + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue( + buildEndpoint({ enabled: false, disabledReason: 'gone' }), + ); + vi.mocked(WebhookDelivery.update).mockResolvedValue([2] as never); + + const res = await request(app).patch(`/admin/webhooks/${endpointId}`).send({ enabled: true }); + + expect(res.status).toBe(200); + expect(res.body.endpoint).toMatchObject({ enabled: true, disabledReason: null }); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'admin_webhook_updated', + metadata: expect.objectContaining({ releasedDeliveries: 2 }), + }), + ); + }); + it('answers 404 for an endpoint that does not exist', async () => { for (const send of [ () => request(app).get(`/admin/webhooks/${endpointId}`), diff --git a/tests/postgres/webhooks.spec.ts b/tests/postgres/webhooks.spec.ts index 969d7a36..2e1fa8c7 100644 --- a/tests/postgres/webhooks.spec.ts +++ b/tests/postgres/webhooks.spec.ts @@ -7,7 +7,12 @@ import { getSequelize, initializeModels } from '../../src/models/index.js'; import { WebhookDelivery } from '../../src/models/webhookDeliveries.js'; import { WebhookEndpoint } from '../../src/models/webhookEndpoints.js'; import { AuthEventService } from '../../src/services/authEventService.js'; -import { createEndpoint, deliverDue, dispatchWebhooks } from '../../src/services/webhookService.js'; +import { + createEndpoint, + deliverDue, + dispatchWebhooks, + updateEndpoint, +} from '../../src/services/webhookService.js'; let server: Server; let port: number; @@ -127,6 +132,33 @@ describe('webhook dispatch against the audit chain', () => { expect(endpoint.failingSince).not.toBeNull(); }); + it('holds events for a disabled endpoint and delivers them once it is turned back on', async () => { + const { endpoint } = await createEndpoint( + { url: `http://127.0.0.1:${port}/hook`, eventTypes: ['user.deleted'] }, + null, + ); + await dispatchWebhooks(); + await updateEndpoint(endpoint.id, { enabled: false }); + + await logEvent('user_deleted', '55555555-5555-4555-8555-555555555555'); + await dispatchWebhooks(); + + // Queued, but nothing is due while the endpoint is off. + expect(await WebhookDelivery.count()).toBe(1); + expect(await deliverDue()).toBe(0); + expect(received).toHaveLength(0); + + const { released } = await updateEndpoint(endpoint.id, { enabled: true }); + expect(released).toBe(1); + + expect(await deliverDue()).toBe(1); + expect(received).toHaveLength(1); + expect(JSON.parse(received[0].body)).toMatchObject({ + type: 'user.deleted', + data: { userId: '55555555-5555-4555-8555-555555555555' }, + }); + }); + it('deletes an endpoint with its deliveries', async () => { const { endpoint } = await createEndpoint( { url: `http://127.0.0.1:${port}/hook`, eventTypes: ['user.deleted'] }, diff --git a/tests/unit/services/webhookService.spec.ts b/tests/unit/services/webhookService.spec.ts index 28a43630..67ee47c6 100644 --- a/tests/unit/services/webhookService.spec.ts +++ b/tests/unit/services/webhookService.spec.ts @@ -198,6 +198,7 @@ describe('endpoints', () => { it('updates fields, and turning an endpoint on clears why it was off', async () => { const record = endpoint({ enabled: false, disabledReason: 'failing', failingSince: at }); vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(record); + vi.mocked(WebhookDelivery.update).mockResolvedValue([0] as never); await updateEndpoint('endpoint-1', { url: 'https://hooks.example.com/b', @@ -215,6 +216,31 @@ describe('endpoints', () => { }); }); + // Events that happened while it was off were queued on hold; turning it back on sends them. + it('releases the deliveries held while it was off when it is turned back on', async () => { + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(endpoint({ enabled: false })); + vi.mocked(WebhookDelivery.update).mockResolvedValue([4] as never); + + const { released } = await updateEndpoint('endpoint-1', { enabled: true }); + + expect(released).toBe(4); + const [values, options] = vi.mocked(WebhookDelivery.update).mock.calls[0] as any; + expect(values.nextAttemptAt).toMatchObject({ fn: 'now' }); + expect(options.where).toMatchObject({ endpointId: 'endpoint-1', nextAttemptAt: null }); + const [statusOp] = Object.getOwnPropertySymbols(options.where.status); + expect(options.where.status[statusOp]).toEqual(['pending', 'failed']); + }); + + it('releases nothing for an endpoint that was already on, or is being turned off', async () => { + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(endpoint()); + expect((await updateEndpoint('endpoint-1', { enabled: true })).released).toBe(0); + + vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(endpoint()); + expect((await updateEndpoint('endpoint-1', { enabled: false })).released).toBe(0); + + expect(WebhookDelivery.update).not.toHaveBeenCalled(); + }); + it('records a manual disable', async () => { const record = endpoint(); vi.mocked(WebhookEndpoint.findByPk).mockResolvedValue(record); @@ -620,7 +646,7 @@ describe('dispatchWebhooks', () => { query.mockResolvedValue(undefined); vi.mocked(WebhookEndpoint.findAll).mockResolvedValue([ endpoint({ id: 'a', eventTypes: ['user.created', 'credential.added'] }), - endpoint({ id: 'b', eventTypes: ['user.created'] }), + endpoint({ id: 'b', eventTypes: ['user.created'], enabled: false }), ]); vi.mocked(User.findByPk).mockResolvedValue({ email: 'a@example.com', phone: null } as any); @@ -631,6 +657,9 @@ describe('dispatchWebhooks', () => { ); expect(inserts).toHaveLength(2); expect(inserts.map(([, options]) => options.replacements.endpointId)).toEqual(['a', 'b']); + // A disabled endpoint's delivery is queued on hold, with no attempt due. + expect(inserts.map(([, options]) => options.replacements.held)).toEqual([false, true]); + expect(inserts[0][0]).toContain('CASE WHEN :held THEN NULL ELSE now() END'); const payload = JSON.parse(inserts[0][1].replacements.payload); expect(payload).toEqual({ id: inserts[0][1].replacements.id, From bf9108b89e2d3a4d095b1f48d4551db056115703 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Sat, 7 Nov 2026 22:06:07 -0500 Subject: [PATCH 7/9] fix(deps): use @seamless-auth/types 0.40.0 --- package-lock.json | 8 ++++---- package.json | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package-lock.json b/package-lock.json index ee7068da..5240e709 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,7 +13,7 @@ "@seamless-auth/messaging": "^0.3.1", "@seamless-auth/messaging-aws": "^0.3.1", "@seamless-auth/messaging-twilio": "^0.3.1", - "@seamless-auth/types": "^0.39.0", + "@seamless-auth/types": "^0.40.0", "@simplewebauthn/server": "^14.0.3", "base64url": "^3.0.1", "bcrypt-ts": "^9.0.2", @@ -2927,9 +2927,9 @@ } }, "node_modules/@seamless-auth/types": { - "version": "0.39.0", - "resolved": "https://registry.npmjs.org/@seamless-auth/types/-/types-0.39.0.tgz", - "integrity": "sha512-xoJLkpgkisvVvSh3aBxByC5GfWm6LaIulusf+6A2ghok/l5FP6r2V8lwLEqbXO6dy/g01RNWxfTupjWAp42b0A==", + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@seamless-auth/types/-/types-0.40.0.tgz", + "integrity": "sha512-NpFVCWE0VSNrBK9M4yBxsloyQgGHXP6B8/QmDPxsFz48/qV6jcDqdUpuV4PAJslG9B9X+4BcnTSQzI+iPSRNsA==", "license": "Apache-2.0", "dependencies": { "zod": "^4.5.0" diff --git a/package.json b/package.json index c552a569..fcac97f4 100644 --- a/package.json +++ b/package.json @@ -52,7 +52,7 @@ "@seamless-auth/messaging": "^0.3.1", "@seamless-auth/messaging-aws": "^0.3.1", "@seamless-auth/messaging-twilio": "^0.3.1", - "@seamless-auth/types": "^0.39.0", + "@seamless-auth/types": "^0.40.0", "@simplewebauthn/server": "^14.0.3", "base64url": "^3.0.1", "bcrypt-ts": "^9.0.2", From 7027943f3a089a3aff82697bd21f790fea8c6f81 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Sat, 7 Nov 2026 22:07:34 -0500 Subject: [PATCH 8/9] fix(oidc): return empty customClaims and regenerate api types for types 0.40.0 --- openapi.json | 185 +++++++++++++++++- src/generated/api.ts | 87 +++++++- src/services/oidcClientRegistry.ts | 1 + tests/integration/oidc/oidcEdge.spec.ts | 2 +- .../unit/services/oidcClientRegistry.spec.ts | 1 + 5 files changed, 272 insertions(+), 4 deletions(-) diff --git a/openapi.json b/openapi.json index 7bf24b7b..0e3b8da3 100644 --- a/openapi.json +++ b/openapi.json @@ -14900,6 +14900,7 @@ "session_revoked", "subject_mismatch", "auth_context_mismatch", + "claims_mismatch", "issuer_mismatch", "audience_mismatch", "client_inactive", @@ -14942,6 +14943,7 @@ "session_revoked", "subject_mismatch", "auth_context_mismatch", + "claims_mismatch", "issuer_mismatch", "audience_mismatch", "client_inactive", @@ -15633,7 +15635,12 @@ "phone_number": "string", "phone_number_verified": true, "roles": [null], - "org_id": "string" + "org_id": "string", + "permissions": [null], + "permissions_omitted": null, + "org_roles": [null], + "org_permissions": [null], + "customClaims": null }, "schema": { "type": "object", @@ -15644,7 +15651,177 @@ "phone_number": { "type": "string" }, "phone_number_verified": { "type": "boolean" }, "roles": { "type": "array", "items": { "type": "string" } }, - "org_id": { "type": "string", "nullable": true } + "org_id": { "type": "string", "nullable": true }, + "permissions": { "type": "array", "items": { "type": "string" } }, + "permissions_omitted": { "type": "boolean", "enum": [true] }, + "org_roles": { "type": "array", "items": { "type": "string" } }, + "org_permissions": { "type": "array", "items": { "type": "string" } }, + "customClaims": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true }, + { + "type": "array", + "items": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + }, + { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "type": "string" }, + { "type": "number" }, + { "type": "boolean" }, + { "nullable": true } + ] + } + } + ] + } + } + ] + } + } + ] + }, + "default": {} + } }, "required": ["sub", "roles", "org_id"] } @@ -34033,6 +34210,7 @@ "nullable": true, "enum": [ "refused", + "misconfigured", "timed_out", "connection_failed", "http_status", @@ -34274,6 +34452,7 @@ "nullable": true, "enum": [ "refused", + "misconfigured", "timed_out", "connection_failed", "http_status", @@ -34490,6 +34669,7 @@ "nullable": true, "enum": [ "refused", + "misconfigured", "timed_out", "connection_failed", "http_status", @@ -35006,6 +35186,7 @@ "nullable": true, "enum": [ "refused", + "misconfigured", "timed_out", "connection_failed", "http_status", diff --git a/src/generated/api.ts b/src/generated/api.ts index c5c25921..38decf96 100644 --- a/src/generated/api.ts +++ b/src/generated/api.ts @@ -14615,6 +14615,7 @@ export interface paths { | 'session_revoked' | 'subject_mismatch' | 'auth_context_mismatch' + | 'claims_mismatch' | 'issuer_mismatch' | 'audience_mismatch' | 'client_inactive' @@ -14661,6 +14662,7 @@ export interface paths { | 'session_revoked' | 'subject_mismatch' | 'auth_context_mismatch' + | 'claims_mismatch' | 'issuer_mismatch' | 'audience_mismatch' | 'client_inactive' @@ -15416,7 +15418,18 @@ export interface paths { * "roles": [ * null * ], - * "org_id": "string" + * "org_id": "string", + * "permissions": [ + * null + * ], + * "permissions_omitted": null, + * "org_roles": [ + * null + * ], + * "org_permissions": [ + * null + * ], + * "customClaims": null * } */ 'application/json': { @@ -15427,6 +15440,74 @@ export interface paths { phone_number_verified?: boolean; roles: string[]; org_id: string | null; + permissions?: string[]; + /** @enum {boolean} */ + permissions_omitted?: true; + org_roles?: string[]; + org_permissions?: string[]; + /** @default {} */ + customClaims: { + [key: string]: + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + }; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | ( + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + } + )[] + | { + [key: string]: + | string + | number + | boolean + | unknown + | (string | number | boolean | unknown)[] + | { + [key: string]: string | number | boolean | unknown; + }; + }; + }; + }; }; }; }; @@ -33277,6 +33358,7 @@ export interface paths { /** @enum {string|null} */ failure: | 'refused' + | 'misconfigured' | 'timed_out' | 'connection_failed' | 'http_status' @@ -33488,6 +33570,7 @@ export interface paths { /** @enum {string|null} */ lastFailure: | 'refused' + | 'misconfigured' | 'timed_out' | 'connection_failed' | 'http_status' @@ -33677,6 +33760,7 @@ export interface paths { /** @enum {string|null} */ lastFailure: | 'refused' + | 'misconfigured' | 'timed_out' | 'connection_failed' | 'http_status' @@ -34041,6 +34125,7 @@ export interface paths { /** @enum {string|null} */ lastFailure: | 'refused' + | 'misconfigured' | 'timed_out' | 'connection_failed' | 'http_status' diff --git a/src/services/oidcClientRegistry.ts b/src/services/oidcClientRegistry.ts index a3bd4b52..adfe14ff 100644 --- a/src/services/oidcClientRegistry.ts +++ b/src/services/oidcClientRegistry.ts @@ -220,5 +220,6 @@ export async function getOidcAccountClaims(userId: string): Promise { }); it('returns account claims only for the user behind a grant-bound session', async () => { - const claims = { sub: USER, roles: [], org_id: null }; + const claims = { sub: USER, roles: [], org_id: null, customClaims: {} }; const path = `/oidc/accounts/${USER}?clientId=app&sessionId=${SESSION}`; vi.mocked(findGrantBoundSession).mockResolvedValue({ id: SESSION, userId: USER } as never); vi.mocked(getOidcAccountClaims).mockResolvedValueOnce(claims); diff --git a/tests/unit/services/oidcClientRegistry.spec.ts b/tests/unit/services/oidcClientRegistry.spec.ts index 03e6a78c..0fd3462e 100644 --- a/tests/unit/services/oidcClientRegistry.spec.ts +++ b/tests/unit/services/oidcClientRegistry.spec.ts @@ -373,6 +373,7 @@ describe('getOidcAccountClaims', () => { phone_number_verified: false, roles: ['user'], org_id: 'org-1', + customClaims: {}, }); }); From a1b14081ac9df441a518e9e4457627114dce0dae Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Sat, 7 Nov 2026 22:11:31 -0500 Subject: [PATCH 9/9] fix(audit-sinks): report unusable sink settings as misconfigured --- docs/adr/0005-extensibility-callouts.md | 4 +- openapi.json | 5 +++ src/generated/api.ts | 5 +++ src/lib/auditSinkTransport.ts | 52 +++++++++++++++------- tests/integration/admin/auditSinks.spec.ts | 9 +++- tests/unit/lib/auditSinkTransport.spec.ts | 10 ++--- 6 files changed, 60 insertions(+), 25 deletions(-) diff --git a/docs/adr/0005-extensibility-callouts.md b/docs/adr/0005-extensibility-callouts.md index a799cb4c..9e71fcfb 100644 --- a/docs/adr/0005-extensibility-callouts.md +++ b/docs/adr/0005-extensibility-callouts.md @@ -90,7 +90,7 @@ All custom claims together get 1 KiB serialized, on top of ADR 0004's permission - OTLP/HTTP with JSON encoding to `/v1/logs`, and syslog (RFC 5424) over TLS (RFC 5425) with octet counting. Plain TCP only outside production, never UDP. - Every record carries the event's `seamless-auth-events/1` line, with `seq`, `prevHash`, `hash` and `payload`, so the chain verifies downstream as an export does. - Each sink has its own cursor and retries until its destination takes the events, backing off to one minute. There is no dead letter: a sink falls behind and reports its lag. -- Credentials are never stored. A sink names env vars ending `_AUDIT_SINK_SECRET`, the same pattern OAuth providers use. +- Credentials are never stored. A sink names env vars ending `_AUDIT_SINK_SECRET`, the same pattern OAuth providers use. A send whose named env var is unset or unusable, or whose settings production does not allow (plain TCP syslog), fails as `misconfigured` before any connection. - Retention never deletes past the oldest sink cursor, and a disabled sink holds it too (decided 2026-11-07). An audit event deleted before a SIEM receives it cannot be recovered, so a disabled sink holds retention until it is deleted. Retention logs a warning naming the holding sink and saying to delete it to release retention. - An OTLP 2xx counts as delivered, including one whose `partialSuccess` reports rejected records (decided 2026-11-07). A collector rejects such records for their content, so retrying them would stall the sink forever. - Syslog records carry `seq` and `hash` in the SD-ID `seamless@32473`. 32473 is the RFC 5612 documentation number, a placeholder until Fells Code has an IANA Private Enterprise Number (#586). A release must not ship with it. @@ -105,7 +105,7 @@ All custom claims together get 1 KiB serialized, on top of ADR 0004's permission - Other private and loopback addresses are refused in production unless the host is listed in `CALLOUT_PRIVATE_HOSTS`. It is an env var, so nothing written through the API can widen it, and it is separate from `OAUTH_PROVIDER_PRIVATE_HOSTS`, so allowing an internal hook service does not also allow it as an identity provider. - Redirects are never followed. Responses are capped at 64 KiB. The deadline covers the whole request, so a destination that trickles bytes cannot hold a sign-in open. - URLs are checked when written and again at connect time. -- Failures are reported as `refused`, `timed_out`, `connection_failed`, `http_status`, `invalid_response` or `too_large`, never with the resolved address or the socket's error text, so the delivery log cannot be used to map the internal network. +- Failures are reported as `refused`, `misconfigured`, `timed_out`, `connection_failed`, `http_status`, `invalid_response` or `too_large`, never with the resolved address or the socket's error text, so the delivery log cannot be used to map the internal network. `refused` means the API would not connect to the destination's address; `misconfigured` means the destination's own settings cannot be used, so no call was attempted. ### E9. Signing secrets are encrypted at rest diff --git a/openapi.json b/openapi.json index 8cc30b2f..e7a407d2 100644 --- a/openapi.json +++ b/openapi.json @@ -10261,6 +10261,7 @@ "nullable": true, "enum": [ "refused", + "misconfigured", "timed_out", "connection_failed", "http_status", @@ -10570,6 +10571,7 @@ "nullable": true, "enum": [ "refused", + "misconfigured", "timed_out", "connection_failed", "http_status", @@ -10841,6 +10843,7 @@ "nullable": true, "enum": [ "refused", + "misconfigured", "timed_out", "connection_failed", "http_status", @@ -11205,6 +11208,7 @@ "nullable": true, "enum": [ "refused", + "misconfigured", "timed_out", "connection_failed", "http_status", @@ -11635,6 +11639,7 @@ "nullable": true, "enum": [ "refused", + "misconfigured", "timed_out", "connection_failed", "http_status", diff --git a/src/generated/api.ts b/src/generated/api.ts index 383bf2de..3939455d 100644 --- a/src/generated/api.ts +++ b/src/generated/api.ts @@ -9730,6 +9730,7 @@ export interface paths { /** @enum {string|null} */ lastFailure: | 'refused' + | 'misconfigured' | 'timed_out' | 'connection_failed' | 'http_status' @@ -9937,6 +9938,7 @@ export interface paths { /** @enum {string|null} */ lastFailure: | 'refused' + | 'misconfigured' | 'timed_out' | 'connection_failed' | 'http_status' @@ -10145,6 +10147,7 @@ export interface paths { /** @enum {string|null} */ lastFailure: | 'refused' + | 'misconfigured' | 'timed_out' | 'connection_failed' | 'http_status' @@ -10616,6 +10619,7 @@ export interface paths { /** @enum {string|null} */ lastFailure: | 'refused' + | 'misconfigured' | 'timed_out' | 'connection_failed' | 'http_status' @@ -10793,6 +10797,7 @@ export interface paths { /** @enum {string|null} */ failure: | 'refused' + | 'misconfigured' | 'timed_out' | 'connection_failed' | 'http_status' diff --git a/src/lib/auditSinkTransport.ts b/src/lib/auditSinkTransport.ts index ce0eedcb..6a3f5a4e 100644 --- a/src/lib/auditSinkTransport.ts +++ b/src/lib/auditSinkTransport.ts @@ -62,9 +62,9 @@ export function testRecord(sinkId: string, at: Date = new Date()): SinkRecord { } /** Thrown before any connection for a sink whose settings or env cannot be used. */ -class SinkRefused extends CalloutError { +class SinkMisconfigured extends CalloutError { constructor(message: string) { - super('refused', message); + super('misconfigured', message); } } @@ -75,34 +75,50 @@ function isProduction(env: EnvSource) { const HOST_NAME = /^(?=.{1,253}$)[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i; -/** What is wrong with a sink's destination, checked when written and again before each send. */ -export function sinkDestinationProblem( +type DestinationProblem = { problem: string; failure: 'refused' | 'misconfigured' }; + +function destinationProblem( settings: OtlpSinkSettings | SyslogSinkSettings, - env: EnvSource = process.env, -): string | null { + env: EnvSource, +): DestinationProblem | null { if (settings.kind === 'otlp') { const problem = calloutUrlProblem(settings.endpoint, env); - return problem ? `endpoint ${problem}` : null; + return problem ? { problem: `endpoint ${problem}`, failure: 'refused' } : null; } - if (!isIP(settings.host) && !HOST_NAME.test(settings.host)) return 'host is not a host name'; + const misconfigured = (problem: string): DestinationProblem => ({ + problem, + failure: 'misconfigured', + }); + if (!isIP(settings.host) && !HOST_NAME.test(settings.host)) { + return misconfigured('host is not a host name'); + } if (settings.transport === 'tcp' && isProduction(env)) { - return 'transport must be tls in production'; + return misconfigured('transport must be tls in production'); } if (Boolean(settings.tlsClientCertEnv) !== Boolean(settings.tlsClientKeyEnv)) { - return 'tlsClientCertEnv and tlsClientKeyEnv must be set together'; + return misconfigured('tlsClientCertEnv and tlsClientKeyEnv must be set together'); } const problem = calloutHostProblem(settings.host, env); - return problem ? `host ${problem}` : null; + return problem ? { problem: `host ${problem}`, failure: 'refused' } : null; +} + +/** What is wrong with a sink's destination, checked when written and again before each send. */ +export function sinkDestinationProblem( + settings: OtlpSinkSettings | SyslogSinkSettings, + env: EnvSource = process.env, +): string | null { + return destinationProblem(settings, env)?.problem ?? null; } function secretFromEnv(name: string, env: EnvSource): string { // The schema already holds names to the pattern; checked again so nothing that bypasses it // can read a secret the server keeps for something else. - if (!AUDIT_SINK_SECRET_ENV_PATTERN.test(name)) throw new SinkRefused(`${name} is not allowed`); + if (!AUDIT_SINK_SECRET_ENV_PATTERN.test(name)) + throw new SinkMisconfigured(`${name} is not allowed`); const value = env[name]; - if (!value) throw new SinkRefused(`${name} is not set`); + if (!value) throw new SinkMisconfigured(`${name} is not set`); return value; } @@ -113,7 +129,7 @@ function otlpHeaders(settings: OtlpSinkSettings, env: EnvSource) { const headers: Record = { 'content-type': 'application/json' }; for (const [name, envName] of Object.entries(settings.headersFromEnv)) { const value = secretFromEnv(envName, env); - if (!HEADER_VALUE.test(value)) throw new SinkRefused(`${envName} is not a header value`); + if (!HEADER_VALUE.test(value)) throw new SinkMisconfigured(`${envName} is not a header value`); headers[name] = value; } return headers; @@ -244,8 +260,12 @@ function writeSyslog( env: EnvSource, timeoutMs: number, ): Promise { - const problem = sinkDestinationProblem(settings, env); - if (problem) return Promise.reject(new SinkRefused(`Audit sink ${problem}`)); + const destination = destinationProblem(settings, env); + if (destination) { + return Promise.reject( + new CalloutError(destination.failure, `Audit sink ${destination.problem}`), + ); + } let material: ReturnType; try { diff --git a/tests/integration/admin/auditSinks.spec.ts b/tests/integration/admin/auditSinks.spec.ts index ec1164f8..07c51471 100644 --- a/tests/integration/admin/auditSinks.spec.ts +++ b/tests/integration/admin/auditSinks.spec.ts @@ -199,7 +199,7 @@ describe('audit sinks', () => { vi.mocked(AuditSink.findByPk).mockResolvedValue(buildSink()); vi.mocked(sendToSink).mockResolvedValue({ ok: false, - failure: 'refused', + failure: 'misconfigured', statusCode: null, durationMs: 3, }); @@ -207,7 +207,12 @@ describe('audit sinks', () => { const res = await request(app).post(`/admin/audit-sinks/${sinkId}/test`); expect(res.status).toBe(200); - expect(res.body).toEqual({ ok: false, failure: 'refused', statusCode: null, durationMs: 3 }); + expect(res.body).toEqual({ + ok: false, + failure: 'misconfigured', + statusCode: null, + durationMs: 3, + }); const [, records] = vi.mocked(sendToSink).mock.calls[0]; expect(records).toHaveLength(1); expect(records[0].event).toBeNull(); diff --git a/tests/unit/lib/auditSinkTransport.spec.ts b/tests/unit/lib/auditSinkTransport.spec.ts index c71180fb..5762ac06 100644 --- a/tests/unit/lib/auditSinkTransport.spec.ts +++ b/tests/unit/lib/auditSinkTransport.spec.ts @@ -215,7 +215,7 @@ describe('OTLP', () => { for (const env of [{}, { OTEL_AUDIT_SINK_SECRET: '' }]) { const attempt = await sendToSink(settings, chain(1).map(eventRecord), env); - expect(attempt).toMatchObject({ ok: false, failure: 'refused', statusCode: null }); + expect(attempt).toMatchObject({ ok: false, failure: 'misconfigured', statusCode: null }); } expect(received).toHaveLength(0); }); @@ -227,7 +227,7 @@ describe('OTLP', () => { { SEAMLESS_SERVICE_TOKEN: 'the-service-token' }, ); - expect(attempt.failure).toBe('refused'); + expect(attempt.failure).toBe('misconfigured'); expect(received).toHaveLength(0); }); @@ -238,7 +238,7 @@ describe('OTLP', () => { { OTEL_AUDIT_SINK_SECRET: 'a\r\nx-injected: 1' }, ); - expect(attempt.failure).toBe('refused'); + expect(attempt.failure).toBe('misconfigured'); expect(received).toHaveLength(0); }); @@ -399,7 +399,7 @@ describe('syslog', () => { expect(sinkDestinationProblem(syslog(port), env)).toBe('transport must be tls in production'); expect((await sendToSink(syslog(port), chain(1).map(eventRecord), env)).failure).toBe( - 'refused', + 'misconfigured', ); expect(connected).toBe(false); }); @@ -546,7 +546,7 @@ describe('syslog', () => { {}, ); - expect(attempt.failure).toBe('refused'); + expect(attempt.failure).toBe('misconfigured'); expect(streams).toHaveLength(0); });