diff --git a/.changeset/audit-chain-head.md b/.changeset/audit-chain-head.md new file mode 100644 index 00000000..7dbeee26 --- /dev/null +++ b/.changeset/audit-chain-head.md @@ -0,0 +1,10 @@ +--- +'seamless-auth-api': minor +--- + +The audit chain head is protected and can be signed (#595). + +- A new migration adds a trigger to `auth_event_chain_head` that refuses INSERT, DELETE and TRUNCATE, and any change to `seq` or `last_hash` outside the `auth_events` insert trigger, which now runs as SECURITY DEFINER. A role that deletes the newest audit events can no longer move the head back to hide it, so `GET /admin/auth-events/integrity` reports the loss as `head_mismatch`. +- New optional `AUDIT_CHAIN_KEY`. When set, every audit insert signs the new head with an HMAC under it, and the integrity check fails a head whose signature is missing (`head_unsigned`, a new `reason`) or does not verify (`head_mismatch`). Set it on every instance. The migration signs the head when the key is set while it runs. Otherwise sign it once with `node dist/scripts/sealAuditHead.js`, and again after rotating the key. Production warns at boot while it is unset. +- The integrity report gains `headSigned`. +- `docs/security-posture.md` now recommends revoking writes on `auth_event_chain_head` as well, and notes that the retention setting is open to any session, so the DELETE privilege is the control. diff --git a/docs/configuration.md b/docs/configuration.md index c105f99d..891ef779 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -115,11 +115,12 @@ so it does nothing at all without an archive directory. The job runs a minute af then daily, and each run also logs the audit chain head as an external anchor. See [Audit trail integrity](./security-posture.md#audit-trail-integrity). -| Variable | Required | Default | Notes | -| ------------------------------ | -------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `AUDIT_RETENTION_DAYS` | No | - | Whole days to keep audit events. Unset, or anything that is not a positive whole number, keeps everything. Set it from the records retention schedule that applies to the deployment, not from a product default: authentication audit events are records. | -| `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. | +| Variable | Required | Default | Notes | +| ------------------------------ | ------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `AUDIT_RETENTION_DAYS` | No | - | Whole days to keep audit events. Unset, or anything that is not a positive whole number, keeps everything. Set it from the records retention schedule that applies to the deployment, not from a product default: authentication audit events are records. | +| `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. | +| `AUDIT_CHAIN_KEY` | Recommended in production | - | HMAC key that signs the audit chain head, so a head moved back over deleted events fails the integrity check. Every instance needs the same value. Set it before migrating, or sign the head once with `node dist/scripts/sealAuditHead.js` afterwards, and again after rotating it. Unset, nothing is signed and production warns at boot. See [A signed head](./security-posture.md#a-signed-head). | 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 diff --git a/docs/security-posture.md b/docs/security-posture.md index 5542681a..26b2f43a 100644 --- a/docs/security-posture.md +++ b/docs/security-posture.md @@ -682,46 +682,102 @@ not cover them, because lockout only ever reads a short window of them. one-row table, `auth_event_chain_head`, advanced with an UPDATE so that concurrent inserts queue on its row lock rather than linking to the same predecessor. - **Append-only.** A trigger refuses every UPDATE and TRUNCATE on the table, and every - DELETE unless the transaction has set `seamless.audit_retention = 'on'`, which only - the retention job does. + DELETE unless the transaction has set `seamless.audit_retention = 'on'`. +- **A protected head.** A trigger on `auth_event_chain_head` refuses INSERT, DELETE and + TRUNCATE, and refuses any change to `seq` or `last_hash` that does not come from the + insert trigger. The insert trigger runs as SECURITY DEFINER, so the application role + needs no write access to those columns. Without this, a role that could delete the + newest events could move the head back to match and the chain still verified. - **No user foreign key.** It used to null `user_id` when a user was deleted. A row now keeps the id of the user it was about after that user is gone. The id is a UUID, and removing old rows is a job for retention, not for user deletion. +The retention setting is not an access control. `seamless.audit_retention` is a custom +setting, and any session can set it, so the trigger only stops the application deleting +events by accident. What decides who can delete events is the DELETE privilege, which is +why the grants below take it away from the application role. + +### A signed head + +With `AUDIT_CHAIN_KEY` set (see [configuration](./configuration.md#audit-retention)), the +head also carries `signature`, an HMAC-SHA256 under that key of the head's `seq` and hash, +and `signed_seq`, the `seq` it was made for. The database never sees the key. Every insert +moves the signature onto the new head in the same transaction, while the head is still +locked. + +A head moved back over a truncated tail, or onto forged events, then has no valid +signature, and making one takes the key. This holds even against a role that owns the +tables and can disable their triggers. + +The application only signs forward from a signature that verifies. A head that is +unsigned, or whose signature is wrong, stays that way and keeps failing the check, since +signing over it would erase the evidence. The head trigger also refuses clearing the +signature or moving `signed_seq` backwards. + +Setting it up: + +- **New deployment.** Set `AUDIT_CHAIN_KEY` before the first migration. The migration + that adds the signature signs the head when the key is set while it runs. +- **Existing deployment.** Set `AUDIT_CHAIN_KEY` on every instance, then run the upgrade. + If the key was not set while the migration ran, sign the head once by hand with + `node dist/scripts/sealAuditHead.js`, run with the server's database environment. It + refuses a chain that does not verify. +- **Every instance needs the same key.** An event written by an instance without it leaves + the head unsigned (`head_unsigned`) until an instance with the key writes the next one. +- **Rotating the key.** Set the new key on every instance and run the seal script once. + Until then the check reports `head_mismatch`, and new events are not signed. + +Without the key nothing is signed, the check works as before, and its report carries +`headSigned: false`. Production logs a warning at boot while the key is unset. + ### Checking it `GET /admin/auth-events/integrity` (admin, read) recomputes every hash and reports the first failure: -| `reason` | Meaning | -| --------------- | ---------------------------------------------------------------- | -| `hash_mismatch` | the row's content no longer matches its hash: it was edited | -| `sequence_gap` | rows are missing from the middle of the chain | -| `broken_link` | `prev_hash` does not match the previous row: rows were reordered | -| `head_mismatch` | the newest rows are missing, or the head itself was changed | +| `reason` | Meaning | +| --------------- | ------------------------------------------------------------------------------------------ | +| `hash_mismatch` | the row's content no longer matches its hash: it was edited | +| `sequence_gap` | rows are missing from the middle of the chain | +| `broken_link` | `prev_hash` does not match the previous row: rows were reordered | +| `head_mismatch` | the newest rows are missing, the head itself was changed, or its signature does not verify | +| `head_unsigned` | `AUDIT_CHAIN_KEY` is set and the head has no signature, or one for an older `seq` | -It also returns `head` (the latest `seq` and hash) and `anchorHash`, which is the -`prev_hash` of the oldest remaining row. Once retention has removed old rows, that is the -hash of the last row archived, and it ties the remaining chain to the archive. +It also returns `head` (the latest `seq` and hash), `headSigned`, and `anchorHash`, which +is the `prev_hash` of the oldest remaining row. Once retention has removed old rows, that is +the hash of the last row archived, and it ties the remaining chain to the archive. ### What it does not stop -A role that owns the table can disable the triggers and rewrite the whole chain -consistently. Nothing inside the database can detect that, so two things outside it close -the gap: +A role that owns the tables can disable the triggers and rewrite the whole chain +consistently. Without the key it can also move the head to match, and with the key it can +still put back an older head and signature that it copied while they were current. Nothing +inside the database can detect either, so two things outside it close the gap: 1. **Least privilege.** Run migrations as the table owner and the application as a role - without UPDATE, DELETE or TRUNCATE on `auth_events`: + that cannot change the trail or its head: ```sql REVOKE UPDATE, DELETE, TRUNCATE ON public.auth_events FROM seamless_app; + REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON public.auth_event_chain_head FROM seamless_app; + GRANT SELECT ON public.auth_event_chain_head TO seamless_app; + GRANT UPDATE (signed_seq, signature) ON public.auth_event_chain_head TO seamless_app; + REVOKE CREATE ON SCHEMA public FROM PUBLIC, seamless_app; ``` - The retention job then needs DELETE, from a separate role. + Postgres 15 and later no longer grant CREATE on `public` to everyone, but a cluster + upgraded from an older version keeps that grant. No role but the owner should create + objects in the schema the audit functions live in. + + The application keeps INSERT on `auth_events`, which the insert trigger chains, and may + only write the signature columns of the head, which it cannot forge without the key. + The retention job needs DELETE on `auth_events`, from a separate role + (`AUDIT_RETENTION_DATABASE_URL`). That role can still delete the newest events, but it + cannot move the head, so the check reports the loss as `head_mismatch`. 2. **External anchors.** Record `head` somewhere the database cannot reach: the evidence - package, a ticket, or a log store. A later check whose chain does not pass through a - recorded head shows the history was rewritten. + package, a ticket, or a log store. The retention job logs it daily. A later check whose + chain does not pass through a recorded head shows the history was rewritten. ### Retention and export diff --git a/openapi.json b/openapi.json index 6e277e0c..68995cca 100644 --- a/openapi.json +++ b/openapi.json @@ -7785,6 +7785,7 @@ "lastSeq": 0, "anchorHash": "string", "head": { "seq": 0, "hash": "string" }, + "headSigned": true, "firstFailure": { "seq": 0, "id": "string", "reason": null } }, "schema": { @@ -7805,6 +7806,7 @@ }, "required": ["seq", "hash"] }, + "headSigned": { "type": "boolean" }, "firstFailure": { "type": "object", "nullable": true, @@ -7813,7 +7815,13 @@ "id": { "type": "string", "nullable": true }, "reason": { "type": "string", - "enum": ["hash_mismatch", "broken_link", "sequence_gap", "head_mismatch"] + "enum": [ + "hash_mismatch", + "broken_link", + "sequence_gap", + "head_mismatch", + "head_unsigned" + ] } }, "required": ["seq", "id", "reason"] @@ -7827,6 +7835,7 @@ "lastSeq", "anchorHash", "head", + "headSigned", "firstFailure" ] } diff --git a/src/generated/api.ts b/src/generated/api.ts index 715cdbb7..d9beae79 100644 --- a/src/generated/api.ts +++ b/src/generated/api.ts @@ -7393,6 +7393,7 @@ export interface paths { * "seq": 0, * "hash": "string" * }, + * "headSigned": true, * "firstFailure": { * "seq": 0, * "id": "string", @@ -7411,11 +7412,17 @@ export interface paths { seq: number; hash: string | null; } | null; + headSigned: boolean; firstFailure: { seq: number; id: string | null; /** @enum {string} */ - reason: 'hash_mismatch' | 'broken_link' | 'sequence_gap' | 'head_mismatch'; + reason: + | 'hash_mismatch' + | 'broken_link' + | 'sequence_gap' + | 'head_mismatch' + | 'head_unsigned'; } | null; }; }; diff --git a/src/migrations/20261120120000-protect-auth-event-chain-head.cjs b/src/migrations/20261120120000-protect-auth-event-chain-head.cjs new file mode 100644 index 00000000..c648ede0 --- /dev/null +++ b/src/migrations/20261120120000-protect-auth-event-chain-head.cjs @@ -0,0 +1,182 @@ +/* + * 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'; + +const { createHmac } = require('crypto'); + +/** + * Protects `auth_event_chain_head` the way `auth_events` is protected, and gives it a + * signature a server secret makes. + * + * Before this the head was an ordinary table. A role that could delete from the end of + * `auth_events` could move the head back to match, and the chain verified. Now: + * + * - A trigger refuses INSERT, DELETE and TRUNCATE on the head, and refuses any change to + * `seq` or `last_hash` that does not come from the `auth_events` insert trigger. That + * trigger now runs as SECURITY DEFINER, so the application role needs no write access + * to the head columns at all. + * - `signed_seq` and `signature` carry an HMAC of the head under `AUDIT_CHAIN_KEY`, which + * the database never sees. The application moves it forward on every insert. A head + * moved back over a truncated tail has no valid signature, and making one takes the key. + * The trigger refuses clearing the signature or moving `signed_seq` backwards. + * + * When `AUDIT_CHAIN_KEY` is set while this runs, the current head is signed here. + * Otherwise it stays unsigned until an operator signs it with the seal script. The + * signing format must match `signAuditHead` in src/services/auditHeadSignature.ts. + * + * @type {import('sequelize-cli').Migration} + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.transaction(async (transaction) => { + const run = (sql, replacements) => + queryInterface.sequelize.query(sql, { transaction, replacements }); + + await run(` + ALTER TABLE public.auth_event_chain_head + ADD COLUMN signed_seq bigint, + ADD COLUMN signature character(64); + `); + + const key = process.env.AUDIT_CHAIN_KEY && process.env.AUDIT_CHAIN_KEY.trim(); + if (key) { + const [[head]] = await run( + 'SELECT seq, last_hash FROM public.auth_event_chain_head WHERE id = 1 FOR UPDATE', + ); + + if (head) { + const signature = createHmac('sha256', key) + .update(`seamless-audit-head:v1:${head.seq}:${head.last_hash ?? ''}`) + .digest('hex'); + + await run( + 'UPDATE public.auth_event_chain_head SET signed_seq = seq, signature = :signature WHERE id = 1', + { signature }, + ); + } + } + + await run(` + -- Redefined, not only altered: as SECURITY DEFINER every call it makes must match + -- its target exactly, or a better-matching overload created in public by another + -- role would run with the owner's privileges. prev_hash is character(64), hence + -- the cast to the text parameter auth_event_hash declares. + CREATE OR REPLACE FUNCTION public.auth_events_chain() + RETURNS trigger + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, public, pg_temp + AS $$ + DECLARE + head record; + BEGIN + UPDATE public.auth_event_chain_head + SET seq = seq + 1 + WHERE id = 1 + RETURNING seq, last_hash INTO head; + + NEW.seq := head.seq; + NEW.prev_hash := head.last_hash; + NEW.hash := public.auth_event_hash(NEW.prev_hash::text, public.auth_event_payload(NEW)); + + UPDATE public.auth_event_chain_head SET last_hash = NEW.hash WHERE id = 1; + + RETURN NEW; + END + $$; + + REVOKE ALL ON FUNCTION public.auth_events_chain() FROM PUBLIC; + + CREATE FUNCTION public.auth_event_chain_head_guard() + RETURNS trigger + LANGUAGE plpgsql + AS $$ + BEGIN + IF TG_OP <> 'UPDATE' THEN + RAISE EXCEPTION 'auth_event_chain_head: % refused', TG_OP + USING ERRCODE = 'insufficient_privilege'; + END IF; + + IF NEW.id IS DISTINCT FROM OLD.id THEN + RAISE EXCEPTION 'auth_event_chain_head: id is fixed' + USING ERRCODE = 'insufficient_privilege'; + END IF; + + -- Depth 1 is a statement aimed at this table. The auth_events insert trigger + -- updating it is depth 2. + IF (NEW.seq, NEW.last_hash) IS DISTINCT FROM (OLD.seq, OLD.last_hash) + AND (pg_trigger_depth() < 2 OR NEW.seq < OLD.seq) THEN + RAISE EXCEPTION 'auth_event_chain_head: the head only moves when an event is inserted' + USING ERRCODE = 'insufficient_privilege'; + END IF; + + IF (NEW.signed_seq, NEW.signature) IS DISTINCT FROM (OLD.signed_seq, OLD.signature) + AND ( + NEW.signed_seq IS NULL + OR NEW.signature IS NULL + OR NEW.signed_seq > NEW.seq + OR NEW.signed_seq < OLD.signed_seq + ) THEN + RAISE EXCEPTION 'auth_event_chain_head: the signature can only move forward' + USING ERRCODE = 'insufficient_privilege'; + END IF; + + RETURN NEW; + END + $$; + + CREATE TRIGGER auth_event_chain_head_guard + BEFORE INSERT OR UPDATE OR DELETE ON public.auth_event_chain_head + FOR EACH ROW EXECUTE FUNCTION public.auth_event_chain_head_guard(); + + CREATE TRIGGER auth_event_chain_head_no_truncate + BEFORE TRUNCATE ON public.auth_event_chain_head + FOR EACH STATEMENT EXECUTE FUNCTION public.auth_event_chain_head_guard(); + `); + }); + }, + + async down(queryInterface) { + await queryInterface.sequelize.transaction(async (transaction) => { + await queryInterface.sequelize.query( + ` + DROP TRIGGER IF EXISTS auth_event_chain_head_no_truncate ON public.auth_event_chain_head; + DROP TRIGGER IF EXISTS auth_event_chain_head_guard ON public.auth_event_chain_head; + DROP FUNCTION IF EXISTS public.auth_event_chain_head_guard(); + + CREATE OR REPLACE FUNCTION public.auth_events_chain() + RETURNS trigger + LANGUAGE plpgsql + SECURITY INVOKER + AS $$ + DECLARE + head record; + BEGIN + UPDATE public.auth_event_chain_head + SET seq = seq + 1 + WHERE id = 1 + RETURNING seq, last_hash INTO head; + + NEW.seq := head.seq; + NEW.prev_hash := head.last_hash; + NEW.hash := public.auth_event_hash(NEW.prev_hash, public.auth_event_payload(NEW)); + + UPDATE public.auth_event_chain_head SET last_hash = NEW.hash WHERE id = 1; + + RETURN NEW; + END + $$; + + ALTER TABLE public.auth_event_chain_head + DROP COLUMN IF EXISTS signature, + DROP COLUMN IF EXISTS signed_seq; + `, + { transaction }, + ); + }); + }, +}; diff --git a/src/models/authEvents.ts b/src/models/authEvents.ts index 2de3a39c..492fcf2c 100644 --- a/src/models/authEvents.ts +++ b/src/models/authEvents.ts @@ -38,7 +38,7 @@ export interface AuthEventAttributes { updated_at?: Date; } -type AuthEventCreationAttributes = Optional< +export type AuthEventCreationAttributes = Optional< AuthEventAttributes, | 'id' | 'created_at' diff --git a/src/schemas/admin.responses.ts b/src/schemas/admin.responses.ts index 28d6669d..1f5094d9 100644 --- a/src/schemas/admin.responses.ts +++ b/src/schemas/admin.responses.ts @@ -30,11 +30,18 @@ export const AuditIntegrityResponseSchema = z.object({ lastSeq: z.number().int().nullable(), anchorHash: z.string().nullable(), head: z.object({ seq: z.number().int(), hash: z.string().nullable() }).nullable(), + headSigned: z.boolean(), firstFailure: z .object({ seq: z.number().int(), id: z.string().nullable(), - reason: z.enum(['hash_mismatch', 'broken_link', 'sequence_gap', 'head_mismatch']), + reason: z.enum([ + 'hash_mismatch', + 'broken_link', + 'sequence_gap', + 'head_mismatch', + 'head_unsigned', + ]), }) .nullable(), }); diff --git a/src/scripts/sealAuditHead.ts b/src/scripts/sealAuditHead.ts new file mode 100644 index 00000000..56322118 --- /dev/null +++ b/src/scripts/sealAuditHead.ts @@ -0,0 +1,28 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +/** + * Signs the audit chain head with `AUDIT_CHAIN_KEY`: once after the key is first set on a + * deployment that migrated without it, and again after the key is rotated. Refuses a + * chain that does not verify. Run as `node dist/scripts/sealAuditHead.js` with the same + * database environment as the server. + */ + +import { getSequelize, initializeModels } from '../models/index.js'; +import { sealAuditChainHead } from '../services/auditIntegrity.js'; + +try { + await initializeModels(); + const head = await sealAuditChainHead(); + console.log(`Signed the audit chain head at seq ${head.seq} (hash ${head.hash ?? 'none'}).`); +} catch (err) { + console.error(`Did not sign the audit chain head: ${(err as Error).message}`); + process.exitCode = 1; +} finally { + await getSequelize() + .close() + .catch(() => undefined); +} diff --git a/src/server.ts b/src/server.ts index fa0b6658..5e0bf9e4 100644 --- a/src/server.ts +++ b/src/server.ts @@ -17,6 +17,7 @@ import { initializeModels } from './models/index.js'; import { LoginHook } from './models/loginHooks.js'; import { TotpCredential } from './models/totpCredentials.js'; import { WebhookEndpoint } from './models/webhookEndpoints.js'; +import { warnIfAuditChainKeyUnset } from './services/auditHeadSignature.js'; import { startAuditMaintenance } from './services/auditRetention.js'; import { startAuditSinkDelivery } from './services/auditSinkService.js'; import { warnOnBreakGlassMisconfiguration } from './services/breakGlassService.js'; @@ -42,6 +43,7 @@ async function startServer() { assertServiceTokenConfig(); assertDevModeIsLocal(); warnIfUnboundOAuthStateSet(); + warnIfAuditChainKeyUnset(); const models = await initializeModels(); diff --git a/src/services/auditHeadSignature.ts b/src/services/auditHeadSignature.ts new file mode 100644 index 00000000..322b72b9 --- /dev/null +++ b/src/services/auditHeadSignature.ts @@ -0,0 +1,135 @@ +/* + * 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 { createHmac, timingSafeEqual } from 'crypto'; +import { QueryTypes, Transaction } from 'sequelize'; + +import { getSequelize } from '../models/index.js'; +import getLogger from '../utils/logger.js'; + +const logger = getLogger('auditHeadSignature'); + +type EnvSource = Record; + +export function auditChainKey(env: EnvSource = process.env): string | null { + return env.AUDIT_CHAIN_KEY?.trim() || null; +} + +export function warnIfAuditChainKeyUnset(env: EnvSource = process.env) { + if (env.NODE_ENV === 'production' && !auditChainKey(env)) { + logger.warn( + 'AUDIT_CHAIN_KEY is not set, so the audit chain head is not signed and a role that can ' + + 'delete the newest audit events can hide that it did. See docs/security-posture.md.', + ); + } +} + +// The migration that adds the signature columns signs the head in this same format, so +// the two must change together. +export function signAuditHead(key: string, seq: number, hash: string | null): string { + return createHmac('sha256', key) + .update(`seamless-audit-head:v1:${seq}:${hash ?? ''}`) + .digest('hex'); +} + +export function auditHeadSignatureValid( + key: string, + seq: number, + hash: string | null, + signature: string | null, +): boolean { + if (!signature) return false; + + const expected = Buffer.from(signAuditHead(key, seq, hash), 'hex'); + const given = Buffer.from(signature, 'hex'); + + return given.length === expected.length && timingSafeEqual(given, expected); +} + +type SignedHeadRow = { + signed_seq: string | null; + signature: string | null; + signed_hash: string | null; +}; + +let warnedUnverifiable = false; + +/** + * Moves the head signature onto a row this transaction just inserted. + * + * Runs while the insert still holds the chain head row lock, so no other insert can move + * the head in between. It only signs forward from a signature that verifies: a head that + * is unsigned, or whose signature is wrong, stays that way, because signing over it would + * erase the evidence that it was changed. `sealAuditChainHead` is how an operator signs + * such a head again. + */ +export async function signInsertedAuditHead( + event: { seq?: string | number | null; hash?: string | null; prev_hash?: string | null }, + transaction: Transaction, + key: string, +): Promise { + if (event.seq === null || event.seq === undefined || !event.hash) return false; + + const seq = Number(event.seq); + const signature = signAuditHead(key, seq, event.hash); + const sequelize = getSequelize(); + + const advanced = await sequelize.query( + `UPDATE public.auth_event_chain_head + SET signed_seq = :seq, signature = :signature + WHERE id = 1 AND signed_seq = :prevSeq AND signature = :prevSignature + RETURNING signed_seq`, + { + replacements: { + seq, + signature, + prevSeq: seq - 1, + prevSignature: signAuditHead(key, seq - 1, event.prev_hash ?? null), + }, + transaction, + type: QueryTypes.SELECT, + }, + ); + + if (advanced.length > 0) return true; + + // The signature lags the head when an insert ran without the key, so it is checked + // against the row it was made for rather than the one just before this insert. + const [current] = await sequelize.query( + `SELECT h.signed_seq, h.signature, e.hash AS signed_hash + FROM public.auth_event_chain_head h + LEFT JOIN public.auth_events e ON e.seq = h.signed_seq + WHERE h.id = 1`, + { transaction, type: QueryTypes.SELECT }, + ); + + const signedSeq = current?.signed_seq ? Number(current.signed_seq) : null; + + if ( + signedSeq === null || + signedSeq >= seq || + !auditHeadSignatureValid(key, signedSeq, current.signed_hash, current.signature) + ) { + if (!warnedUnverifiable) { + warnedUnverifiable = true; + logger.error( + 'The audit chain head signature does not verify, so new events are not being signed. ' + + 'Check GET /admin/auth-events/integrity, then sign the head again with ' + + 'node dist/scripts/sealAuditHead.js. See docs/security-posture.md.', + ); + } + return false; + } + + await sequelize.query( + `UPDATE public.auth_event_chain_head + SET signed_seq = :seq, signature = :signature + WHERE id = 1 AND signed_seq = :signedSeq`, + { replacements: { seq, signature, signedSeq }, transaction }, + ); + + return true; +} diff --git a/src/services/auditIntegrity.ts b/src/services/auditIntegrity.ts index c2611f3b..6e93bdfb 100644 --- a/src/services/auditIntegrity.ts +++ b/src/services/auditIntegrity.ts @@ -4,11 +4,13 @@ * See LICENSE file in the project root for full license information */ -import { QueryTypes } from 'sequelize'; +import { QueryTypes, Transaction } from 'sequelize'; import { getSequelize } from '../models/index.js'; +import { auditChainKey, auditHeadSignatureValid, signAuditHead } from './auditHeadSignature.js'; -export type ChainFailureReason = 'hash_mismatch' | 'broken_link' | 'sequence_gap' | 'head_mismatch'; +export type ChainFailureReason = + 'hash_mismatch' | 'broken_link' | 'sequence_gap' | 'head_mismatch' | 'head_unsigned'; export interface AuditIntegrityReport { verified: boolean; @@ -19,6 +21,8 @@ export interface AuditIntegrityReport { /** The `prev_hash` of the oldest remaining row: the last hash retention archived away. */ anchorHash: string | null; head: { seq: number; hash: string | null } | null; + /** Whether the head carries a valid `AUDIT_CHAIN_KEY` signature. Always false without the key. */ + headSigned: boolean; firstFailure: { seq: number; id: string | null; reason: ChainFailureReason } | null; } @@ -31,9 +35,15 @@ type ChainRow = { first_failure: { seq: string; id: string; - reason: Exclude; + reason: Exclude; + } | null; + head: { + seq: string; + hash: string | null; + signed_seq: string | null; + signature: string | null; + signed_hash: string | null; } | null; - head: { seq: string; hash: string | null } | null; }; // The expected hash is recomputed with the same database functions the insert trigger @@ -78,30 +88,39 @@ const VERIFY_CHAIN_SQL = ` ) AS first_failure, ( SELECT row_to_json(h) FROM ( - SELECT seq, last_hash AS hash FROM public.auth_event_chain_head WHERE id = 1 + SELECT h.seq, h.last_hash AS hash, h.signed_seq, h.signature, s.hash AS signed_hash + FROM public.auth_event_chain_head h + LEFT JOIN public.auth_events s ON s.seq = h.signed_seq + WHERE h.id = 1 ) h ) AS head `; const toNumber = (value: string | null) => (value === null ? null : Number(value)); -/** - * Walks the whole audit chain and reports the first place it does not hold. - * - * A row whose content changed fails its own hash. A row removed from the middle leaves a - * gap in `seq`. Rows removed from the end leave the chain head ahead of the newest row. - * Rewriting the entire chain consistently is not detectable from inside the database, - * which is why the head this returns is worth recording somewhere else. - */ -export async function verifyAuthEventChain(): Promise { +type HeadSignature = 'valid' | 'invalid' | 'unsigned' | 'stale'; + +function headSignature(key: string, head: NonNullable): HeadSignature { + if (head.signature === null || head.signed_seq === null) return 'unsigned'; + + const signedSeq = Number(head.signed_seq); + if (!auditHeadSignatureValid(key, signedSeq, head.signed_hash, head.signature)) { + return 'invalid'; + } + + return signedSeq === Number(head.seq) ? 'valid' : 'stale'; +} + +async function inspectChain(transaction?: Transaction) { const [row] = await getSequelize().query(VERIFY_CHAIN_SQL, { type: QueryTypes.SELECT, + transaction, }); const head = row.head ? { seq: Number(row.head.seq), hash: row.head.hash } : null; const lastSeq = toNumber(row.last_seq); - let firstFailure: AuditIntegrityReport['firstFailure'] = row.first_failure + let chainFailure: AuditIntegrityReport['firstFailure'] = row.first_failure ? { seq: Number(row.first_failure.seq), id: row.first_failure.id, @@ -112,8 +131,39 @@ export async function verifyAuthEventChain(): Promise { const headMatches = head !== null && head.seq === (lastSeq ?? head.seq) && head.hash === row.last_hash; - if (!firstFailure && !headMatches) { - firstFailure = { seq: head?.seq ?? lastSeq ?? 0, id: null, reason: 'head_mismatch' }; + if (!chainFailure && !headMatches) { + chainFailure = { seq: head?.seq ?? lastSeq ?? 0, id: null, reason: 'head_mismatch' }; + } + + return { row, head, lastSeq, chainFailure }; +} + +/** + * Walks the whole audit chain and reports the first place it does not hold. + * + * A row whose content changed fails its own hash. A row removed from the middle leaves a + * gap in `seq`. Rows removed from the end leave the chain head ahead of the newest row. + * With `AUDIT_CHAIN_KEY` set, the head must also carry a signature made with it, so a + * head moved back over a truncated tail, which the database alone would accept, fails. + * Rewriting the entire chain consistently is not detectable from inside the database, + * which is why the head this returns is worth recording somewhere else. + */ +export async function verifyAuthEventChain(): Promise { + const { row, head, lastSeq, chainFailure } = await inspectChain(); + const key = auditChainKey(); + + let firstFailure = chainFailure; + let headSigned = false; + + if (key && row.head && head) { + const signature = headSignature(key, row.head); + headSigned = signature === 'valid'; + + if (!firstFailure && signature === 'invalid') { + firstFailure = { seq: head.seq, id: null, reason: 'head_mismatch' }; + } else if (!firstFailure && signature !== 'valid') { + firstFailure = { seq: head.seq, id: null, reason: 'head_unsigned' }; + } } return { @@ -124,6 +174,55 @@ export async function verifyAuthEventChain(): Promise { lastSeq, anchorHash: row.anchor_hash, head, + headSigned, firstFailure, }; } + +export class AuditHeadSealError extends Error { + constructor(message: string) { + super(message); + this.name = 'AuditHeadSealError'; + } +} + +/** + * Signs the current chain head with `AUDIT_CHAIN_KEY`, replacing whatever signature it had. + * + * This is an operator attesting that the head as it stands is genuine: once after the key + * is first set, and after the key is rotated. It refuses a chain that does not verify on + * its own, and holds the head lock throughout so no insert moves the head mid-check. + */ +export async function sealAuditChainHead(): Promise<{ seq: number; hash: string | null }> { + const key = auditChainKey(); + if (!key) throw new AuditHeadSealError('AUDIT_CHAIN_KEY is not set.'); + + return getSequelize().transaction(async (transaction) => { + await getSequelize().query( + 'SELECT id FROM public.auth_event_chain_head WHERE id = 1 FOR UPDATE', + { type: QueryTypes.SELECT, transaction }, + ); + + const { head, chainFailure } = await inspectChain(transaction); + + if (!head) throw new AuditHeadSealError('The audit chain head row is missing.'); + if (chainFailure) { + throw new AuditHeadSealError( + `The audit chain does not verify (${chainFailure.reason} at seq ${chainFailure.seq}). ` + + 'Investigate before signing its head.', + ); + } + + await getSequelize().query( + `UPDATE public.auth_event_chain_head + SET signed_seq = :seq, signature = :signature + WHERE id = 1`, + { + replacements: { seq: head.seq, signature: signAuditHead(key, head.seq, head.hash) }, + transaction, + }, + ); + + return head; + }); +} diff --git a/src/services/authEventService.ts b/src/services/authEventService.ts index 4e173065..e2ab4867 100644 --- a/src/services/authEventService.ts +++ b/src/services/authEventService.ts @@ -9,10 +9,12 @@ import { Request } from 'express'; import { classifyDeviceClass } from '../lib/deviceClass.js'; import { mailProviderFor } from '../lib/mailProvider.js'; import { isOwnerEmail } from '../lib/ownerAdmin.js'; -import { AuthEvent } from '../models/authEvents.js'; +import { AuthEvent, AuthEventCreationAttributes } from '../models/authEvents.js'; +import { getSequelize } from '../models/index.js'; import type { AuthEventType } from '../schemas/authEvent.types.js'; import type { AuthenticatedRequest } from '../types/types.js'; import { redactMetadata } from '../utils/redaction.js'; +import { auditChainKey, signInsertedAuditHead } from './auditHeadSignature.js'; import { recordAuditWriteFailure } from './auditHealth.js'; import { recordAuthFailure } from './authFailureCounter.js'; @@ -77,6 +79,22 @@ interface AuthEventContextOptions { metadata?: Record | null; } +async function appendAuthEvent(values: AuthEventCreationAttributes) { + const key = auditChainKey(); + + if (!key) { + await AuthEvent.create(values); + return; + } + + // One transaction, so the head row lock the insert trigger takes is still held when + // the signature moves onto the new head. + await getSequelize().transaction(async (transaction) => { + const event = await AuthEvent.create(values, { transaction }); + await signInsertedAuditHead(event, transaction, key); + }); +} + function deploymentId() { return process.env.APP_ID?.trim() || null; } @@ -117,7 +135,7 @@ export class AuthEventService { await recordAuthFailure({ userId, type: normalizedType }); try { - await AuthEvent.create({ + await appendAuthEvent({ user_id: userId, actor_user_id: actorUserId, session_id: sessionId, diff --git a/tests/integration/admin/admin.spec.ts b/tests/integration/admin/admin.spec.ts index 1f68dc0a..456eac40 100644 --- a/tests/integration/admin/admin.spec.ts +++ b/tests/integration/admin/admin.spec.ts @@ -516,6 +516,7 @@ describe('GET /admin/auth-events/integrity', () => { lastSeq: 10, anchorHash: null, head: { seq: 10, hash: 'a'.repeat(64) }, + headSigned: false, firstFailure: { seq: 4, id: 'event-4', reason: 'hash_mismatch' }, }; (verifyAuthEventChain as any).mockResolvedValue(report); diff --git a/tests/postgres/auditChainHead.spec.ts b/tests/postgres/auditChainHead.spec.ts new file mode 100644 index 00000000..0d0e4ec2 --- /dev/null +++ b/tests/postgres/auditChainHead.spec.ts @@ -0,0 +1,236 @@ +import { QueryTypes } from 'sequelize'; +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; + +import { getSequelize, initializeModels } from '../../src/models/index.js'; +import { sealAuditChainHead, verifyAuthEventChain } from '../../src/services/auditIntegrity.js'; +import { AuthEventService } from '../../src/services/authEventService.js'; + +const KEY = 'audit-chain-head-test-key'; + +type Head = { + seq: string; + last_hash: string | null; + signed_seq: string | null; + signature: string | null; +}; + +async function head() { + const [row] = await getSequelize().query( + 'SELECT seq, last_hash, signed_seq, signature FROM auth_event_chain_head WHERE id = 1', + { type: QueryTypes.SELECT }, + ); + return row; +} + +async function logEvents(count: number) { + await Promise.all( + Array.from({ length: count }, (_, index) => + AuthEventService.logContext({ type: 'login_success', metadata: { index } }), + ), + ); +} + +async function hashAt(seq: number) { + const [row] = await getSequelize().query<{ hash: string }>( + 'SELECT hash FROM auth_events WHERE seq = :seq', + { replacements: { seq }, type: QueryTypes.SELECT }, + ); + return row.hash; +} + +async function withGuardDisabled(fn: () => Promise) { + const sequelize = getSequelize(); + await sequelize.query( + 'ALTER TABLE auth_event_chain_head DISABLE TRIGGER auth_event_chain_head_guard', + ); + try { + await fn(); + } finally { + await sequelize.query( + 'ALTER TABLE auth_event_chain_head ENABLE TRIGGER auth_event_chain_head_guard', + ); + } +} + +// The steps from the review: retention's setting is open to any session, so DELETE the +// newest rows under it, then move the head back to the last row left. +async function truncateTail(keep: number) { + await getSequelize().transaction(async (transaction) => { + await getSequelize().query("SET LOCAL seamless.audit_retention = 'on'", { transaction }); + await getSequelize().query('DELETE FROM auth_events WHERE seq > :keep', { + replacements: { keep }, + transaction, + }); + }); +} + +beforeAll(async () => { + await initializeModels(); +}); + +afterEach(() => { + delete process.env.AUDIT_CHAIN_KEY; +}); + +afterAll(async () => { + await getSequelize().close(); +}); + +describe('auth_event_chain_head guard', () => { + it.each([ + ['UPDATE seq', 'UPDATE auth_event_chain_head SET seq = seq - 1'], + ['UPDATE last_hash', "UPDATE auth_event_chain_head SET last_hash = repeat('0', 64)"], + ['INSERT', 'INSERT INTO auth_event_chain_head (id, seq) VALUES (2, 0)'], + ['DELETE', 'DELETE FROM auth_event_chain_head'], + ['TRUNCATE', 'TRUNCATE auth_event_chain_head'], + ])('refuses %s', async (_op, sql) => { + await logEvents(1); + + await expect(getSequelize().query(sql)).rejects.toThrow(/auth_event_chain_head/); + }); + + it('refuses re-heading a truncated tail, so the truncation is reported', async () => { + await logEvents(3); + const { seq } = await head(); + const keep = Number(seq) - 2; + const keptHash = await hashAt(keep); + + await truncateTail(keep); + + await expect( + getSequelize().query( + 'UPDATE auth_event_chain_head SET seq = :keep, last_hash = :keptHash WHERE id = 1', + { replacements: { keep, keptHash } }, + ), + ).rejects.toThrow(/only moves when an event is inserted/); + + expect((await verifyAuthEventChain()).firstFailure).toMatchObject({ + reason: 'head_mismatch', + }); + + // Leaves the shared database verifying for the files that run after this one. + await withGuardDisabled(() => + getSequelize().query( + 'UPDATE auth_event_chain_head SET seq = :keep, last_hash = :keptHash WHERE id = 1', + { replacements: { keep, keptHash } }, + ), + ); + }); + + it('still lets the insert trigger advance the head', async () => { + const before = Number((await head()).seq); + + await logEvents(5); + + expect(Number((await head()).seq)).toBe(before + 5); + expect((await verifyAuthEventChain()).verified).toBe(true); + }); +}); + +describe('signed chain head', () => { + it('reports an unsigned head as a failure once the key is set, and seals it', async () => { + process.env.AUDIT_CHAIN_KEY = KEY; + + const unsigned = await verifyAuthEventChain(); + expect(unsigned).toMatchObject({ verified: false, headSigned: false }); + expect(unsigned.firstFailure?.reason).toBe('head_unsigned'); + + const sealed = await sealAuditChainHead(); + const report = await verifyAuthEventChain(); + + expect(report).toMatchObject({ verified: true, headSigned: true }); + expect(report.head).toEqual(sealed); + }); + + it('carries the signature forward across concurrent inserts', async () => { + process.env.AUDIT_CHAIN_KEY = KEY; + await sealAuditChainHead(); + + await logEvents(15); + + const current = await head(); + expect(current.signed_seq).toBe(current.seq); + expect(await verifyAuthEventChain()).toMatchObject({ verified: true, headSigned: true }); + }); + + it('catches up after an insert made without the key', async () => { + process.env.AUDIT_CHAIN_KEY = KEY; + await sealAuditChainHead(); + + delete process.env.AUDIT_CHAIN_KEY; + await logEvents(1); + process.env.AUDIT_CHAIN_KEY = KEY; + + expect((await verifyAuthEventChain()).firstFailure?.reason).toBe('head_unsigned'); + + await logEvents(1); + + expect(await verifyAuthEventChain()).toMatchObject({ verified: true, headSigned: true }); + }); + + it('reports a head re-pointed past the trigger, even with the signature moved too', async () => { + process.env.AUDIT_CHAIN_KEY = KEY; + await sealAuditChainHead(); + await logEvents(3); + const { seq, signature } = await head(); + const keep = Number(seq) - 2; + const keptHash = await hashAt(keep); + + await truncateTail(keep); + await withGuardDisabled(() => + getSequelize().query( + `UPDATE auth_event_chain_head + SET seq = :keep, last_hash = :keptHash, signed_seq = :keep, signature = :signature + WHERE id = 1`, + { replacements: { keep, keptHash, signature } }, + ), + ); + + expect((await verifyAuthEventChain()).firstFailure).toMatchObject({ + reason: 'head_mismatch', + }); + + // Signing forward from a signature that does not verify would hide the tampering. + await logEvents(1); + + expect(await verifyAuthEventChain()).toMatchObject({ verified: false, headSigned: false }); + + await sealAuditChainHead(); + }); + + it('refuses clearing the signature or moving it backwards', async () => { + process.env.AUDIT_CHAIN_KEY = KEY; + await sealAuditChainHead(); + + await expect( + getSequelize().query('UPDATE auth_event_chain_head SET signature = NULL, signed_seq = NULL'), + ).rejects.toThrow(/only move forward/); + await expect( + getSequelize().query('UPDATE auth_event_chain_head SET signed_seq = signed_seq - 1'), + ).rejects.toThrow(/only move forward/); + }); + + it('refuses to seal a chain that does not verify', async () => { + process.env.AUDIT_CHAIN_KEY = KEY; + await logEvents(1); + const { seq, last_hash: lastHash } = await head(); + const sequelize = getSequelize(); + + await sequelize.query('ALTER TABLE auth_events DISABLE TRIGGER auth_events_append_only'); + try { + await sequelize.query(`UPDATE auth_events SET metadata = '{"index":99}' WHERE seq = :seq`, { + replacements: { seq }, + }); + + await expect(sealAuditChainHead()).rejects.toThrow(/does not verify \(hash_mismatch/); + + await sequelize.query(`UPDATE auth_events SET metadata = '{"index":0}' WHERE seq = :seq`, { + replacements: { seq }, + }); + } finally { + await sequelize.query('ALTER TABLE auth_events ENABLE TRIGGER auth_events_append_only'); + } + + expect((await head()).last_hash).toBe(lastHash); + }); +}); diff --git a/tests/unit/scripts/sealAuditHead.spec.ts b/tests/unit/scripts/sealAuditHead.spec.ts new file mode 100644 index 00000000..c3956ca6 --- /dev/null +++ b/tests/unit/scripts/sealAuditHead.spec.ts @@ -0,0 +1,43 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const close = vi.fn(); +const initializeModels = vi.fn(); +const sealAuditChainHead = vi.fn(); + +vi.mock('../../../src/models/index.js', () => ({ + getSequelize: () => ({ close }), + initializeModels, +})); + +vi.mock('../../../src/services/auditIntegrity.js', () => ({ sealAuditChainHead })); + +beforeEach(() => { + vi.resetModules(); + process.exitCode = undefined; + close.mockResolvedValue(undefined); +}); + +describe('sealAuditHead script', () => { + it('signs the head and closes the connection', async () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => undefined); + sealAuditChainHead.mockResolvedValue({ seq: 7, hash: 'a'.repeat(64) }); + + await import('../../../src/scripts/sealAuditHead.js'); + + expect(log).toHaveBeenCalledWith(expect.stringContaining('seq 7')); + expect(close).toHaveBeenCalled(); + expect(process.exitCode).toBeUndefined(); + }); + + it('exits non-zero when the head cannot be signed', async () => { + const err = vi.spyOn(console, 'error').mockImplementation(() => undefined); + sealAuditChainHead.mockRejectedValue(new Error('does not verify')); + close.mockRejectedValue(new Error('already closed')); + + await import('../../../src/scripts/sealAuditHead.js'); + + expect(err).toHaveBeenCalledWith(expect.stringContaining('does not verify')); + expect(process.exitCode).toBe(1); + process.exitCode = undefined; + }); +}); diff --git a/tests/unit/services/auditHeadSignature.spec.ts b/tests/unit/services/auditHeadSignature.spec.ts new file mode 100644 index 00000000..a191d62c --- /dev/null +++ b/tests/unit/services/auditHeadSignature.spec.ts @@ -0,0 +1,140 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const query = vi.fn(); +const error = vi.fn(); + +vi.mock('../../../src/models/index.js', () => ({ + getSequelize: () => ({ query }), +})); + +vi.mock('../../../src/utils/logger.js', () => ({ + default: () => ({ error, warn: vi.fn(), info: vi.fn(), debug: vi.fn() }), +})); + +const KEY = 'unit-audit-key'; +const A = 'a'.repeat(64); +const B = 'b'.repeat(64); +const tx = { id: 'tx' } as never; + +async function load() { + return import('../../../src/services/auditHeadSignature.js'); +} + +beforeEach(() => { + vi.resetModules(); +}); + +describe('auditChainKey', () => { + it('reads a trimmed key and treats a blank one as unset', async () => { + const { auditChainKey } = await load(); + + expect(auditChainKey({ AUDIT_CHAIN_KEY: ' k ' })).toBe('k'); + expect(auditChainKey({ AUDIT_CHAIN_KEY: ' ' })).toBeNull(); + expect(auditChainKey({})).toBeNull(); + }); +}); + +describe('auditHeadSignatureValid', () => { + it('accepts its own signature and nothing else', async () => { + const { auditHeadSignatureValid, signAuditHead } = await load(); + const signature = signAuditHead(KEY, 4, A); + + expect(auditHeadSignatureValid(KEY, 4, A, signature)).toBe(true); + expect(auditHeadSignatureValid(KEY, 5, A, signature)).toBe(false); + expect(auditHeadSignatureValid(KEY, 4, B, signature)).toBe(false); + expect(auditHeadSignatureValid('other', 4, A, signature)).toBe(false); + expect(auditHeadSignatureValid(KEY, 4, A, null)).toBe(false); + expect(auditHeadSignatureValid(KEY, 4, A, 'zz')).toBe(false); + }); + + it('signs an empty head distinctly from any row', async () => { + const { signAuditHead } = await load(); + + expect(signAuditHead(KEY, 0, null)).not.toBe(signAuditHead(KEY, 0, A)); + }); +}); + +describe('signInsertedAuditHead', () => { + it('moves the signature forward from the previous head in one statement', async () => { + const { signAuditHead, signInsertedAuditHead } = await load(); + query.mockResolvedValueOnce([{ signed_seq: '5' }]); + + await expect(signInsertedAuditHead({ seq: '5', hash: B, prev_hash: A }, tx, KEY)).resolves.toBe( + true, + ); + + expect(query).toHaveBeenCalledTimes(1); + expect(query.mock.calls[0][1]).toMatchObject({ + replacements: { + seq: 5, + signature: signAuditHead(KEY, 5, B), + prevSeq: 4, + prevSignature: signAuditHead(KEY, 4, A), + }, + transaction: tx, + }); + }); + + it('catches up from an older signature that still verifies', async () => { + const { signAuditHead, signInsertedAuditHead } = await load(); + query + .mockResolvedValueOnce([]) + .mockResolvedValueOnce([ + { signed_seq: '3', signature: signAuditHead(KEY, 3, A), signed_hash: A }, + ]) + .mockResolvedValueOnce([]); + + await expect( + signInsertedAuditHead({ seq: 5, hash: B, prev_hash: 'c'.repeat(64) }, tx, KEY), + ).resolves.toBe(true); + + expect(query.mock.calls[2][1]).toMatchObject({ + replacements: { seq: 5, signature: signAuditHead(KEY, 5, B), signedSeq: 3 }, + }); + expect(error).not.toHaveBeenCalled(); + }); + + it.each([ + ['unsigned', { signed_seq: null, signature: null, signed_hash: null }], + ['signed with another key', { signed_seq: '3', signature: 'f'.repeat(64), signed_hash: A }], + ['signed ahead of the insert', { signed_seq: '9', signature: 'f'.repeat(64), signed_hash: A }], + ])('leaves a head that is %s alone and says so once', async (_case, current) => { + const { signInsertedAuditHead } = await load(); + query.mockResolvedValue([]); + query.mockResolvedValueOnce([]).mockResolvedValueOnce([current]); + + await expect(signInsertedAuditHead({ seq: 5, hash: B, prev_hash: A }, tx, KEY)).resolves.toBe( + false, + ); + await signInsertedAuditHead({ seq: 6, hash: A, prev_hash: B }, tx, KEY); + + expect(query).toHaveBeenCalledTimes(4); + expect(error).toHaveBeenCalledTimes(1); + error.mockClear(); + }); + + it('does nothing for a row the database did not chain', async () => { + const { signInsertedAuditHead } = await load(); + + await expect(signInsertedAuditHead({ seq: null, hash: B }, tx, KEY)).resolves.toBe(false); + await expect(signInsertedAuditHead({ seq: 1, hash: null }, tx, KEY)).resolves.toBe(false); + expect(query).not.toHaveBeenCalled(); + }); +}); + +describe('warnIfAuditChainKeyUnset', () => { + it('warns only in production without the key', async () => { + const warn = vi.fn(); + vi.doMock('../../../src/utils/logger.js', () => ({ + default: () => ({ error, warn, info: vi.fn(), debug: vi.fn() }), + })); + const { warnIfAuditChainKeyUnset } = await load(); + + warnIfAuditChainKeyUnset({ NODE_ENV: 'development' }); + warnIfAuditChainKeyUnset({ NODE_ENV: 'production', AUDIT_CHAIN_KEY: 'k' }); + expect(warn).not.toHaveBeenCalled(); + + warnIfAuditChainKeyUnset({ NODE_ENV: 'production' }); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('AUDIT_CHAIN_KEY is not set')); + }); +}); diff --git a/tests/unit/services/auditIntegrity.spec.ts b/tests/unit/services/auditIntegrity.spec.ts index 8c03a20f..d0bbd264 100644 --- a/tests/unit/services/auditIntegrity.spec.ts +++ b/tests/unit/services/auditIntegrity.spec.ts @@ -1,13 +1,21 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { getSequelize } from '../../../src/models/index.js'; -import { verifyAuthEventChain } from '../../../src/services/auditIntegrity.js'; +import { signAuditHead } from '../../../src/services/auditHeadSignature.js'; +import { + AuditHeadSealError, + sealAuditChainHead, + verifyAuthEventChain, +} from '../../../src/services/auditIntegrity.js'; vi.mock('../../../src/models/index.js', () => ({ getSequelize: vi.fn(), })); const query = vi.fn(); +const transaction = vi.fn(); +const KEY = 'unit-audit-key'; +const C = 'c'.repeat(64); function chainRow(overrides: Record = {}) { return { @@ -24,7 +32,8 @@ function chainRow(overrides: Record = {}) { beforeEach(() => { vi.clearAllMocks(); - vi.mocked(getSequelize).mockReturnValue({ query } as never); + vi.mocked(getSequelize).mockReturnValue({ query, transaction } as never); + transaction.mockImplementation((fn: (tx: unknown) => unknown) => fn({ id: 'tx' })); }); describe('verifyAuthEventChain', () => { @@ -112,3 +121,132 @@ describe('verifyAuthEventChain', () => { expect(report.firstFailure?.reason).toBe('head_mismatch'); }); }); + +function signedHead(overrides: Record = {}) { + return { + seq: '3', + hash: C, + signed_seq: '3', + signature: signAuditHead(KEY, 3, C), + signed_hash: C, + ...overrides, + }; +} + +describe('verifyAuthEventChain with AUDIT_CHAIN_KEY', () => { + beforeEach(() => { + vi.stubEnv('AUDIT_CHAIN_KEY', KEY); + }); + + it('verifies a head signed with the key', async () => { + query.mockResolvedValue([chainRow({ head: signedHead() })]); + + expect(await verifyAuthEventChain()).toMatchObject({ + verified: true, + headSigned: true, + head: { seq: 3, hash: C }, + }); + }); + + it('reports an unsigned head', async () => { + query.mockResolvedValue([ + chainRow({ head: signedHead({ signed_seq: null, signature: null, signed_hash: null }) }), + ]); + + expect(await verifyAuthEventChain()).toMatchObject({ + verified: false, + headSigned: false, + firstFailure: { seq: 3, id: null, reason: 'head_unsigned' }, + }); + }); + + it('reports a signature that lags the head as unsigned', async () => { + const B = 'b'.repeat(64); + query.mockResolvedValue([ + chainRow({ + head: signedHead({ signed_seq: '2', signature: signAuditHead(KEY, 2, B), signed_hash: B }), + }), + ]); + + expect((await verifyAuthEventChain()).firstFailure?.reason).toBe('head_unsigned'); + }); + + it('reports a signature that does not verify as a head mismatch', async () => { + query.mockResolvedValue([ + chainRow({ head: signedHead({ signature: signAuditHead('another-key', 3, C) }) }), + ]); + + expect(await verifyAuthEventChain()).toMatchObject({ + verified: false, + headSigned: false, + firstFailure: { seq: 3, id: null, reason: 'head_mismatch' }, + }); + }); + + it('reports a signature over a row that is gone as a head mismatch', async () => { + query.mockResolvedValue([chainRow({ head: signedHead({ signed_hash: null }) })]); + + expect((await verifyAuthEventChain()).firstFailure?.reason).toBe('head_mismatch'); + }); + + it('reports a broken row ahead of the signature', async () => { + query.mockResolvedValue([ + chainRow({ + head: signedHead({ signature: null }), + first_failure: { seq: '2', id: 'event-2', reason: 'hash_mismatch' }, + }), + ]); + + expect((await verifyAuthEventChain()).firstFailure?.reason).toBe('hash_mismatch'); + }); + + it('does not check signatures without the key', async () => { + vi.stubEnv('AUDIT_CHAIN_KEY', ''); + query.mockResolvedValue([chainRow({ head: signedHead({ signature: null }) })]); + + expect(await verifyAuthEventChain()).toMatchObject({ verified: true, headSigned: false }); + }); +}); + +describe('sealAuditChainHead', () => { + it('refuses without the key', async () => { + vi.stubEnv('AUDIT_CHAIN_KEY', ''); + + await expect(sealAuditChainHead()).rejects.toBeInstanceOf(AuditHeadSealError); + expect(transaction).not.toHaveBeenCalled(); + }); + + it('locks the head, checks the chain and signs the head', async () => { + vi.stubEnv('AUDIT_CHAIN_KEY', KEY); + query + .mockResolvedValueOnce([{ id: 1 }]) + .mockResolvedValueOnce([chainRow({ head: signedHead({ signature: null }) })]) + .mockResolvedValueOnce([]); + + await expect(sealAuditChainHead()).resolves.toEqual({ seq: 3, hash: C }); + + expect(query.mock.calls[0][0]).toContain('FOR UPDATE'); + expect(query.mock.calls[1][1]).toMatchObject({ transaction: { id: 'tx' } }); + expect(query.mock.calls[2][1]).toMatchObject({ + replacements: { seq: 3, signature: signAuditHead(KEY, 3, C) }, + transaction: { id: 'tx' }, + }); + }); + + it('refuses a chain that does not verify', async () => { + vi.stubEnv('AUDIT_CHAIN_KEY', KEY); + query + .mockResolvedValueOnce([{ id: 1 }]) + .mockResolvedValueOnce([chainRow({ last_seq: '2', last_hash: 'b'.repeat(64) })]); + + await expect(sealAuditChainHead()).rejects.toThrow(/head_mismatch at seq 3/); + expect(query).toHaveBeenCalledTimes(2); + }); + + it('refuses when the head row is missing', async () => { + vi.stubEnv('AUDIT_CHAIN_KEY', KEY); + query.mockResolvedValueOnce([]).mockResolvedValueOnce([chainRow({ head: null })]); + + await expect(sealAuditChainHead()).rejects.toThrow(/head row is missing/); + }); +}); diff --git a/tests/unit/services/authEventService.spec.ts b/tests/unit/services/authEventService.spec.ts index 362b24e6..e8efba5b 100644 --- a/tests/unit/services/authEventService.spec.ts +++ b/tests/unit/services/authEventService.spec.ts @@ -6,6 +6,16 @@ vi.mock('../../../src/models/authEvents.js', () => ({ }, })); +const transaction = vi.fn(async (fn: (tx: unknown) => unknown) => fn({ id: 'tx' })); +vi.mock('../../../src/models/index.js', () => ({ + getSequelize: () => ({ transaction }), +})); + +vi.mock('../../../src/services/auditHeadSignature.js', () => ({ + auditChainKey: vi.fn(() => null), + signInsertedAuditHead: vi.fn(async () => true), +})); + vi.mock('../../../src/utils/logger.js', () => ({ default: vi.fn(() => ({ error: vi.fn(), @@ -33,6 +43,26 @@ describe('AuthEventService', () => { vi.clearAllMocks(); }); + it('signs the new head in the same transaction when AUDIT_CHAIN_KEY is set', async () => { + const { AuthEvent } = await import('../../../src/models/authEvents.js'); + const { auditChainKey, signInsertedAuditHead } = + await import('../../../src/services/auditHeadSignature.js'); + const { AuthEventService } = await import('../../../src/services/authEventService.js'); + const event = { seq: '9', hash: 'a'.repeat(64), prev_hash: null }; + vi.mocked(auditChainKey).mockReturnValue('key'); + vi.mocked(AuthEvent.create).mockResolvedValue(event as never); + + await AuthEventService.log({ type: 'login_success', req: buildReq() }); + + expect(AuthEvent.create).toHaveBeenCalledWith( + expect.objectContaining({ type: 'login_success' }), + { + transaction: { id: 'tx' }, + }, + ); + expect(signInsertedAuditHead).toHaveBeenCalledWith(event, { id: 'tx' }, 'key'); + }); + it('logs event successfully', async () => { const { AuthEvent } = await import('../../../src/models/authEvents.js'); const { AuthEventService } = await import('../../../src/services/authEventService.js');