From f3baf8206291a8d7f932dc466231a234bdd28d64 Mon Sep 17 00:00:00 2001 From: Alvaro Salinas Dockar Date: Tue, 24 Nov 2026 10:13:16 -0400 Subject: [PATCH 1/8] fix(alerts): sign the webhook's timestamp with its body Every attempt carries X-HIE-Timestamp, and X-HIE-Signature is the HMAC-SHA256 of "{timestamp}.{body}": a captured delivery can no longer be replayed later to a receiver that pruned its event ids. Receivers enforce a tolerance, 5 minutes by default. No release signed the body alone, so there is no compatibility mode. The webhook secret is trimmed when read. Refs #38 --- docs/decisions.md | 6 ++++-- docs/development.md | 2 +- docs/running.md | 2 +- docs/sources.md | 3 ++- src/alerts.rs | 44 ++++++++++++++++++++++++++++++++------- src/config.rs | 23 +++++++++++++++++++-- tests/alert_webhook.rs | 47 ++++++++++++++++++++++++++++++++++-------- tests/alerts.rs | 6 +++++- 8 files changed, 109 insertions(+), 24 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index c406ba3..39c4acb 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -484,7 +484,7 @@ Several engine instances may share one PostgreSQL. A source is run by the instan **Why:** - External monitoring and paging tools are meant to receive the engine's alerts through its webhook, so it needs a stable shape, a way to prove the sender, and delivery that survives a receiver's outage and the engine's restarts. A host application shows whether an alert reached them, and needs to tell "no webhook configured" from "not delivered yet". -- Writing the event with the alert, in one transaction, means no alert change is lost between the two; storing the exact body means every retry is the same bytes, so a receiver de-duplicates by `event_id` and a signature never depends on when it was computed. +- Writing the event with the alert, in one transaction, means no alert change is lost between the two; storing the exact body means every retry is the same bytes, so a receiver de-duplicates by `event_id` and a signature never depends on when it was computed (until the amendment below). - A body-only HMAC (the shape GitHub's webhooks use) is the simplest scheme receivers verify. A replayed request carries an `event_id` the receiver has seen; an old event names an old alert. - Claiming by `event_id` with a conditional update, and fencing the outcome by the attempt number, lets several instances on one store send without sending one attempt twice, on SQLite and PostgreSQL alike, and keeps a stalled instance from overwriting a newer outcome. - Binding an event to its URL keeps alert text and recipients from going to a receiver configured later for something else; waiting for that URL keeps a brief misconfiguration from losing them. @@ -493,11 +493,13 @@ Several engine instances may share one PostgreSQL. A source is run by the instan **Cost / not yet:** - The body changed: the old `feed`, `kind`, `alert_id`, `notify` and `cleared` keys are gone (`text` stays), and a clear is now posted only when the channels recorded on the alert when it fired include the webhook (a later edit of the rule does not change that; a rule turned off or deleted left its open alert open, with no clear, until decision 43 made it clear the alert). `alerts:` refuses unknown keys, so a misspelt `webhook_secret` cannot send unsigned; a file with stray keys there no longer starts. While instances of an earlier version share the store, those still post the old body, unsigned. In the library, an `Alerter` now only records events: they are sent by the task `Alerter::start` returns, which `build` keeps with the source manager. - A receiver can still get an event twice, and a late `fired` after its `cleared`; it must de-duplicate. `event_id` covers retries of one event, not a second alert raised for one condition. Receivers match the two events of an alert by its `id`, which is never given again (decision 38). -- No timestamp is signed: a receiver that forgets the `event_id`s it has seen accepts a replay of an old event. Use HTTPS. +- No timestamp was signed: a receiver that forgot the `event_id`s it had seen accepted a replay of an old event (amended below, before any release carried the signature). Use HTTPS. - Sends are sequential, one per instance at a time: with a receiver that times out, waiting events queue behind each other. Claims and due times use each instance's clock, as source leases do: instances on one store need synchronised clocks. All instances on a store need the same `alerts:` settings. - The API shows the latest event only: a `fired` that failed is shown until its `cleared` is written. A monitor tracking delivery re-reads the alerts it still follows; delivery changes do not move a cursor. Events are kept with their alert and removed with it when `retention.history` purges it (decision 38), waiting ones included: by then only an event parked for an earlier URL, or never sent, can still be waiting. - No mail sink, per-rule URLs, redelivery endpoint or delivery metrics. +*Amended 2026-11-24:* every attempt carries `X-HIE-Timestamp`, the Unix seconds when it was sent, and `X-HIE-Signature` is the HMAC-SHA256 of `{timestamp}.{raw body}` (the scheme of Stripe and Standard Webhooks) instead of the body alone. Receivers refuse a timestamp outside a tolerance they enforce, 5 minutes by default, and keep the `event_id`s they have seen for at least that long. Why: with the body alone, anyone who captured one delivery could replay it later to a receiver that had pruned its `event_id`s, or never kept them (a `fired` that pages someone again); adding a timestamp after receivers verify the body-only signature would break every one of them. The stored body is still the same bytes on every attempt; the timestamp and the signature are computed per attempt when it leaves, so a retry is never stale, and the receiver's window need not cover the backoff. No release signed the body alone (0.2.0 sent unsigned events), so there is no compatibility mode. Cost: a receiver whose clock is off by more than its tolerance refuses every event, and gets them again on each retry until the five retries are spent; instances need synchronised clocks already. Each attempt's signature depends on when it is sent. + ## 41. Check now has an id and an outcome **Chosen:** `POST /api/sources/{id}/check-now` records a check in the store and answers its `check_id`; `GET /api/checks/{id}` answers `pending`, `found`, `nothing_new` or `failed`, with when it was asked for and answered. A check is recorded with a baseline, the source's newest load at that moment, and is answered by the first scan of the source that starts after it was recorded, on the instance holding the source: each pass reads the source's pending checks just before its scan and answers exactly those when the scan ends, before delivering. `found` lists the source's loads after the baseline up to the end of that scan, read with their current status when asked; `nothing_new` when there are none; `failed` when the source is paused, its credential is not loaded, the scan failed, or the source was deleted (unless another instance held it then), with one of a fixed set of reasons and the loads taken before the failure. The first answer stays. Checks are purged with events and alerts after `retention.history` (decision 38), counted from when they were asked for, answered or not. The route keeps its name; nothing new is needed to ask for a check. diff --git a/docs/development.md b/docs/development.md index 9e6e793..e301776 100644 --- a/docs/development.md +++ b/docs/development.md @@ -27,7 +27,7 @@ cargo clippy --all-targets --no-default-features -- -D warnings cargo test --no-default-features --lib --test secrets --test no_backend_startup --test check --test s3_credentials ``` -The end-to-end tests run the real Python transforms against a stand-in FHIR server. `tests/pipeline.rs` covers a folder source: the outage and recovery, the duplicate file and the re-sent rows, each kind of bad row, reprocessing with a correction, the silence alert, and a load whose rows were all filtered out raising no alert while a mixed load's alert counts its failing rows, again only when more of them fail. `tests/events.rs` covers the event log: each outcome stored with its event before the next record is sent (the stand-in FHIR server reads the log through its own store handle on every request) or transformed (the probe transform reads the SQLite file), nothing stored when the event cannot be (a SQLite trigger refuses it, for an admission and for a delivery), outcomes for a record put back while it was transformed or sent changing nothing, a transform that cannot finish now (logged once per reason and runner), a submission opened, failing a poll, settled by its receipts or refused with an answer that echoes signed URLs and the engine's own path, a submission not opened when a record changed while it was written (on both bulk paths), a Retry, a refusal and an unsendable file of 450 rows each (more than one chunk), an older answer that cannot roll a record's attempts back, content taken meanwhile not admitted twice, a Retry that finds nothing, a finish reporting failing rows beyond the most an earlier finish saw, the API's paging, filters, cursor and refusals, the retention purge (old events and alerts, the alerts kept, the highest alert id kept so no id is given again, the alert counter unchanged, two purges at once counted once, more than one chunk) a restart that stops the first engine for good, distinct rejected records per day (a record rejected twice once, filtered rows apart, a midnight event in the day it starts, coverage from when the log began and within the retention) and that start kept across a reopen; with `HIE_TEST_DATABASE_URL`, an event committed later with a lower id never skipped by a reader, a finish that waits for a Retry's row lock (and one that counts the failing rows committed while it waited), an alert cleared while the purge waits for it kept, a record put back while its file is rejected left as it was put back, each test waiting until PostgreSQL shows the lock wait. `tests/alerts.rs` covers the rules: the one a source is born with and that a replace does not bring back, the CRUD, and the `rejected_share` and `silence` rules firing once and clearing, `rejected_share` weighing the failing rows among those a load kept (a load that kept none neither fires nor clears it); and rule ids never given again (after a delete, a reopen, and on a SQLite store whose rules table was made the old way), with `created_at` set by the engine; and reading alerts by period and in pages: `since` at its boundary (as the list returns it, finer, with an offset), every combination with `source` and `open` walked at several page sizes, a walk that keeps its place while alerts are added, cleared and removed, the default page of 100, and malformed queries refused without echoing them, on SQLite and, with `HIE_TEST_DATABASE_URL`, PostgreSQL; and, through the pipeline and the API, the webhook's delivery state: an alert from before events were recorded cleared and delivered, signed, with the API's time strings, events waiting for this URL (`pending`) and for another (`parked`), a rule without the `webhook` channel (`not_requested`), an engine without a URL (`not_configured`), and no URL, secret or fingerprint in the answer. `tests/alert_webhook.rs` drives the webhook sender against a local receiver under the production log filter at `trace`: the signature over the raw body, fired before cleared, one `event_id` and one body over retries, giving up after five retries, a redirect refused, an unreachable receiver, one that does not answer in time, two instances on one store sending each event once, an attempt whose outcome was lost sent again unchanged by another instance, and an event waiting for its own URL across restarts; no URL, secret or receiver answer reaches a log line or the store. Unit tests pin the signature to RFC 4231 and, in the store, with time passed in and two handles on one file, the claim, the fence against late outcomes and replacement rows, the last attempt with no outcome, the order of fired and cleared per URL, and the alert and its event written or rolled back together. `tests/check.rs` checks that `hie check` refuses bad `alerts:` settings without printing the URL or the secret. `tests/bulk_submit.rs` drives both bulk paths against a stand-in consumer: an NDJSON export handed over as source objects, and a lab CSV transformed, given derived ids, written by the engine and settled by receipts. Against a stand-in public bucket it checks that an anonymous source reading a whole bucket hands over each object's public URL with its key encoded once, every read unsigned and the engine's file route unused; that a store object is never served from that route, even when a local file shares its key, while a staged zip entry is; that keys and entries stay apart under a relative bulk directory; that entries staged by an earlier version are recognised at start-up, served, settled and retried, whether the engine starts from a relative or an absolute configuration path; that an archived folder file from an earlier version is served again on retry; and that a file taken from a bucket and retried after its source became a folder is rejected rather than served. `tests/bulk_logs.rs` runs under the production log filter asked for everything at `trace`: a failing poll, a refusal that echoes signed URLs (one on a bracketed IPv6 host, one with parentheses in its path) and the engine's own path with the token, a relative status target that carries a signature, a cleanup that cannot remove a submission's files, a token endpoint failure and a status URL stored during a working delivery (a statement parameter on PostgreSQL) keep signatures and tokens out of every log line, the alerts, the stored errors and answers, and the event log. A folder file recorded through a symbolic link and `..` is served as the filesystem resolves that path. With an in-memory store it checks that a URL that cannot be signed yet keeps its records pending while open submissions are polled, and that an object no configuration can hand over is rejected without stalling the pass. `tests/object_source.rs` covers the object-store path the S3 source uses, with an in-memory store; `tests/sqs_source.rs` adds a notification queue to it, against a stand-in SQS that checks the SigV4 headers: the bucket listed once at start, then only announced objects taken, with their messages deleted after the pass and test events, foreign keys, gone objects and keys that are not object paths consumed without effect; `tests/overlap.rs` checks that HFS receives the first Bundle well before a slow transform finishes the file; the same source was run by hand against a MinIO (the `ghcr.io/coollabsio/minio` mirror HFS's CI pins) holding the Synthea export, on both delivery paths against an HFS that requires tokens: 632 resources by REST and the same 632 by `$bulk-submit` through pre-signed URLs, each resource stored once, objects archived under the processed prefix, and a re-uploaded file recognised as a duplicate. `tests/fhir_server_source.rs` covers pulling another FHIR server: pages followed, a cursor per type that moves once the records are stored, nothing pulled twice, the token on every call, and the connection test. `tests/database_source.rs` covers the database source on SQLite: runs of the query past a cursor, the cursor moving once the rows are stored, nothing read twice, `cursor_start`, and the connection test; `tests/mssql_source.rs` runs the same source against a SQL Server when `HIE_TEST_MSSQL_URL` is set, and is skipped otherwise. `tests/leases.rs` puts two instances on one store: one runs the source, the other stands by, and takes over when the lease lapses. `tests/test_terminology.py` covers the terminology helpers against a stand-in HTS and the lab transform using them. `tests/zip_drop.rs` covers zips: a drop in a read-only bucket unpacked once and left in place, and one in a folder unpacked and archived, with a broken zip reported. `tests/hl7v2.rs` covers HL7 v2: a file of messages through a folder source, and messages over MLLP spooled, acknowledged, delivered, and resent as duplicates; `tests/test_hl7.py` covers the Python helpers. `tests/api.rs` drives a source through the API: test, create, check now, pause, resume, replace, delete, and its contact read from a file and from the API, kept by a replace that sends back what it read, cleared by one without it, and refused when too long or more than one line. `tests/loads.rs` covers the loads list across sources: the fields of the per-source list, newest first, each `status` filter and `failed` (unreadable, rejected rows while in progress or done, rows filtered out on purpose that do not count, and what takes a load out), a walk by cursor while loads arrive and leave the filter, the limits and the refused queries, a store written by an earlier version (its loads with no mark of failing rows), and a deleted source whose id is created again; a unit test checks that SQLite chooses each page through an index. `tests/check_outcome.rs` drives the scans of a source another instance holds by hand: concurrent checks answered by the one scan after them with its one load, a check asked for once a scan started answered by the next with what the earlier one took, nothing new, a folder that cannot be listed (a fixed reason, no path), an unknown check, a replaced source's runner answering earlier checks, and a paused or deleted source failing them, but not one another instance still holds; the loads paged with the answer's cursor, malformed parameters refused with `invalid_query` and `field`, and the retention purge removing old checks, answered or not (`tests/events.rs` adds, on PostgreSQL, a check purge that waits for another instance's and moves on to the next old rows); unit tests in `src/db.rs` cover the snapshot, the first answer staying, pages of loads and the purge. `tests/check.rs` runs `hie check`: it refuses to start while `hie.yaml` has a `runtime` key or `HIE_RUNTIME_URL` is set, and passes when the variable is unset or blank; it prints a source's contact and refuses an invalid one naming the file, in both builds; `hie check` and `hie run` refuse an S3 file that names neither a credential nor `anonymous`, and `hie run` refuses a sealed store started with another key, or a key set in two places, before serving. Stored credentials: unit tests pin the sealed format against values computed independently (Python's `hmac`/`hashlib` and libsodium), the derivation against RFC 5869, and walk the key state machine (sealed and unsealed stores against every kind of key input, key files that are links, FIFOs or readable by others, a key file that cannot be created, concurrent first starts); the registration of sources for credentials is tested with pause points that force each interleaving, on SQLite and, with `HIE_TEST_DATABASE_URL`, PostgreSQL. `tests/secret_store.rs` covers persistence, refusals with both key ids, and values moved or altered in the database. `tests/secrets.rs` covers `/api/secrets` (shapes, bodies refused without echoing them, the `409` while used, `503 store_busy`, the `503 secrets_unavailable` of a store without a usable key, on the credential routes, on creating, replacing and testing a source, and in its `credential` alert, with no path), and the 503s of a build without a store; `tests/no_backend_startup.rs` runs that build's binary with a credential source file, which is skipped. The default rule's birth is tested on both stores too: given once, not again after a replace, a failed start, a restart or a file put back, given again by a create and kept when its write or start fails, never twice when two handles race (one held inside its transaction while the other waits), nothing recorded or published when it fails, and sources an earlier version left marked born without a rule. `tests/s3_credentials.rs` signs against a stand-in bucket that records key ids: the Test, the source, a rotation, the queue, an alert raised once and cleared, and a source waiting for its credential while its submissions are polled (a check asked for meanwhile fails, saying the credential is not loaded). `tests/secret_refs.rs` puts two engines on one store; `tests/secrets_canary.rs` checks that a canary secret appears in no answer, log line at `trace`, source file or database byte. `tests/worker.rs` runs the real launcher over a small test program for the long-lived worker cases of the `limited-process@1` contract (answers in order from one process, a reply written in pieces, a deadline and a late reply, a worker that exits or stays silent before it is ready, one that stops reading) and the engine's own duties: the pin check, setup errors, a stray line on stdout, the stderr tail, the run directories, the limits, the process group, the environment and cancelled calls; `tests/pipeline.rs` adds rows that hang, crash or run out of memory, each rejected once with the rows after it delivered, and `tests/api.rs` the bound on concurrent tries. `tests/worker.rs` also runs the real `hie_runtime/` with transforms that write to file descriptor 1 directly and through a child process, every record still getting its own reply. `tests/test_worker.py` checks the worker over its pipes (a write to file descriptor 1 included) and, on Linux, under the launcher's memory limit. +The end-to-end tests run the real Python transforms against a stand-in FHIR server. `tests/pipeline.rs` covers a folder source: the outage and recovery, the duplicate file and the re-sent rows, each kind of bad row, reprocessing with a correction, the silence alert, and a load whose rows were all filtered out raising no alert while a mixed load's alert counts its failing rows, again only when more of them fail. `tests/events.rs` covers the event log: each outcome stored with its event before the next record is sent (the stand-in FHIR server reads the log through its own store handle on every request) or transformed (the probe transform reads the SQLite file), nothing stored when the event cannot be (a SQLite trigger refuses it, for an admission and for a delivery), outcomes for a record put back while it was transformed or sent changing nothing, a transform that cannot finish now (logged once per reason and runner), a submission opened, failing a poll, settled by its receipts or refused with an answer that echoes signed URLs and the engine's own path, a submission not opened when a record changed while it was written (on both bulk paths), a Retry, a refusal and an unsendable file of 450 rows each (more than one chunk), an older answer that cannot roll a record's attempts back, content taken meanwhile not admitted twice, a Retry that finds nothing, a finish reporting failing rows beyond the most an earlier finish saw, the API's paging, filters, cursor and refusals, the retention purge (old events and alerts, the alerts kept, the highest alert id kept so no id is given again, the alert counter unchanged, two purges at once counted once, more than one chunk) a restart that stops the first engine for good, distinct rejected records per day (a record rejected twice once, filtered rows apart, a midnight event in the day it starts, coverage from when the log began and within the retention) and that start kept across a reopen; with `HIE_TEST_DATABASE_URL`, an event committed later with a lower id never skipped by a reader, a finish that waits for a Retry's row lock (and one that counts the failing rows committed while it waited), an alert cleared while the purge waits for it kept, a record put back while its file is rejected left as it was put back, each test waiting until PostgreSQL shows the lock wait. `tests/alerts.rs` covers the rules: the one a source is born with and that a replace does not bring back, the CRUD, and the `rejected_share` and `silence` rules firing once and clearing, `rejected_share` weighing the failing rows among those a load kept (a load that kept none neither fires nor clears it); and rule ids never given again (after a delete, a reopen, and on a SQLite store whose rules table was made the old way), with `created_at` set by the engine; and reading alerts by period and in pages: `since` at its boundary (as the list returns it, finer, with an offset), every combination with `source` and `open` walked at several page sizes, a walk that keeps its place while alerts are added, cleared and removed, the default page of 100, and malformed queries refused without echoing them, on SQLite and, with `HIE_TEST_DATABASE_URL`, PostgreSQL; and, through the pipeline and the API, the webhook's delivery state: an alert from before events were recorded cleared and delivered, signed, with the API's time strings, events waiting for this URL (`pending`) and for another (`parked`), a rule without the `webhook` channel (`not_requested`), an engine without a URL (`not_configured`), and no URL, secret or fingerprint in the answer. `tests/alert_webhook.rs` drives the webhook sender against a local receiver under the production log filter at `trace`: the signature over each attempt's `X-HIE-Timestamp` and the raw body (a signature over the body alone does not match), fired before cleared, one `event_id` and one body over retries, giving up after five retries, a redirect refused, an unreachable receiver, one that does not answer in time, two instances on one store sending each event once, an attempt whose outcome was lost sent again unchanged by another instance, and an event waiting for its own URL across restarts; no URL, secret or receiver answer reaches a log line or the store. Unit tests pin the HMAC to RFC 4231 and the signed string to a value computed independently (Python's `hmac`), the webhook secret read without the whitespace around it, and, in the store, with time passed in and two handles on one file, the claim, the fence against late outcomes and replacement rows, the last attempt with no outcome, the order of fired and cleared per URL, and the alert and its event written or rolled back together. `tests/check.rs` checks that `hie check` refuses bad `alerts:` settings without printing the URL or the secret. `tests/bulk_submit.rs` drives both bulk paths against a stand-in consumer: an NDJSON export handed over as source objects, and a lab CSV transformed, given derived ids, written by the engine and settled by receipts. Against a stand-in public bucket it checks that an anonymous source reading a whole bucket hands over each object's public URL with its key encoded once, every read unsigned and the engine's file route unused; that a store object is never served from that route, even when a local file shares its key, while a staged zip entry is; that keys and entries stay apart under a relative bulk directory; that entries staged by an earlier version are recognised at start-up, served, settled and retried, whether the engine starts from a relative or an absolute configuration path; that an archived folder file from an earlier version is served again on retry; and that a file taken from a bucket and retried after its source became a folder is rejected rather than served. `tests/bulk_logs.rs` runs under the production log filter asked for everything at `trace`: a failing poll, a refusal that echoes signed URLs (one on a bracketed IPv6 host, one with parentheses in its path) and the engine's own path with the token, a relative status target that carries a signature, a cleanup that cannot remove a submission's files, a token endpoint failure and a status URL stored during a working delivery (a statement parameter on PostgreSQL) keep signatures and tokens out of every log line, the alerts, the stored errors and answers, and the event log. A folder file recorded through a symbolic link and `..` is served as the filesystem resolves that path. With an in-memory store it checks that a URL that cannot be signed yet keeps its records pending while open submissions are polled, and that an object no configuration can hand over is rejected without stalling the pass. `tests/object_source.rs` covers the object-store path the S3 source uses, with an in-memory store; `tests/sqs_source.rs` adds a notification queue to it, against a stand-in SQS that checks the SigV4 headers: the bucket listed once at start, then only announced objects taken, with their messages deleted after the pass and test events, foreign keys, gone objects and keys that are not object paths consumed without effect; `tests/overlap.rs` checks that HFS receives the first Bundle well before a slow transform finishes the file; the same source was run by hand against a MinIO (the `ghcr.io/coollabsio/minio` mirror HFS's CI pins) holding the Synthea export, on both delivery paths against an HFS that requires tokens: 632 resources by REST and the same 632 by `$bulk-submit` through pre-signed URLs, each resource stored once, objects archived under the processed prefix, and a re-uploaded file recognised as a duplicate. `tests/fhir_server_source.rs` covers pulling another FHIR server: pages followed, a cursor per type that moves once the records are stored, nothing pulled twice, the token on every call, and the connection test. `tests/database_source.rs` covers the database source on SQLite: runs of the query past a cursor, the cursor moving once the rows are stored, nothing read twice, `cursor_start`, and the connection test; `tests/mssql_source.rs` runs the same source against a SQL Server when `HIE_TEST_MSSQL_URL` is set, and is skipped otherwise. `tests/leases.rs` puts two instances on one store: one runs the source, the other stands by, and takes over when the lease lapses. `tests/test_terminology.py` covers the terminology helpers against a stand-in HTS and the lab transform using them. `tests/zip_drop.rs` covers zips: a drop in a read-only bucket unpacked once and left in place, and one in a folder unpacked and archived, with a broken zip reported. `tests/hl7v2.rs` covers HL7 v2: a file of messages through a folder source, and messages over MLLP spooled, acknowledged, delivered, and resent as duplicates; `tests/test_hl7.py` covers the Python helpers. `tests/api.rs` drives a source through the API: test, create, check now, pause, resume, replace, delete, and its contact read from a file and from the API, kept by a replace that sends back what it read, cleared by one without it, and refused when too long or more than one line. `tests/loads.rs` covers the loads list across sources: the fields of the per-source list, newest first, each `status` filter and `failed` (unreadable, rejected rows while in progress or done, rows filtered out on purpose that do not count, and what takes a load out), a walk by cursor while loads arrive and leave the filter, the limits and the refused queries, a store written by an earlier version (its loads with no mark of failing rows), and a deleted source whose id is created again; a unit test checks that SQLite chooses each page through an index. `tests/check_outcome.rs` drives the scans of a source another instance holds by hand: concurrent checks answered by the one scan after them with its one load, a check asked for once a scan started answered by the next with what the earlier one took, nothing new, a folder that cannot be listed (a fixed reason, no path), an unknown check, a replaced source's runner answering earlier checks, and a paused or deleted source failing them, but not one another instance still holds; the loads paged with the answer's cursor, malformed parameters refused with `invalid_query` and `field`, and the retention purge removing old checks, answered or not (`tests/events.rs` adds, on PostgreSQL, a check purge that waits for another instance's and moves on to the next old rows); unit tests in `src/db.rs` cover the snapshot, the first answer staying, pages of loads and the purge. `tests/check.rs` runs `hie check`: it refuses to start while `hie.yaml` has a `runtime` key or `HIE_RUNTIME_URL` is set, and passes when the variable is unset or blank; it prints a source's contact and refuses an invalid one naming the file, in both builds; `hie check` and `hie run` refuse an S3 file that names neither a credential nor `anonymous`, and `hie run` refuses a sealed store started with another key, or a key set in two places, before serving. Stored credentials: unit tests pin the sealed format against values computed independently (Python's `hmac`/`hashlib` and libsodium), the derivation against RFC 5869, and walk the key state machine (sealed and unsealed stores against every kind of key input, key files that are links, FIFOs or readable by others, a key file that cannot be created, concurrent first starts); the registration of sources for credentials is tested with pause points that force each interleaving, on SQLite and, with `HIE_TEST_DATABASE_URL`, PostgreSQL. `tests/secret_store.rs` covers persistence, refusals with both key ids, and values moved or altered in the database. `tests/secrets.rs` covers `/api/secrets` (shapes, bodies refused without echoing them, the `409` while used, `503 store_busy`, the `503 secrets_unavailable` of a store without a usable key, on the credential routes, on creating, replacing and testing a source, and in its `credential` alert, with no path), and the 503s of a build without a store; `tests/no_backend_startup.rs` runs that build's binary with a credential source file, which is skipped. The default rule's birth is tested on both stores too: given once, not again after a replace, a failed start, a restart or a file put back, given again by a create and kept when its write or start fails, never twice when two handles race (one held inside its transaction while the other waits), nothing recorded or published when it fails, and sources an earlier version left marked born without a rule. `tests/s3_credentials.rs` signs against a stand-in bucket that records key ids: the Test, the source, a rotation, the queue, an alert raised once and cleared, and a source waiting for its credential while its submissions are polled (a check asked for meanwhile fails, saying the credential is not loaded). `tests/secret_refs.rs` puts two engines on one store; `tests/secrets_canary.rs` checks that a canary secret appears in no answer, log line at `trace`, source file or database byte. `tests/worker.rs` runs the real launcher over a small test program for the long-lived worker cases of the `limited-process@1` contract (answers in order from one process, a reply written in pieces, a deadline and a late reply, a worker that exits or stays silent before it is ready, one that stops reading) and the engine's own duties: the pin check, setup errors, a stray line on stdout, the stderr tail, the run directories, the limits, the process group, the environment and cancelled calls; `tests/pipeline.rs` adds rows that hang, crash or run out of memory, each rejected once with the rows after it delivered, and `tests/api.rs` the bound on concurrent tries. `tests/worker.rs` also runs the real `hie_runtime/` with transforms that write to file descriptor 1 directly and through a child process, every record still getting its own reply. `tests/test_worker.py` checks the worker over its pipes (a write to file descriptor 1 included) and, on Linux, under the launcher's memory limit. They are skipped if no Python 3.9+ is found; set `HIE_TEST_PYTHON` to point at one. diff --git a/docs/running.md b/docs/running.md index 91dca0e..5f3887a 100644 --- a/docs/running.md +++ b/docs/running.md @@ -80,7 +80,7 @@ To build the image yourself: `docker build -t hie .` | `HIE_DATABASE_URL` | | The store, overriding `database:` in `hie.yaml`: a `postgres://user:password@host/db` URL. Set it here so the password is not in the file | | `HIE_INSTANCE_ID` | host, pid and a random tail | This instance's name in the leases, when several share one store; also the owner of its credential registrations (otherwise an id kept in `sources/.hie-instance-id`) | | `HIE_ALERT_WEBHOOK_URL` | `alerts.webhook_url` in `hie.yaml` | Where [alert events](sources.md#the-alert-webhook) are posted, `http` or `https`. A chat webhook's URL is itself a credential: set it here rather than in the file | -| `HIE_ALERT_WEBHOOK_SECRET` | `alerts.webhook_secret` in `hie.yaml` | The secret that signs alert events (`X-HIE-Signature`); unsigned without one | +| `HIE_ALERT_WEBHOOK_SECRET` | `alerts.webhook_secret` in `hie.yaml` | The secret that signs alert events (`X-HIE-Signature`, over `X-HIE-Timestamp` and the body); unsigned without one. Leading and trailing whitespace is ignored | | `HIE_TERMINOLOGY_SERVER` | `terminology_url` in `hie.yaml` | The HTS transforms may ask through `lookup` and `translate` | | `HIE_TERMINOLOGY_TOKEN` | | A bearer token for that HTS, when it requires one | | `HIE_SECRET_KEY` | | The secret key that seals stored credentials: 32 random bytes in base64, e.g. from `openssl rand -base64 32`. See [Credentials and the secret key](#credentials-and-the-secret-key) | diff --git a/docs/sources.md b/docs/sources.md index edd00c6..d8d9160 100644 --- a/docs/sources.md +++ b/docs/sources.md @@ -113,7 +113,8 @@ Each change of an alert is one **event**, `fired` or `cleared`, written in the s ``` - `alert` is the alert as `GET /api/alerts` lists it, with the same time strings; a `fired` event has `cleared_at` and `cleared_reason` null. `notify` is `[]` for an alert without a rule. `source.name` is null when the engine does not know it; `source` is null for an alert about no source. `text` is the field Slack and Teams incoming webhooks display. -- Headers: `Content-Type: application/json`, `X-HIE-Event-Id` and `X-HIE-Event` (the body's `event_id` and `event`), and, when `alerts.webhook_secret` is set, `X-HIE-Signature: sha256=`: the HMAC-SHA256 of the **raw body** under the secret, lowercase hex. A receiver verifies it over the bytes it received, before parsing, with a constant-time comparison, and trusts the body, not the other headers. Without a secret the events are unsigned. Use HTTPS: the signature proves who sent an event, not that nobody read it. +- Headers: `Content-Type: application/json`, `X-HIE-Event-Id` and `X-HIE-Event` (the body's `event_id` and `event`), `X-HIE-Timestamp` (when this attempt was sent, in Unix seconds), and, when `alerts.webhook_secret` is set, `X-HIE-Signature: sha256=`: the HMAC-SHA256, under the secret, of the timestamp exactly as sent, a `.`, and the **raw body** (`{X-HIE-Timestamp}.{body}`), lowercase hex. The secret is trimmed of leading and trailing whitespace when read, so a secret file that ends in a newline signs with the secret it holds. Without a secret the events are unsigned. Use HTTPS: the signature proves who sent an event, not that nobody read it. +- **Verifying:** a receiver computes the HMAC over `X-HIE-Timestamp`, `.` and the bytes it received, before parsing, and compares it with `X-HIE-Signature` in constant time; then it refuses a timestamp further than its **tolerance** from its own clock, in either direction. Use **5 minutes** (300 seconds) unless the two clocks are known to drift further; a wider window only lets an old request be replayed for longer. Within the tolerance, de-duplication by `X-HIE-Event-Id` (below) catches a replay, so a receiver keeps the ids it has seen for at least the tolerance. Each attempt, a retry included, is stamped and signed when it leaves, with the same body: the tolerance never has to cover the retry backoff. Trust the body, not the other headers. No release signed the body alone, so there is no older scheme to accept. - **Retries:** any answer but a 2xx, a timeout (10 s; 3 s to connect) or a connection failure is a failed attempt. The engine tries again up to five times, waiting `alerts.webhook_backoff_ms` (from 1 to 3 600 000; 10 000 by default) and doubling each time: 10 s, 20 s, 40 s, 80 s, 160 s. Redirects are not followed: a 3xx is a failed attempt. Every attempt sends the same bytes with the same `event_id`. - **De-duplication:** a receiver may get an event more than once (its 2xx was lost to a timeout, or an instance stopped before storing the outcome). It keeps the `event_id`s it has seen, answers a repeated one with a 2xx and does nothing else. `event_id` identifies one event and its retries, not a condition: a source whose lease lapsed in the middle of a pass can raise a second alert, with its own events, for the same condition. - **Order:** a `cleared` event waits until its alert's `fired` event for the same URL has been delivered or given up on; a `fired` event still waiting for an earlier URL does not hold back a `cleared` for the current one. Still, a receiver may get a `cleared` for an alert it has not seen (fired before this engine version, while no URL was set, or whose `fired` failed), and a late `fired` after its `cleared` (a retry of an attempt that timed out): a late `fired` does not reopen a cleared alert. Match the two events of one alert by `alert.id`: an alert id is never given again. diff --git a/src/alerts.rs b/src/alerts.rs index eafc7d1..27f752c 100644 --- a/src/alerts.rs +++ b/src/alerts.rs @@ -468,12 +468,20 @@ pub fn payload(event_id: &str, event: &str, alert: &AlertRow, source_name: Optio .to_string() } -/// `sha256=` and the lowercase hex HMAC-SHA256 of `body` under `secret`: the -/// `X-HIE-Signature` header. -pub fn signature(secret: &[u8], body: &[u8]) -> String { +/// The `X-HIE-Signature` header of an attempt sent at `timestamp` (the +/// `X-HIE-Timestamp` header, Unix seconds): `sha256=` and the lowercase hex +/// HMAC-SHA256, under `secret`, of the timestamp, a `.` and the raw body. +pub fn signature(secret: &[u8], timestamp: &str, body: &[u8]) -> String { + hmac_sha256_hex(secret, &[timestamp.as_bytes(), b".", body]) +} + +/// The lowercase hex HMAC-SHA256 of `parts`, one after the other, with `sha256=`. +fn hmac_sha256_hex(secret: &[u8], parts: &[&[u8]]) -> String { let mut mac = hmac::Hmac::::new_from_slice(secret).expect("HMAC accepts keys of any length"); - mac.update(body); + for part in parts { + mac.update(part); + } format!("sha256={}", hex::encode(mac.finalize().into_bytes())) } @@ -573,12 +581,21 @@ impl Sender { .header("X-HIE-Event-Id", &claim.event_id) .header("X-HIE-Event", &claim.event) .body(claim.payload.clone()); + // Each attempt is stamped, and signed, when it leaves: a retry carries + // the same body with a fresh timestamp, so a receiver's tolerance never + // has to cover the backoff. + let timestamp = chrono::Utc::now().timestamp().to_string(); if let Some(secret) = &self.webhook.secret { request = request.header( "X-HIE-Signature", - signature(secret.expose_secret().as_bytes(), claim.payload.as_bytes()), + signature( + secret.expose_secret().as_bytes(), + ×tamp, + claim.payload.as_bytes(), + ), ); } + request = request.header("X-HIE-Timestamp", timestamp); match request.send().await { Ok(response) => { let status = response.status(); @@ -1180,13 +1197,26 @@ mod tests { #[test] fn the_signature_is_hmac_sha256_in_hex() { - // RFC 4231, test case 2. + // RFC 4231, test case 2, its data given in pieces. assert_eq!( - signature(b"Jefe", b"what do ya want for nothing?"), + hmac_sha256_hex(b"Jefe", &[b"what do ya ", b"want for nothing?"]), "sha256=5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" ); } + #[test] + fn the_signature_covers_the_timestamp_a_dot_and_the_body() { + // Python: hmac.new(b"Jefe", b'1700000000.{"event":"fired"}', sha256).hexdigest() + assert_eq!( + signature(b"Jefe", "1700000000", br#"{"event":"fired"}"#), + "sha256=0722f7348e182a55af4ded8a8a61167dcd847b9ddc53b77a32b666e371df4b4e" + ); + assert_ne!( + signature(b"Jefe", "1700000001", br#"{"event":"fired"}"#), + signature(b"Jefe", "1700000000", br#"{"event":"fired"}"#) + ); + } + #[test] fn event_ids_are_random_v4_uuids() { let (a, b) = (uuid_v4(), uuid_v4()); diff --git a/src/config.rs b/src/config.rs index 8b1eef0..ffddcdb 100644 --- a/src/config.rs +++ b/src/config.rs @@ -157,6 +157,7 @@ impl RetentionConfig { pub struct AlertConfig { /// Trimmed; `None` when unset or blank. pub webhook_url: Option, + /// Trimmed of leading and trailing whitespace when read. pub webhook_secret: Option, /// The wait before the first retry, doubling for each one after it. /// `None` means `AlertConfig::DEFAULT_BACKOFF_MS`. @@ -219,7 +220,9 @@ impl<'de> Deserialize<'de> for AlertConfig { Some(s) if s.trim().is_empty() => { return Err(D::Error::custom("alerts.webhook_secret is blank")); } - other => other.map(secrecy::SecretString::from), + // A secret file with a trailing newline signs with + // the secret it holds, not with the newline too. + other => other.map(|s| secrecy::SecretString::from(s.trim().to_string())), }; } Some("webhook_backoff_ms") => { @@ -293,7 +296,7 @@ impl AlertConfig { self.webhook_url = Some(url); } if let Some(secret) = read("HIE_ALERT_WEBHOOK_SECRET")? { - self.webhook_secret = Some(secrecy::SecretString::from(secret)); + self.webhook_secret = Some(secrecy::SecretString::from(secret.trim().to_string())); } Ok(()) } @@ -1428,6 +1431,22 @@ mod tests { alerts.webhook_secret.as_ref().unwrap().expose_secret(), "from-env" ); + // A secret read from a file keeps no trailing newline, from either place. + alerts + .apply_env(env(vec![( + "HIE_ALERT_WEBHOOK_SECRET", + " from-file\n".into(), + )])) + .unwrap(); + assert_eq!( + alerts.webhook_secret.as_ref().unwrap().expose_secret(), + "from-file" + ); + let block = alerts_from("alerts:\n webhook_secret: |\n from-a-block\n").unwrap(); + assert_eq!( + block.webhook_secret.as_ref().unwrap().expose_secret(), + "from-a-block" + ); #[cfg(unix)] { use std::os::unix::ffi::OsStringExt; diff --git a/tests/alert_webhook.rs b/tests/alert_webhook.rs index 014c8f8..51c10f7 100644 --- a/tests/alert_webhook.rs +++ b/tests/alert_webhook.rs @@ -1,10 +1,11 @@ -//! The alert webhook against a local receiver: the signature over the raw body, -//! retries with one stable `event_id`, giving up after five retries, redirects -//! refused, two instances on one store sending each event once, an attempt whose -//! outcome was lost sent again with the same bytes, and events parked while -//! their URL is not the configured one. Driven through `Alerter` on a store of -//! its own, no transform involved. A test binary of its own, so its log -//! subscriber is the process's: no URL, secret or receiver answer may reach it. +//! The alert webhook against a local receiver: the signature over the +//! timestamp and the raw body, retries with one stable `event_id`, giving up +//! after five retries, redirects refused, two instances on one store sending +//! each event once, an attempt whose outcome was lost sent again with the same +//! bytes, and events parked while their URL is not the configured one. Driven +//! through `Alerter` on a store of its own, no transform involved. A test +//! binary of its own, so its log subscriber is the process's: no URL, secret or +//! receiver answer may reach it. use std::sync::{Arc, Mutex, OnceLock}; use std::time::{Duration, Instant}; @@ -69,6 +70,14 @@ fn assert_no_canary_logged() { } } +/// What a signature over the body alone, the scheme before timestamps, would be. +fn body_only_signature(secret: &[u8], body: &[u8]) -> String { + use hmac::{KeyInit, Mac}; + let mut mac = hmac::Hmac::::new_from_slice(secret).unwrap(); + mac.update(body); + format!("sha256={}", hex::encode(mac.finalize().into_bytes())) +} + /// One request as the receiver got it. #[derive(Clone, Debug)] struct Received { @@ -227,9 +236,23 @@ async fn fired_and_cleared_events_are_signed_over_the_raw_body() { let got = receiver.got(); for r in &got { + // Signed over the timestamp, a dot and the raw body; the body alone + // does not verify. + let timestamp = r.header("x-hie-timestamp").unwrap(); + assert!(timestamp.bytes().all(|b| b.is_ascii_digit()), "{timestamp}"); + let sent_at: i64 = timestamp.parse().unwrap(); + assert!( + (chrono::Utc::now().timestamp() - sent_at).abs() <= 5, + "a timestamp of the attempt: {sent_at}" + ); + let signed = r.header("x-hie-signature").unwrap(); assert_eq!( - r.header("x-hie-signature").unwrap(), - hie::alerts::signature(SECRET_CANARY.as_bytes(), &r.body) + signed, + hie::alerts::signature(SECRET_CANARY.as_bytes(), ×tamp, &r.body) + ); + assert_ne!( + signed, + body_only_signature(SECRET_CANARY.as_bytes(), &r.body) ); assert_eq!(r.header("content-type").unwrap(), "application/json"); assert!(r.header("user-agent").unwrap().starts_with("hie/")); @@ -314,6 +337,12 @@ async fn a_failing_receiver_gets_the_same_event_until_it_answers() { got.iter().all(|r| r.header("x-hie-signature").is_none()), "unsigned without a secret" ); + // Each attempt is stamped when it leaves, never earlier than the one before. + let stamps: Vec = got + .iter() + .map(|r| r.header("x-hie-timestamp").unwrap().parse().unwrap()) + .collect(); + assert!(stamps.windows(2).all(|w| w[0] <= w[1]), "{stamps:?}"); // The receiver's side of de-duplication: one event, however many requests. let mut ids: Vec = got .iter() diff --git a/tests/alerts.rs b/tests/alerts.rs index 4dcfb18..697c80c 100644 --- a/tests/alerts.rs +++ b/tests/alerts.rs @@ -1061,7 +1061,11 @@ async fn the_webhook_gets_each_alert_change_and_the_api_shows_its_delivery() { let (headers, body) = &got[0]; assert_eq!( headers["x-hie-signature"].to_str().unwrap(), - hie::alerts::signature(b"secretcanary", body) + hie::alerts::signature( + b"secretcanary", + headers["x-hie-timestamp"].to_str().unwrap(), + body + ) ); let payload: Value = serde_json::from_slice(body).unwrap(); assert_eq!(payload["event_id"], hook["event_id"]); From 613354b4634d1bdd00ea5f33b4e2c08faa272d35 Mon Sep 17 00:00:00 2001 From: Alvaro Salinas Dockar Date: Tue, 24 Nov 2026 10:15:42 -0400 Subject: [PATCH 2/8] fix(alerts): list every webhook event of an alert, not only the latest A fired event parked for an earlier URL, or failed, was hidden behind a cleared event delivered to the current one. GET /api/alerts keeps the latest event's fields in webhook and adds webhook.events, every event of the alert oldest first, read with the page in one statement. Refs #38 --- docs/api.md | 2 +- docs/decisions.md | 4 +-- docs/development.md | 2 +- docs/sources.md | 2 +- src/api.rs | 71 ++++++++++++++++++++++++++++++++++----------- tests/alerts.rs | 46 +++++++++++++++++++++++++++++ 6 files changed, 105 insertions(+), 22 deletions(-) diff --git a/docs/api.md b/docs/api.md index 7292e06..4a1a883 100644 --- a/docs/api.md +++ b/docs/api.md @@ -30,7 +30,7 @@ The HTTP API clients and UIs use, and how it and the engine's own calls to HFS a | `GET /api/records?source=&status=&file_id=` | Records; `status` is `received`, `pending`, `sent` or `rejected` | | `GET /api/records/{id}` | One record: file, line, original and corrected row, resources sent, HFS response | | `POST /api/records/{id}/reprocess` | Runs a record again; body `{"raw": {...}}` replaces the row and keeps the original | -| `GET /api/alerts?source=&open=true&since=&limit=100&cursor=` | Alerts, newest first, each with its rule, recipients, channels, when and why it cleared, and `webhook`: the delivery of its latest webhook event (`event`, `event_id`, `state`, `attempts`, `last_error`, `last_status`, `delivered_at`; null for alerts from before events were recorded); `open=true` lists only those not cleared. `since` and `cursor` read a period page by page (see [Reading alerts by period](#reading-alerts-by-period)). Kept for `retention.history` (see [Alerts and retention](#alerts-and-retention)). Also `webhook: {configured, signed}`, this instance's webhook settings (see [the alert webhook](sources.md#the-alert-webhook)) | +| `GET /api/alerts?source=&open=true&since=&limit=100&cursor=` | Alerts, newest first, each with its rule, recipients, channels, when and why it cleared, and `webhook`: the delivery of its latest webhook event (`event`, `event_id`, `state`, `attempts`, `last_error`, `last_status`, `delivered_at`), and in `webhook.events` every event of the alert with the same fields, oldest first (a `fired` still parked or failed stays visible after its `cleared` is delivered); null for alerts from before events were recorded; `open=true` lists only those not cleared. `since` and `cursor` read a period page by page (see [Reading alerts by period](#reading-alerts-by-period)). Kept for `retention.history` (see [Alerts and retention](#alerts-and-retention)). Also `webhook: {configured, signed}`, this instance's webhook settings (see [the alert webhook](sources.md#the-alert-webhook)) | | `GET /api/events?source=&kind=&since=&cursor=&limit=` | The event log, oldest first: each record's attempts and outcomes, each load's steps, each submission's steps (see [Events](#events)) | | `GET /api/alert-rules?source=` | Every rule, each with its `created_at`; `POST` creates one (`400` names what is wrong with it). `created_at` is set by the engine, never by the body. A rule id is never given again, like alert and event ids. A `missing_by` rule may name a `tz` (see [sources](sources.md#alerts-and-rules)) | | `GET` / `PUT` / `DELETE /api/alert-rules/{id}` | One rule: read, replace, remove. A `PUT` that turns the rule off (`enabled: false`) or changes its `condition`, `threshold`, `tz` or `source_id`, and a `DELETE`, clear the rule's open alerts in the same transaction, each with its webhook `cleared` event; a change of `notify` or `channels` alone does not | diff --git a/docs/decisions.md b/docs/decisions.md index 39c4acb..e0e1820 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -495,10 +495,10 @@ Several engine instances may share one PostgreSQL. A source is run by the instan - A receiver can still get an event twice, and a late `fired` after its `cleared`; it must de-duplicate. `event_id` covers retries of one event, not a second alert raised for one condition. Receivers match the two events of an alert by its `id`, which is never given again (decision 38). - No timestamp was signed: a receiver that forgot the `event_id`s it had seen accepted a replay of an old event (amended below, before any release carried the signature). Use HTTPS. - Sends are sequential, one per instance at a time: with a receiver that times out, waiting events queue behind each other. Claims and due times use each instance's clock, as source leases do: instances on one store need synchronised clocks. All instances on a store need the same `alerts:` settings. -- The API shows the latest event only: a `fired` that failed is shown until its `cleared` is written. A monitor tracking delivery re-reads the alerts it still follows; delivery changes do not move a cursor. Events are kept with their alert and removed with it when `retention.history` purges it (decision 38), waiting ones included: by then only an event parked for an earlier URL, or never sent, can still be waiting. +- The API showed the latest event only (until the amendment below added every event): a `fired` that failed was shown until its `cleared` was written. A monitor tracking delivery re-reads the alerts it still follows; delivery changes do not move a cursor. Events are kept with their alert and removed with it when `retention.history` purges it (decision 38), waiting ones included: by then only an event parked for an earlier URL, or never sent, can still be waiting. - No mail sink, per-rule URLs, redelivery endpoint or delivery metrics. -*Amended 2026-11-24:* every attempt carries `X-HIE-Timestamp`, the Unix seconds when it was sent, and `X-HIE-Signature` is the HMAC-SHA256 of `{timestamp}.{raw body}` (the scheme of Stripe and Standard Webhooks) instead of the body alone. Receivers refuse a timestamp outside a tolerance they enforce, 5 minutes by default, and keep the `event_id`s they have seen for at least that long. Why: with the body alone, anyone who captured one delivery could replay it later to a receiver that had pruned its `event_id`s, or never kept them (a `fired` that pages someone again); adding a timestamp after receivers verify the body-only signature would break every one of them. The stored body is still the same bytes on every attempt; the timestamp and the signature are computed per attempt when it leaves, so a retry is never stale, and the receiver's window need not cover the backoff. No release signed the body alone (0.2.0 sent unsigned events), so there is no compatibility mode. Cost: a receiver whose clock is off by more than its tolerance refuses every event, and gets them again on each retry until the five retries are spent; instances need synchronised clocks already. Each attempt's signature depends on when it is sent. +*Amended 2026-11-24:* every attempt carries `X-HIE-Timestamp`, the Unix seconds when it was sent, and `X-HIE-Signature` is the HMAC-SHA256 of `{timestamp}.{raw body}` (the scheme of Stripe and Standard Webhooks) instead of the body alone. Receivers refuse a timestamp outside a tolerance they enforce, 5 minutes by default, and keep the `event_id`s they have seen for at least that long. Why: with the body alone, anyone who captured one delivery could replay it later to a receiver that had pruned its `event_id`s, or never kept them (a `fired` that pages someone again); adding a timestamp after receivers verify the body-only signature would break every one of them. The stored body is still the same bytes on every attempt; the timestamp and the signature are computed per attempt when it leaves, so a retry is never stale, and the receiver's window need not cover the backoff. No release signed the body alone (0.2.0 sent unsigned events), so there is no compatibility mode. Cost: a receiver whose clock is off by more than its tolerance refuses every event, and gets them again on each retry until the five retries are spent; instances need synchronised clocks already. Each attempt's signature depends on when it is sent. Also: `GET /api/alerts` adds `webhook.events`, every event of each alert, read with the page in one statement: showing the latest event only could hide a `fired` parked for an earlier URL behind a `cleared` delivered to the current one. ## 41. Check now has an id and an outcome diff --git a/docs/development.md b/docs/development.md index e301776..799c9ea 100644 --- a/docs/development.md +++ b/docs/development.md @@ -27,7 +27,7 @@ cargo clippy --all-targets --no-default-features -- -D warnings cargo test --no-default-features --lib --test secrets --test no_backend_startup --test check --test s3_credentials ``` -The end-to-end tests run the real Python transforms against a stand-in FHIR server. `tests/pipeline.rs` covers a folder source: the outage and recovery, the duplicate file and the re-sent rows, each kind of bad row, reprocessing with a correction, the silence alert, and a load whose rows were all filtered out raising no alert while a mixed load's alert counts its failing rows, again only when more of them fail. `tests/events.rs` covers the event log: each outcome stored with its event before the next record is sent (the stand-in FHIR server reads the log through its own store handle on every request) or transformed (the probe transform reads the SQLite file), nothing stored when the event cannot be (a SQLite trigger refuses it, for an admission and for a delivery), outcomes for a record put back while it was transformed or sent changing nothing, a transform that cannot finish now (logged once per reason and runner), a submission opened, failing a poll, settled by its receipts or refused with an answer that echoes signed URLs and the engine's own path, a submission not opened when a record changed while it was written (on both bulk paths), a Retry, a refusal and an unsendable file of 450 rows each (more than one chunk), an older answer that cannot roll a record's attempts back, content taken meanwhile not admitted twice, a Retry that finds nothing, a finish reporting failing rows beyond the most an earlier finish saw, the API's paging, filters, cursor and refusals, the retention purge (old events and alerts, the alerts kept, the highest alert id kept so no id is given again, the alert counter unchanged, two purges at once counted once, more than one chunk) a restart that stops the first engine for good, distinct rejected records per day (a record rejected twice once, filtered rows apart, a midnight event in the day it starts, coverage from when the log began and within the retention) and that start kept across a reopen; with `HIE_TEST_DATABASE_URL`, an event committed later with a lower id never skipped by a reader, a finish that waits for a Retry's row lock (and one that counts the failing rows committed while it waited), an alert cleared while the purge waits for it kept, a record put back while its file is rejected left as it was put back, each test waiting until PostgreSQL shows the lock wait. `tests/alerts.rs` covers the rules: the one a source is born with and that a replace does not bring back, the CRUD, and the `rejected_share` and `silence` rules firing once and clearing, `rejected_share` weighing the failing rows among those a load kept (a load that kept none neither fires nor clears it); and rule ids never given again (after a delete, a reopen, and on a SQLite store whose rules table was made the old way), with `created_at` set by the engine; and reading alerts by period and in pages: `since` at its boundary (as the list returns it, finer, with an offset), every combination with `source` and `open` walked at several page sizes, a walk that keeps its place while alerts are added, cleared and removed, the default page of 100, and malformed queries refused without echoing them, on SQLite and, with `HIE_TEST_DATABASE_URL`, PostgreSQL; and, through the pipeline and the API, the webhook's delivery state: an alert from before events were recorded cleared and delivered, signed, with the API's time strings, events waiting for this URL (`pending`) and for another (`parked`), a rule without the `webhook` channel (`not_requested`), an engine without a URL (`not_configured`), and no URL, secret or fingerprint in the answer. `tests/alert_webhook.rs` drives the webhook sender against a local receiver under the production log filter at `trace`: the signature over each attempt's `X-HIE-Timestamp` and the raw body (a signature over the body alone does not match), fired before cleared, one `event_id` and one body over retries, giving up after five retries, a redirect refused, an unreachable receiver, one that does not answer in time, two instances on one store sending each event once, an attempt whose outcome was lost sent again unchanged by another instance, and an event waiting for its own URL across restarts; no URL, secret or receiver answer reaches a log line or the store. Unit tests pin the HMAC to RFC 4231 and the signed string to a value computed independently (Python's `hmac`), the webhook secret read without the whitespace around it, and, in the store, with time passed in and two handles on one file, the claim, the fence against late outcomes and replacement rows, the last attempt with no outcome, the order of fired and cleared per URL, and the alert and its event written or rolled back together. `tests/check.rs` checks that `hie check` refuses bad `alerts:` settings without printing the URL or the secret. `tests/bulk_submit.rs` drives both bulk paths against a stand-in consumer: an NDJSON export handed over as source objects, and a lab CSV transformed, given derived ids, written by the engine and settled by receipts. Against a stand-in public bucket it checks that an anonymous source reading a whole bucket hands over each object's public URL with its key encoded once, every read unsigned and the engine's file route unused; that a store object is never served from that route, even when a local file shares its key, while a staged zip entry is; that keys and entries stay apart under a relative bulk directory; that entries staged by an earlier version are recognised at start-up, served, settled and retried, whether the engine starts from a relative or an absolute configuration path; that an archived folder file from an earlier version is served again on retry; and that a file taken from a bucket and retried after its source became a folder is rejected rather than served. `tests/bulk_logs.rs` runs under the production log filter asked for everything at `trace`: a failing poll, a refusal that echoes signed URLs (one on a bracketed IPv6 host, one with parentheses in its path) and the engine's own path with the token, a relative status target that carries a signature, a cleanup that cannot remove a submission's files, a token endpoint failure and a status URL stored during a working delivery (a statement parameter on PostgreSQL) keep signatures and tokens out of every log line, the alerts, the stored errors and answers, and the event log. A folder file recorded through a symbolic link and `..` is served as the filesystem resolves that path. With an in-memory store it checks that a URL that cannot be signed yet keeps its records pending while open submissions are polled, and that an object no configuration can hand over is rejected without stalling the pass. `tests/object_source.rs` covers the object-store path the S3 source uses, with an in-memory store; `tests/sqs_source.rs` adds a notification queue to it, against a stand-in SQS that checks the SigV4 headers: the bucket listed once at start, then only announced objects taken, with their messages deleted after the pass and test events, foreign keys, gone objects and keys that are not object paths consumed without effect; `tests/overlap.rs` checks that HFS receives the first Bundle well before a slow transform finishes the file; the same source was run by hand against a MinIO (the `ghcr.io/coollabsio/minio` mirror HFS's CI pins) holding the Synthea export, on both delivery paths against an HFS that requires tokens: 632 resources by REST and the same 632 by `$bulk-submit` through pre-signed URLs, each resource stored once, objects archived under the processed prefix, and a re-uploaded file recognised as a duplicate. `tests/fhir_server_source.rs` covers pulling another FHIR server: pages followed, a cursor per type that moves once the records are stored, nothing pulled twice, the token on every call, and the connection test. `tests/database_source.rs` covers the database source on SQLite: runs of the query past a cursor, the cursor moving once the rows are stored, nothing read twice, `cursor_start`, and the connection test; `tests/mssql_source.rs` runs the same source against a SQL Server when `HIE_TEST_MSSQL_URL` is set, and is skipped otherwise. `tests/leases.rs` puts two instances on one store: one runs the source, the other stands by, and takes over when the lease lapses. `tests/test_terminology.py` covers the terminology helpers against a stand-in HTS and the lab transform using them. `tests/zip_drop.rs` covers zips: a drop in a read-only bucket unpacked once and left in place, and one in a folder unpacked and archived, with a broken zip reported. `tests/hl7v2.rs` covers HL7 v2: a file of messages through a folder source, and messages over MLLP spooled, acknowledged, delivered, and resent as duplicates; `tests/test_hl7.py` covers the Python helpers. `tests/api.rs` drives a source through the API: test, create, check now, pause, resume, replace, delete, and its contact read from a file and from the API, kept by a replace that sends back what it read, cleared by one without it, and refused when too long or more than one line. `tests/loads.rs` covers the loads list across sources: the fields of the per-source list, newest first, each `status` filter and `failed` (unreadable, rejected rows while in progress or done, rows filtered out on purpose that do not count, and what takes a load out), a walk by cursor while loads arrive and leave the filter, the limits and the refused queries, a store written by an earlier version (its loads with no mark of failing rows), and a deleted source whose id is created again; a unit test checks that SQLite chooses each page through an index. `tests/check_outcome.rs` drives the scans of a source another instance holds by hand: concurrent checks answered by the one scan after them with its one load, a check asked for once a scan started answered by the next with what the earlier one took, nothing new, a folder that cannot be listed (a fixed reason, no path), an unknown check, a replaced source's runner answering earlier checks, and a paused or deleted source failing them, but not one another instance still holds; the loads paged with the answer's cursor, malformed parameters refused with `invalid_query` and `field`, and the retention purge removing old checks, answered or not (`tests/events.rs` adds, on PostgreSQL, a check purge that waits for another instance's and moves on to the next old rows); unit tests in `src/db.rs` cover the snapshot, the first answer staying, pages of loads and the purge. `tests/check.rs` runs `hie check`: it refuses to start while `hie.yaml` has a `runtime` key or `HIE_RUNTIME_URL` is set, and passes when the variable is unset or blank; it prints a source's contact and refuses an invalid one naming the file, in both builds; `hie check` and `hie run` refuse an S3 file that names neither a credential nor `anonymous`, and `hie run` refuses a sealed store started with another key, or a key set in two places, before serving. Stored credentials: unit tests pin the sealed format against values computed independently (Python's `hmac`/`hashlib` and libsodium), the derivation against RFC 5869, and walk the key state machine (sealed and unsealed stores against every kind of key input, key files that are links, FIFOs or readable by others, a key file that cannot be created, concurrent first starts); the registration of sources for credentials is tested with pause points that force each interleaving, on SQLite and, with `HIE_TEST_DATABASE_URL`, PostgreSQL. `tests/secret_store.rs` covers persistence, refusals with both key ids, and values moved or altered in the database. `tests/secrets.rs` covers `/api/secrets` (shapes, bodies refused without echoing them, the `409` while used, `503 store_busy`, the `503 secrets_unavailable` of a store without a usable key, on the credential routes, on creating, replacing and testing a source, and in its `credential` alert, with no path), and the 503s of a build without a store; `tests/no_backend_startup.rs` runs that build's binary with a credential source file, which is skipped. The default rule's birth is tested on both stores too: given once, not again after a replace, a failed start, a restart or a file put back, given again by a create and kept when its write or start fails, never twice when two handles race (one held inside its transaction while the other waits), nothing recorded or published when it fails, and sources an earlier version left marked born without a rule. `tests/s3_credentials.rs` signs against a stand-in bucket that records key ids: the Test, the source, a rotation, the queue, an alert raised once and cleared, and a source waiting for its credential while its submissions are polled (a check asked for meanwhile fails, saying the credential is not loaded). `tests/secret_refs.rs` puts two engines on one store; `tests/secrets_canary.rs` checks that a canary secret appears in no answer, log line at `trace`, source file or database byte. `tests/worker.rs` runs the real launcher over a small test program for the long-lived worker cases of the `limited-process@1` contract (answers in order from one process, a reply written in pieces, a deadline and a late reply, a worker that exits or stays silent before it is ready, one that stops reading) and the engine's own duties: the pin check, setup errors, a stray line on stdout, the stderr tail, the run directories, the limits, the process group, the environment and cancelled calls; `tests/pipeline.rs` adds rows that hang, crash or run out of memory, each rejected once with the rows after it delivered, and `tests/api.rs` the bound on concurrent tries. `tests/worker.rs` also runs the real `hie_runtime/` with transforms that write to file descriptor 1 directly and through a child process, every record still getting its own reply. `tests/test_worker.py` checks the worker over its pipes (a write to file descriptor 1 included) and, on Linux, under the launcher's memory limit. +The end-to-end tests run the real Python transforms against a stand-in FHIR server. `tests/pipeline.rs` covers a folder source: the outage and recovery, the duplicate file and the re-sent rows, each kind of bad row, reprocessing with a correction, the silence alert, and a load whose rows were all filtered out raising no alert while a mixed load's alert counts its failing rows, again only when more of them fail. `tests/events.rs` covers the event log: each outcome stored with its event before the next record is sent (the stand-in FHIR server reads the log through its own store handle on every request) or transformed (the probe transform reads the SQLite file), nothing stored when the event cannot be (a SQLite trigger refuses it, for an admission and for a delivery), outcomes for a record put back while it was transformed or sent changing nothing, a transform that cannot finish now (logged once per reason and runner), a submission opened, failing a poll, settled by its receipts or refused with an answer that echoes signed URLs and the engine's own path, a submission not opened when a record changed while it was written (on both bulk paths), a Retry, a refusal and an unsendable file of 450 rows each (more than one chunk), an older answer that cannot roll a record's attempts back, content taken meanwhile not admitted twice, a Retry that finds nothing, a finish reporting failing rows beyond the most an earlier finish saw, the API's paging, filters, cursor and refusals, the retention purge (old events and alerts, the alerts kept, the highest alert id kept so no id is given again, the alert counter unchanged, two purges at once counted once, more than one chunk) a restart that stops the first engine for good, distinct rejected records per day (a record rejected twice once, filtered rows apart, a midnight event in the day it starts, coverage from when the log began and within the retention) and that start kept across a reopen; with `HIE_TEST_DATABASE_URL`, an event committed later with a lower id never skipped by a reader, a finish that waits for a Retry's row lock (and one that counts the failing rows committed while it waited), an alert cleared while the purge waits for it kept, a record put back while its file is rejected left as it was put back, each test waiting until PostgreSQL shows the lock wait. `tests/alerts.rs` covers the rules: the one a source is born with and that a replace does not bring back, the CRUD, and the `rejected_share` and `silence` rules firing once and clearing, `rejected_share` weighing the failing rows among those a load kept (a load that kept none neither fires nor clears it); and rule ids never given again (after a delete, a reopen, and on a SQLite store whose rules table was made the old way), with `created_at` set by the engine; and reading alerts by period and in pages: `since` at its boundary (as the list returns it, finer, with an offset), every combination with `source` and `open` walked at several page sizes, a walk that keeps its place while alerts are added, cleared and removed, the default page of 100, and malformed queries refused without echoing them, on SQLite and, with `HIE_TEST_DATABASE_URL`, PostgreSQL; and, through the pipeline and the API, the webhook's delivery state: an alert from before events were recorded cleared and delivered, signed, with the API's time strings, events waiting for this URL (`pending`) and for another (`parked`), a `fired` parked for another URL still listed in `webhook.events` after its `cleared` was delivered, an alert with two events counted once in a page, a rule without the `webhook` channel (`not_requested`), an engine without a URL (`not_configured`), and no URL, secret or fingerprint in the answer. `tests/alert_webhook.rs` drives the webhook sender against a local receiver under the production log filter at `trace`: the signature over each attempt's `X-HIE-Timestamp` and the raw body (a signature over the body alone does not match), fired before cleared, one `event_id` and one body over retries, giving up after five retries, a redirect refused, an unreachable receiver, one that does not answer in time, two instances on one store sending each event once, an attempt whose outcome was lost sent again unchanged by another instance, and an event waiting for its own URL across restarts; no URL, secret or receiver answer reaches a log line or the store. Unit tests pin the HMAC to RFC 4231 and the signed string to a value computed independently (Python's `hmac`), the webhook secret read without the whitespace around it, and, in the store, with time passed in and two handles on one file, the claim, the fence against late outcomes and replacement rows, the last attempt with no outcome, the order of fired and cleared per URL, and the alert and its event written or rolled back together. `tests/check.rs` checks that `hie check` refuses bad `alerts:` settings without printing the URL or the secret. `tests/bulk_submit.rs` drives both bulk paths against a stand-in consumer: an NDJSON export handed over as source objects, and a lab CSV transformed, given derived ids, written by the engine and settled by receipts. Against a stand-in public bucket it checks that an anonymous source reading a whole bucket hands over each object's public URL with its key encoded once, every read unsigned and the engine's file route unused; that a store object is never served from that route, even when a local file shares its key, while a staged zip entry is; that keys and entries stay apart under a relative bulk directory; that entries staged by an earlier version are recognised at start-up, served, settled and retried, whether the engine starts from a relative or an absolute configuration path; that an archived folder file from an earlier version is served again on retry; and that a file taken from a bucket and retried after its source became a folder is rejected rather than served. `tests/bulk_logs.rs` runs under the production log filter asked for everything at `trace`: a failing poll, a refusal that echoes signed URLs (one on a bracketed IPv6 host, one with parentheses in its path) and the engine's own path with the token, a relative status target that carries a signature, a cleanup that cannot remove a submission's files, a token endpoint failure and a status URL stored during a working delivery (a statement parameter on PostgreSQL) keep signatures and tokens out of every log line, the alerts, the stored errors and answers, and the event log. A folder file recorded through a symbolic link and `..` is served as the filesystem resolves that path. With an in-memory store it checks that a URL that cannot be signed yet keeps its records pending while open submissions are polled, and that an object no configuration can hand over is rejected without stalling the pass. `tests/object_source.rs` covers the object-store path the S3 source uses, with an in-memory store; `tests/sqs_source.rs` adds a notification queue to it, against a stand-in SQS that checks the SigV4 headers: the bucket listed once at start, then only announced objects taken, with their messages deleted after the pass and test events, foreign keys, gone objects and keys that are not object paths consumed without effect; `tests/overlap.rs` checks that HFS receives the first Bundle well before a slow transform finishes the file; the same source was run by hand against a MinIO (the `ghcr.io/coollabsio/minio` mirror HFS's CI pins) holding the Synthea export, on both delivery paths against an HFS that requires tokens: 632 resources by REST and the same 632 by `$bulk-submit` through pre-signed URLs, each resource stored once, objects archived under the processed prefix, and a re-uploaded file recognised as a duplicate. `tests/fhir_server_source.rs` covers pulling another FHIR server: pages followed, a cursor per type that moves once the records are stored, nothing pulled twice, the token on every call, and the connection test. `tests/database_source.rs` covers the database source on SQLite: runs of the query past a cursor, the cursor moving once the rows are stored, nothing read twice, `cursor_start`, and the connection test; `tests/mssql_source.rs` runs the same source against a SQL Server when `HIE_TEST_MSSQL_URL` is set, and is skipped otherwise. `tests/leases.rs` puts two instances on one store: one runs the source, the other stands by, and takes over when the lease lapses. `tests/test_terminology.py` covers the terminology helpers against a stand-in HTS and the lab transform using them. `tests/zip_drop.rs` covers zips: a drop in a read-only bucket unpacked once and left in place, and one in a folder unpacked and archived, with a broken zip reported. `tests/hl7v2.rs` covers HL7 v2: a file of messages through a folder source, and messages over MLLP spooled, acknowledged, delivered, and resent as duplicates; `tests/test_hl7.py` covers the Python helpers. `tests/api.rs` drives a source through the API: test, create, check now, pause, resume, replace, delete, and its contact read from a file and from the API, kept by a replace that sends back what it read, cleared by one without it, and refused when too long or more than one line. `tests/loads.rs` covers the loads list across sources: the fields of the per-source list, newest first, each `status` filter and `failed` (unreadable, rejected rows while in progress or done, rows filtered out on purpose that do not count, and what takes a load out), a walk by cursor while loads arrive and leave the filter, the limits and the refused queries, a store written by an earlier version (its loads with no mark of failing rows), and a deleted source whose id is created again; a unit test checks that SQLite chooses each page through an index. `tests/check_outcome.rs` drives the scans of a source another instance holds by hand: concurrent checks answered by the one scan after them with its one load, a check asked for once a scan started answered by the next with what the earlier one took, nothing new, a folder that cannot be listed (a fixed reason, no path), an unknown check, a replaced source's runner answering earlier checks, and a paused or deleted source failing them, but not one another instance still holds; the loads paged with the answer's cursor, malformed parameters refused with `invalid_query` and `field`, and the retention purge removing old checks, answered or not (`tests/events.rs` adds, on PostgreSQL, a check purge that waits for another instance's and moves on to the next old rows); unit tests in `src/db.rs` cover the snapshot, the first answer staying, pages of loads and the purge. `tests/check.rs` runs `hie check`: it refuses to start while `hie.yaml` has a `runtime` key or `HIE_RUNTIME_URL` is set, and passes when the variable is unset or blank; it prints a source's contact and refuses an invalid one naming the file, in both builds; `hie check` and `hie run` refuse an S3 file that names neither a credential nor `anonymous`, and `hie run` refuses a sealed store started with another key, or a key set in two places, before serving. Stored credentials: unit tests pin the sealed format against values computed independently (Python's `hmac`/`hashlib` and libsodium), the derivation against RFC 5869, and walk the key state machine (sealed and unsealed stores against every kind of key input, key files that are links, FIFOs or readable by others, a key file that cannot be created, concurrent first starts); the registration of sources for credentials is tested with pause points that force each interleaving, on SQLite and, with `HIE_TEST_DATABASE_URL`, PostgreSQL. `tests/secret_store.rs` covers persistence, refusals with both key ids, and values moved or altered in the database. `tests/secrets.rs` covers `/api/secrets` (shapes, bodies refused without echoing them, the `409` while used, `503 store_busy`, the `503 secrets_unavailable` of a store without a usable key, on the credential routes, on creating, replacing and testing a source, and in its `credential` alert, with no path), and the 503s of a build without a store; `tests/no_backend_startup.rs` runs that build's binary with a credential source file, which is skipped. The default rule's birth is tested on both stores too: given once, not again after a replace, a failed start, a restart or a file put back, given again by a create and kept when its write or start fails, never twice when two handles race (one held inside its transaction while the other waits), nothing recorded or published when it fails, and sources an earlier version left marked born without a rule. `tests/s3_credentials.rs` signs against a stand-in bucket that records key ids: the Test, the source, a rotation, the queue, an alert raised once and cleared, and a source waiting for its credential while its submissions are polled (a check asked for meanwhile fails, saying the credential is not loaded). `tests/secret_refs.rs` puts two engines on one store; `tests/secrets_canary.rs` checks that a canary secret appears in no answer, log line at `trace`, source file or database byte. `tests/worker.rs` runs the real launcher over a small test program for the long-lived worker cases of the `limited-process@1` contract (answers in order from one process, a reply written in pieces, a deadline and a late reply, a worker that exits or stays silent before it is ready, one that stops reading) and the engine's own duties: the pin check, setup errors, a stray line on stdout, the stderr tail, the run directories, the limits, the process group, the environment and cancelled calls; `tests/pipeline.rs` adds rows that hang, crash or run out of memory, each rejected once with the rows after it delivered, and `tests/api.rs` the bound on concurrent tries. `tests/worker.rs` also runs the real `hie_runtime/` with transforms that write to file descriptor 1 directly and through a child process, every record still getting its own reply. `tests/test_worker.py` checks the worker over its pipes (a write to file descriptor 1 included) and, on Linux, under the launcher's memory limit. They are skipped if no Python 3.9+ is found; set `HIE_TEST_PYTHON` to point at one. diff --git a/docs/sources.md b/docs/sources.md index d8d9160..ec6bf3d 100644 --- a/docs/sources.md +++ b/docs/sources.md @@ -119,6 +119,6 @@ Each change of an alert is one **event**, `fired` or `cleared`, written in the s - **De-duplication:** a receiver may get an event more than once (its 2xx was lost to a timeout, or an instance stopped before storing the outcome). It keeps the `event_id`s it has seen, answers a repeated one with a 2xx and does nothing else. `event_id` identifies one event and its retries, not a condition: a source whose lease lapsed in the middle of a pass can raise a second alert, with its own events, for the same condition. - **Order:** a `cleared` event waits until its alert's `fired` event for the same URL has been delivered or given up on; a `fired` event still waiting for an earlier URL does not hold back a `cleared` for the current one. Still, a receiver may get a `cleared` for an alert it has not seen (fired before this engine version, while no URL was set, or whose `fired` failed), and a late `fired` after its `cleared` (a retry of an attempt that timed out): a late `fired` does not reopen a cleared alert. Match the two events of one alert by `alert.id`: an alert id is never given again. - **One URL per event:** an event is sent only to the URL configured when it was written. After the URL changes, events still waiting for the earlier one stay `pending` (the API shows them `parked`) and go out if that URL comes back; a start without a URL leaves them waiting too. Rotating the secret signs waiting events with the new one; a blank secret is refused. Every instance on one store must have the same `alerts:` settings: any of them may send any waiting event, from oldest to newest, one at a time. -- **Delivery state:** `GET /api/alerts` answers `webhook: {configured, signed}` for this instance's settings, and each alert's `webhook`: its latest event (`event`, `event_id`), its `state`, `attempts`, `last_error`, `last_status` (the HTTP status of the last answer, null when there was none) and `delivered_at`. `state` is `pending` (waiting for its first attempt, being sent, waiting for a retry, or a `cleared` waiting for its `fired`), `parked` (pending for another URL than this instance's), `delivered`, `failed` (five retries spent, or the last attempt recorded no outcome), `not_requested` (the rule's channels leave out `webhook`) or `not_configured` (no URL was set when the event happened). `webhook` is null for alerts recorded before events were. `last_error` is the error of the last **failed** attempt, kept after a later delivery, and a fixed sentence (`HTTP 503 Service Unavailable`, `timeout`, `connection failed`, `request failed`, `no outcome recorded for the last attempt`): never the URL or what the receiver answered. `last_status` is the HTTP status of the **latest** attempt, null while it runs or when it got no answer. A monitor that tracks delivery re-reads the alerts it still cares about (open ones, or ones not yet `delivered`): the state changes after the alert is listed. +- **Delivery state:** `GET /api/alerts` answers `webhook: {configured, signed}` for this instance's settings, and each alert's `webhook`: its latest event (`event`, `event_id`), its `state`, `attempts`, `last_error`, `last_status` (the HTTP status of the last answer, null when there was none) and `delivered_at`; `webhook.events` lists every event of the alert, oldest first, with the same fields, so a `fired` parked for an earlier URL, or failed, is still seen once its `cleared` is delivered. `state` is `pending` (waiting for its first attempt, being sent, waiting for a retry, or a `cleared` waiting for its `fired`), `parked` (pending for another URL than this instance's), `delivered`, `failed` (five retries spent, or the last attempt recorded no outcome), `not_requested` (the rule's channels leave out `webhook`) or `not_configured` (no URL was set when the event happened). `webhook` is null for alerts recorded before events were. `last_error` is the error of the last **failed** attempt, kept after a later delivery, and a fixed sentence (`HTTP 503 Service Unavailable`, `timeout`, `connection failed`, `request failed`, `no outcome recorded for the last attempt`): never the URL or what the receiver answered. `last_status` is the HTTP status of the **latest** attempt, null while it runs or when it got no answer. A monitor that tracks delivery re-reads the alerts it still cares about (open ones, or ones not yet `delivered`): the state changes after the alert is listed. - The webhook URL and secret never reach the log, the store or an answer; the store keeps a fingerprint of the URL to tell destinations apart. Events go out over HTTP/1.1. At `debug` and `trace`, the HTTP client logs the receiver's host and port when it connects. While `hie.yaml` gives `alerts:` any value, and whenever it is not valid YAML, its parse errors leave out every quoted value. - The body before this version was `{text, feed, kind, alert_id, notify}` (and `cleared: true` on a clear), and a clear was posted even for a rule without the `webhook` channel. Receivers reading anything but `text` need the new fields. diff --git a/src/api.rs b/src/api.rs index 637db72..e8c2d20 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1066,8 +1066,9 @@ struct AlertListQuery { /// Newest first, a page at a time: `next_cursor` is set only when more alerts /// match, and the next page holds those older (by id) than the last one here. -/// Each alert comes with its latest webhook event, read in the same statement; -/// a pending event written for another URL than this instance's is `parked`. +/// Each alert comes with its webhook events, read in the same statement: the +/// latest one's delivery, and every one in `events`; a pending event written +/// for another URL than this instance's is `parked`. async fn list_alerts( State(s): State, q: Result, QueryRejection>, @@ -1088,25 +1089,28 @@ async fn list_alerts( json!({"alerts": [], "next_cursor": null, "webhook": webhook}), )); } - let mut rows = s.db.query_json( + // The page of alerts, then every webhook event of each, in one statement: + // the latest event and the history agree, and a page holds `limit` alerts + // whatever their events. + let joined = s.db.query_json( &format!( - "SELECT alerts.id, alerts.feed_id AS source_id, alerts.kind, alerts.message, alerts.rule_id, - alerts.notify, alerts.channels, - {} AS created_at, {} AS cleared_at, alerts.cleared_reason, + "SELECT a.id, a.feed_id AS source_id, a.kind, a.message, a.rule_id, + a.notify, a.channels, + {} AS created_at, {} AS cleared_at, a.cleared_reason, w.event AS webhook_event, w.event_id AS webhook_event_id, CASE WHEN w.state = 'pending' AND w.destination <> CAST($6 AS TEXT) THEN 'parked' ELSE w.state END AS webhook_state, w.attempts AS webhook_attempts, w.last_error AS webhook_last_error, w.last_status AS webhook_last_status, {} AS webhook_delivered_at - FROM alerts - LEFT JOIN alert_webhooks w - ON w.id = (SELECT MAX(x.id) FROM alert_webhooks x WHERE x.alert_id = alerts.id) - WHERE (CAST($1 AS TEXT) IS NULL OR alerts.feed_id = CAST($1 AS TEXT)) - AND (CAST($3 AS BIGINT) = 0 OR alerts.cleared_at IS NULL) - AND (CAST($4 AS BIGINT) IS NULL OR alerts.created_at >= CAST($4 AS BIGINT)) AND alerts.id <= $5 - ORDER BY alerts.id DESC LIMIT $2", - s.db.iso("alerts.created_at"), - s.db.iso("alerts.cleared_at"), + FROM (SELECT * FROM alerts + WHERE (CAST($1 AS TEXT) IS NULL OR alerts.feed_id = CAST($1 AS TEXT)) + AND (CAST($3 AS BIGINT) = 0 OR alerts.cleared_at IS NULL) + AND (CAST($4 AS BIGINT) IS NULL OR alerts.created_at >= CAST($4 AS BIGINT)) AND alerts.id <= $5 + ORDER BY alerts.id DESC LIMIT $2) a + LEFT JOIN alert_webhooks w ON w.alert_id = a.id + ORDER BY a.id DESC, w.id", + s.db.iso("a.created_at"), + s.db.iso("a.cleared_at"), s.db.iso("w.delivered_at") ), params![ @@ -1119,6 +1123,27 @@ async fn list_alerts( s.alerts.destination() ], )?; + let mut rows: Vec = Vec::new(); + for row in joined { + let row = alert_json(row); + match rows.last_mut() { + Some(last) if last["id"] == row["id"] => { + if let (Some(Value::Array(events)), Value::Object(event)) = + (last["webhook"].get_mut("events"), &row["webhook"]) + { + events.push(Value::Object(event.clone())); + } + last["webhook"] = latest_with_history(&last["webhook"]); + } + _ => { + let mut row = row; + if row["webhook"].is_object() { + row["webhook"]["events"] = json!([row["webhook"].clone()]); + } + rows.push(row); + } + } + } let page = usize::try_from(limit).unwrap_or(usize::MAX); let next_cursor = if rows.len() > page { rows.truncate(page); @@ -1129,7 +1154,6 @@ async fn list_alerts( } else { None }; - let rows: Vec = rows.into_iter().map(alert_json).collect(); Ok(Json(json!({ "alerts": rows, "next_cursor": next_cursor, @@ -1137,9 +1161,22 @@ async fn list_alerts( }))) } +/// The `webhook` of an alert whose `events` just grew: its own fields are the +/// newest event's, and `events` stays every event, oldest first. +fn latest_with_history(webhook: &Value) -> Value { + let events = webhook["events"].clone(); + let mut latest = events + .as_array() + .and_then(|e| e.last()) + .cloned() + .unwrap_or(Value::Null); + latest["events"] = events; + latest +} + /// An alert row as the API answers it: the stored lists parsed, and the /// `webhook_*` columns folded into `webhook` (`null` for an alert recorded -/// before events were). +/// before events were; that row's event alone, before its history is added). fn alert_json(mut row: Value) -> Value { for key in ["notify", "channels"] { if let Some(Value::String(text)) = row.get(key) { diff --git a/tests/alerts.rs b/tests/alerts.rs index 697c80c..95d5ebd 100644 --- a/tests/alerts.rs +++ b/tests/alerts.rs @@ -1004,6 +1004,52 @@ async fn the_webhook_gets_each_alert_change_and_the_api_shows_its_delivery() { let all = lab.get("/api/alerts").await; assert_eq!(webhook_of(&all, &waiting[0])["state"], "pending"); assert_eq!(webhook_of(&all, &waiting[1])["state"], "parked"); + assert_eq!( + webhook_of(&all, &waiting[1])["events"], + json!([{"event": "fired", "event_id": "waits-elsewhere", "state": "parked", "attempts": 0, + "last_error": null, "last_status": null, "delivered_at": null}]) + ); + // A later `cleared` delivered to this URL does not hide the `fired` still + // parked for the other one: the latest event is the clear, and `events` + // lists both, oldest first. + lab.db + .query_json( + "INSERT INTO alert_webhooks (event_id, alert_id, event, destination, payload, state, attempts, last_status, delivered_at, next_attempt_at, created_at) + VALUES ('cleared-here', $1, 'cleared', $2, '{}', 'delivered', 1, 200, 1700000000456, 0, 2) RETURNING id", + vec![ + hie::db::Param::Int(waiting[1].as_i64().unwrap()), + hie::db::Param::Text(ours.clone()), + ], + ) + .unwrap(); + let all = lab.get("/api/alerts").await; + let hook = webhook_of(&all, &waiting[1]); + assert_eq!( + (hook["event"].as_str(), hook["state"].as_str()), + (Some("cleared"), Some("delivered")) + ); + assert_eq!(hook["delivered_at"], "2023-11-14T22:13:20.456Z"); + let states: Vec<_> = hook["events"] + .as_array() + .unwrap() + .iter() + .map(|e| { + ( + e["event_id"].as_str().unwrap(), + e["state"].as_str().unwrap(), + ) + }) + .collect(); + assert_eq!( + states, + [("waits-elsewhere", "parked"), ("cleared-here", "delivered")] + ); + assert_eq!(hook["events"][1]["delivered_at"], hook["delivered_at"]); + // Two events of one alert still make one alert of the page. + let paged = lab.get("/api/alerts?source=other&limit=1").await; + assert_eq!(paged["alerts"].as_array().unwrap().len(), 1); + assert_eq!(paged["alerts"][0]["id"], waiting[1]); + assert!(paged["next_cursor"].is_string()); let alerts = lab.get("/api/alerts?source=lab-results").await; assert_eq!( alerts["webhook"], From 80dfd1ba7e0111d7a0fe4cbb3e0fb06d598a07d7 Mon Sep 17 00:00:00 2001 From: Alvaro Salinas Dockar Date: Tue, 24 Nov 2026 10:16:11 -0400 Subject: [PATCH 3/8] fix(alerts): say how long a receiver keeps event ids; test a re-signed retry Refs #38 --- docs/decisions.md | 2 +- docs/development.md | 2 +- docs/sources.md | 2 +- tests/alert_webhook.rs | 48 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 51 insertions(+), 3 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index e0e1820..6003d17 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -498,7 +498,7 @@ Several engine instances may share one PostgreSQL. A source is run by the instan - The API showed the latest event only (until the amendment below added every event): a `fired` that failed was shown until its `cleared` was written. A monitor tracking delivery re-reads the alerts it still follows; delivery changes do not move a cursor. Events are kept with their alert and removed with it when `retention.history` purges it (decision 38), waiting ones included: by then only an event parked for an earlier URL, or never sent, can still be waiting. - No mail sink, per-rule URLs, redelivery endpoint or delivery metrics. -*Amended 2026-11-24:* every attempt carries `X-HIE-Timestamp`, the Unix seconds when it was sent, and `X-HIE-Signature` is the HMAC-SHA256 of `{timestamp}.{raw body}` (the scheme of Stripe and Standard Webhooks) instead of the body alone. Receivers refuse a timestamp outside a tolerance they enforce, 5 minutes by default, and keep the `event_id`s they have seen for at least that long. Why: with the body alone, anyone who captured one delivery could replay it later to a receiver that had pruned its `event_id`s, or never kept them (a `fired` that pages someone again); adding a timestamp after receivers verify the body-only signature would break every one of them. The stored body is still the same bytes on every attempt; the timestamp and the signature are computed per attempt when it leaves, so a retry is never stale, and the receiver's window need not cover the backoff. No release signed the body alone (0.2.0 sent unsigned events), so there is no compatibility mode. Cost: a receiver whose clock is off by more than its tolerance refuses every event, and gets them again on each retry until the five retries are spent; instances need synchronised clocks already. Each attempt's signature depends on when it is sent. Also: `GET /api/alerts` adds `webhook.events`, every event of each alert, read with the page in one statement: showing the latest event only could hide a `fired` parked for an earlier URL behind a `cleared` delivered to the current one. +*Amended 2026-11-24:* every attempt carries `X-HIE-Timestamp`, the Unix seconds when it was sent, and `X-HIE-Signature` is the HMAC-SHA256 of `{timestamp}.{raw body}` (the scheme of Stripe and Standard Webhooks) instead of the body alone: the pattern Stripe and Standard Webhooks use, in HIE's own headers. Receivers refuse a timestamp outside a tolerance they enforce, 5 minutes by default, and keep the `event_id`s they have acted on for at least twice that long. Why: with the body alone, anyone who captured one delivery could replay it later to a receiver that had pruned its `event_id`s, or never kept them (a `fired` that pages someone again); adding a timestamp after receivers verify the body-only signature would break every one of them. The stored body is still the same bytes on every attempt; the timestamp and the signature are computed per attempt when it leaves, so a retry is never stale, and the receiver's window need not cover the backoff. No release signed the body alone (0.2.0 sent unsigned events), so there is no compatibility mode. Cost: a receiver whose clock is off by more than its tolerance refuses every event, and gets them again on each retry until the five retries are spent; instances need synchronised clocks already. Each attempt's signature depends on when it is sent. Also: the secret is trimmed of leading and trailing whitespace when read, from `hie.yaml` or the environment, so a secret file ending in a newline signs with the secret it holds; a secret meant to begin or end with whitespace now signs without it. And `GET /api/alerts` adds `webhook.events`, every event of each alert, read with the page in one statement: showing the latest event only could hide a `fired` parked for an earlier URL behind a `cleared` delivered to the current one. ## 41. Check now has an id and an outcome diff --git a/docs/development.md b/docs/development.md index 799c9ea..2c1271a 100644 --- a/docs/development.md +++ b/docs/development.md @@ -27,7 +27,7 @@ cargo clippy --all-targets --no-default-features -- -D warnings cargo test --no-default-features --lib --test secrets --test no_backend_startup --test check --test s3_credentials ``` -The end-to-end tests run the real Python transforms against a stand-in FHIR server. `tests/pipeline.rs` covers a folder source: the outage and recovery, the duplicate file and the re-sent rows, each kind of bad row, reprocessing with a correction, the silence alert, and a load whose rows were all filtered out raising no alert while a mixed load's alert counts its failing rows, again only when more of them fail. `tests/events.rs` covers the event log: each outcome stored with its event before the next record is sent (the stand-in FHIR server reads the log through its own store handle on every request) or transformed (the probe transform reads the SQLite file), nothing stored when the event cannot be (a SQLite trigger refuses it, for an admission and for a delivery), outcomes for a record put back while it was transformed or sent changing nothing, a transform that cannot finish now (logged once per reason and runner), a submission opened, failing a poll, settled by its receipts or refused with an answer that echoes signed URLs and the engine's own path, a submission not opened when a record changed while it was written (on both bulk paths), a Retry, a refusal and an unsendable file of 450 rows each (more than one chunk), an older answer that cannot roll a record's attempts back, content taken meanwhile not admitted twice, a Retry that finds nothing, a finish reporting failing rows beyond the most an earlier finish saw, the API's paging, filters, cursor and refusals, the retention purge (old events and alerts, the alerts kept, the highest alert id kept so no id is given again, the alert counter unchanged, two purges at once counted once, more than one chunk) a restart that stops the first engine for good, distinct rejected records per day (a record rejected twice once, filtered rows apart, a midnight event in the day it starts, coverage from when the log began and within the retention) and that start kept across a reopen; with `HIE_TEST_DATABASE_URL`, an event committed later with a lower id never skipped by a reader, a finish that waits for a Retry's row lock (and one that counts the failing rows committed while it waited), an alert cleared while the purge waits for it kept, a record put back while its file is rejected left as it was put back, each test waiting until PostgreSQL shows the lock wait. `tests/alerts.rs` covers the rules: the one a source is born with and that a replace does not bring back, the CRUD, and the `rejected_share` and `silence` rules firing once and clearing, `rejected_share` weighing the failing rows among those a load kept (a load that kept none neither fires nor clears it); and rule ids never given again (after a delete, a reopen, and on a SQLite store whose rules table was made the old way), with `created_at` set by the engine; and reading alerts by period and in pages: `since` at its boundary (as the list returns it, finer, with an offset), every combination with `source` and `open` walked at several page sizes, a walk that keeps its place while alerts are added, cleared and removed, the default page of 100, and malformed queries refused without echoing them, on SQLite and, with `HIE_TEST_DATABASE_URL`, PostgreSQL; and, through the pipeline and the API, the webhook's delivery state: an alert from before events were recorded cleared and delivered, signed, with the API's time strings, events waiting for this URL (`pending`) and for another (`parked`), a `fired` parked for another URL still listed in `webhook.events` after its `cleared` was delivered, an alert with two events counted once in a page, a rule without the `webhook` channel (`not_requested`), an engine without a URL (`not_configured`), and no URL, secret or fingerprint in the answer. `tests/alert_webhook.rs` drives the webhook sender against a local receiver under the production log filter at `trace`: the signature over each attempt's `X-HIE-Timestamp` and the raw body (a signature over the body alone does not match), fired before cleared, one `event_id` and one body over retries, giving up after five retries, a redirect refused, an unreachable receiver, one that does not answer in time, two instances on one store sending each event once, an attempt whose outcome was lost sent again unchanged by another instance, and an event waiting for its own URL across restarts; no URL, secret or receiver answer reaches a log line or the store. Unit tests pin the HMAC to RFC 4231 and the signed string to a value computed independently (Python's `hmac`), the webhook secret read without the whitespace around it, and, in the store, with time passed in and two handles on one file, the claim, the fence against late outcomes and replacement rows, the last attempt with no outcome, the order of fired and cleared per URL, and the alert and its event written or rolled back together. `tests/check.rs` checks that `hie check` refuses bad `alerts:` settings without printing the URL or the secret. `tests/bulk_submit.rs` drives both bulk paths against a stand-in consumer: an NDJSON export handed over as source objects, and a lab CSV transformed, given derived ids, written by the engine and settled by receipts. Against a stand-in public bucket it checks that an anonymous source reading a whole bucket hands over each object's public URL with its key encoded once, every read unsigned and the engine's file route unused; that a store object is never served from that route, even when a local file shares its key, while a staged zip entry is; that keys and entries stay apart under a relative bulk directory; that entries staged by an earlier version are recognised at start-up, served, settled and retried, whether the engine starts from a relative or an absolute configuration path; that an archived folder file from an earlier version is served again on retry; and that a file taken from a bucket and retried after its source became a folder is rejected rather than served. `tests/bulk_logs.rs` runs under the production log filter asked for everything at `trace`: a failing poll, a refusal that echoes signed URLs (one on a bracketed IPv6 host, one with parentheses in its path) and the engine's own path with the token, a relative status target that carries a signature, a cleanup that cannot remove a submission's files, a token endpoint failure and a status URL stored during a working delivery (a statement parameter on PostgreSQL) keep signatures and tokens out of every log line, the alerts, the stored errors and answers, and the event log. A folder file recorded through a symbolic link and `..` is served as the filesystem resolves that path. With an in-memory store it checks that a URL that cannot be signed yet keeps its records pending while open submissions are polled, and that an object no configuration can hand over is rejected without stalling the pass. `tests/object_source.rs` covers the object-store path the S3 source uses, with an in-memory store; `tests/sqs_source.rs` adds a notification queue to it, against a stand-in SQS that checks the SigV4 headers: the bucket listed once at start, then only announced objects taken, with their messages deleted after the pass and test events, foreign keys, gone objects and keys that are not object paths consumed without effect; `tests/overlap.rs` checks that HFS receives the first Bundle well before a slow transform finishes the file; the same source was run by hand against a MinIO (the `ghcr.io/coollabsio/minio` mirror HFS's CI pins) holding the Synthea export, on both delivery paths against an HFS that requires tokens: 632 resources by REST and the same 632 by `$bulk-submit` through pre-signed URLs, each resource stored once, objects archived under the processed prefix, and a re-uploaded file recognised as a duplicate. `tests/fhir_server_source.rs` covers pulling another FHIR server: pages followed, a cursor per type that moves once the records are stored, nothing pulled twice, the token on every call, and the connection test. `tests/database_source.rs` covers the database source on SQLite: runs of the query past a cursor, the cursor moving once the rows are stored, nothing read twice, `cursor_start`, and the connection test; `tests/mssql_source.rs` runs the same source against a SQL Server when `HIE_TEST_MSSQL_URL` is set, and is skipped otherwise. `tests/leases.rs` puts two instances on one store: one runs the source, the other stands by, and takes over when the lease lapses. `tests/test_terminology.py` covers the terminology helpers against a stand-in HTS and the lab transform using them. `tests/zip_drop.rs` covers zips: a drop in a read-only bucket unpacked once and left in place, and one in a folder unpacked and archived, with a broken zip reported. `tests/hl7v2.rs` covers HL7 v2: a file of messages through a folder source, and messages over MLLP spooled, acknowledged, delivered, and resent as duplicates; `tests/test_hl7.py` covers the Python helpers. `tests/api.rs` drives a source through the API: test, create, check now, pause, resume, replace, delete, and its contact read from a file and from the API, kept by a replace that sends back what it read, cleared by one without it, and refused when too long or more than one line. `tests/loads.rs` covers the loads list across sources: the fields of the per-source list, newest first, each `status` filter and `failed` (unreadable, rejected rows while in progress or done, rows filtered out on purpose that do not count, and what takes a load out), a walk by cursor while loads arrive and leave the filter, the limits and the refused queries, a store written by an earlier version (its loads with no mark of failing rows), and a deleted source whose id is created again; a unit test checks that SQLite chooses each page through an index. `tests/check_outcome.rs` drives the scans of a source another instance holds by hand: concurrent checks answered by the one scan after them with its one load, a check asked for once a scan started answered by the next with what the earlier one took, nothing new, a folder that cannot be listed (a fixed reason, no path), an unknown check, a replaced source's runner answering earlier checks, and a paused or deleted source failing them, but not one another instance still holds; the loads paged with the answer's cursor, malformed parameters refused with `invalid_query` and `field`, and the retention purge removing old checks, answered or not (`tests/events.rs` adds, on PostgreSQL, a check purge that waits for another instance's and moves on to the next old rows); unit tests in `src/db.rs` cover the snapshot, the first answer staying, pages of loads and the purge. `tests/check.rs` runs `hie check`: it refuses to start while `hie.yaml` has a `runtime` key or `HIE_RUNTIME_URL` is set, and passes when the variable is unset or blank; it prints a source's contact and refuses an invalid one naming the file, in both builds; `hie check` and `hie run` refuse an S3 file that names neither a credential nor `anonymous`, and `hie run` refuses a sealed store started with another key, or a key set in two places, before serving. Stored credentials: unit tests pin the sealed format against values computed independently (Python's `hmac`/`hashlib` and libsodium), the derivation against RFC 5869, and walk the key state machine (sealed and unsealed stores against every kind of key input, key files that are links, FIFOs or readable by others, a key file that cannot be created, concurrent first starts); the registration of sources for credentials is tested with pause points that force each interleaving, on SQLite and, with `HIE_TEST_DATABASE_URL`, PostgreSQL. `tests/secret_store.rs` covers persistence, refusals with both key ids, and values moved or altered in the database. `tests/secrets.rs` covers `/api/secrets` (shapes, bodies refused without echoing them, the `409` while used, `503 store_busy`, the `503 secrets_unavailable` of a store without a usable key, on the credential routes, on creating, replacing and testing a source, and in its `credential` alert, with no path), and the 503s of a build without a store; `tests/no_backend_startup.rs` runs that build's binary with a credential source file, which is skipped. The default rule's birth is tested on both stores too: given once, not again after a replace, a failed start, a restart or a file put back, given again by a create and kept when its write or start fails, never twice when two handles race (one held inside its transaction while the other waits), nothing recorded or published when it fails, and sources an earlier version left marked born without a rule. `tests/s3_credentials.rs` signs against a stand-in bucket that records key ids: the Test, the source, a rotation, the queue, an alert raised once and cleared, and a source waiting for its credential while its submissions are polled (a check asked for meanwhile fails, saying the credential is not loaded). `tests/secret_refs.rs` puts two engines on one store; `tests/secrets_canary.rs` checks that a canary secret appears in no answer, log line at `trace`, source file or database byte. `tests/worker.rs` runs the real launcher over a small test program for the long-lived worker cases of the `limited-process@1` contract (answers in order from one process, a reply written in pieces, a deadline and a late reply, a worker that exits or stays silent before it is ready, one that stops reading) and the engine's own duties: the pin check, setup errors, a stray line on stdout, the stderr tail, the run directories, the limits, the process group, the environment and cancelled calls; `tests/pipeline.rs` adds rows that hang, crash or run out of memory, each rejected once with the rows after it delivered, and `tests/api.rs` the bound on concurrent tries. `tests/worker.rs` also runs the real `hie_runtime/` with transforms that write to file descriptor 1 directly and through a child process, every record still getting its own reply. `tests/test_worker.py` checks the worker over its pipes (a write to file descriptor 1 included) and, on Linux, under the launcher's memory limit. +The end-to-end tests run the real Python transforms against a stand-in FHIR server. `tests/pipeline.rs` covers a folder source: the outage and recovery, the duplicate file and the re-sent rows, each kind of bad row, reprocessing with a correction, the silence alert, and a load whose rows were all filtered out raising no alert while a mixed load's alert counts its failing rows, again only when more of them fail. `tests/events.rs` covers the event log: each outcome stored with its event before the next record is sent (the stand-in FHIR server reads the log through its own store handle on every request) or transformed (the probe transform reads the SQLite file), nothing stored when the event cannot be (a SQLite trigger refuses it, for an admission and for a delivery), outcomes for a record put back while it was transformed or sent changing nothing, a transform that cannot finish now (logged once per reason and runner), a submission opened, failing a poll, settled by its receipts or refused with an answer that echoes signed URLs and the engine's own path, a submission not opened when a record changed while it was written (on both bulk paths), a Retry, a refusal and an unsendable file of 450 rows each (more than one chunk), an older answer that cannot roll a record's attempts back, content taken meanwhile not admitted twice, a Retry that finds nothing, a finish reporting failing rows beyond the most an earlier finish saw, the API's paging, filters, cursor and refusals, the retention purge (old events and alerts, the alerts kept, the highest alert id kept so no id is given again, the alert counter unchanged, two purges at once counted once, more than one chunk) a restart that stops the first engine for good, distinct rejected records per day (a record rejected twice once, filtered rows apart, a midnight event in the day it starts, coverage from when the log began and within the retention) and that start kept across a reopen; with `HIE_TEST_DATABASE_URL`, an event committed later with a lower id never skipped by a reader, a finish that waits for a Retry's row lock (and one that counts the failing rows committed while it waited), an alert cleared while the purge waits for it kept, a record put back while its file is rejected left as it was put back, each test waiting until PostgreSQL shows the lock wait. `tests/alerts.rs` covers the rules: the one a source is born with and that a replace does not bring back, the CRUD, and the `rejected_share` and `silence` rules firing once and clearing, `rejected_share` weighing the failing rows among those a load kept (a load that kept none neither fires nor clears it); and rule ids never given again (after a delete, a reopen, and on a SQLite store whose rules table was made the old way), with `created_at` set by the engine; and reading alerts by period and in pages: `since` at its boundary (as the list returns it, finer, with an offset), every combination with `source` and `open` walked at several page sizes, a walk that keeps its place while alerts are added, cleared and removed, the default page of 100, and malformed queries refused without echoing them, on SQLite and, with `HIE_TEST_DATABASE_URL`, PostgreSQL; and, through the pipeline and the API, the webhook's delivery state: an alert from before events were recorded cleared and delivered, signed, with the API's time strings, events waiting for this URL (`pending`) and for another (`parked`), a `fired` parked for another URL still listed in `webhook.events` after its `cleared` was delivered, an alert with two events counted once in a page, a rule without the `webhook` channel (`not_requested`), an engine without a URL (`not_configured`), and no URL, secret or fingerprint in the answer. `tests/alert_webhook.rs` drives the webhook sender against a local receiver under the production log filter at `trace`: the signature over each attempt's `X-HIE-Timestamp` and the raw body (a signature over the body alone does not match, and a retry a second later is stamped and signed again over the same body), fired before cleared, one `event_id` and one body over retries, giving up after five retries, a redirect refused, an unreachable receiver, one that does not answer in time, two instances on one store sending each event once, an attempt whose outcome was lost sent again unchanged by another instance, and an event waiting for its own URL across restarts; no URL, secret or receiver answer reaches a log line or the store. Unit tests pin the HMAC to RFC 4231 and the signed string to a value computed independently (Python's `hmac`), the webhook secret read without the whitespace around it, and, in the store, with time passed in and two handles on one file, the claim, the fence against late outcomes and replacement rows, the last attempt with no outcome, the order of fired and cleared per URL, and the alert and its event written or rolled back together. `tests/check.rs` checks that `hie check` refuses bad `alerts:` settings without printing the URL or the secret. `tests/bulk_submit.rs` drives both bulk paths against a stand-in consumer: an NDJSON export handed over as source objects, and a lab CSV transformed, given derived ids, written by the engine and settled by receipts. Against a stand-in public bucket it checks that an anonymous source reading a whole bucket hands over each object's public URL with its key encoded once, every read unsigned and the engine's file route unused; that a store object is never served from that route, even when a local file shares its key, while a staged zip entry is; that keys and entries stay apart under a relative bulk directory; that entries staged by an earlier version are recognised at start-up, served, settled and retried, whether the engine starts from a relative or an absolute configuration path; that an archived folder file from an earlier version is served again on retry; and that a file taken from a bucket and retried after its source became a folder is rejected rather than served. `tests/bulk_logs.rs` runs under the production log filter asked for everything at `trace`: a failing poll, a refusal that echoes signed URLs (one on a bracketed IPv6 host, one with parentheses in its path) and the engine's own path with the token, a relative status target that carries a signature, a cleanup that cannot remove a submission's files, a token endpoint failure and a status URL stored during a working delivery (a statement parameter on PostgreSQL) keep signatures and tokens out of every log line, the alerts, the stored errors and answers, and the event log. A folder file recorded through a symbolic link and `..` is served as the filesystem resolves that path. With an in-memory store it checks that a URL that cannot be signed yet keeps its records pending while open submissions are polled, and that an object no configuration can hand over is rejected without stalling the pass. `tests/object_source.rs` covers the object-store path the S3 source uses, with an in-memory store; `tests/sqs_source.rs` adds a notification queue to it, against a stand-in SQS that checks the SigV4 headers: the bucket listed once at start, then only announced objects taken, with their messages deleted after the pass and test events, foreign keys, gone objects and keys that are not object paths consumed without effect; `tests/overlap.rs` checks that HFS receives the first Bundle well before a slow transform finishes the file; the same source was run by hand against a MinIO (the `ghcr.io/coollabsio/minio` mirror HFS's CI pins) holding the Synthea export, on both delivery paths against an HFS that requires tokens: 632 resources by REST and the same 632 by `$bulk-submit` through pre-signed URLs, each resource stored once, objects archived under the processed prefix, and a re-uploaded file recognised as a duplicate. `tests/fhir_server_source.rs` covers pulling another FHIR server: pages followed, a cursor per type that moves once the records are stored, nothing pulled twice, the token on every call, and the connection test. `tests/database_source.rs` covers the database source on SQLite: runs of the query past a cursor, the cursor moving once the rows are stored, nothing read twice, `cursor_start`, and the connection test; `tests/mssql_source.rs` runs the same source against a SQL Server when `HIE_TEST_MSSQL_URL` is set, and is skipped otherwise. `tests/leases.rs` puts two instances on one store: one runs the source, the other stands by, and takes over when the lease lapses. `tests/test_terminology.py` covers the terminology helpers against a stand-in HTS and the lab transform using them. `tests/zip_drop.rs` covers zips: a drop in a read-only bucket unpacked once and left in place, and one in a folder unpacked and archived, with a broken zip reported. `tests/hl7v2.rs` covers HL7 v2: a file of messages through a folder source, and messages over MLLP spooled, acknowledged, delivered, and resent as duplicates; `tests/test_hl7.py` covers the Python helpers. `tests/api.rs` drives a source through the API: test, create, check now, pause, resume, replace, delete, and its contact read from a file and from the API, kept by a replace that sends back what it read, cleared by one without it, and refused when too long or more than one line. `tests/loads.rs` covers the loads list across sources: the fields of the per-source list, newest first, each `status` filter and `failed` (unreadable, rejected rows while in progress or done, rows filtered out on purpose that do not count, and what takes a load out), a walk by cursor while loads arrive and leave the filter, the limits and the refused queries, a store written by an earlier version (its loads with no mark of failing rows), and a deleted source whose id is created again; a unit test checks that SQLite chooses each page through an index. `tests/check_outcome.rs` drives the scans of a source another instance holds by hand: concurrent checks answered by the one scan after them with its one load, a check asked for once a scan started answered by the next with what the earlier one took, nothing new, a folder that cannot be listed (a fixed reason, no path), an unknown check, a replaced source's runner answering earlier checks, and a paused or deleted source failing them, but not one another instance still holds; the loads paged with the answer's cursor, malformed parameters refused with `invalid_query` and `field`, and the retention purge removing old checks, answered or not (`tests/events.rs` adds, on PostgreSQL, a check purge that waits for another instance's and moves on to the next old rows); unit tests in `src/db.rs` cover the snapshot, the first answer staying, pages of loads and the purge. `tests/check.rs` runs `hie check`: it refuses to start while `hie.yaml` has a `runtime` key or `HIE_RUNTIME_URL` is set, and passes when the variable is unset or blank; it prints a source's contact and refuses an invalid one naming the file, in both builds; `hie check` and `hie run` refuse an S3 file that names neither a credential nor `anonymous`, and `hie run` refuses a sealed store started with another key, or a key set in two places, before serving. Stored credentials: unit tests pin the sealed format against values computed independently (Python's `hmac`/`hashlib` and libsodium), the derivation against RFC 5869, and walk the key state machine (sealed and unsealed stores against every kind of key input, key files that are links, FIFOs or readable by others, a key file that cannot be created, concurrent first starts); the registration of sources for credentials is tested with pause points that force each interleaving, on SQLite and, with `HIE_TEST_DATABASE_URL`, PostgreSQL. `tests/secret_store.rs` covers persistence, refusals with both key ids, and values moved or altered in the database. `tests/secrets.rs` covers `/api/secrets` (shapes, bodies refused without echoing them, the `409` while used, `503 store_busy`, the `503 secrets_unavailable` of a store without a usable key, on the credential routes, on creating, replacing and testing a source, and in its `credential` alert, with no path), and the 503s of a build without a store; `tests/no_backend_startup.rs` runs that build's binary with a credential source file, which is skipped. The default rule's birth is tested on both stores too: given once, not again after a replace, a failed start, a restart or a file put back, given again by a create and kept when its write or start fails, never twice when two handles race (one held inside its transaction while the other waits), nothing recorded or published when it fails, and sources an earlier version left marked born without a rule. `tests/s3_credentials.rs` signs against a stand-in bucket that records key ids: the Test, the source, a rotation, the queue, an alert raised once and cleared, and a source waiting for its credential while its submissions are polled (a check asked for meanwhile fails, saying the credential is not loaded). `tests/secret_refs.rs` puts two engines on one store; `tests/secrets_canary.rs` checks that a canary secret appears in no answer, log line at `trace`, source file or database byte. `tests/worker.rs` runs the real launcher over a small test program for the long-lived worker cases of the `limited-process@1` contract (answers in order from one process, a reply written in pieces, a deadline and a late reply, a worker that exits or stays silent before it is ready, one that stops reading) and the engine's own duties: the pin check, setup errors, a stray line on stdout, the stderr tail, the run directories, the limits, the process group, the environment and cancelled calls; `tests/pipeline.rs` adds rows that hang, crash or run out of memory, each rejected once with the rows after it delivered, and `tests/api.rs` the bound on concurrent tries. `tests/worker.rs` also runs the real `hie_runtime/` with transforms that write to file descriptor 1 directly and through a child process, every record still getting its own reply. `tests/test_worker.py` checks the worker over its pipes (a write to file descriptor 1 included) and, on Linux, under the launcher's memory limit. They are skipped if no Python 3.9+ is found; set `HIE_TEST_PYTHON` to point at one. diff --git a/docs/sources.md b/docs/sources.md index ec6bf3d..38fc0b7 100644 --- a/docs/sources.md +++ b/docs/sources.md @@ -114,7 +114,7 @@ Each change of an alert is one **event**, `fired` or `cleared`, written in the s - `alert` is the alert as `GET /api/alerts` lists it, with the same time strings; a `fired` event has `cleared_at` and `cleared_reason` null. `notify` is `[]` for an alert without a rule. `source.name` is null when the engine does not know it; `source` is null for an alert about no source. `text` is the field Slack and Teams incoming webhooks display. - Headers: `Content-Type: application/json`, `X-HIE-Event-Id` and `X-HIE-Event` (the body's `event_id` and `event`), `X-HIE-Timestamp` (when this attempt was sent, in Unix seconds), and, when `alerts.webhook_secret` is set, `X-HIE-Signature: sha256=`: the HMAC-SHA256, under the secret, of the timestamp exactly as sent, a `.`, and the **raw body** (`{X-HIE-Timestamp}.{body}`), lowercase hex. The secret is trimmed of leading and trailing whitespace when read, so a secret file that ends in a newline signs with the secret it holds. Without a secret the events are unsigned. Use HTTPS: the signature proves who sent an event, not that nobody read it. -- **Verifying:** a receiver computes the HMAC over `X-HIE-Timestamp`, `.` and the bytes it received, before parsing, and compares it with `X-HIE-Signature` in constant time; then it refuses a timestamp further than its **tolerance** from its own clock, in either direction. Use **5 minutes** (300 seconds) unless the two clocks are known to drift further; a wider window only lets an old request be replayed for longer. Within the tolerance, de-duplication by `X-HIE-Event-Id` (below) catches a replay, so a receiver keeps the ids it has seen for at least the tolerance. Each attempt, a retry included, is stamped and signed when it leaves, with the same body: the tolerance never has to cover the retry backoff. Trust the body, not the other headers. No release signed the body alone, so there is no older scheme to accept. +- **Verifying:** `X-HIE-Timestamp` is decimal digits only. A receiver computes the HMAC over that header's exact bytes, `.` and the body bytes it received, before parsing, and compares it with `X-HIE-Signature` in constant time; then it refuses a timestamp further than its **tolerance** from its own clock, in either direction. Use **5 minutes** (300 seconds) unless the two clocks are known to drift further; a wider window only lets a captured request be replayed for longer. Within the window a replay is caught by de-duplication on the verified body's `event_id` (below): a request stamped up to one tolerance ahead of the receiver's clock stays valid for two tolerances after it arrives, so keep each `event_id` acted on for at least **twice the tolerance** after the last request accepted for it, and for as long as acting on it twice would matter. Each attempt, a retry included, is a new request stamped and signed when it leaves, with the same body and `event_id`: the tolerance never has to cover the retry backoff, but de-duplication does. Trust the body, not the other headers. No release signed the body alone, so there is no older scheme to accept. - **Retries:** any answer but a 2xx, a timeout (10 s; 3 s to connect) or a connection failure is a failed attempt. The engine tries again up to five times, waiting `alerts.webhook_backoff_ms` (from 1 to 3 600 000; 10 000 by default) and doubling each time: 10 s, 20 s, 40 s, 80 s, 160 s. Redirects are not followed: a 3xx is a failed attempt. Every attempt sends the same bytes with the same `event_id`. - **De-duplication:** a receiver may get an event more than once (its 2xx was lost to a timeout, or an instance stopped before storing the outcome). It keeps the `event_id`s it has seen, answers a repeated one with a 2xx and does nothing else. `event_id` identifies one event and its retries, not a condition: a source whose lease lapsed in the middle of a pass can raise a second alert, with its own events, for the same condition. - **Order:** a `cleared` event waits until its alert's `fired` event for the same URL has been delivered or given up on; a `fired` event still waiting for an earlier URL does not hold back a `cleared` for the current one. Still, a receiver may get a `cleared` for an alert it has not seen (fired before this engine version, while no URL was set, or whose `fired` failed), and a late `fired` after its `cleared` (a retry of an attempt that timed out): a late `fired` does not reopen a cleared alert. Match the two events of one alert by `alert.id`: an alert id is never given again. diff --git a/tests/alert_webhook.rs b/tests/alert_webhook.rs index 51c10f7..ad0961a 100644 --- a/tests/alert_webhook.rs +++ b/tests/alert_webhook.rs @@ -308,6 +308,54 @@ async fn fired_and_cleared_events_are_signed_over_the_raw_body() { assert_no_canary_logged(); } +#[tokio::test] +async fn a_signed_retry_is_stamped_and_signed_again_when_it_leaves() { + let (receiver, url) = receiver().await; + receiver.script.lock().unwrap().push(503); + let dir = tempfile::tempdir().unwrap(); + // A backoff over a second: the retry leaves in a later second than the + // first attempt, so a timestamp kept from it would show. + let e = engine( + &dir.path().join("hie.db"), + &settings(Some(&url), Some(SECRET_CANARY), 1100), + true, + ); + e.alerts + .raise(Some("lab-results"), "unreadable_file", "cannot read r.csv") + .unwrap(); + let alert = last_alert(&e.db); + wait_for("delivered on the retry", || { + events(&e.db, alert)[0]["state"] == "delivered" + }) + .await; + let got = receiver.got(); + assert_eq!(got.len(), 2); + assert_eq!(got[0].body, got[1].body, "one body, byte for byte"); + assert_eq!( + got[0].header("x-hie-event-id"), + got[1].header("x-hie-event-id") + ); + let stamps: Vec = got + .iter() + .map(|r| r.header("x-hie-timestamp").unwrap()) + .collect(); + assert!( + stamps[0].parse::().unwrap() < stamps[1].parse::().unwrap(), + "{stamps:?}" + ); + for (r, stamp) in got.iter().zip(&stamps) { + assert_eq!( + r.header("x-hie-signature").unwrap(), + hie::alerts::signature(SECRET_CANARY.as_bytes(), stamp, &r.body) + ); + } + assert_ne!( + got[0].header("x-hie-signature"), + got[1].header("x-hie-signature") + ); + assert_no_canary_logged(); +} + #[tokio::test] async fn a_failing_receiver_gets_the_same_event_until_it_answers() { let (receiver, url) = receiver().await; From dca3c48326a086a40354cf0d649390c8d87a1ded Mon Sep 17 00:00:00 2001 From: Alvaro Salinas Dockar Date: Tue, 24 Nov 2026 10:20:03 -0400 Subject: [PATCH 4/8] docs(alerts): say where the timestamp amendment changes decision 40's reasons Refs #38 --- docs/decisions.md | 4 ++-- docs/sources.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 6003d17..5700af2 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -485,7 +485,7 @@ Several engine instances may share one PostgreSQL. A source is run by the instan **Why:** - External monitoring and paging tools are meant to receive the engine's alerts through its webhook, so it needs a stable shape, a way to prove the sender, and delivery that survives a receiver's outage and the engine's restarts. A host application shows whether an alert reached them, and needs to tell "no webhook configured" from "not delivered yet". - Writing the event with the alert, in one transaction, means no alert change is lost between the two; storing the exact body means every retry is the same bytes, so a receiver de-duplicates by `event_id` and a signature never depends on when it was computed (until the amendment below). -- A body-only HMAC (the shape GitHub's webhooks use) is the simplest scheme receivers verify. A replayed request carries an `event_id` the receiver has seen; an old event names an old alert. +- A body-only HMAC (the shape GitHub's webhooks use) is the simplest scheme receivers verify. A replayed request carries an `event_id` the receiver has seen; an old event names an old alert. (The amendment below signs a timestamp with the body, so that a receiver need not remember every `event_id` for ever.) - Claiming by `event_id` with a conditional update, and fencing the outcome by the attempt number, lets several instances on one store send without sending one attempt twice, on SQLite and PostgreSQL alike, and keeps a stalled instance from overwriting a newer outcome. - Binding an event to its URL keeps alert text and recipients from going to a receiver configured later for something else; waiting for that URL keeps a brief misconfiguration from losing them. - Redirects are refused because a redirected POST becomes a GET without the body, and would carry the signature to another host. @@ -498,7 +498,7 @@ Several engine instances may share one PostgreSQL. A source is run by the instan - The API showed the latest event only (until the amendment below added every event): a `fired` that failed was shown until its `cleared` was written. A monitor tracking delivery re-reads the alerts it still follows; delivery changes do not move a cursor. Events are kept with their alert and removed with it when `retention.history` purges it (decision 38), waiting ones included: by then only an event parked for an earlier URL, or never sent, can still be waiting. - No mail sink, per-rule URLs, redelivery endpoint or delivery metrics. -*Amended 2026-11-24:* every attempt carries `X-HIE-Timestamp`, the Unix seconds when it was sent, and `X-HIE-Signature` is the HMAC-SHA256 of `{timestamp}.{raw body}` (the scheme of Stripe and Standard Webhooks) instead of the body alone: the pattern Stripe and Standard Webhooks use, in HIE's own headers. Receivers refuse a timestamp outside a tolerance they enforce, 5 minutes by default, and keep the `event_id`s they have acted on for at least twice that long. Why: with the body alone, anyone who captured one delivery could replay it later to a receiver that had pruned its `event_id`s, or never kept them (a `fired` that pages someone again); adding a timestamp after receivers verify the body-only signature would break every one of them. The stored body is still the same bytes on every attempt; the timestamp and the signature are computed per attempt when it leaves, so a retry is never stale, and the receiver's window need not cover the backoff. No release signed the body alone (0.2.0 sent unsigned events), so there is no compatibility mode. Cost: a receiver whose clock is off by more than its tolerance refuses every event, and gets them again on each retry until the five retries are spent; instances need synchronised clocks already. Each attempt's signature depends on when it is sent. Also: the secret is trimmed of leading and trailing whitespace when read, from `hie.yaml` or the environment, so a secret file ending in a newline signs with the secret it holds; a secret meant to begin or end with whitespace now signs without it. And `GET /api/alerts` adds `webhook.events`, every event of each alert, read with the page in one statement: showing the latest event only could hide a `fired` parked for an earlier URL behind a `cleared` delivered to the current one. +*Amended 2026-11-24:* every attempt carries `X-HIE-Timestamp`, the Unix seconds when it was sent, and `X-HIE-Signature` is the HMAC-SHA256 of `{timestamp}.{raw body}` (the scheme of Stripe and Standard Webhooks) instead of the body alone, as Stripe-style webhooks do, in HIE's own headers. Receivers refuse a timestamp outside a tolerance they enforce, 5 minutes by default, and keep the `event_id`s they have acted on for at least twice that long. Why: with the body alone, anyone who captured one delivery could replay it later to a receiver that had pruned its `event_id`s, or never kept them (a `fired` that pages someone again); adding a timestamp after receivers verify the body-only signature would break every one of them. The stored body is still the same bytes on every attempt; the timestamp and the signature are computed per attempt when it leaves, so a retry is never stale, and the receiver's window need not cover the backoff. No release signed the body alone (0.2.0 sent unsigned events), so there is no compatibility mode. Cost: a receiver whose clock is off by more than its tolerance refuses every event, and gets them again on each retry until the five retries are spent; instances need synchronised clocks already. Each attempt's signature depends on when it is sent. Also: the secret is trimmed of leading and trailing whitespace when read, from `hie.yaml` or the environment, so a secret file ending in a newline signs with the secret it holds; a secret meant to begin or end with whitespace now signs without it. And `GET /api/alerts` adds `webhook.events`, every event of each alert, read with the page in one statement: showing the latest event only could hide a `fired` parked for an earlier URL behind a `cleared` delivered to the current one. ## 41. Check now has an id and an outcome diff --git a/docs/sources.md b/docs/sources.md index 38fc0b7..81a8395 100644 --- a/docs/sources.md +++ b/docs/sources.md @@ -115,7 +115,7 @@ Each change of an alert is one **event**, `fired` or `cleared`, written in the s - `alert` is the alert as `GET /api/alerts` lists it, with the same time strings; a `fired` event has `cleared_at` and `cleared_reason` null. `notify` is `[]` for an alert without a rule. `source.name` is null when the engine does not know it; `source` is null for an alert about no source. `text` is the field Slack and Teams incoming webhooks display. - Headers: `Content-Type: application/json`, `X-HIE-Event-Id` and `X-HIE-Event` (the body's `event_id` and `event`), `X-HIE-Timestamp` (when this attempt was sent, in Unix seconds), and, when `alerts.webhook_secret` is set, `X-HIE-Signature: sha256=`: the HMAC-SHA256, under the secret, of the timestamp exactly as sent, a `.`, and the **raw body** (`{X-HIE-Timestamp}.{body}`), lowercase hex. The secret is trimmed of leading and trailing whitespace when read, so a secret file that ends in a newline signs with the secret it holds. Without a secret the events are unsigned. Use HTTPS: the signature proves who sent an event, not that nobody read it. - **Verifying:** `X-HIE-Timestamp` is decimal digits only. A receiver computes the HMAC over that header's exact bytes, `.` and the body bytes it received, before parsing, and compares it with `X-HIE-Signature` in constant time; then it refuses a timestamp further than its **tolerance** from its own clock, in either direction. Use **5 minutes** (300 seconds) unless the two clocks are known to drift further; a wider window only lets a captured request be replayed for longer. Within the window a replay is caught by de-duplication on the verified body's `event_id` (below): a request stamped up to one tolerance ahead of the receiver's clock stays valid for two tolerances after it arrives, so keep each `event_id` acted on for at least **twice the tolerance** after the last request accepted for it, and for as long as acting on it twice would matter. Each attempt, a retry included, is a new request stamped and signed when it leaves, with the same body and `event_id`: the tolerance never has to cover the retry backoff, but de-duplication does. Trust the body, not the other headers. No release signed the body alone, so there is no older scheme to accept. -- **Retries:** any answer but a 2xx, a timeout (10 s; 3 s to connect) or a connection failure is a failed attempt. The engine tries again up to five times, waiting `alerts.webhook_backoff_ms` (from 1 to 3 600 000; 10 000 by default) and doubling each time: 10 s, 20 s, 40 s, 80 s, 160 s. Redirects are not followed: a 3xx is a failed attempt. Every attempt sends the same bytes with the same `event_id`. +- **Retries:** any answer but a 2xx, a timeout (10 s; 3 s to connect) or a connection failure is a failed attempt. The engine tries again up to five times, waiting `alerts.webhook_backoff_ms` (from 1 to 3 600 000; 10 000 by default) and doubling each time: 10 s, 20 s, 40 s, 80 s, 160 s. Redirects are not followed: a 3xx is a failed attempt. Every attempt sends the same body, byte for byte, with the same `event_id`; its `X-HIE-Timestamp` and signature are those of the attempt. - **De-duplication:** a receiver may get an event more than once (its 2xx was lost to a timeout, or an instance stopped before storing the outcome). It keeps the `event_id`s it has seen, answers a repeated one with a 2xx and does nothing else. `event_id` identifies one event and its retries, not a condition: a source whose lease lapsed in the middle of a pass can raise a second alert, with its own events, for the same condition. - **Order:** a `cleared` event waits until its alert's `fired` event for the same URL has been delivered or given up on; a `fired` event still waiting for an earlier URL does not hold back a `cleared` for the current one. Still, a receiver may get a `cleared` for an alert it has not seen (fired before this engine version, while no URL was set, or whose `fired` failed), and a late `fired` after its `cleared` (a retry of an attempt that timed out): a late `fired` does not reopen a cleared alert. Match the two events of one alert by `alert.id`: an alert id is never given again. - **One URL per event:** an event is sent only to the URL configured when it was written. After the URL changes, events still waiting for the earlier one stay `pending` (the API shows them `parked`) and go out if that URL comes back; a start without a URL leaves them waiting too. Rotating the secret signs waiting events with the new one; a blank secret is refused. Every instance on one store must have the same `alerts:` settings: any of them may send any waiting event, from oldest to newest, one at a time. From 14b2cf3d19792559b59e406c8442a209dc50c6a9 Mon Sep 17 00:00:00 2001 From: Alvaro Salinas Dockar Date: Tue, 24 Nov 2026 10:23:51 -0400 Subject: [PATCH 5/8] docs(alerts): call the signing scheme Stripe-style only Refs #38 --- docs/decisions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/decisions.md b/docs/decisions.md index 5700af2..661acef 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -498,7 +498,7 @@ Several engine instances may share one PostgreSQL. A source is run by the instan - The API showed the latest event only (until the amendment below added every event): a `fired` that failed was shown until its `cleared` was written. A monitor tracking delivery re-reads the alerts it still follows; delivery changes do not move a cursor. Events are kept with their alert and removed with it when `retention.history` purges it (decision 38), waiting ones included: by then only an event parked for an earlier URL, or never sent, can still be waiting. - No mail sink, per-rule URLs, redelivery endpoint or delivery metrics. -*Amended 2026-11-24:* every attempt carries `X-HIE-Timestamp`, the Unix seconds when it was sent, and `X-HIE-Signature` is the HMAC-SHA256 of `{timestamp}.{raw body}` (the scheme of Stripe and Standard Webhooks) instead of the body alone, as Stripe-style webhooks do, in HIE's own headers. Receivers refuse a timestamp outside a tolerance they enforce, 5 minutes by default, and keep the `event_id`s they have acted on for at least twice that long. Why: with the body alone, anyone who captured one delivery could replay it later to a receiver that had pruned its `event_id`s, or never kept them (a `fired` that pages someone again); adding a timestamp after receivers verify the body-only signature would break every one of them. The stored body is still the same bytes on every attempt; the timestamp and the signature are computed per attempt when it leaves, so a retry is never stale, and the receiver's window need not cover the backoff. No release signed the body alone (0.2.0 sent unsigned events), so there is no compatibility mode. Cost: a receiver whose clock is off by more than its tolerance refuses every event, and gets them again on each retry until the five retries are spent; instances need synchronised clocks already. Each attempt's signature depends on when it is sent. Also: the secret is trimmed of leading and trailing whitespace when read, from `hie.yaml` or the environment, so a secret file ending in a newline signs with the secret it holds; a secret meant to begin or end with whitespace now signs without it. And `GET /api/alerts` adds `webhook.events`, every event of each alert, read with the page in one statement: showing the latest event only could hide a `fired` parked for an earlier URL behind a `cleared` delivered to the current one. +*Amended 2026-11-24:* every attempt carries `X-HIE-Timestamp`, the Unix seconds when it was sent, and `X-HIE-Signature` is the HMAC-SHA256 of `{timestamp}.{raw body}` instead of the body alone, as Stripe-style webhooks do, in HIE's own headers. Receivers refuse a timestamp outside a tolerance they enforce, 5 minutes by default, and keep the `event_id`s they have acted on for at least twice that long. Why: with the body alone, anyone who captured one delivery could replay it later to a receiver that had pruned its `event_id`s, or never kept them (a `fired` that pages someone again); adding a timestamp after receivers verify the body-only signature would break every one of them. The stored body is still the same bytes on every attempt; the timestamp and the signature are computed per attempt when it leaves, so a retry is never stale, and the receiver's window need not cover the backoff. No release signed the body alone (0.2.0 sent unsigned events), so there is no compatibility mode. Cost: a receiver whose clock is off by more than its tolerance refuses every event, and gets them again on each retry until the five retries are spent; instances need synchronised clocks already. Each attempt's signature depends on when it is sent. Also: the secret is trimmed of leading and trailing whitespace when read, from `hie.yaml` or the environment, so a secret file ending in a newline signs with the secret it holds; a secret meant to begin or end with whitespace now signs without it. And `GET /api/alerts` adds `webhook.events`, every event of each alert, read with the page in one statement: showing the latest event only could hide a `fired` parked for an earlier URL behind a `cleared` delivered to the current one. ## 41. Check now has an id and an outcome From d457b3f0095957ee9bcaa32997febd2b60a4e817 Mon Sep 17 00:00:00 2001 From: Alvaro Salinas Dockar Date: Tue, 24 Nov 2026 11:02:44 -0400 Subject: [PATCH 6/8] fix(alerts): trim the webhook secret in place; spell out the payload's alert fields Refs #38 --- docs/decisions.md | 2 +- docs/sources.md | 2 +- src/config.rs | 14 ++++++++++++-- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 661acef..5a6dd45 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -480,7 +480,7 @@ Several engine instances may share one PostgreSQL. A source is run by the instan - `/api/alerts` keeps its typed parameters, so a value of the wrong type or given twice is refused without `field`, and an unknown parameter is ignored, unlike `/api/events`, which names the field of every refusal. `/api/records` and the per-source loads list keep the extractor's plain-text `400`; `/api/loads` (42) answers `invalid_query` as `/api/alerts` does. ## 40. The alert webhook is a signed, retried and recorded contract -**Chosen:** Every change of an alert, `fired` and `cleared`, is an event with a random `event_id`, written with its exact body in the same transaction as the alert, in the store's `alert_webhooks`. The body is `{event_id, event, alert: {id, rule_id, kind, message, notify, created_at, cleared_at, cleared_reason}, source: {id, name}, text}`. With `alerts.webhook_secret` (or `HIE_ALERT_WEBHOOK_SECRET`) set, `X-HIE-Signature: sha256=` carries the HMAC-SHA256 of the raw body. A sender task per instance posts waiting events oldest first: a 2xx delivers; anything else, a 3xx included (redirects are not followed), is retried up to five times after `alerts.webhook_backoff_ms` (10 s), doubling, then the event is `failed`. Each attempt is claimed with one conditional update, for a lease of 60 s, and its outcome is stored only while the claim is still that attempt's; a last attempt whose outcome was never stored ends `failed`. A `cleared` event waits for its `fired` event for the same URL to be delivered or given up on. Each event belongs to the URL configured when it was written and waits for that URL. `GET /api/alerts` shows, per alert, the delivery of its latest event (`event`, `state`, `attempts`, `last_error`, `last_status`, `delivered_at`), and `webhook: {configured, signed}` for the instance. Events not requested by the rule's channels, or written with no URL configured, are recorded as `not_requested` and `not_configured` and never sent. +**Chosen:** Every change of an alert, `fired` and `cleared`, is an event with a random `event_id`, written with its exact body in the same transaction as the alert, in the store's `alert_webhooks`. The body is `{event_id, event, alert: {id, rule_id, kind, message, notify, created_at, cleared_at, cleared_reason}, source: {id, name}, text}`. With `alerts.webhook_secret` (or `HIE_ALERT_WEBHOOK_SECRET`) set, `X-HIE-Signature: sha256=` carries the HMAC-SHA256 of the raw body (amended below: of a timestamp and the body). A sender task per instance posts waiting events oldest first: a 2xx delivers; anything else, a 3xx included (redirects are not followed), is retried up to five times after `alerts.webhook_backoff_ms` (10 s), doubling, then the event is `failed`. Each attempt is claimed with one conditional update, for a lease of 60 s, and its outcome is stored only while the claim is still that attempt's; a last attempt whose outcome was never stored ends `failed`. A `cleared` event waits for its `fired` event for the same URL to be delivered or given up on. Each event belongs to the URL configured when it was written and waits for that URL. `GET /api/alerts` shows, per alert, the delivery of its latest event (`event`, `state`, `attempts`, `last_error`, `last_status`, `delivered_at`; amended below: and of every event), and `webhook: {configured, signed}` for the instance. Events not requested by the rule's channels, or written with no URL configured, are recorded as `not_requested` and `not_configured` and never sent. **Why:** - External monitoring and paging tools are meant to receive the engine's alerts through its webhook, so it needs a stable shape, a way to prove the sender, and delivery that survives a receiver's outage and the engine's restarts. A host application shows whether an alert reached them, and needs to tell "no webhook configured" from "not delivered yet". diff --git a/docs/sources.md b/docs/sources.md index 81a8395..9160e7f 100644 --- a/docs/sources.md +++ b/docs/sources.md @@ -112,7 +112,7 @@ Each change of an alert is one **event**, `fired` or `cleared`, written in the s } ``` -- `alert` is the alert as `GET /api/alerts` lists it, with the same time strings; a `fired` event has `cleared_at` and `cleared_reason` null. `notify` is `[]` for an alert without a rule. `source.name` is null when the engine does not know it; `source` is null for an alert about no source. `text` is the field Slack and Teams incoming webhooks display. +- `alert` holds these fields of the alert as `GET /api/alerts` lists it (`id`, `rule_id`, `kind`, `message`, `notify`, `created_at`, `cleared_at`, `cleared_reason`), with the same time strings, and nothing else: no delivery state; a `fired` event has `cleared_at` and `cleared_reason` null. `notify` is `[]` for an alert without a rule. `source.name` is null when the engine does not know it; `source` is null for an alert about no source. `text` is the field Slack and Teams incoming webhooks display. - Headers: `Content-Type: application/json`, `X-HIE-Event-Id` and `X-HIE-Event` (the body's `event_id` and `event`), `X-HIE-Timestamp` (when this attempt was sent, in Unix seconds), and, when `alerts.webhook_secret` is set, `X-HIE-Signature: sha256=`: the HMAC-SHA256, under the secret, of the timestamp exactly as sent, a `.`, and the **raw body** (`{X-HIE-Timestamp}.{body}`), lowercase hex. The secret is trimmed of leading and trailing whitespace when read, so a secret file that ends in a newline signs with the secret it holds. Without a secret the events are unsigned. Use HTTPS: the signature proves who sent an event, not that nobody read it. - **Verifying:** `X-HIE-Timestamp` is decimal digits only. A receiver computes the HMAC over that header's exact bytes, `.` and the body bytes it received, before parsing, and compares it with `X-HIE-Signature` in constant time; then it refuses a timestamp further than its **tolerance** from its own clock, in either direction. Use **5 minutes** (300 seconds) unless the two clocks are known to drift further; a wider window only lets a captured request be replayed for longer. Within the window a replay is caught by de-duplication on the verified body's `event_id` (below): a request stamped up to one tolerance ahead of the receiver's clock stays valid for two tolerances after it arrives, so keep each `event_id` acted on for at least **twice the tolerance** after the last request accepted for it, and for as long as acting on it twice would matter. Each attempt, a retry included, is a new request stamped and signed when it leaves, with the same body and `event_id`: the tolerance never has to cover the retry backoff, but de-duplication does. Trust the body, not the other headers. No release signed the body alone, so there is no older scheme to accept. - **Retries:** any answer but a 2xx, a timeout (10 s; 3 s to connect) or a connection failure is a failed attempt. The engine tries again up to five times, waiting `alerts.webhook_backoff_ms` (from 1 to 3 600 000; 10 000 by default) and doubling each time: 10 s, 20 s, 40 s, 80 s, 160 s. Redirects are not followed: a 3xx is a failed attempt. Every attempt sends the same body, byte for byte, with the same `event_id`; its `X-HIE-Timestamp` and signature are those of the attempt. diff --git a/src/config.rs b/src/config.rs index ffddcdb..a077bc3 100644 --- a/src/config.rs +++ b/src/config.rs @@ -186,6 +186,16 @@ fn is_http_url(text: &str) -> bool { .is_some_and(|u| matches!(u.scheme(), "http" | "https") && u.host().is_some()) } +/// `text` without the whitespace around it, in place: the secret it holds is +/// moved on, not copied, so the one copy is wiped with the `SecretString`. +fn trimmed(mut text: String) -> String { + let end = text.trim_end().len(); + text.truncate(end); + let start = text.len() - text.trim_start().len(); + text.drain(..start); + text +} + /// What a malformed `alerts:` block is refused with: the keys it may have and /// nothing of the values it has. const ALERTS_SHAPE: &str = "alerts: expected a mapping with webhook_url (an http or https URL), webhook_secret (text) and webhook_backoff_ms (milliseconds)"; @@ -222,7 +232,7 @@ impl<'de> Deserialize<'de> for AlertConfig { } // A secret file with a trailing newline signs with // the secret it holds, not with the newline too. - other => other.map(|s| secrecy::SecretString::from(s.trim().to_string())), + other => other.map(|s| secrecy::SecretString::from(trimmed(s))), }; } Some("webhook_backoff_ms") => { @@ -296,7 +306,7 @@ impl AlertConfig { self.webhook_url = Some(url); } if let Some(secret) = read("HIE_ALERT_WEBHOOK_SECRET")? { - self.webhook_secret = Some(secrecy::SecretString::from(secret.trim().to_string())); + self.webhook_secret = Some(secrecy::SecretString::from(trimmed(secret))); } Ok(()) } From f535075985213aae07cf5613adbbd9b23317eae2 Mon Sep 17 00:00:00 2001 From: Alvaro Salinas Dockar Date: Tue, 24 Nov 2026 11:10:57 -0400 Subject: [PATCH 7/8] fix(alerts): wipe the untrimmed webhook secret Refs #38 --- src/config.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/config.rs b/src/config.rs index a077bc3..1c2eb4e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -186,14 +186,13 @@ fn is_http_url(text: &str) -> bool { .is_some_and(|u| matches!(u.scheme(), "http" | "https") && u.host().is_some()) } -/// `text` without the whitespace around it, in place: the secret it holds is -/// moved on, not copied, so the one copy is wiped with the `SecretString`. +/// `text` without the whitespace around it, in a string of its own exact +/// size; `text` is wiped, so no untrimmed copy of the secret is left behind. fn trimmed(mut text: String) -> String { - let end = text.trim_end().len(); - text.truncate(end); - let start = text.len() - text.trim_start().len(); - text.drain(..start); - text + use zeroize::Zeroize; + let out = text.trim().to_owned(); + text.zeroize(); + out } /// What a malformed `alerts:` block is refused with: the keys it may have and From 43dc3f97fd4fe9ae0bfc33bfbecbf2f1d7b5607e Mon Sep 17 00:00:00 2001 From: Alvaro Salinas Dockar Date: Tue, 24 Nov 2026 11:19:39 -0400 Subject: [PATCH 8/8] docs(alerts): say which copy of the secret is wiped Refs #38 --- src/config.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/config.rs b/src/config.rs index 1c2eb4e..347082b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -187,7 +187,8 @@ fn is_http_url(text: &str) -> bool { } /// `text` without the whitespace around it, in a string of its own exact -/// size; `text` is wiped, so no untrimmed copy of the secret is left behind. +/// size; the buffer `text` held is wiped. (The parsed YAML that `text` was +/// copied from is not this function's to wipe.) fn trimmed(mut text: String) -> String { use zeroize::Zeroize; let out = text.trim().to_owned();