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 6fcd1ae0..86023ff9 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 5489c5b4..20f5ce8c 100644 --- a/docs/adr/0005-extensibility-callouts.md +++ b/docs/adr/0005-extensibility-callouts.md @@ -97,7 +97,10 @@ Among roles of one kind, sets apply in role-name order, so the last name alphabe - 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. ### E8. Every callout follows the same reachability rules @@ -109,7 +112,7 @@ Among roles of one kind, sets apply in role-name order, so the last name alphabe - 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 @@ -120,6 +123,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, 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. - Login hooks (#419): - A denied sign-in answers 403 `login_denied`, with the hook's `userMessage` as `message`. A hook that fails closed answers 503 `login_hook_unavailable`, since the user did nothing wrong and can retry. diff --git a/docs/configuration.md b/docs/configuration.md index 0f81d507..3f5f37e6 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -112,19 +112,38 @@ 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. 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 + +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 037dc9d9..50d3a311 100644 --- a/openapi.json +++ b/openapi.json @@ -7301,6 +7301,9 @@ "admin_webhook_updated", "session_created", "webhook_endpoint_disabled", + "admin_audit_sink_created", + "admin_audit_sink_updated", + "admin_audit_sink_deleted", "admin_login_hook_deleted", "admin_login_hook_secret_rotated", "admin_login_hook_set", @@ -7457,6 +7460,9 @@ "admin_webhook_updated", "session_created", "webhook_endpoint_disabled", + "admin_audit_sink_created", + "admin_audit_sink_updated", + "admin_audit_sink_deleted", "admin_login_hook_deleted", "admin_login_hook_secret_rotated", "admin_login_hook_set", @@ -10169,6 +10175,1623 @@ } } }, + "/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", + "misconfigured", + "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", + "misconfigured", + "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", + "misconfigured", + "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", + "misconfigured", + "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", + "misconfigured", + "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 6467be2c..715cdbb7 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' | 'admin_login_hook_deleted' | 'admin_login_hook_secret_rotated' | 'admin_login_hook_set' @@ -7057,6 +7060,9 @@ export interface paths { | 'admin_webhook_updated' | 'session_created' | 'webhook_endpoint_disabled' + | 'admin_audit_sink_created' + | 'admin_audit_sink_updated' + | 'admin_audit_sink_deleted' | 'admin_login_hook_deleted' | 'admin_login_hook_secret_rotated' | 'admin_login_hook_set' @@ -9667,6 +9673,1283 @@ 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' + | 'misconfigured' + | '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' + | 'misconfigured' + | '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' + | 'misconfigured' + | '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' + | 'misconfigured' + | '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' + | 'misconfigured' + | '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..6a3f5a4e --- /dev/null +++ b/src/lib/auditSinkTransport.ts @@ -0,0 +1,383 @@ +/* + * 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. + */ +// 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'; + +/** + * 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 SinkMisconfigured extends CalloutError { + constructor(message: string) { + super('misconfigured', 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; + +type DestinationProblem = { problem: string; failure: 'refused' | 'misconfigured' }; + +function destinationProblem( + settings: OtlpSinkSettings | SyslogSinkSettings, + env: EnvSource, +): DestinationProblem | null { + if (settings.kind === 'otlp') { + const problem = calloutUrlProblem(settings.endpoint, env); + return problem ? { problem: `endpoint ${problem}`, failure: 'refused' } : null; + } + + 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 misconfigured('transport must be tls in production'); + } + if (Boolean(settings.tlsClientCertEnv) !== Boolean(settings.tlsClientKeyEnv)) { + return misconfigured('tlsClientCertEnv and tlsClientKeyEnv must be set together'); + } + + const problem = calloutHostProblem(settings.host, env); + 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 SinkMisconfigured(`${name} is not allowed`); + const value = env[name]; + if (!value) throw new SinkMisconfigured(`${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 SinkMisconfigured(`${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 destination = destinationProblem(settings, env); + if (destination) { + return Promise.reject( + new CalloutError(destination.failure, `Audit sink ${destination.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 a0485f49..00f65070 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', 'admin_login_hook_deleted', 'admin_login_hook_secret_rotated', 'admin_login_hook_set', diff --git a/src/server.ts b/src/server.ts index e6b4dc11..fa0b6658 100644 --- a/src/server.ts +++ b/src/server.ts @@ -18,6 +18,7 @@ import { LoginHook } from './models/loginHooks.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 { startLoginHookMaintenance } from './services/loginHookService.js'; import { initializeMetadataService } from './services/metadataServiceBootstrap.js'; @@ -75,6 +76,7 @@ async function startServer() { startOidcPayloadPurge(); startBackchannelLogoutSweep(); startWebhookDelivery(); + startAuditSinkDelivery(); startLoginHookMaintenance(); } catch (err) { logger.error('Failed to start server:', err); 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..a7fe11b4 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,21 @@ function getRetentionSequelize(env = process.env): Sequelize { return retentionSequelize; } +/** + * 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<{ 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 ? { sinkId: row.id, seq: Number(row.cursorSeq) } : null; +} + async function writeArchiveFile(archiveDir: string, events: ExportedAuthEvent[]) { const first = events[0]; const last = events[events.length - 1]; @@ -92,8 +107,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 +165,7 @@ export async function runAuditRetention( let archived = 0; for (;;) { + 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', @@ -175,9 +190,17 @@ export async function runAuditRetention( if (maxSeq === null || Number(maxSeq) < 1) return 'finished' as const; + 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; + 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 2f8af71f..e76e08a2 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..07c51471 --- /dev/null +++ b/tests/integration/admin/auditSinks.spec.ts @@ -0,0 +1,220 @@ +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: 'misconfigured', + 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: '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/postgres/auditSinks.spec.ts b/tests/postgres/auditSinks.spec.ts new file mode 100644 index 00000000..a94f5c91 --- /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 disabled 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 d18e6788..72f343e6 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..5762ac06 --- /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: 'misconfigured', 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('misconfigured'); + 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('misconfigured'); + 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( + 'misconfigured', + ); + 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('misconfigured'); + 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 4beb14ca..648762dc 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..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' })); @@ -123,6 +129,54 @@ 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: [{ 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: [{ id: 'sink-new', cursorSeq: '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 +311,18 @@ describe('separate retention connection', () => { retentionQuery.mockImplementation(async (sql: string) => sql.includes('pg_try_advisory_xact_lock') ? [{ locked: true }] : [{ max_seq: null }], ); + query.mockResolvedValue([]); 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); + }); +});