From 7640432b8956dea2ab225da1e8ffa908d8e765aa Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 13:15:10 -0600 Subject: [PATCH 01/26] Say what settings_error_detail returns at the ai-policy, cluster-vip and check sites BACKLOG #5113. Three docstrings said the renderer's output carries no configured value: _ai_policy ("NO MESSAGE DATA AND NO CONFIGURED VALUE"), _cluster_vip ("the field path and the message and no configured value") and checks._settings_error ("with no configured value in it"). settings_error_detail drops pydantic's input but returns each validator's message as written, and at least the [backup] schedule_at and snapshot_method refusals quote the value they refused (measured: BackupSettings(schedule_at='zz-canary-77') renders "got 'zz-canary-77'"). Each site now says that and points at the function's docstring, which names the messages that quote a value. Also tightens the test_cli_settings_error_render module docstring, which said the arms print the message "without the value": the leg it describes plants the secret in the input, so it now says "without the planted input". All four are docstrings; none is program output. The function's return value is unchanged. Verified-by: tests --- messagefoundry/__main__.py | 15 +++++++++------ messagefoundry/checks.py | 8 +++++--- tests/test_cli_settings_error_render.py | 2 +- 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/messagefoundry/__main__.py b/messagefoundry/__main__.py index 18b2cd5fb5..f2a4ed8e0b 100644 --- a/messagefoundry/__main__.py +++ b/messagefoundry/__main__.py @@ -14957,11 +14957,13 @@ def _ai_policy(args: argparse.Namespace) -> int: WHAT IT GUARANTEES, stated as what it is rather than as what it is not. This docstring said "Prints config only -- never message data (PHI-safe)" and nothing else. That sentence is TRUE -- no HL7 reaches this function -- and it is what let a disclosure through review, because the value - that leaked was CONFIG, which the sentence says nothing about. So: NO MESSAGE DATA AND NO - CONFIGURED VALUE. On the success path that is the [ai] fields named in ``payload`` below; on the + that leaked was CONFIG, which the sentence says nothing about. So: NO MESSAGE DATA, and config + only as follows. On the success path that is the [ai] fields named in ``payload`` below; on the failure path it is a field path and a message from - :func:`~messagefoundry.config.settings.settings_error_detail`, whose docstring carries the - argument for why ``str(exc)`` is not safe here. Measured at ``19c98e023``: this subcommand, on a + :func:`~messagefoundry.config.settings.settings_error_detail`, which drops pydantic's ``input`` + but returns each validator's message as written, so a message that quotes the value it refused + still prints that value. That function's docstring says which do, and carries the argument for + why ``str(exc)`` is not safe here. Measured at ``19c98e023``: this subcommand, on a ``[store]`` missing ``server`` with ``MEFOR_STORE_PASSWORD`` set as it is on any server-DB node, printed that password to the stdout the IDE's ``runJson`` bridge reads. ``tests/test_cli_ai_policy.py`` pins the absence with a planted secret and a control. @@ -15040,8 +15042,9 @@ def _cluster_vip(args: argparse.Namespace) -> int: this line. The installer then puts that line in a ``throw`` (``Get-VipSettings``: "Could not read [cluster.vip]: ..."), which lands in the operator's transcript and in whatever captured the install. :func:`~messagefoundry.config.settings.settings_error_detail` gives the field path and - the message and no configured value; ``tests/test_cli_cluster_vip.py`` pins it with a planted - secret.""" + the message without pydantic's ``input``; ``tests/test_cli_cluster_vip.py`` pins that with a + planted secret. It returns each validator's message as written, so a message that quotes the + value it refused still prints that value; that function's docstring says which do.""" from pydantic import ValidationError from messagefoundry.config.settings import load_settings, settings_error_detail diff --git a/messagefoundry/checks.py b/messagefoundry/checks.py index 8b89a50d87..77d681061f 100644 --- a/messagefoundry/checks.py +++ b/messagefoundry/checks.py @@ -3038,12 +3038,14 @@ def _with_source(result: CheckResult, note: str | None) -> CheckResult: def _settings_error(exc: Exception) -> str: - """A ``load_settings`` failure for a check detail, with no configured value in it. + """A ``load_settings`` failure for a check detail, without pydantic's ``input`` in it. ``str(exc)`` on a pydantic error prints ``input_value=``, so an unquoted numeric password would land in check output and any CI log (BACKLOG #1182). Every check's settings arm goes through the one - designated renderer, :func:`~messagefoundry.config.settings.settings_error_detail`. Imported - lazily, as every engine import in this module is.""" + designated renderer, :func:`~messagefoundry.config.settings.settings_error_detail`. That renderer + returns each validator's message as written, so a message that quotes the value it refused still + carries that value here; its docstring says which do. Imported lazily, as every engine import in + this module is.""" from messagefoundry.config.settings import settings_error_detail return settings_error_detail(exc) diff --git a/tests/test_cli_settings_error_render.py b/tests/test_cli_settings_error_render.py index 2b4177a6a7..7c96587041 100644 --- a/tests/test_cli_settings_error_render.py +++ b/tests/test_cli_settings_error_render.py @@ -15,7 +15,7 @@ ``load_settings`` to raise a ``ValidationError`` from a plain model that DOES carry the secret -- the shape a section added later outside ``_InputHidingModel`` would raise -- and asserts its control first: the planted secret is in ``str(exc)``. Each arm must then render it through -``settings_error_detail`` and print the field and message without the value, except the +``settings_error_detail`` and print the field and message without the planted input, except the ``_NO_DETAIL_ARMS``, which print no text of the failure at all. ``_ARMS`` holds at least the operator commands vault BACKLOG #2760 moved onto the renderer and From 39d5aa66eaa67bd40bea2b887b752d5a13679967 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 13:15:56 -0600 Subject: [PATCH 02/26] docs/AI.md: say what the ai-policy error line carries BACKLOG #5113. The ai-policy section said the subcommand prints "no message data and no configured value", and that settings_error_detail renders "field path and message, never the value". The function drops pydantic's input but returns each validator's message as written, and some refusals quote the value they refused, so the error line can print it. The section now says so and points at that function's docstring, which names the messages that do. Doc only; no behaviour changes. Proposed PR title: Say what settings_error_detail returns where docstrings and docs/AI.md claimed no configured value (BACKLOG #5113) Proposed vault banner: BUILT on engine branch b20053-5113 (batch 20053). The _ai_policy, _cluster_vip and checks._settings_error docstrings and the docs/AI.md ai-policy section now say settings_error_detail drops pydantic's input but returns each validator's message as written, so a refusal that quotes its value still prints it, and point at the function's docstring. One further copy, the test_cli_settings_error_render module docstring, was tightened. Return value unchanged. Verified-by: tests --- docs/AI.md | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/AI.md b/docs/AI.md index 2dbd1ac7ac..d0007d2558 100644 --- a/docs/AI.md +++ b/docs/AI.md @@ -178,13 +178,17 @@ effective policy, and prints the **same JSON** to stdout — except `assist_perm `null`** (RBAC is not evaluable offline). `--json` prints only the JSON object (the IDE parses stdout); on error it prints `{"error": "..."}`. -It prints **no message data and no configured value**. That is narrower than the "config only, never -message data" this line used to say, and the difference is the point: no HL7 ever reaches this -subcommand, so the only thing its output could disclose was config, which that sentence said nothing -about. It did disclose config — `str(ValidationError)` carries `input_value=` for every failing -field, so a `[store]` missing `server` put `MEFOR_STORE_PASSWORD` on the stdout the IDE reads. The -error line is now rendered by `settings_error_detail` (field path and message, never the value); -that function's docstring carries the argument, and `tests/test_cli_ai_policy.py` pins it. +It prints **no message data**, and of config only the policy JSON above or an error line. That is +narrower than the "config only, never message data" this line used to say, and the difference is +the point: no HL7 ever reaches this subcommand, so the only thing its output could disclose was +config, which that sentence said nothing about. It did disclose config — `str(ValidationError)` +carries `input_value=` for every failing field, so a `[store]` missing `server` put +`MEFOR_STORE_PASSWORD` on the stdout the IDE reads. The error line is now rendered by +`settings_error_detail`, which prints the field path and message and drops pydantic's input, and +`tests/test_cli_ai_policy.py` pins that. It does not hide a value a validator quotes in its own +message: some refusals quote the value they refused, and that line prints it. That function's +docstring in [config/settings.py](../messagefoundry/config/settings.py) says which do, and carries +the argument. --- From a60db0946b895da766b587c0e671f4ee78953acf Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 13:25:11 -0600 Subject: [PATCH 03/26] docs: say which SQL Server preset values are braced and that server is checked and sent plain BACKLOG #5034. The Database Security paragraph in docs/CONNECTIONS.md said the SQL Server preset braces each value. _build_dsn in messagefoundry/transports/database.py braces odbc_driver, database, app_name and, under auth="sql", username and password, and sends server unbraced as SERVER=, after refusing ;, {, }, = and any character that is not printable. The paragraph now says that, says the braced values rest on the driver reading the }} escape, says only odbc_driver of them is checked for a control character, and points to the preset's other server refusals. The DatabasePoll Security line no longer restates "checks every value". Doc-only. Review findings about the code itself (braced preset values not checked for a control character or non-ASCII text, the server error text saying "control character" for an isprintable test, a None database or app_name sent as the text None) are left for the Manager to file. Proposed PR title: docs: the SQL Server preset braces five values and checks server, sent plain (BACKLOG #5034) Proposed vault banner: SHIPPED -- docs/CONNECTIONS.md Security paragraph names the braced preset values and the validated, unbraced server (closing step 1). Verified-by: tests --- docs/CONNECTIONS.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index c6e2f540d7..e7405f8c03 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -2055,8 +2055,18 @@ SQLSTATE, such as an unsupported column type, and `07006`. On the walk to the ne alone reads only the first result set, so an error from a later statement in the batch is not read before the commit. -**Security.** Values are bound as **parameters** (never string-interpolated into SQL); the connection -string checks every value (no connection-string injection; the SQL Server preset braces each one, and the generic dialect braces the driver name, and the password for the drivers it lists, and sends the rest plain, see [*Values*](#values-on-the-generic-dialect)); TLS is **on by default** and a +**Security.** Values are bound as **parameters** (never string-interpolated into SQL). Against +connection-string injection, the SQL Server preset braces `odbc_driver`, `database` and `app_name`, +and, under `auth = "sql"`, `username` and `password`. A braced value rests on the driver reading the +ODBC `}}` escape; the password paragraph under [*Values*](#values-on-the-generic-dialect) says which +drivers were measured to read it. The preset checks `odbc_driver` for a control character, by the +driver rules under [*The port an `allowed_db` entry binds*](#the-port-an-allowed_db-entry-binds), +and does not check `database`, `app_name`, `username` or `password` for one. The preset sends +`server` unbraced, as `SERVER=,`, so that the driver reads the port the preset adds, +and the build refuses a `server` that holds `;`, `{`, `}`, `=` or a character that is not printable; +the same section gives the preset's other `server` refusals. The generic dialect braces the driver +name, and the password for the drivers it lists, and sends the rest plain, see +[*Values*](#values-on-the-generic-dialect). TLS is **on by default** and a weakened posture (`encrypt=false` / `trust_server_certificate=true`, `dialect="sqlserver"` only) is **refused at construction** at every posture, unless the connection declares `tls_hop_attested` with its reason; there is **no env-var route to a weakened DB hop** (owner ruling 2026-11-14, vault BACKLOG @@ -3086,7 +3096,7 @@ kills the poller; it retries next interval. is **refused at construction** through the same cell as the `Database(...)` destination, at every posture unless the connection declares `tls_hop_attested` with its reason; `MEFOR_ALLOW_INSECURE_TLS` does not relax it (owner ruling 2026-11-14, vault BACKLOG #3533 item 2). The connection -string checks every value, as for the destination; secrets go through `env()`. The polled `server` is gated by the same +string is built as for the `Database(...)` connection; secrets go through `env()`. The polled `server` is gated by the same fail-closed `[egress].allowed_db` allowlist as the destination — although the source pulls data *in*, it still dials out to a host, so the allowlist guards against polling an arbitrary server. From 3e90531b0ec624dc5062f2576c218d9a727b2fb5 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 13:28:06 -0600 Subject: [PATCH 04/26] Repair round one: point at the renderer's docstring rather than restate it BACKLOG #5113, code-review round-c2429672 repairs. Each site now says settings_error_detail drops pydantic's input but not a value an error's own message quotes (a validator's, a library's, or a plain loader error's, which it returns as str(exc)), and that the function's docstring names at least some that do, rather than "says which do". _ai_policy scopes its guarantee to stdout and says stderr is not covered: measured, ai-policy on an enabled [cluster.vip] prints the VIP address in a load warning on stderr. _cluster_vip names tests/test_cli_settings_error_render.py as what pins the renderer on its arm (test_cli_cluster_vip.py's planted secret is already hidden by the model layer, so it cannot fail on the renderer), and its heading now says a VALIDATION error is never stringified, since other errors are returned as str(exc). checks._settings_error names the model layer (BACKLOG #296) as the first layer and itself as the second. Docstrings only; no program output and no behaviour changes. Net prose lines: +3. Verified-by: tests --- messagefoundry/__main__.py | 38 ++++++++++++++++++++------------------ messagefoundry/checks.py | 13 +++++++------ 2 files changed, 27 insertions(+), 24 deletions(-) diff --git a/messagefoundry/__main__.py b/messagefoundry/__main__.py index f2a4ed8e0b..49dd61861b 100644 --- a/messagefoundry/__main__.py +++ b/messagefoundry/__main__.py @@ -14957,15 +14957,16 @@ def _ai_policy(args: argparse.Namespace) -> int: WHAT IT GUARANTEES, stated as what it is rather than as what it is not. This docstring said "Prints config only -- never message data (PHI-safe)" and nothing else. That sentence is TRUE -- no HL7 reaches this function -- and it is what let a disclosure through review, because the value - that leaked was CONFIG, which the sentence says nothing about. So: NO MESSAGE DATA, and config - only as follows. On the success path that is the [ai] fields named in ``payload`` below; on the - failure path it is a field path and a message from - :func:`~messagefoundry.config.settings.settings_error_detail`, which drops pydantic's ``input`` - but returns each validator's message as written, so a message that quotes the value it refused - still prints that value. That function's docstring says which do, and carries the argument for - why ``str(exc)`` is not safe here. Measured at ``19c98e023``: this subcommand, on a - ``[store]`` missing ``server`` with ``MEFOR_STORE_PASSWORD`` set as it is on any server-DB node, - printed that password to the stdout the IDE's ``runJson`` bridge reads. + that leaked was CONFIG, which the sentence says nothing about. So: ON STDOUT, NO MESSAGE DATA, + and config only as follows. On the success path that is the [ai] fields named in ``payload`` + below; on the failure path it is the text + :func:`~messagefoundry.config.settings.settings_error_detail` returns, which drops pydantic's + ``input`` but not a value an error's own message quotes. That function's docstring names at + least some messages that quote one, and carries the argument for not printing ``str(exc)``. + Stderr is not covered: the load's warnings go there, and some quote a configured value. Measured + at ``19c98e023``: this subcommand, on a ``[store]`` missing ``server`` with + ``MEFOR_STORE_PASSWORD`` set as it is on any server-DB node, printed that password to the stdout + the IDE's ``runJson`` bridge reads. ``tests/test_cli_ai_policy.py`` pins the absence with a planted secret and a control. ``OSError`` is in the catch for the reason ``_cluster_vip`` states at length: a @@ -15036,15 +15037,16 @@ def _cluster_vip(args: argparse.Namespace) -> int: is an easy typo for the file inside the directory, and a traceback there would leave stdout empty and the caller reporting "printed nothing" instead of the reason. - THE ERROR IS RENDERED, NEVER STRINGIFIED. ``str(ValidationError)`` carries ``input_value=`` for - each failing field, and an ``after``-mode section validator's input is the whole section mapping - -- so a ``[store]`` missing ``server`` renders the env-supplied ``MEFOR_STORE_PASSWORD`` into - this line. The installer then puts that line in a ``throw`` (``Get-VipSettings``: "Could not read - [cluster.vip]: ..."), which lands in the operator's transcript and in whatever captured the - install. :func:`~messagefoundry.config.settings.settings_error_detail` gives the field path and - the message without pydantic's ``input``; ``tests/test_cli_cluster_vip.py`` pins that with a - planted secret. It returns each validator's message as written, so a message that quotes the - value it refused still prints that value; that function's docstring says which do.""" + A VALIDATION ERROR IS RENDERED, NEVER STRINGIFIED. ``str(ValidationError)`` carries + ``input_value=`` for each failing field, and an ``after``-mode section validator's input is the + whole section mapping -- so a ``[store]`` missing ``server`` renders the env-supplied + ``MEFOR_STORE_PASSWORD`` into this line. The installer then puts that line in a ``throw`` + (``Get-VipSettings``: "Could not read [cluster.vip]: ..."), which lands in the operator's + transcript and in whatever captured the install. + :func:`~messagefoundry.config.settings.settings_error_detail` drops pydantic's ``input`` but not + a value an error's own message quotes, and its docstring names at least some messages that quote + one. ``tests/test_cli_settings_error_render.py`` pins the renderer on this + arm; ``tests/test_cli_cluster_vip.py`` pins the absence of a planted env secret.""" from pydantic import ValidationError from messagefoundry.config.settings import load_settings, settings_error_detail diff --git a/messagefoundry/checks.py b/messagefoundry/checks.py index 77d681061f..80f7820d8f 100644 --- a/messagefoundry/checks.py +++ b/messagefoundry/checks.py @@ -3040,12 +3040,13 @@ def _with_source(result: CheckResult, note: str | None) -> CheckResult: def _settings_error(exc: Exception) -> str: """A ``load_settings`` failure for a check detail, without pydantic's ``input`` in it. - ``str(exc)`` on a pydantic error prints ``input_value=``, so an unquoted numeric password would land - in check output and any CI log (BACKLOG #1182). Every check's settings arm goes through the one - designated renderer, :func:`~messagefoundry.config.settings.settings_error_detail`. That renderer - returns each validator's message as written, so a message that quotes the value it refused still - carries that value here; its docstring says which do. Imported lazily, as every engine import in - this module is.""" + ``str(exc)`` on a pydantic error from a model that does not hide its input prints + ``input_value=``, so an unquoted numeric password could land in check output and any CI log + (BACKLOG #1182); the settings models hide it themselves since BACKLOG #296, and this is the + second layer. Every check's settings arm goes through the one designated renderer, + :func:`~messagefoundry.config.settings.settings_error_detail`, which drops pydantic's ``input`` + but not a value an error's own message quotes; its docstring names at least some messages that + quote one. Imported lazily, as every engine import in this module is.""" from messagefoundry.config.settings import settings_error_detail return settings_error_detail(exc) From 89ea6944f4631bc998225ae29f97a03fb7c296e6 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 13:29:06 -0600 Subject: [PATCH 05/26] docs/AI.md: repair round one on the ai-policy disclosure paragraph BACKLOG #5113, code-review round-c2429672 repairs. The paragraph now scopes the guarantee to stdout and says stderr is not covered (the load's warnings go there; measured, an enabled [cluster.vip] prints its address). It names both layers that keep pydantic's input out of the error line, the settings models and settings_error_detail, says neither hides a value an error's own message quotes, and points at the function's docstring as naming at least some that do. It names test_cli_settings_error_render.py as what pins the renderer, since test_cli_ai_policy.py's planted secret is already hidden by the model layer. The "narrower than this line used to say" history is dropped. Doc only; net prose lines: 0. Proposed PR title: Say what settings_error_detail returns where docstrings and docs/AI.md claimed no configured value (BACKLOG #5113) Proposed vault banner: BUILT on engine branch b20053-5113 (batch 20053). The _ai_policy, _cluster_vip and checks._settings_error docstrings and the docs/AI.md ai-policy section now say settings_error_detail drops pydantic's input but not a value an error's own message quotes, and point at the function's docstring. ai-policy's guarantee is scoped to stdout. One further copy, the test_cli_settings_error_render module docstring, was tightened. Return value unchanged. Verified-by: tests --- docs/AI.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/AI.md b/docs/AI.md index d0007d2558..0f1fd75013 100644 --- a/docs/AI.md +++ b/docs/AI.md @@ -178,17 +178,17 @@ effective policy, and prints the **same JSON** to stdout — except `assist_perm `null`** (RBAC is not evaluable offline). `--json` prints only the JSON object (the IDE parses stdout); on error it prints `{"error": "..."}`. -It prints **no message data**, and of config only the policy JSON above or an error line. That is -narrower than the "config only, never message data" this line used to say, and the difference is -the point: no HL7 ever reaches this subcommand, so the only thing its output could disclose was -config, which that sentence said nothing about. It did disclose config — `str(ValidationError)` -carries `input_value=` for every failing field, so a `[store]` missing `server` put -`MEFOR_STORE_PASSWORD` on the stdout the IDE reads. The error line is now rendered by -`settings_error_detail`, which prints the field path and message and drops pydantic's input, and -`tests/test_cli_ai_policy.py` pins that. It does not hide a value a validator quotes in its own -message: some refusals quote the value they refused, and that line prints it. That function's -docstring in [config/settings.py](../messagefoundry/config/settings.py) says which do, and carries -the argument. +On stdout it prints **no message data**, and of config only the policy JSON above or the error +line. No HL7 reaches this subcommand, so config is what its output can disclose, and it once did: +`str(ValidationError)` carried `input_value=` for every failing field, so a `[store]` missing +`server` put `MEFOR_STORE_PASSWORD` on the stdout the IDE reads. Two layers now keep pydantic's +input out of the error line: the settings models hide it themselves, and the line is rendered by +`settings_error_detail`. Neither hides a value an error's own message quotes, and some refusals +quote the value they refused. That function's docstring in +[config/settings.py](../messagefoundry/config/settings.py) names at least some that do. +`tests/test_cli_ai_policy.py` pins the absence of an env-supplied secret, and +`tests/test_cli_settings_error_render.py` pins the renderer on this subcommand. Stderr is not +covered: the settings load's warnings go there, and some quote a configured value. --- From 84a291cf9f003fdf33a9ca435c1fc91429a31509 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 13:29:36 -0600 Subject: [PATCH 06/26] settings: the URL check's docstring names an ASCII scheme, judged after lower-casing (BACKLOG #5116) _looks_like_url's docstring is the one statement docs/CONFIGURATION.md now links for the backup and DR path keys. It said "a letter", but _URL_SCHEME is ASCII only, and the shape is judged after str.lower(), so say both. Docstring only; no behaviour change. Verified-by: tests --- messagefoundry/config/settings.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/messagefoundry/config/settings.py b/messagefoundry/config/settings.py index 944b98e146..8333cdd8bf 100644 --- a/messagefoundry/config/settings.py +++ b/messagefoundry/config/settings.py @@ -7811,10 +7811,10 @@ def _dwell_inside_expiry(self) -> ApprovalsSettings: def _looks_like_url(value: str) -> bool: """Whether ``value``, stripped and lower-cased, starts with ``://``, where the scheme is - a letter and then at least one more letter, digit, ``+``, ``.`` or ``-``. These settings take a - LOCAL or UNC path. A fixed list of seven cloud schemes let ``sftp://`` or ``s3a://`` load as a - bogus local path (vault BACKLOG #2600). A value with any other shape once stripped is not - detected, and can load as a path. + an ASCII letter and then at least one more ASCII letter, digit, ``+``, ``.`` or ``-``. These + settings take a LOCAL or UNC path. A fixed list of seven cloud schemes let ``sftp://`` or + ``s3a://`` load as a bogus local path (vault BACKLOG #2600). A value with any other shape once + stripped and lower-cased is not detected, and can load as a path. It hands back no text, because a refusal quotes no part of the value: see :func:`settings_error_detail`.""" From 4c62e43561f609ade40512ee812e03c31f27a3c1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 13:30:31 -0600 Subject: [PATCH 07/26] docs: CONFIGURATION.md's backup and DR path rows state the URL check's real shape (BACKLOG #5116) The four rows ([backup] destination; [dr] seed_archive, seed_dir, restore_token) each said a URL "whose scheme has two or more characters" is rejected. The check, _looks_like_url, needs a leading ASCII letter, so a digit-led scheme such as 1s:// is missed and loads as a path. The destination row now names _looks_like_url as the one statement of the shape, and says it misses at least a one-letter scheme, a scheme holding _, and a digit-led one. Each [dr] row links it and says what its own key does with a missed value: seed_archive and restore_token load it as a path; seed_dir still refuses it unless it is absolute on the platform that loads the settings, since _seed_dir_absolute runs too. Proposed PR title: CONFIGURATION.md states the backup/DR URL check's real shape (BACKLOG #5116) Proposed vault banner: BUILT on branch b20053-5116 (batch 20053): the four CONFIGURATION.md rows link _looks_like_url, whose docstring now says ASCII and lower-cased; each row says what its key does with a missed value. Verified-by: tests --- docs/CONFIGURATION.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 3f248b43e6..06d86fa2ad 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -3466,7 +3466,7 @@ stated once in the `dr_paused` comment of `BackupRunner`. | Key | Type | Default | Notes | |---|---|---|---| | `enabled` | bool | `false` | opt-in master switch; a deployment with no `[backup]` is unaffected | -| `destination` | path | `""` | local or UNC destination dir (e.g. `D:/mefor-backups`). **Required (non-empty) when enabled.** A `://` URL (`s3://`, `https://`, `sftp://`, …) whose scheme has two or more characters is **rejected** — there is no remote target. A one-letter scheme reads as a drive letter, so `C://x` stays a path | +| `destination` | path | `""` | local or UNC destination dir (e.g. `D:/mefor-backups`). **Required (non-empty) when enabled.** A `://` URL (`s3://`, `https://`, `sftp://`, …) is **rejected** — there is no cloud or URL target. The URL check is `_looks_like_url` in [config/settings.py](../messagefoundry/config/settings.py), whose docstring states the one shape it detects; the `[dr]` path keys share it. It misses at least a one-letter scheme, a scheme holding `_` (`my_s3://`) and a scheme that starts with a digit (`1s://`). A one-letter scheme reads as a drive letter, so `C://x` stays a path. Here a value the check misses loads as a path, relative to the working directory of the process that runs the backup (`serve`, or the `messagefoundry backup` command) where it is not absolute, as `C://x` is not on POSIX. The value can reach at least the service log and a failed run's `dr_backup` audit row and alert, so keep a credential out of it | | `schedule_at` | str | `"02:00"` | daily local `"HH:MM"` the scheduled backup runs at (the same clock grammar as `[retention].vacuum_at`). `""` = **on-demand only** (the `messagefoundry backup` CLI), no scheduled pass | | `retention_keep` | int | `7` | keep-N: after a successful, **verified** new archive, prune the oldest archives beyond the newest N at the destination. `0` = keep all, which on an enforcing instance needs `[security].allow_keeping_backup_archives_indefinitely = true` or `serve` refuses (BACKLOG #1967). Only archives that passed every configured check are counted: a backup is written as `.part` and renamed onto its canonical name after the verify, so a verify-**failed** archive keeps a `.failed` name and can evict a good one in neither this prune nor any later one. The flip side: `.failed` and `.part` files at the destination sit **outside** keep-N and nothing expires them — clear them yourself (ADR 0049) | | `snapshot_method` | str | `vacuum_into` | `vacuum_into` (default; a defragmented copy) or `online_backup` (a page-for-page copy). Neither holds the store write lock for the copy (BACKLOG #1937). The copy still has costs, so an off-peak `schedule_at` remains sensible; ADR 0049 points to where they are stated | @@ -3503,9 +3503,9 @@ cluster leader it would serve nothing. | `release_hook` | str | `""` | the symmetric command run on `POST /dr/release` to hand the VIP back to the recovered primary. `""` = no hook; whitespace-only rejected at load | | `pass_environment` | list of names | `[]` | Environment variable **names** both hooks are given, beyond what a shell needs to start (vault BACKLOG #2587). A hook gets an **allowlist**: the platform's start-up names, such as `PATH`, `SYSTEMROOT`, `TEMP` and `USERPROFILE` on Windows or `PATH`, `HOME` and the locale names on POSIX; on Windows the names that say where programs and shared data are installed, such as `ProgramFiles` and `ALLUSERSPROFILE`; and the names listed here. **No other variable crosses**, so list what the hook's own tools read, such as a cloud CLI's profile or a proxy. `PSModulePath` is not passed: PowerShell builds its own when it is unset. Nor is `PSExecutionPolicyPreference`, the process-scope execution policy a parent shell can set, so a PowerShell **script** hook runs under the execution policy the machine, Group Policy and the engine's account set; where that refuses scripts, give `-ExecutionPolicy` on the hook's command line or list that name here. Names only; the value comes from the engine's own environment when the hook runs, and a listed name that is not set there is logged as a WARNING, by name, when the engine starts with `enabled` and a hook configured, and again each time a hook runs. A hook that exits non-zero names this setting in its reason. A variable a hook needs that you did not list is not reported: the hook's own output is discarded, so test a hook under the service's environment before you need it. **Refused at load**: at least an entry that is not a variable name, such as `NAME=value`; any of the engine's own names, which are any `MEFOR_*` name and `VAULT_TOKEN` and `PGPASSWORD`; and `PYTHONINSPECT`, which leaves a child waiting at a prompt. `messagefoundry/childenv.py` (`pass_environment_refusal`) holds the rule. Under `[secrets].provider = "env"`, a name a secret-reference setting such as `[auth].ad_bind_password_secret` reads is refused too (in `[sandbox].pass_environment` as well). A connection secret a config module reads under another name is not known to the loader, so do not list one. A name you list reaches the hook with its value, so list a credential only when the hook needs it. `messagefoundry/childenv.py` (`hook_environment`) is the source of record for the full lists. Env: `MEFOR_DR_PASS_ENVIRONMENT`, comma-separated. | | `takeover_timeout_seconds` | float (>0) | `30.0` | bound on the takeover/release hook **and** on the cold-seed restore-verify at the DR site, its KeyProvider-reachability check included: a hook or restore-verify that doesn't succeed within this **aborts activation closed**, with no silent retry-forever. The bound reaches the key probe only where the key resolves off the event loop, which it tries to do under `[store].key_provider` `vault` or `env`, whatever `encryption_key_file` holds, and `auto` or `dpapi` with no `encryption_key_file` set (vault BACKLOG #5888). The key resolves on the event loop at least under `host`, under `auto` or `dpapi` with a key file set, and under any provider when the engine cannot start a thread for the probe, which it logs as a WARNING. A key probe that hangs on the loop stalls the whole engine, activation included, and the bound cannot fire until the probe returns. A probe the bound abandons keeps its thread until the provider answers. It also bounds the activation's digest of the running config dir, taken only for the `dr.activate` audit row: a dir that does not answer in time is recorded as `unreadable` and does **not** abort the activation. It also bounds the activation's preflights (the trust anchors and, in `serve`, the connection key files), which **abort** it after the takeover hook when they do not finish in time. What that bound leaves out is in [ADR 0048](adr/0048-third-tier-disaster-recovery-standby.md), the amendment for vault BACKLOG #3094. A **takeover** hook that runs past it is killed, with the processes it started. If the engine cannot put the hook in a Windows job object, or cannot signal its POSIX process group, it logs one WARNING and the kill reaches only the hook's shell. The abort is recorded once the hook has exited, or after at most 5 more seconds (vault BACKLOG #2622). At least these escape that kill: on POSIX a process that leaves the hook's process group (`setsid`, and `sudo` in its default `use_pty` mode) or that the engine's account may not signal; on Windows, work the hook hands to another service, such as WMI or Task Scheduler. A **release** hook that runs past it is left to finish, as before. Under `supervise` on Windows it still ends if the supervisor process dies while its engine shard runs, because each engine shard runs in the supervisor's kill-on-close job (BACKLOG #5978) | -| `seed_archive` | path | `""` | the `.mfbak` archive activation **verifies** the cold seed against. With `enabled = true`, this or `seed_dir` must be set, or the load refuses the box: no activation could name a seed (BACKLOG #5965). A whitespace-only or space-padded value is refused too. Activation does not load it — on a **SQLite** store, restore it first with `messagefoundry restore --to ` and name the same archive here, so activation can check the store actually carries it. `""` = the operator supplies the archive path in the `POST /dr/activate` request body instead (the runbook path), which needs `seed_dir` below. A `://` URL whose scheme has two or more characters is rejected (a one-letter scheme reads as a drive letter, so `C://x` stays a path) — local/UNC only, like the backup destination. On a **SQLite** store a **config-only** archive cannot be a seed here and is refused: it carries no `store.db`, so nothing could have been restored from it — `messagefoundry restore --to` rejects one for the same reason, and with `--config-to` alone restores only its config bundle. On a server-DB (Postgres/SQL Server) store that refusal does not apply, and **`messagefoundry restore --to` is not part of the drill** — it rejects a config-only archive on *every* backend, so running it here is a hard error. There the DBA restores the live database natively and the archive named here is the **config bundle**, which by default is all a server-DB backup writes (`[backup].config_only_on_server_db`). That bundle restores with `messagefoundry restore --config-to ` and no `--to` (vault BACKLOG #5233). Activation instead gates the restored **live database**, not the archive: `POST /dr/activate` must carry `dba_attests_restored=true` **and** the restored database must already carry prior `dr_backup` history, or activation **refuses closed**; `restore_token` below adds an optional vintage floor on top of those two | -| `seed_dir` | path | `""` | the **one directory** a `POST /dr/activate` request body may name an archive under (vault BACKLOG #2581). `""` (default) = a request may name **no** archive, and activation uses `seed_archive`. Must be an **absolute** path on the DR box; a relative one is rejected at load, and so is a whitespace-only or space-padded one (BACKLOG #5965). A request path is confined to this directory the way `[api].config_reload_roots` confines a reload path, and activation verifies the resolved path. A refusal aborts activation (422) with one generic message that names no part of the path; the `dr_activation_aborted` audit row records the path that was asked for. If this directory itself cannot be resolved within `takeover_timeout_seconds`, activation aborts and says so. `seed_archive` is operator configuration and is not confined by this key. A `://` URL whose scheme has two or more characters is rejected (a one-letter scheme reads as a drive letter, so `C://x` stays a path), like `seed_archive` | -| `restore_token` | path | `""` | **opt-in server-DB DR restore token** (BACKLOG #223, [ADR 0102](adr/0102-server-db-dr-restore-vintage-completeness-attestation-residual.md)). A local/UNC path to a small JSON token the DBA places on the DR box recording the **expected** source-backup anchor of a native (Postgres/SQL Server) restore. When set, the server-DB seed gate cross-checks it against the restored database's own latest successful `dr_backup` archive — a **vintage floor** a bare boolean attestation cannot give: a stale or wrong native restore's latest anchor differs, so activation **refuses closed**. `""` (default) = off (the gate is byte-unchanged). On a SQLite store any value is refused at load, since no check reads it there, and so is a whitespace-only or space-padded value (BACKLOG #5965). A `://` URL whose scheme has two or more characters is rejected (a one-letter scheme reads as a drive letter, so `C://x` stays a path) | +| `seed_archive` | path | `""` | the `.mfbak` archive activation **verifies** the cold seed against. With `enabled = true`, this or `seed_dir` must be set, or the load refuses the box: no activation could name a seed (BACKLOG #5965). A whitespace-only or space-padded value is refused too. Activation does not load it — on a **SQLite** store, restore it first with `messagefoundry restore --to ` and name the same archive here, so activation can check the store actually carries it. `""` = the operator supplies the archive path in the `POST /dr/activate` request body instead (the runbook path), which needs `seed_dir` below. Local/UNC only, like the backup destination: a `://` URL is rejected by the URL check named under [`[backup]` `destination`](#backup--scheduled-dr-backup--restore-verify), and a value it misses loads here as a path, relative to the engine's working directory where it is not absolute. On a **SQLite** store a **config-only** archive cannot be a seed here and is refused: it carries no `store.db`, so nothing could have been restored from it — `messagefoundry restore --to` rejects one for the same reason, and with `--config-to` alone restores only its config bundle. On a server-DB (Postgres/SQL Server) store that refusal does not apply, and **`messagefoundry restore --to` is not part of the drill** — it rejects a config-only archive on *every* backend, so running it here is a hard error. There the DBA restores the live database natively and the archive named here is the **config bundle**, which by default is all a server-DB backup writes (`[backup].config_only_on_server_db`). That bundle restores with `messagefoundry restore --config-to ` and no `--to` (vault BACKLOG #5233). Activation instead gates the restored **live database**, not the archive: `POST /dr/activate` must carry `dba_attests_restored=true` **and** the restored database must already carry prior `dr_backup` history, or activation **refuses closed**; `restore_token` below adds an optional vintage floor on top of those two | +| `seed_dir` | path | `""` | the **one directory** a `POST /dr/activate` request body may name an archive under (vault BACKLOG #2581). `""` (default) = a request may name **no** archive, and activation uses `seed_archive`. Must be an **absolute** path on the DR box; a relative one is rejected at load, and so is a whitespace-only or space-padded one (BACKLOG #5965). A request path is confined to this directory the way `[api].config_reload_roots` confines a reload path, and activation verifies the resolved path. A refusal aborts activation (422) with one generic message that names no part of the path; the `dr_activation_aborted` audit row records the path that was asked for. If this directory itself cannot be resolved within `takeover_timeout_seconds`, activation aborts and says so. `seed_archive` is operator configuration and is not confined by this key. A `://` URL is rejected by the URL check named under [`[backup]` `destination`](#backup--scheduled-dr-backup--restore-verify). A value it misses is still refused here unless it is absolute on the platform that loads the settings, as `C://x` is on Windows and is not on POSIX | +| `restore_token` | path | `""` | **opt-in server-DB DR restore token** (BACKLOG #223, [ADR 0102](adr/0102-server-db-dr-restore-vintage-completeness-attestation-residual.md)). A local/UNC path to a small JSON token the DBA places on the DR box recording the **expected** source-backup anchor of a native (Postgres/SQL Server) restore. When set, the server-DB seed gate cross-checks it against the restored database's own latest successful `dr_backup` archive — a **vintage floor** a bare boolean attestation cannot give: a stale or wrong native restore's latest anchor differs, so activation **refuses closed**. `""` (default) = off (the gate is byte-unchanged). On a SQLite store any value is refused at load, since no check reads it there, and so is a whitespace-only or space-padded value (BACKLOG #5965). A `://` URL is rejected by the URL check named under [`[backup]` `destination`](#backup--scheduled-dr-backup--restore-verify); on a server-DB store a value it misses loads as a path, relative to the engine's working directory where it is not absolute | ### `[approvals]` Optional **dual-control (maker-checker)** approval for high-value actions (ASVS 2.3.5) — see From 9011f2fe8d08c0636324b059f89071d1e327efe0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 13:40:01 -0600 Subject: [PATCH 08/26] docs: at-rest cipher row states the keyless gate the code has (BACKLOG #5270) The in-process at-rest cipher row of the crypto inventory in docs/ASVS-L2-PHASE0-CHANGES.md said every built-in environment derives data_class=phi, that a non-PHI instance ran the plaintext cipher with no opt-out, and named the opt-out as [store].allow_unencrypted_phi. The code has none of that: _keyless_store_gate (__main__.py) reads no data class since BACKLOG #1279, and _reject_relocated_keys (config/settings.py) refuses the [store] spelling at load. The row now states the rule as the code has it: with no store key, serve refuses to start in every environment unless the [security] opt-out applies (allow_unencrypted_phi = true or encrypt_stored_data = false), which under the default enforce level also needs the strict acknowledgment, and [store].require_encryption still wins. It cites the gate functions and links SECURITY-LOOSENING.md, and carries a dated CORRECTED note naming what it used to say. Verified-by: tests --- docs/ASVS-L2-PHASE0-CHANGES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ASVS-L2-PHASE0-CHANGES.md b/docs/ASVS-L2-PHASE0-CHANGES.md index 4ff566b61a..a07d1fe53b 100644 --- a/docs/ASVS-L2-PHASE0-CHANGES.md +++ b/docs/ASVS-L2-PHASE0-CHANGES.md @@ -173,7 +173,7 @@ for, not how it is protected before it gets there. | Session tokens | 256-bit CSPRNG (`secrets.token_urlsafe(32)`); stored only as SHA-256 | `sessions.token_hash`. Client side, the VS Code extension keeps the plaintext token in VS Code SecretStorage, keyed by engine URL (`ide/src/auth.ts`) | Idle 30 min / absolute 12 h; revoked on logout/password-change/disable | | WebAuthn ceremony challenges ([ADR 0068](adr/0068-browser-webauthn-passkeys-offloopback.md)) | First-party 64-byte CSPRNG (`secrets.token_bytes(64)` in `auth/webauthn.py`), passed as the explicit `challenge=` to the `webauthn` library (ASVS 6.7.2 evidence) | Process-local bounded TTL'd `ChallengeCache` keyed by `(session token-hash, kind)` — never persisted, never logged | Single-use (pop-on-verify); 120 s monotonic TTL; new ceremony overwrites the session's pending one; per-user cap 16 (self-evicting), global safety bound 4096 (refuse, cause-named) | | WebAuthn credentials ([ADR 0068](adr/0068-browser-webauthn-passkeys-offloopback.md)) | COSE public keys verified by the `webauthn` library (`cryptography` transitively — ECDSA P-256 et al.); sign-count updated via strict compare-and-set (a CAS miss = clone signal → reject + `auth.webauthn_clone_suspected` audit; 0 is legitimate for synced passkeys) | `webauthn_credentials` table, keyed `credential_id_hash` (SHA-256 hex of the raw id — the `sessions.token_hash` precedent). Public keys stored **plaintext by design** (verification material, not a secret) — deliberately excluded from the store cipher and the id-keyed rekey loops | Enrolled behind the password-only re-proof (WP-14); self-removable behind the full step-up (last-required-factor delete refused); `admin_reset_mfa` clears all; rp_id pinned at mint (origin migration → visibly "unusable") | -| Store-at-rest cipher — in-process (`[store].cipher_provider = aesgcm`, default) | AES-256-GCM (`mfenc:v1::…`, additive AAD-bound `mfenc:v2`) in-process keyring cipher. **The shipped default is key-required, NOT keyless:** every built-in environment (`dev`/`staging`/`prod`) derives `data_class=phi` ([ADR 0148](adr/0148-phi-default-posture-and-an-explicit-security-enforcement-level.md) GIVEN 1), and a PHI instance **refuses to start keyless** in *any* environment (the `serve` gate in [`__main__.py`](../messagefoundry/__main__.py); `[store].require_encryption` forces the refusal even for a synthetic instance). The identity/plaintext cipher runs only on a **synthetic / non-PHI** instance (`data_class ≠ phi`, e.g. CI) or via the loud, audited `[store].allow_unencrypted_phi` opt-out (a second `[security].allow_unencrypted_phi_under_strict_enforcement` ack under strict enforcement). Covers the `_CIPHER_COLUMNS` set — `messages.raw`/`.summary`/`.metadata`/`.error`, `queue.payload`/`.last_error`, `message_events.detail`, `users.totp_secret`, `connection_event.reason`, `alert_instance.reason` (`summary`/`metadata` carry ingest-derived MRN/patient-name PHI); WebAuthn COSE public keys are deliberately excluded (verification material, not a secret). **Usage scope:** this DEK is the confidentiality key for the at-rest store columns above **and for the `.mfbak` DR archive**, which seals the SQLite snapshot + config bundle under the *same* resolved DEK (`store/backup_codec.py`); it is **not** a transport, signing, or token key, is never used to verify a signature, and never leaves the engine host. The archive limb is stated because the negative half of a usage scope is what an operator acts on: an earlier wording said "the at-rest store columns **only**", which understated what discarding this key destroys and implied a backup could be restored without it. | **Keyring:** active key `MEFOR_STORE_ENCRYPTION_KEY` (or DPAPI-protected `MEFOR_STORE_ENCRYPTION_KEY_FILE`) + decrypt-only `MEFOR_STORE_ENCRYPTION_KEYS_RETIRED`; `key_id` = SHA-256 fingerprint | **See key-management policy below** | +| Store-at-rest cipher — in-process (`[store].cipher_provider = aesgcm`, default) | AES-256-GCM (`mfenc:v1::…`, additive AAD-bound `mfenc:v2`) in-process keyring cipher. **The shipped default is key-required, NOT keyless:** with no store key configured, `serve` **refuses to start**, in every environment, unless the loud, audited at-rest opt-out applies (the keyless gate, `_keyless_store_gate` in [`__main__.py`](../messagefoundry/__main__.py), whose opt-out rule is `keyless_opt_out_refusal` in [`config/settings.py`](../messagefoundry/config/settings.py); at least `provision-admin` and `supervise` apply the same gate). The gate reads no environment label and no data class: every instance carries patient data ([ADR 0186](adr/0186-retire-the-synthetic-data-declaration-every-instance-carries-patient-data.md), BACKLOG #1279), and a config that still sets the retired data-class lever is refused at load. The opt-out is set in `[security]` alone, as `[security].allow_unencrypted_phi = true` or `[security].encrypt_stored_data = false`. Under `[security].enforcement = enforce`, the shipped default, it also needs `[security].allow_unencrypted_phi_under_strict_enforcement = true` ([ADR 0140](adr/0140-two-acknowledged-production-phi-no-loosen-carve-outs-single-factor-admin-at-exposure-keyless-phi-in-production.md), keyed on the enforcement level and renamed by [ADR 0148](adr/0148-phi-default-posture-and-an-explicit-security-enforcement-level.md)), and at least `[store].require_encryption` refuses a keyless start even past it. Setting `allow_unencrypted_phi` in its old `[store]` section is refused at load ([ADR 0118](adr/0118-secure-by-default-security-configuration-section.md)). What each switch loosens is in [SECURITY-LOOSENING.md](SECURITY-LOOSENING.md). CORRECTED 2026-12-01 by BACKLOG #5270: the earlier text keyed this gate on the retired data-class rule, said the plaintext cipher ran with no opt-out on any instance that rule exempted, and named the opt-out by its retired `[store]` spelling. Covers the `_CIPHER_COLUMNS` set — `messages.raw`/`.summary`/`.metadata`/`.error`, `queue.payload`/`.last_error`, `message_events.detail`, `users.totp_secret`, `connection_event.reason`, `alert_instance.reason` (`summary`/`metadata` carry ingest-derived MRN/patient-name PHI); WebAuthn COSE public keys are deliberately excluded (verification material, not a secret). **Usage scope:** this DEK is the confidentiality key for the at-rest store columns above **and for the `.mfbak` DR archive**, which seals the SQLite snapshot + config bundle under the *same* resolved DEK (`store/backup_codec.py`); it is **not** a transport, signing, or token key, is never used to verify a signature, and never leaves the engine host. The archive limb is stated because the negative half of a usage scope is what an operator acts on: an earlier wording said "the at-rest store columns **only**", which understated what discarding this key destroys and implied a backup could be restored without it. | **Keyring:** active key `MEFOR_STORE_ENCRYPTION_KEY` (or DPAPI-protected `MEFOR_STORE_ENCRYPTION_KEY_FILE`) + decrypt-only `MEFOR_STORE_ENCRYPTION_KEYS_RETIRED`; `key_id` = SHA-256 fingerprint | **See key-management policy below** | | Vault Transit KeyProvider (opt-in, [ADR 0019](adr/0019-pluggable-keyprovider-hsm-kms-vault.md)) | Envelope-unwraps the store DEK: Vault Transit `decrypt_data` returns the base64 32-byte DEK, decrypting the wrapped DEK (`vault:v1:…`) against a **non-extractable KEK held inside Vault**; only the wrapped DEK sits at rest. **Fail-closed** — any missing config or Transit/transport failure raises `KeyProviderError` and `serve` refuses to start (never degrades to the identity/plaintext cipher); key material is never logged (only the exception type). `hvac` in [`store/keyprovider_vault.py`](../messagefoundry/store/keyprovider_vault.py). **Usage scope:** the Vault KEK **only** unwraps the store DEK inside Vault — it never encrypts store data directly and never leaves Vault; the DEK it yields protects the at-rest store columns above **and the `.mfbak` DR archive** (same DEK, same caveat as the row above), and no transport / signing / token material. | Env-sourced: `MEFOR_STORE_VAULT_ADDR` / `MEFOR_STORE_VAULT_TOKEN` / `MEFOR_STORE_VAULT_TRANSIT_KEY` / `MEFOR_STORE_VAULT_WRAPPED_DEK`; `hvac` behind the optional `[vault]` extra | **OFF by default** — `[store].key_provider` defaults to `auto` (env-then-DPAPI key sourcing for the in-process `aesgcm` cipher), not `vault` | | Store-at-rest cipher — Transit mode (`[store].cipher_provider = vault_transit`, opt-in, [ADR 0138](adr/0138-transit-bulk-crypto-provider-dek-out-of-engine-heap-for-asvs-13-3-3-demand-gated.md)) | Bulk at-rest AEAD encrypt/decrypt runs **inside** Vault/OpenBao Transit — each value is stored as the `mfenc:v3:` marker + Transit's own `vault:v1:…` ciphertext, and the audit-chain MAC is computed **inside** Transit via `generate_hmac` (forgery-**resistant**, not keyless SHA-256). `TransitCipher` in [`store/crypto_transit.py`](../messagefoundry/store/crypto_transit.py) imports **none** of the six stdlib crypto modules — every primitive is delegated over the Vault HTTP seam, so the plaintext DEK **never enters engine heap** (ASVS 13.3.3 isolated security module; 13.3.1's L3 hardware clause still wants the vault HSM-sealed). ASVS 11.3.3 cell-binding rides for free — `cell_aad(table, column, *pk)` is forwarded as Transit `associated_data`. **Fail-closed** — missing config or an unreachable/unknown Transit key raises `KeyProviderError` and `serve` refuses to start (never degrades to plaintext); a per-op Transit failure raises `CipherError`, surfacing only the exception **type**, never key material or PHI. **Usage scope:** the data key encrypts/decrypts the at-rest store columns above. The audit key computes at least the audit-chain MAC, the ADR 0217 row seals (`TransitCipher.seal_key_name` returns it) and the fixed-input probes beside them. With `MEFOR_STORE_TRANSIT_AUDIT_KEY` unset the audit key **is** the data key (`_key_names` in `store/crypto_transit.py`), so one key does all of it. Both are Vault-resident, non-exportable, and protect no transport / signing / token material. | Env-named Transit keys `MEFOR_STORE_TRANSIT_KEY` (data) + optional `MEFOR_STORE_TRANSIT_AUDIT_KEY` (audit MAC; unset ⇒ reuses the data key), reached via `MEFOR_STORE_VAULT_ADDR` / `MEFOR_STORE_VAULT_TOKEN`; `hvac` behind the optional `[vault]` extra | **OFF by default** — `[store].cipher_provider` defaults to `aesgcm`; the key material stays inside Vault, so **roll the Transit key version in Vault** (prior versions still decrypt existing `mfenc:v3` rows) | | Sealed read-through caches (BACKLOG #1174) | AES-256-GCM under a random 256-bit key generated per process; 96-bit nonce = 4-byte random per-process prefix + 8-byte counter, so a nonce never repeats under one key (a forked child draws a new prefix). AAD binds each value to its cache scope and key. Memory hygiene for the decoded values of the transform-state and reference caches, not at-rest protection: the key lives in the same process (`store/sealed_cache.py`). **Usage scope:** this key seals only the decoded values of the engine's own transform-state and reference read-through caches, in its own process's memory. It never protects data at rest, the DR archive, a transport, a signature or a token, it is never used by another process or a sandbox child, and it is not derived from, and cannot open, anything the store DEK protects | In process memory only; never persisted, logged or exported | A new key every process start; nothing to rotate or recover | From 3f7408fd8057ca00929b05fb5a30dc0f806a68e1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 13:41:16 -0600 Subject: [PATCH 09/26] tests: pin the at-rest cipher row's keyless rule to the code (BACKLOG #5270) tests/test_crypto_inventory_doc.py did not read this row's rule, so the retired data-class text and the refused [store] spelling sat in the crypto inventory with the guard green. New tests: - section 4 uses neither of two words of the retired data-class rule and names no key the loader refuses, read from _RELOCATED_TO_SECURITY and _REMOVED_KEYS in both the dotted and MEFOR_ environment spellings; - the row names only keys a settings model has, and names each setting that decides a keyless start, matched whole so the strict-ack key cannot stand in for the opt-out it extends; - the gate functions the row cites still exist; - the rule the row states holds: _keyless_store_gate on loaded settings refuses by default, needs the strict ack under the default enforce level for either [security] switch, lets require_encryption win, and the loader refuses [store].allow_unencrypted_phi; - a negative control feeds the old row text and planted variants back through the checker. Each new doc test fails on the row as origin/main has it. Proposed PR title: The at-rest cipher row in the crypto inventory states the keyless gate the code has (BACKLOG #5270) Proposed vault banner: CLOSED by engine PR : docs/ASVS-L2-PHASE0-CHANGES.md's in-process at-rest cipher row now states the keyless gate as the code has it (no data class; the [security] opt-out; the [store] spelling refused), and tests/test_crypto_inventory_doc.py pins it, with a negative control on the old text. Verified-by: tests --- tests/test_crypto_inventory_doc.py | 179 +++++++++++++++++++++++++++++ 1 file changed, 179 insertions(+) diff --git a/tests/test_crypto_inventory_doc.py b/tests/test_crypto_inventory_doc.py index 2b8f6d5613..fb2f3b7a19 100644 --- a/tests/test_crypto_inventory_doc.py +++ b/tests/test_crypto_inventory_doc.py @@ -21,6 +21,12 @@ claim (false since ADR 0148), the "no classical-public-key data at rest" PQC claim (false given the WebAuthn COSE + OIDC RP keys), and the "default keyless posture" audit-chain claim (false because ``serve`` refuses to start with no store key). +* **The in-process at-rest cipher row states the keyless gate the code has** (BACKLOG #5270): §4 + uses neither of two words of the retired data-class rule and names no config key the loader + refuses; the row names each setting that decides a keyless start and only keys a settings model + has; the gate functions it cites exist; and the rule it states (refused by default, the + ``[security]`` opt-out, the strict acknowledgment under enforce, ``[store].require_encryption`` + winning, the ``[store]`` spelling refused) is read back from ``_keyless_store_gate`` and the loader. * **Every migration row keeps a dated milestone + a named owner** (11.1.4), and the section states a review cadence tied to this guard. @@ -33,6 +39,12 @@ import importlib.util import re from pathlib import Path +from typing import TYPE_CHECKING + +import pytest + +if TYPE_CHECKING: + from messagefoundry.config.settings import ServiceSettings _ROOT = Path(__file__).resolve().parent.parent _PKG = _ROOT / "messagefoundry" @@ -251,6 +263,173 @@ def test_review_cadence_ties_to_this_guard() -> None: ) +# The in-process at-rest cipher row states when a keyless start is refused (BACKLOG #5270). It used to +# key that rule on every built-in environment deriving a PHI data class, to say a non-PHI instance ran +# the plaintext cipher with no opt-out, and to name the opt-out by its `[store]` spelling. The data +# class is gone (BACKLOG #1279, ADR 0186) and that spelling is refused at load (ADR 0118). +_AT_REST_ROW_PREFIX = "| Store-at-rest cipher — in-process" + +# Two words the retired rule's text used that §4 does not otherwise use, matched case-folded over all +# of §4. This catches those two spellings only, not every restatement of the rule. If an accurate new +# sentence needs one of them, narrow the match rather than reword true prose. +_RETIRED_DATA_CLASS_WORDS = ("data_class", "non-phi") + +# The false phrasings the row carried before BACKLOG #5270, plus two planted variants: the opt-out's +# refused environment spelling and a key no settings model has. The negative control below feeds each +# back through the checker, so every arm of the guard is shown to fire. +_RETIRED_AT_REST_TEXT = ( + "every built-in environment (`dev`/`staging`/`prod`) derives `data_class=phi`", + "The identity/plaintext cipher runs only on a **synthetic / non-PHI** instance", + "via the loud, audited `[store].allow_unencrypted_phi` opt-out", + "set `MEFOR_STORE_ALLOW_UNENCRYPTED_PHI=true`", + "set `[security].allow_unencrypted_ph = true`", +) + +# The settings the row names as deciding a keyless start: the two [security] switches the loader folds +# into the opt-out the gate reads, the enforcement level and its second acknowledgment, and the store +# setting that wins over the opt-out. Matched with a trailing word boundary, because +# `[security].allow_unencrypted_phi` is a prefix of the strict-acknowledgment key. +_AT_REST_SWITCHES = ( + "[security].allow_unencrypted_phi", + "[security].encrypt_stored_data", + "[security].enforcement", + "[security].allow_unencrypted_phi_under_strict_enforcement", + "[store].require_encryption", +) + +# The gate functions the row cites, by the module that must still define each at module level. +_AT_REST_GATE_SYMBOLS = ( + ("_keyless_store_gate", "messagefoundry.__main__"), + ("keyless_opt_out_refusal", "messagefoundry.config.settings"), +) + +_DOTTED_KEY = re.compile(r"\[([a-z_]+)\]\.([a-z_]+)") + + +def _names(text: str, spelling: str) -> bool: + """Does ``text`` name ``spelling`` whole, not as the prefix of a longer key?""" + return re.search(re.escape(spelling) + r"(?![A-Za-z0-9_])", text) is not None + + +def _at_rest_cipher_row() -> str: + rows = [line for line in _section4().splitlines() if line.startswith(_AT_REST_ROW_PREFIX)] + assert len(rows) == 1, f"expected one {_AT_REST_ROW_PREFIX!r} row in §4, found {len(rows)}" + return rows[0] + + +def _retired_data_class_claims(text: str) -> list[str]: + """The retired data-class words in ``text``, and the keys in it the loader refuses. + + The refused keys are read from the loader's own tables, in both spellings it refuses: the dotted + ``[section].key`` and the ``MEFOR_
_`` environment variable.""" + from messagefoundry.config.settings import _RELOCATED_TO_SECURITY, _REMOVED_KEYS + + folded = text.casefold() + found = [word for word in _RETIRED_DATA_CLASS_WORDS if word in folded] + for section, key in sorted(set(_RELOCATED_TO_SECURITY) | set(_REMOVED_KEYS)): + for spelling in (f"[{section}].{key}", f"MEFOR_{section.upper()}_{key.upper()}"): + if _names(text, spelling): + found.append(spelling) + return found + + +def _unknown_keys(text: str) -> list[str]: + """The ``[section].key`` names in ``text`` that no ``ServiceSettings`` section model has.""" + from messagefoundry.config.settings import ServiceSettings + + unknown: set[str] = set() + for section, key in _DOTTED_KEY.findall(text): + field = ServiceSettings.model_fields.get(section) + fields = getattr(field.annotation if field is not None else None, "model_fields", {}) + if key not in fields: + unknown.add(f"[{section}].{key}") + return sorted(unknown) + + +def _missing_switches(row: str) -> list[str]: + return [switch for switch in _AT_REST_SWITCHES if not _names(row, switch)] + + +def test_section4_uses_no_retired_data_class_word_or_refused_key() -> None: + # BACKLOG #5270: the keyless gate reads no data class, and the opt-out is set in [security] only. + present = _retired_data_class_claims(_section4()) + assert not present, ( + "§4 of docs/ASVS-L2-PHASE0-CHANGES.md uses a word of the retired data-class rule or names a " + f"config key the loader refuses: {present}" + ) + + +def test_at_rest_cipher_row_names_only_real_keys_and_every_switch() -> None: + row = _at_rest_cipher_row() + unknown = _unknown_keys(row) + assert not unknown, ( + f"the at-rest cipher row names a config key no settings model has: {unknown}" + ) + missing = _missing_switches(row) + assert not missing, f"the at-rest cipher row no longer names the setting(s) {missing}" + + +def test_at_rest_cipher_row_cites_gate_symbols_that_exist() -> None: + # Rename guard: the row points readers at these two functions as the gate. + import importlib + + row = _at_rest_cipher_row() + for name, module in _AT_REST_GATE_SYMBOLS: + assert f"`{name}`" in row, f"the at-rest cipher row no longer cites `{name}`" + assert callable(getattr(importlib.import_module(module), name, None)), ( + f"the at-rest cipher row cites `{name}`, which {module} no longer defines" + ) + + +def _load(tmp_path: Path, toml: str) -> ServiceSettings: + from messagefoundry.config.settings import load_settings + + path = tmp_path / "messagefoundry.toml" + path.write_text(toml, encoding="utf-8") + return load_settings(config_path=path, environ={}, default_file=False) + + +def test_the_keyless_rule_the_row_states_holds_in_code(tmp_path: Path) -> None: + # The row's behavioural claims, read from the gate `serve` calls: keyless is refused by default, + # enforce is the shipped default and then needs the second acknowledgment, either [security] + # switch opts out, [store].require_encryption wins over the opt-out, and the [store] spelling of + # the opt-out is refused at load. No key is configured in any of these (environ is empty). + from messagefoundry.__main__ import _keyless_store_gate + from messagefoundry.config.settings import ( + KEYLESS_REFUSED_BY_NO_OPT_OUT, + KEYLESS_REFUSED_BY_NO_STRICT_ACK, + KEYLESS_REFUSED_BY_REQUIRE_ENCRYPTION, + SecurityEnforcement, + ) + + default = _load(tmp_path, "") + assert default.security.enforcement is SecurityEnforcement.ENFORCE + assert _keyless_store_gate(default) == KEYLESS_REFUSED_BY_NO_OPT_OUT + for switch in ("allow_unencrypted_phi = true", "encrypt_stored_data = false"): + assert _keyless_store_gate(_load(tmp_path, f"[security]\n{switch}\n")) == ( + KEYLESS_REFUSED_BY_NO_STRICT_ACK + ), switch + acked = f"[security]\n{switch}\nallow_unencrypted_phi_under_strict_enforcement = true\n" + assert _keyless_store_gate(_load(tmp_path, acked)) is None, switch + forced = f"{acked}[store]\nrequire_encryption = true\n" + assert _keyless_store_gate(_load(tmp_path, forced)) == ( + KEYLESS_REFUSED_BY_REQUIRE_ENCRYPTION + ), switch + with pytest.raises(ValueError, match=r"\[store\]\.allow_unencrypted_phi moved to \[security\]"): + _load(tmp_path, "[store]\nallow_unencrypted_phi = true\n") + + +def test_at_rest_guard_fires_on_the_text_it_replaced() -> None: + # Negative control: each retired or planted phrasing, fed back in, is caught. + for old in _RETIRED_AT_REST_TEXT: + assert _retired_data_class_claims(old) or _unknown_keys(old), ( + f"the at-rest guard misses the retired text {old!r}" + ) + # A row naming only the strict-acknowledgment key does not name the opt-out it extends. + only_strict = "`[security].allow_unencrypted_phi_under_strict_enforcement = true`" + assert "[security].allow_unencrypted_phi" in _missing_switches(only_strict) + + def test_guard_detects_a_removed_provider_row() -> None: # The guard must actually catch a dropped provider row (mirrors # test_secret_rotation_inventory.test_scanner_flags_a_planted_secret) — a real regression can't pass From 7578fe53ab5f337a25f0992a9b89f86cbd4c0f44 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 14:04:08 -0600 Subject: [PATCH 10/26] tests: pin the anchor check's refusal of a PEM block with no data, in each position (BACKLOG #5230) The fix itself landed with BACKLOG #5229 (PR 3301, 15b74a93247): the read-to-end check, _reads_to_the_end, refuses a file whose cadata= load stops early without an error. This adds a test for the block with no data under a CERTIFICATE label (LF and CRLF) and an X509 CRL label, between two certificates, after both and before both, and asserts cafile= refuses each file too. The between and after rows fail against anchor_cadata as it stood before 15b74a93247 (DID NOT RAISE); the before rows were already refused there, by the trial load. The controls: nothing, or a well-formed CRL, between the two certificates loads both by path and through the check. Test only; no product code changes. Proposed PR title: Pin the anchor check's refusal of a PEM block with no data (BACKLOG #5230) Proposed vault banner: ALREADY MET by BACKLOG #5229 (PR 3301, 15b74a93247), which refuses the shape and corrected the CONFIGURATION.md sentence; branch b20053-5230 adds the row's regression test with its controls. Verified-by: tests --- tests/test_trust_anchor_byte_binding.py | 75 +++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/tests/test_trust_anchor_byte_binding.py b/tests/test_trust_anchor_byte_binding.py index ec55dae97c..74d69936aa 100644 --- a/tests/test_trust_anchor_byte_binding.py +++ b/tests/test_trust_anchor_byte_binding.py @@ -838,6 +838,81 @@ def test_a_block_the_load_stops_at_refuses_as_cafile_does( assert anchor_cadata(good.pem, _SPEC) +#: A PEM block with no data, under a label ``cadata=`` reads as a certificate and one it skips, +#: and with CRLF line ends. +_EMPTY_BLOCKS = [ + pytest.param(b"-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----\n", id="certificate"), + pytest.param( + b"-----BEGIN CERTIFICATE-----\r\n-----END CERTIFICATE-----\r\n", id="certificate-crlf" + ), + pytest.param(b"-----BEGIN X509 CRL-----\n-----END X509 CRL-----\n", id="crl"), +] + + +def _well_formed_crl() -> bytes: + """A parseable CRL from a throwaway issuer, for the control: ``cadata=`` skips it.""" + key = ec.generate_private_key(ec.SECP256R1()) + crl = ( + x509.CertificateRevocationListBuilder() + .issuer_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "crl-issuer")])) + .last_update(_NB) + .next_update(_NA) + .sign(key, hashes.SHA256()) + ) + return crl.public_bytes(serialization.Encoding.PEM) + + +@pytest.mark.parametrize("empty", _EMPTY_BLOCKS) +@pytest.mark.parametrize("where", ["between", "after", "before"]) +def test_an_empty_pem_block_refuses_wherever_it_sits( + tmp_path: Path, cas: tuple[_Ca, _Ca], empty: bytes, where: str +) -> None: + """A PEM block with no data, behind at least one certificate, stops the ``cadata=`` load + without an error: between two certificates the second never loads, and the load reports + success. ``cafile=`` refuses the file in every position, and so does the check, naming it. + Behind a certificate the read-to-end check finds the stop + (:func:`~messagefoundry.auth.trust_anchors._reads_to_the_end`, BACKLOG #5229). In front of + every certificate ``cadata=`` itself raises, and the check refuses with OpenSSL's reason. Both + fixture CAs stand for legitimate anchors here. The controls are in the next test.""" + first, second = cas + data = {"between": first.pem + empty + second.pem, "after": first.pem + second.pem + empty} + data["before"] = empty + first.pem + second.pem + anchor = tmp_path / "ca.pem" + anchor.write_bytes(data[where]) + with pytest.raises(ssl.SSLError): + ssl.create_default_context(cafile=str(anchor)) + text = data[where].decode() + if where == "before": + with pytest.raises(ssl.SSLError, match="no start line"): + ssl.create_default_context(cadata=text) + refusal, reason = "cannot load", "no start line" + else: # the gap: no error, and what loaded is all the caller learns + loaded = sorted(_subjects(ssl.create_default_context(cadata=text))) + assert loaded == ([first.name] if where == "between" else sorted([first.name, second.name])) + refusal, reason = "stops reading", "Remove or repair the block" + with pytest.raises(TrustAnchorError, match=refusal) as refused: + anchor_cadata(data[where], _SPEC) + assert refused.value.scope == "unloadable" + assert repr(_SPEC.path) in str(refused.value) + assert reason in str(refused.value) + + +@pytest.mark.parametrize("middle", ["nothing", "a well-formed CRL"]) +def test_two_certificates_load_both_with_no_empty_block_between( + tmp_path: Path, cas: tuple[_Ca, _Ca], middle: str +) -> None: + """The controls for the empty-block refusal above, under the same checks: the two + certificates with nothing between them, or a well-formed CRL, which ``cadata=`` skips, load + both by path, and the check passes them and returns text that loads both.""" + first, second = cas + data = first.pem + (_well_formed_crl() if middle != "nothing" else b"") + second.pem + anchor = tmp_path / "ca.pem" + anchor.write_bytes(data) + both = sorted([first.name, second.name]) + assert sorted(_subjects(ssl.create_default_context(cafile=str(anchor)))) == both + assert sorted(_subjects(ssl.create_default_context(cadata=anchor_cadata(data, _SPEC)))) == both + + def test_a_read_to_end_load_that_raises_refuses_naming_the_error( monkeypatch: pytest.MonkeyPatch, cas: tuple[_Ca, _Ca] ) -> None: From f59362bffc58546f96695b617d15b76dd49bca26 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 14:43:48 -0600 Subject: [PATCH 11/26] docs: make four operator-doc security statements say what the code does (BACKLOG #2734) Doc-only. Each statement was read against the code at engine origin/main 5294970d8b1. - CLOUD-DEPLOYMENT.md, edge relay (items 1 and 2): the relay's outbound to an off-loopback host is refused under the default enforcement unless it runs TLS or carries tls_hop_attested or cleartext_accepted (InsecureHopGuard in transports/mllp.py and transports/tcp.py, decided by insecure_hop_disposition). Tcp() has no TLS. "drains on reconnect, nothing is dropped" now says a row that exhausts RetryPolicy.max_attempts (default 100) is dead-lettered and replayable. - REMOTE-CONSOLE.md (item 5): on a Windows service the bind is the installer's -ListenHost (default 127.0.0.1), registered as serve --host, which overrides [security].listen_address. - AOAG-DEPLOYMENT.md (item 6): install-service.ps1 sets SERVICE_AUTO_START, so the cold DR engine's service must be set to manual start after each install or re-run. The command carries the host circuit breaker. - SECURITY.md (item 7): three links written (#audit), not two, landed on the route-table heading; they now point at #audit-1, the anchor other docs already use for the Audit section. No heading renamed. Items 3 (PHI.md) and 4 (DEPLOYMENT.md container TLS) are already true on main: PHI.md section 1 and its transport table, and the DEPLOYMENT.md container Exposure bullet, state the code's behaviour. Verified-by: tests --- docs/AOAG-DEPLOYMENT.md | 11 +++++++++++ docs/CLOUD-DEPLOYMENT.md | 24 ++++++++++++++++++------ docs/REMOTE-CONSOLE.md | 10 +++++++++- docs/SECURITY.md | 6 +++--- 4 files changed, 41 insertions(+), 10 deletions(-) diff --git a/docs/AOAG-DEPLOYMENT.md b/docs/AOAG-DEPLOYMENT.md index 91d938aa47..850bd175ea 100644 --- a/docs/AOAG-DEPLOYMENT.md +++ b/docs/AOAG-DEPLOYMENT.md @@ -532,6 +532,17 @@ two hospital engines and the DR engine. Give each an **identical config dir** an identical-config check** below (a divergent DR config dead-letters rows on promotion). This cold posture is the deliberate counterpart to the cross-WAN-leadership hazard above; the two hospital engines, both warm and active-eligible, are what actually cover in-hospital engine failover. + **Stopped is not enough: set the DR engine's service to manual start.** `install-service.ps1` + registers every service to start automatically (`SERVICE_AUTO_START`), so a stopped DR engine + starts by itself at its next reboot and joins the lease race. After each install, and after every + re-run of the installer, which sets automatic start again, run this on the DR engine VM, with your + `-ServiceName` if you changed it from the default `MessageFoundry`: + + ```powershell + if ([Environment]::MachineName -ne '') { Write-Host "STOP this must run on , but this is $([Environment]::MachineName); nothing ran" } else { Set-Service -Name MessageFoundry -StartupType Manual; Get-Service -Name MessageFoundry | Select-Object Name, Status, StartType } + ``` + + A manual service still starts on demand, so the §6 runbook's start step is unchanged. - Timing defaults (`[…]` = `[cluster]`, with the invariant `heartbeat < fence < ttl` enforced at config load): `heartbeat_seconds = 10`, `leader_fence_timeout_seconds = 20`, `leader_lease_ttl_seconds = 30`, `node_timeout_seconds = 30`. `[store].pool_size ≥ 2` is diff --git a/docs/CLOUD-DEPLOYMENT.md b/docs/CLOUD-DEPLOYMENT.md index 7f6de189a9..59a3530701 100644 --- a/docs/CLOUD-DEPLOYMENT.md +++ b/docs/CLOUD-DEPLOYMENT.md @@ -325,14 +325,26 @@ MLLP/TCP connectors** verbatim. **Why the staged store is the selling point.** The relay's **at-least-once staged store** ([ADR 0001](adr/0001-staged-pipeline-architecture.md)) is the **WAN buffer**: a WAN blip queues outbound rows in -the relay's durable store and **drains on reconnect** — nothing is dropped (the count-and-log invariant -holds end to end). The same property protects the cloud engine's inbound. This sidesteps the real cloud -objection (a WAN-crossing, TLS-less MLLP feed) **without changing the engine**: +the relay's durable store, and they drain on reconnect while each row still has retry attempts left. +A row that uses them up during a long outage is dead-lettered, not dropped, and an operator replays it, +as the retry-budget paragraph above says. Either way the count-and-log invariant holds end to end. The +same property protects the cloud engine's inbound. This sidesteps the real cloud objection (a +WAN-crossing, TLS-less MLLP feed) **without changing the engine**: - MLLP stays on the **LAN** (loopback-or-segment near the EHR), so it never crosses the WAN in cleartext. -- The relay→cloud hop rides the **private encrypted link** (VPN / Direct Connect / ExpressRoute) — and you - can additionally run the relay's outbound MLLP with `tls=True` (MLLP-over-TLS) for defense in depth. -- A WAN outage is a **buffered queue**, not lost messages. +- The relay→cloud hop rides the **private encrypted link** (VPN / Direct Connect / ExpressRoute). The + engine cannot see that link, so it judges the outbound hop on its own settings. Under the default + `[security].enforcement = enforce`, an outbound to a host off the relay's loopback is refused at + build unless it runs TLS or carries a per-hop declaration, and a refused outbound is recorded failed + while the rest of the graph starts. An outbound `MLLP()` takes `tls=True` (MLLP-over-TLS), and a + TLS hop off loopback must then pass the + [revocation guard](DEPLOYMENT.md#revocation-guard-behavior) too. `Tcp()` has no TLS option, so it needs + [`tls_hop_attested`](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested), with its reason, to + claim the private link secures the hop, or + [`cleartext_accepted`](CONNECTIONS.md#declaring-a-cleartext-hop-cleartext_accepted), which crosses + with a warning and an audit row at every build. +- A WAN outage is a **buffered queue**, not lost messages: what outlasts the retry budget waits in the + dead-letter queue for a replay. The edge relay can be a **single node** (POC/edge SQLite is fine — its job is buffering, and DB-tier HA lives at the cloud engine), or itself an HA pair on-prem if the edge must survive a node loss. Its diff --git a/docs/REMOTE-CONSOLE.md b/docs/REMOTE-CONSOLE.md index 5e8febd120..fbaaca087a 100644 --- a/docs/REMOTE-CONSOLE.md +++ b/docs/REMOTE-CONSOLE.md @@ -32,6 +32,14 @@ configure TLS. (`[api].host` was the old spelling; [ADR 0118](adr/0118-secure-by-default-security-configuration-section.md) moved the bind/console/origin switches to `[security]` and setting them in `[api]` is now **refused at config load**.) +**On a Windows service, the bind address is the installer's `-ListenHost`, not `listen_address`.** +`install-service.ps1` registers the service with `serve --host `, and `-ListenHost` +defaults to `127.0.0.1`. `serve --host` overrides `[security].local_access_only` and +`listen_address`, so on a service a `listen_address` in the TOML changes nothing. Re-run the +installer with the arguments you installed with, plus `-ListenHost` set to the bind address, such as +`-ListenHost 10.0.0.12`; it reconfigures the existing service ([`SERVICE.md`](SERVICE.md#install)). The engine still reports an off-box `--host` +as a posture loosening, and every TLS rule below applies to it as it does to `listen_address`. + ### How hard is the TLS requirement? **For the browser console, absolute.** An off-loopback `/ui` bind without an operator certificate is refused at @@ -369,7 +377,7 @@ mTLS here is **transport authentication only** unless you also populate | Engine won't start: `refusing to serve a PLAINTEXT proxy-to-engine hop on the non-loopback API bind host …` | Option B with no `tls_cert_file` on a bind that is not loopback. The refusal names both ways out; [SECURITY.md, Plaintext proxy hop](SECURITY.md#plaintext-proxy-hop) explains them. | | Engine won't start: `refusing to serve the browser ops dashboard … without an operator certificate` | An off-loopback `/ui` bind without one. The engine would still encrypt the hop on its generated self-signed placeholder, but no trust store vouches for that certificate, so the browser surface refuses it. Configure `tls_cert_file` (Option A), or Option B with the engine kept on loopback behind a proxy on the same machine. `--allow-insecure-bind` does **not** cover `/ui`. | | Engine won't start: `…serve_web_console=true needs the web console package` | Install `messagefoundry-webconsole` (or set `serve_web_console = false` for a JSON-only engine). | -| Engine won't start: `refusing to serve … on non-loopback host` | An off-loopback `[security].listen_address` without an operator certificate on the JSON API. The engine would serve the placeholder there too, and refuses it for the same reason. Same fix as above. | +| Engine won't start: `refusing to serve … on non-loopback host` | An off-loopback bind (`[security].listen_address`, or on a service the installer's `-ListenHost`) without an operator certificate on the JSON API. The engine would serve the placeholder there too, and refuses it for the same reason. Same fix as above. | | Engine won't start: `refusing to serve the API with in-process TLS on non-loopback host … performs NO certificate revocation check` | The [API revocation gate](SECURITY.md#api-revocation-gate). Set `MEFOR_TLS_REVOCATION_ATTESTED=1` in the **service environment** (not the TOML), or move to Option B with the engine on loopback and let the proxy do revocation. | | Engine won't start: `refusing to serve on a … PHI instance … behind an upstream TLS terminator … without: [api].proxy_intra_service_auth …` | The Posture-B attestation gate on Option B. Declare **both** `[api].proxy_intra_service_auth` (`mtls`/`network`/`shared_secret`) and `[api].proxy_tls_min_version` (`1.2`/`1.3`) — see Option B's block. It fires on a PHI instance under `enforcement = enforce` with an off-loopback bind; the loopback-behind-a-proxy variant warns instead. | | Signed in, but every route returns `403` with `X-MFA-Required: 1` | `[security].require_mfa` is on (the default) and this account hasn't enrolled a factor. Enrol a factor at `/ui/account`: TOTP first, or a passkey the browser stores as discoverable. A local account the requirement covers cannot change its password until it holds one of those: the engine answers `enrol an authenticator app first`. A directory account may enrol either ([the order](SECURITY.md#webauthn-passkeys-wp-14b-adr-0068)). Until then, the console answers most pages with a redirect, usually to `/ui/mfa`. That page sends an account with no factor on to `/ui/account` to enrol. The account and enrolment pages serve the session meanwhile. | diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 5080ef82cf..570b4054f8 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -923,7 +923,7 @@ below that, at 1 s, because M is an average and some people are faster. The comm the `auth.login_success` or `auth.reauth` row when it is served, and its refusal row when it is refused (BACKLOG #3220, #3728). That includes a directory lock refusal: that row has its own action, `auth.directory_login_locked`, which the audit read routes show only to `users:manage` - ([Audit](#audit) names them), so the marker shows a reader without it no lock there (BACKLOG + ([Audit](#audit-1) names them), so the marker shows a reader without it no lock there (BACKLOG #3726). The other rows the attempt writes, such as a role resync or a session rotation, do not carry it. With the list set, a too-early step-up's code is redeemed before the refusal, because only the exchange yields the `amr`. The outcome rows of such a step-up carry @@ -5343,7 +5343,7 @@ slack. | Client-address monoculture | the set of distinct observed client addresses | allow-list in use **and** no trusted proxy declared **and** ≥ 50 observations **and** all resolved to the same loopback address | **LOG** — one-shot WARNING + `client_address_monoculture` on `GET /security/posture` | n/a | (derived; no knob) | | Login attempt rate, per client IP **and** globally | `api.security.client_ip`, which returns the ASGI `scope["client"][0]` the *Client source network* row evaluates; an attempt with no address is counted under the literal `"unknown"` | > 10 attempts per IP (`login_rate_limit_per_ip`), or > 60 across all clients (`login_rate_limit_global`), in a rolling 60 s window (`login_rate_limit_window_seconds`); a refused attempt is not itself counted. How a paid passkey sign-in `POST /ui/login` is counted is stated once, under [WebAuthn passkeys](#webauthn-passkeys-wp-14b-adr-0068), *The combined passkey sign-in* | **THROTTLE** — 429 `too many attempts` with **no** `Retry-After` on the three JSON routes; 429 + a `Retry-After` of the whole sign-in window on `POST /ui/login` and on `POST /ui/login/passkey`, the passkey sign-in's begin leg; a **303** redirect to `/ui/login?e=rate_limited` (no 429, no `Retry-After`) on `GET /ui/sso`, `POST /ui/oidc/start` and `GET /ui/oidc/callback` (a sign-in return; a step-up return draws the ceremony budget, BACKLOG #3374), and on `GET /ui/oidc/start` only when its interstitial is skipped (see the [Route → limiter map](#route--limiter-map)). WARNING-logged, deliberately **not** audited | on, 10 / 60 / 60 s | `[auth].login_rate_limit_enabled` | | Credential-ceremony rate, per **actor** | `identity.user_id` (**not** an IP); on an IdP step-up's return, which has no session, the user id its staged flow names | > `login_rate_limit_per_ip` (10) ceremonies per actor per 60 s, on each of the actor's keys (the *Credential ceremonies* row of [Business-logic limits](#business-logic-limits-asvs-213) names them); **no** global dimension (`glob=0`, deliberately) | **THROTTLE** 429, logged | on with the row above | *gated by the same* `[auth].login_rate_limit_enabled` | -| Consecutive credential failures on one account | the account's two failure counters (ADR 0197): the **sign-in** counter and the **second-step** counter | ≥ 5 consecutive failures on one counter locks for 15 minutes, with one exception: while the credential in force is engine-generated (set by an administrator's account creation, `POST /users`, and by both resets), sign-in failures are counted and audited but arm no sign-in lock (`lockout_arms`, ADR 0197 Amendment A); a lapsed window restarts the counter; the second-step lock on a local account, and the sign-in lock on a local account holding a discoverable passkey under the configured relying party (BACKLOG #3937), and the sign-in lock on a local account with a TOTP enrolled, unless the engine KNOWS this release refuses that enrolment (at least a marker it refuses, a key under 160 bits, BACKLOG #5340, or no secret; a TOTP it cannot judge still escalates, and a known-refused one escalates too in the races listed under [WebAuthn passkeys](#webauthn-passkeys-wp-14b-adr-0068), BACKLOG #3422), double per cycle up to 24 hours | **DENY** before any verify on the password and second-factor legs, plus an audit row whose name is leg-specific — on the password path the uniform `auth.login_failed` (`bad_credentials`) row every refused sign-in that reaches the engine writes and then `auth.login_locked`, which only `users:manage` reads ([Audit](#audit)), `auth.mfa_failed` / `auth.webauthn_failed` with `reason=locked` on at least the TOTP/recovery and assertion legs, and on a directory account's two enrolment legs (the sign-in password path still runs a dummy argon2 verify to keep timing flat). The second-step lock refuses every one of those legs. The sign-in lock has **two** exceptions: it does **not** refuse a combined sign-in, either the password and a TOTP code in one request on a local account with TOTP enrolled, or the password and a passkey assertion in one request on a local account holding a discoverable passkey under the request's relying party ([WebAuthn passkeys](#webauthn-passkeys-wp-14b-adr-0068), ADR 0197 Amendment A wave 2); and it refuses **no** second-factor leg. The Kerberos and OIDC sign-ins also refuse a row under either lock, but only **after** the ticket or token has verified, audited `auth.directory_login_locked` with `reason=locked` (`_directory_login_refusal`, BACKLOG #1638, its own action since #3726); neither leg feeds the counter. The password legs of the post-session re-proofs, `POST /me/reauth` and `POST /me/password` and their console twins `POST /ui/reauth` and `POST /ui/account/password`, **feed** the sign-in counter but are **not** refused by either lock; the IdP step-up of an `oidc` session checks no engine credential and feeds neither counter; each **session** may fail `lockout_threshold` re-proofs (5 by default), and the failure that reaches it revokes that session, audited as `auth.reauth` with `session_revoked=true` or `auth.password_change_failed` with `reason=session_revoked`. A password or code the console refuses at the JSON models' length bounds, at least at `POST /ui/reauth`, `POST /ui/mfa` and the TOTP enrolment confirm `POST /ui/account/mfa/verify`, reaches the service on no leg, so it is not audited and feeds neither counter nor the session's re-proof count, as the JSON route's 422 feeds none (BACKLOG #5398, #5399). Each of those routes measures its code with surrounding space stripped, by length only, and sends that stripped code, so a correct code padded with space still reaches the service | 5 / 15 min | `[auth].lockout_threshold`, `lockout_minutes`, `lockout_max_minutes` | +| Consecutive credential failures on one account | the account's two failure counters (ADR 0197): the **sign-in** counter and the **second-step** counter | ≥ 5 consecutive failures on one counter locks for 15 minutes, with one exception: while the credential in force is engine-generated (set by an administrator's account creation, `POST /users`, and by both resets), sign-in failures are counted and audited but arm no sign-in lock (`lockout_arms`, ADR 0197 Amendment A); a lapsed window restarts the counter; the second-step lock on a local account, and the sign-in lock on a local account holding a discoverable passkey under the configured relying party (BACKLOG #3937), and the sign-in lock on a local account with a TOTP enrolled, unless the engine KNOWS this release refuses that enrolment (at least a marker it refuses, a key under 160 bits, BACKLOG #5340, or no secret; a TOTP it cannot judge still escalates, and a known-refused one escalates too in the races listed under [WebAuthn passkeys](#webauthn-passkeys-wp-14b-adr-0068), BACKLOG #3422), double per cycle up to 24 hours | **DENY** before any verify on the password and second-factor legs, plus an audit row whose name is leg-specific — on the password path the uniform `auth.login_failed` (`bad_credentials`) row every refused sign-in that reaches the engine writes and then `auth.login_locked`, which only `users:manage` reads ([Audit](#audit-1)), `auth.mfa_failed` / `auth.webauthn_failed` with `reason=locked` on at least the TOTP/recovery and assertion legs, and on a directory account's two enrolment legs (the sign-in password path still runs a dummy argon2 verify to keep timing flat). The second-step lock refuses every one of those legs. The sign-in lock has **two** exceptions: it does **not** refuse a combined sign-in, either the password and a TOTP code in one request on a local account with TOTP enrolled, or the password and a passkey assertion in one request on a local account holding a discoverable passkey under the request's relying party ([WebAuthn passkeys](#webauthn-passkeys-wp-14b-adr-0068), ADR 0197 Amendment A wave 2); and it refuses **no** second-factor leg. The Kerberos and OIDC sign-ins also refuse a row under either lock, but only **after** the ticket or token has verified, audited `auth.directory_login_locked` with `reason=locked` (`_directory_login_refusal`, BACKLOG #1638, its own action since #3726); neither leg feeds the counter. The password legs of the post-session re-proofs, `POST /me/reauth` and `POST /me/password` and their console twins `POST /ui/reauth` and `POST /ui/account/password`, **feed** the sign-in counter but are **not** refused by either lock; the IdP step-up of an `oidc` session checks no engine credential and feeds neither counter; each **session** may fail `lockout_threshold` re-proofs (5 by default), and the failure that reaches it revokes that session, audited as `auth.reauth` with `session_revoked=true` or `auth.password_change_failed` with `reason=session_revoked`. A password or code the console refuses at the JSON models' length bounds, at least at `POST /ui/reauth`, `POST /ui/mfa` and the TOTP enrolment confirm `POST /ui/account/mfa/verify`, reaches the service on no leg, so it is not audited and feeds neither counter nor the session's re-proof count, as the JSON route's 422 feeds none (BACKLOG #5398, #5399). Each of those routes measures its code with surrounding space stripped, by length only, and sends that stripped code, so a correct code padded with space still reaches the service | 5 / 15 min | `[auth].lockout_threshold`, `lockout_minutes`, `lockout_max_minutes` | | New client IP during a session | this request's address vs `session.client` | knob on **and** a session exists, is unrevoked, has an anchor, and the two are not the same host (as [Administrative-interface defense-in-depth](#administrative-interface-defense-in-depth-wp-l3-13-asvs-842) defines it) | **CHALLENGE** — force a fresh step-up on a step-up route, a PHI read (`require_phi_read`, a monitoring `reveal`, the console's `phi=True` pages) or a paced write (`require_paced`, the console's writes), since vault BACKLOG #2620 for the last two; the base gate (`require`) and `require_monitoring_read` never ask, so the JSON monitoring polls are not refused. A first sighting also writes `auth.new_address_reverify_required` + an out-of-band notice, debounced and capped per session as that section states; repeats WARNING-log only. **Never** an RBAC deny | **on**; `false` is a named loosening | `[auth].admin_new_ip_step_up` | | First-seen sign-in address — sign-in owes no second factor (local leg) | the sign-in's client address vs the account's known-address record (the `known_login_addresses` table, vault BACKLOG #2145): one row per host from which the account finished a sign-in, passed a step-up, or confirmed a factor enrolment, keyed on the account id and deleted with the account. An administrator's password reset or MFA reset, or a `provision-admin` takeover, deletes every address in it (vault BACKLOG #2946, #3849). In the same transaction it writes one marker row stamped at the epoch. No lookback read returns that row, it still counts as a row of any age, and no prune deletes it. Revoking every session clears nothing. These events write a row: a local sign-in that owed no factor, from a known address or with no baseline yet; a directory sign-in that owes nothing more, whatever the verdict except a failed read, so a first-seen address and an account's first sign-in both write (no directory session is seeded, so there is no challenge to skip); a combined sign-in; a second factor proved (a TOTP or recovery code at the MFA gate, or a passkey assertion), whether it finishes a sign-in or is a step-up on a session that has already met its factor; a factor enrolment confirmed, TOTP or passkey, first or later, from a known address or by an account with no baseline yet (not from a first-seen address, because a holder of the password alone may enrol an authenticator, ADR 0197 Amendment A; this only delays such a holder until a code from that authenticator is proved, and the enrolment sends its own notice); and a step-up, by password or at the IdP, by an account that owes no second factor. That test is asked of the account, not of this session. Under `require_mfa` every directory account owes a factor, so no directory step-up by password or at the IdP writes, even one that re-proved the MFA claim. At the sign-in itself a failed record read writes nothing, on either leg. A combined sign-in is the exception, because it proved its second factor from that address. A factor proved afterwards still writes. Nothing is written for a request with no client address. A host compares as one key: an IPv4-mapped form is its IPv4 address, and every loopback form is one host. Only a row seen within the lookback (`_LOGIN_ADDRESS_LOOKBACK_SECONDS` in `auth/service.py`, 90 days) counts as a match, and each write prunes the account's older rows. The no-baseline test reads rows of any age, so an account whose only row came from an enrolment and has aged out is still judged, not failed open. Read through the record's primary key at session mint on the local, Kerberos and OIDC legs, after the first credential verified | no known address seen within the lookback is the same host **and** the account has a baseline: it has finished a sign-in before, or holds a row of any age. With neither, no client address, or a failed read, the signal fails open and writes `auth.login_address_unevaluated` with `reason` `no_baseline`, `unknown_address` or `read_failed` | **CHALLENGE** — `auth.login_new_ip` + an out-of-band `login_new_ip` notice (at most one per account and address per 15 minutes; the audit row is written every time), and the session is minted **without** step-up freshness (`seed_reauth=False`), except a combined sign-in (password and a TOTP code or a passkey assertion in one request, under the conditions of [Step-up re-verification](#step-up-re-verification-on-sensitive-operations-wp-l3-16-asvs-753); ADR 0197 and its Amendment A), which proved the second factor in the same request and is seeded as `verify_mfa` seeds it. **Never** refuses the login. The challenged sign-in does not make its address known, so a second sign-in from it is challenged again; a step-up from that address passes the challenge and records it (vault BACKLOG #2145) | on | (no knob) | | First-seen sign-in address — sign-in owes a second factor, or any directory sign-in | as the row above | as the row above | **LOG** — the same audit row and notice. A directory sign-in that owes nothing more also records the address, so the next one from it is not reported again; nothing else changes. **Under the shipped `require_mfa` a Kerberos sign-in always owes a factor**, and so does an OIDC one while `oidc_require_mfa_claim` is off. Such a sign-in records nothing; the factor leg that finishes it records the address instead: a TOTP or recovery code, a passkey, or a factor enrolment, under the conditions in the row above. So on this leg, as on the local one, every sign-in is unjudged (`no_baseline`) until one finishes, and a sign-in abandoned at the factor prompt records nothing. Under the same default no directory step-up records an address (see the row above). Such a session is born without step-up freshness anyway. [Step-up re-verification](#step-up-re-verification-on-sensitive-operations-wp-l3-16-asvs-753) says what stamps a window, and what an action-bound route still asks inside one. CORRECTED 2026-11-26 (vault BACKLOG #2964 item 28): this named a user-verified passkey with no condition; the list is replaced by the pointer. A Kerberos or password session steps up with the account password; an `oidc` session steps up at the IdP. Under the shipped `require_mfa` scope (`every_local_account`) this is the path every password-only local sign-in takes. A combined sign-in (password and a TOTP code or a passkey assertion in one request) owes nothing more, so it takes the row above instead and is seeded from any address. **Never** refuses the login (BACKLOG #288) | on | (no knob) | @@ -7715,7 +7715,7 @@ changed is what a campaign costs, and whom: `lockout_threshold` times locks it only when the password was right. The rows that lock leaves are now read only with `users:manage`, and a sign-in refused by a live lock writes the same `auth.login_failed` row as a wrong credential. So a reader without `users:manage` sees one - identical row per refused attempt, whichever candidate it sent; see [Audit](#audit) for which rows + identical row per refused attempt, whichever candidate it sent; see [Audit](#audit-1) for which rows are hidden and from whom. - **A local account with a discoverable passkey** (ADR 0197 Amendment A, wave 2). The owner signs in with the password and a passkey assertion in one request, through a usernameless ceremony, From 4c8ce9a9de2890bc55d1b840120d8d383b41179c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 14:58:05 -0600 Subject: [PATCH 12/26] docs: repair the operator-doc fixes after review round one (BACKLOG #2734) Doc-only. Round-one findings applied: - CLOUD-DEPLOYMENT.md: stop restating the cleartext-hop rules and link to their one statement; drop the false "audit row" for cleartext_accepted (it is a WARNING log line); stop calling Direct Connect and ExpressRoute encrypted, and say tls_hop_attested fits only a link that encrypts the whole hop; name the [egress] allow-list; say a dead-lettered row is replayable until [retention].dead_letter_days purges its body; say the relay's inbound listener meets the bind guard. - REMOTE-CONSOLE.md: the service's --host and --port both override the TOML; drop "changes nothing" (a contradictory listen_address still refuses at load); a re-run leaves the service stopped. - AOAG-DEPLOYMENT.md: match the service by exact name with -InputObject, as the installer does; drop "joins the lease race" (promotable = false stops that); set Automatic while the DR engine carries traffic, and Manual again at failback. Net prose lines: +7. Verified-by: tests --- docs/AOAG-DEPLOYMENT.md | 14 +++++++++----- docs/CLOUD-DEPLOYMENT.md | 40 +++++++++++++++++++++------------------- docs/REMOTE-CONSOLE.md | 15 ++++++++------- 3 files changed, 38 insertions(+), 31 deletions(-) diff --git a/docs/AOAG-DEPLOYMENT.md b/docs/AOAG-DEPLOYMENT.md index 850bd175ea..d4f65c3e5a 100644 --- a/docs/AOAG-DEPLOYMENT.md +++ b/docs/AOAG-DEPLOYMENT.md @@ -534,15 +534,19 @@ two hospital engines and the DR engine. Give each an **identical config dir** an engines, both warm and active-eligible, are what actually cover in-hospital engine failover. **Stopped is not enough: set the DR engine's service to manual start.** `install-service.ps1` registers every service to start automatically (`SERVICE_AUTO_START`), so a stopped DR engine - starts by itself at its next reboot and joins the lease race. After each install, and after every - re-run of the installer, which sets automatic start again, run this on the DR engine VM, with your - `-ServiceName` if you changed it from the default `MessageFoundry`: + starts by itself at its next reboot, against the cold posture. After each install, and after every + re-run of the installer, which sets automatic start again, run this on the DR engine VM. It matches + the service by its exact name, as the installer does, because `-Name` also matches a display name; + put your `-ServiceName` in `$n` if you changed it from the default `MessageFoundry`: ```powershell - if ([Environment]::MachineName -ne '') { Write-Host "STOP this must run on , but this is $([Environment]::MachineName); nothing ran" } else { Set-Service -Name MessageFoundry -StartupType Manual; Get-Service -Name MessageFoundry | Select-Object Name, Status, StartType } + if ([Environment]::MachineName -ne '') { Write-Host "STOP this must run on , but this is $([Environment]::MachineName); nothing ran" } else { $n = 'MessageFoundry'; $svc = Get-Service | Where-Object { $_.Name -eq $n }; if (-not $svc) { Write-Host "STOP no service is named $n here; nothing changed" } else { Set-Service -InputObject $svc -StartupType Manual; Get-Service | Where-Object { $_.Name -eq $n } | Select-Object Name, Status, StartType } } ``` - A manual service still starts on demand, so the §6 runbook's start step is unchanged. + A manual service still starts on demand, so the §6 runbook's start step works as written. While a + §6 activation has the DR engine carrying the traffic, a manual start type means a reboot of its VM + leaves no engine running: run the same line with `-StartupType Automatic` once it is up, and with + `Manual` again at failback. - Timing defaults (`[…]` = `[cluster]`, with the invariant `heartbeat < fence < ttl` enforced at config load): `heartbeat_seconds = 10`, `leader_fence_timeout_seconds = 20`, `leader_lease_ttl_seconds = 30`, `node_timeout_seconds = 30`. `[store].pool_size ≥ 2` is diff --git a/docs/CLOUD-DEPLOYMENT.md b/docs/CLOUD-DEPLOYMENT.md index 59a3530701..27027daa74 100644 --- a/docs/CLOUD-DEPLOYMENT.md +++ b/docs/CLOUD-DEPLOYMENT.md @@ -326,25 +326,27 @@ MLLP/TCP connectors** verbatim. **Why the staged store is the selling point.** The relay's **at-least-once staged store** ([ADR 0001](adr/0001-staged-pipeline-architecture.md)) is the **WAN buffer**: a WAN blip queues outbound rows in the relay's durable store, and they drain on reconnect while each row still has retry attempts left. -A row that uses them up during a long outage is dead-lettered, not dropped, and an operator replays it, -as the retry-budget paragraph above says. Either way the count-and-log invariant holds end to end. The -same property protects the cloud engine's inbound. This sidesteps the real cloud objection (a -WAN-crossing, TLS-less MLLP feed) **without changing the engine**: - -- MLLP stays on the **LAN** (loopback-or-segment near the EHR), so it never crosses the WAN in cleartext. -- The relay→cloud hop rides the **private encrypted link** (VPN / Direct Connect / ExpressRoute). The - engine cannot see that link, so it judges the outbound hop on its own settings. Under the default - `[security].enforcement = enforce`, an outbound to a host off the relay's loopback is refused at - build unless it runs TLS or carries a per-hop declaration, and a refused outbound is recorded failed - while the rest of the graph starts. An outbound `MLLP()` takes `tls=True` (MLLP-over-TLS), and a - TLS hop off loopback must then pass the - [revocation guard](DEPLOYMENT.md#revocation-guard-behavior) too. `Tcp()` has no TLS option, so it needs - [`tls_hop_attested`](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested), with its reason, to - claim the private link secures the hop, or - [`cleartext_accepted`](CONNECTIONS.md#declaring-a-cleartext-hop-cleartext_accepted), which crosses - with a warning and an audit row at every build. -- A WAN outage is a **buffered queue**, not lost messages: what outlasts the retry budget waits in the - dead-letter queue for a replay. +A row that uses them up during a long outage is dead-lettered, not dropped, and an operator can replay +it, as the retry-budget paragraph above says, until `[retention].dead_letter_days` purges its body. +Either way the count-and-log invariant holds end to end. The same property protects the cloud +engine's inbound. This sidesteps the real cloud objection (a WAN-crossing, TLS-less MLLP feed) +**without changing the engine**: + +- MLLP stays on the **LAN** (loopback-or-segment near the EHR), so it never crosses the WAN in + cleartext. The relay's inbound listener, bound off loopback so the EHR can reach it, meets the + bind guard like any other listener. +- The relay→cloud hop rides a **private link** (VPN / Direct Connect / ExpressRoute). The engine + cannot see that link, so it judges the outbound hop on the outbound's own settings, and a hop with + no TLS to a host off the relay is refused under the default enforcement. + [`DEPLOYMENT.md`](DEPLOYMENT.md#channel--tls-posture-matrix) and + [`CONNECTIONS.md`](CONNECTIONS.md#declaring-a-cleartext-hop-cleartext_accepted) state that rule + once. In short: an outbound `MLLP()` can take `tls=True`; `Tcp()` has no TLS option, so it crosses + only on a per-hop declaration. + [`tls_hop_attested`](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested) fits only a link that + encrypts the whole hop. Direct Connect and ExpressRoute do not encrypt by themselves, so over + either without an encrypting layer the honest declaration is `cleartext_accepted`. The cloud host + must also be on the [`[egress]`](CONFIGURATION.md#egress) allow-list. +- A WAN outage is a **buffered queue**, not lost messages, within the bounds above. The edge relay can be a **single node** (POC/edge SQLite is fine — its job is buffering, and DB-tier HA lives at the cloud engine), or itself an HA pair on-prem if the edge must survive a node loss. Its diff --git a/docs/REMOTE-CONSOLE.md b/docs/REMOTE-CONSOLE.md index fbaaca087a..f4437a35a5 100644 --- a/docs/REMOTE-CONSOLE.md +++ b/docs/REMOTE-CONSOLE.md @@ -32,13 +32,14 @@ configure TLS. (`[api].host` was the old spelling; [ADR 0118](adr/0118-secure-by-default-security-configuration-section.md) moved the bind/console/origin switches to `[security]` and setting them in `[api]` is now **refused at config load**.) -**On a Windows service, the bind address is the installer's `-ListenHost`, not `listen_address`.** -`install-service.ps1` registers the service with `serve --host `, and `-ListenHost` -defaults to `127.0.0.1`. `serve --host` overrides `[security].local_access_only` and -`listen_address`, so on a service a `listen_address` in the TOML changes nothing. Re-run the -installer with the arguments you installed with, plus `-ListenHost` set to the bind address, such as -`-ListenHost 10.0.0.12`; it reconfigures the existing service ([`SERVICE.md`](SERVICE.md#install)). The engine still reports an off-box `--host` -as a posture loosening, and every TLS rule below applies to it as it does to `listen_address`. +**On a Windows service, the address and port it binds are the installer's `-ListenHost` and +`-Port`.** `install-service.ps1` registers the service with `serve --host --port +`, defaults `127.0.0.1` and `8765`, and those flags override `[security].listen_address` and +`[api].port`, so editing the TOML does not move the bind. Re-run `install-service.ps1` with the +arguments you installed with, plus `-ListenHost` set to the bind address, such as +`-ListenHost 10.0.0.12` ([`SERVICE.md`](SERVICE.md#install)). The re-run stops the service and +does not start it again, so start it afterwards. Every TLS rule below applies to an off-box +`--host` as it does to `listen_address`. ### How hard is the TLS requirement? From 2cfbe6631092565aae5269101c4af90cca694f13 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 15:09:16 -0600 Subject: [PATCH 13/26] docs: hand-over record for the operator-doc corrections (BACKLOG #2734) Empty commit. It carries the hand-over the two commits before it lack. Proposed PR title: docs: correct four operator-doc security statements to match the code (BACKLOG #2734) Proposed vault banner: PARTIAL -- doc-only. Items 1, 2, 5, 6 and 7 corrected on branch b20053-2734r: the relay hop needs TLS or a per-hop declaration and the egress allow-list (CLOUD-DEPLOYMENT.md); a long outage dead-letters rows, replayable until dead_letter_days purges them; a Windows service binds the installer's -ListenHost and -Port (REMOTE-CONSOLE.md); the DR engine's service is set to manual start (AOAG-DEPLOYMENT.md); three, not two, (#audit) links in SECURITY.md now point at #audit-1. Items 3 and 4 were already true on main (PHI.md section 1 and transport table; DEPLOYMENT.md container Exposure bullet). Review round two's findings ship open and are listed in the PR body. Closing step 3's installer start-mode switch is not built. Verified-by: none From 275bbdc4d491747c8789f7f250c982cffad66eea Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 15:21:07 -0600 Subject: [PATCH 14/26] docs: repair round three of the operator-doc corrections (BACKLOG #2734) A third repair round past the usual two, under decision d20261201T211301968-bfe13e. Doc-only; each statement checked against engine origin/main code first. CLOUD-DEPLOYMENT.md, edge relay: restore that an off-box tls=True MLLP outbound must also pass the revocation guard; say the on-box carve-out is the relay's loopback only (is_loopback_hop_host), so its LAN address is off-box; drop the bullet's restatement of the linked hop rule; state the site-to-site VPN case as the engine judges it; give the inbound bind guard's outcome and what crosses it; note an outbound's own dead_letter_days overrides the global key; and make the Mermaid node and the "never crosses the WAN in cleartext" lines agree with the cleartext_accepted and tls_hop_attested guidance. CLOUD-PHI-HIPAA.md: "private encrypted link" and the TLS-in-transit checklist line were false against main; corrected. AOAG-DEPLOYMENT.md: promotable = false at the activation step; Manual does not stop a DR engine failback restarts; other start paths start it; the installer re-arms automatic start on every run. REMOTE-CONSOLE.md: restart and confirm the bind after a re-run, since the installer only warns when its stop times out. Proposed PR title: docs: correct four operator-doc security statements to match the code (BACKLOG #2734) Proposed vault banner: PARTIAL -- doc-only. Items 1, 2, 5, 6 and 7 corrected on branch b20053-2734s (three repair rounds): the relay hop needs TLS, which then meets the revocation guard, or a per-hop declaration, plus the egress allow-list (CLOUD-DEPLOYMENT.md, CLOUD-PHI-HIPAA.md); a long outage dead-letters rows, replayable until the dead-letter window purges them; a Windows service binds the installer's -ListenHost and -Port (REMOTE-CONSOLE.md); the DR engine's service is set to manual start, and what that does and does not stop (AOAG-DEPLOYMENT.md); three (#audit) links in SECURITY.md now point at #audit-1. Items 3 and 4 were already true on main. The installer start-mode switch is not built. Verified-by: tests --- docs/AOAG-DEPLOYMENT.md | 25 ++++++++++++++++-------- docs/CLOUD-DEPLOYMENT.md | 42 +++++++++++++++++++++++++--------------- docs/CLOUD-PHI-HIPAA.md | 10 ++++++---- docs/REMOTE-CONSOLE.md | 4 +++- 4 files changed, 52 insertions(+), 29 deletions(-) diff --git a/docs/AOAG-DEPLOYMENT.md b/docs/AOAG-DEPLOYMENT.md index d4f65c3e5a..d6e030044c 100644 --- a/docs/AOAG-DEPLOYMENT.md +++ b/docs/AOAG-DEPLOYMENT.md @@ -533,9 +533,10 @@ two hospital engines and the DR engine. Give each an **identical config dir** an posture is the deliberate counterpart to the cross-WAN-leadership hazard above; the two hospital engines, both warm and active-eligible, are what actually cover in-hospital engine failover. **Stopped is not enough: set the DR engine's service to manual start.** `install-service.ps1` - registers every service to start automatically (`SERVICE_AUTO_START`), so a stopped DR engine - starts by itself at its next reboot, against the cold posture. After each install, and after every - re-run of the installer, which sets automatic start again, run this on the DR engine VM. It matches + sets the service to start automatically (`SERVICE_AUTO_START`) on every run, a re-run over an + existing service included, so a stopped DR engine starts by itself at its next reboot, against the + cold posture. A manual start type lasts only until the installer's next run, so set it again after + every run of the installer: run this on the DR engine VM. It matches the service by its exact name, as the installer does, because `-Name` also matches a display name; put your `-ServiceName` in `$n` if you changed it from the default `MessageFoundry`: @@ -543,10 +544,15 @@ two hospital engines and the DR engine. Give each an **identical config dir** an if ([Environment]::MachineName -ne '') { Write-Host "STOP this must run on , but this is $([Environment]::MachineName); nothing ran" } else { $n = 'MessageFoundry'; $svc = Get-Service | Where-Object { $_.Name -eq $n }; if (-not $svc) { Write-Host "STOP no service is named $n here; nothing changed" } else { Set-Service -InputObject $svc -StartupType Manual; Get-Service | Where-Object { $_.Name -eq $n } | Select-Object Name, Status, StartType } } ``` - A manual service still starts on demand, so the §6 runbook's start step works as written. While a - §6 activation has the DR engine carrying the traffic, a manual start type means a reboot of its VM - leaves no engine running: run the same line with `-StartupType Automatic` once it is up, and with - `Manual` again at failback. + A manual start type stops only the start at boot. A manual service still starts on demand, so the + §6 runbook's start step starts it, and so do at least these: the `Restart-Service` and + `Start-Service` lines in [SERVICE.md](SERVICE.md), the `Start-Service` line the installer prints + as its next step, and the restart after a re-run of the installer in + [REMOTE-CONSOLE.md](REMOTE-CONSOLE.md). While a §6 activation has the DR engine carrying the + traffic, a manual start type means a reboot of its VM leaves no engine running: run the same line + with `-StartupType Automatic` once it is up, and with `Manual` again at failback. Setting `Manual` + does not stop the service: failback's engine-side step 2 restarts the DR engine, and it runs on + after that until it is stopped. - Timing defaults (`[…]` = `[cluster]`, with the invariant `heartbeat < fence < ttl` enforced at config load): `heartbeat_seconds = 10`, `leader_fence_timeout_seconds = 20`, `leader_lease_ttl_seconds = 30`, `node_timeout_seconds = 30`. `[store].pool_size ≥ 2` is @@ -723,7 +729,10 @@ Document which pattern you chose; the §6 runbook's sender-repoint step executes *not* already competing for the lease — **start its NSSM service now**, after (a) confirming the listener resolves to the DR subnet (step 4) and (b) running the **identical-config check** (§5.1) so promotion does not dead-letter rows. On start it acquires the lease within ≈ one heartbeat and - on-promotion `reset_stale_inflight` re-pends in-flight rows. Repoint senders per the §5.4 pattern: + on-promotion `reset_stale_inflight` re-pends in-flight rows. That holds only for a promotable + node: a DR engine set `[cluster].promotable = false` (§5.1) never acquires or renews the lease, + so this start leaves it a non-leader and, with the hospital engines down, the cluster with no + leader. Repoint senders per the §5.4 pattern: a global LB / GSLB follows automatically via the health check *once the service is up*; per-DC VIPs execute the sender cutover list; with RHI, **advertise the DR /32** now. 6. **Verify the hospital-side /32 was withdrawn.** If the hospital site advertised the MLLP VIP as a diff --git a/docs/CLOUD-DEPLOYMENT.md b/docs/CLOUD-DEPLOYMENT.md index 27027daa74..a6a97e5fff 100644 --- a/docs/CLOUD-DEPLOYMENT.md +++ b/docs/CLOUD-DEPLOYMENT.md @@ -284,7 +284,7 @@ flowchart TB end end - WAN_LINK["Private encrypted link
site-to-site VPN, AWS Direct Connect
or Azure ExpressRoute"]:::ext + WAN_LINK["Private link
site-to-site VPN, AWS Direct Connect
or Azure ExpressRoute"]:::ext subgraph CLOUD["Your cloud VPC"] LB["L4 load balancer
operator-built, section 3"]:::ext @@ -327,25 +327,35 @@ MLLP/TCP connectors** verbatim. 0001](adr/0001-staged-pipeline-architecture.md)) is the **WAN buffer**: a WAN blip queues outbound rows in the relay's durable store, and they drain on reconnect while each row still has retry attempts left. A row that uses them up during a long outage is dead-lettered, not dropped, and an operator can replay -it, as the retry-budget paragraph above says, until `[retention].dead_letter_days` purges its body. +it, as the retry-budget paragraph above says, until `[retention].dead_letter_days` purges its body, +or the outbound's own `dead_letter_days`, which overrides that key for the rows it dead-letters. Either way the count-and-log invariant holds end to end. The same property protects the cloud -engine's inbound. This sidesteps the real cloud objection (a WAN-crossing, TLS-less MLLP feed) -**without changing the engine**: - -- MLLP stays on the **LAN** (loopback-or-segment near the EHR), so it never crosses the WAN in - cleartext. The relay's inbound listener, bound off loopback so the EHR can reach it, meets the - bind guard like any other listener. +engine's inbound. The relay answers the real cloud objection (a WAN-crossing, TLS-less MLLP feed) +**without changing the engine** only where its outbound hop is encrypted, as the second bullet +says: + +- The sender's MLLP ends at the relay, on the **LAN** (loopback-or-segment near the EHR). The + relay's inbound listener is bound off loopback so the EHR can reach it, so under the default + enforcement the bind guard refuses it without `tls=True`: at start the engine leaves that + listener unbound and starts the rest, and `messagefoundry check` refuses the whole config. What + crosses that refusal is `tls=True` with a certificate on the listener, or `tls_hop_attested` with + its reason; `serve --allow-insecure-bind` does nothing there + ([Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary)). - The relay→cloud hop rides a **private link** (VPN / Direct Connect / ExpressRoute). The engine - cannot see that link, so it judges the outbound hop on the outbound's own settings, and a hop with - no TLS to a host off the relay is refused under the default enforcement. + cannot see that link, so it judges the outbound hop on the outbound's own settings, by the rule [`DEPLOYMENT.md`](DEPLOYMENT.md#channel--tls-posture-matrix) and - [`CONNECTIONS.md`](CONNECTIONS.md#declaring-a-cleartext-hop-cleartext_accepted) state that rule - once. In short: an outbound `MLLP()` can take `tls=True`; `Tcp()` has no TLS option, so it crosses - only on a per-hop declaration. + [`CONNECTIONS.md`](CONNECTIONS.md#declaring-a-cleartext-hop-cleartext_accepted) state once. Its + on-box carve-out covers only the relay's loopback (`127.0.0.0/8`, `::1`, `localhost`), so the + relay's own LAN address counts as off-box. An outbound `MLLP()` with `tls=True` to an off-box + host must also pass the [revocation guard](DEPLOYMENT.md#revocation-guard-behavior). [`tls_hop_attested`](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested) fits only a link that - encrypts the whole hop. Direct Connect and ExpressRoute do not encrypt by themselves, so over - either without an encrypting layer the honest declaration is `cleartext_accepted`. The cloud host - must also be on the [`[egress]`](CONFIGURATION.md#egress) allow-list. + encrypts the whole hop. The engine judges a hop over a site-to-site VPN on the same settings + whether the VPN is there or not, and the VPN encrypts the whole hop only where its tunnel runs + from the relay to the cloud engine; a leg outside the tunnel, such as one between the relay and + a separate VPN gateway, is cleartext. Direct Connect and ExpressRoute do not encrypt by + themselves, so over either without an encrypting layer the honest declaration is + `cleartext_accepted`, and MLLP or TCP then crosses the WAN in cleartext. The cloud host must also + be on the [`[egress]`](CONFIGURATION.md#egress) allow-list. - A WAN outage is a **buffered queue**, not lost messages, within the bounds above. The edge relay can be a **single node** (POC/edge SQLite is fine — its job is buffering, and DB-tier HA diff --git a/docs/CLOUD-PHI-HIPAA.md b/docs/CLOUD-PHI-HIPAA.md index a85cee1b38..bd8d71b01c 100644 --- a/docs/CLOUD-PHI-HIPAA.md +++ b/docs/CLOUD-PHI-HIPAA.md @@ -85,7 +85,8 @@ PHI at rest is protected in **two layers**, and the engine layer is **fail-close - **MLLP data plane:** **MLLP-over-TLS** (`tls=True` per connection). A non-loopback MLLP listener without TLS is **refused at wiring time** (`check_mllp_tls_exposure`). For partners that cross a WAN, prefer the **edge-relay** topology ([`CLOUD-DEPLOYMENT.md`](CLOUD-DEPLOYMENT.md) §5) so MLLP stays on the LAN and - the WAN hop rides a private encrypted link. + the WAN hop rides a private link. That hop is encrypted only where the relay's outbound sets + `tls=True` or the link itself encrypts it; that section says how the engine judges it. - **raw-TCP / X12:** **plaintext-only** (no TLS option), and **exposed-gated** since PR #558 — `check_tcp_tls_exposure` **refuses** a non-loopback raw-TCP/X12 bind at startup, parity with the MLLP/DICOM/HTTP guards. Keep them loopback-bound, OS-firewalled/segmented, or behind a TLS-terminating @@ -118,8 +119,8 @@ PHI at rest is protected in **two layers**, and the engine layer is **fail-close - **PrivateLink / private endpoints** for the managed-DB and secret-manager connections, so that traffic never traverses the public internet even within the provider. - **No public MLLP ingress.** MLLP is never exposed on a public load balancer. Partners reach it via: - - the **edge-relay** topology (MLLP terminated on-prem near the EHR, forwarded over a private encrypted - link — the recommended path), or + - the **edge-relay** topology (MLLP terminated on-prem near the EHR, forwarded over a private link, + encrypted only as the bullet above says — the recommended path), or - an **internal** L4 NLB reachable only from your private network / VPN (`aws-load-balancer-scheme: internal`), never `internet-facing`. - **Segment the management plane** (console/IDE → API) from the data plane; keep the API off general-user @@ -180,7 +181,8 @@ PHI at rest is protected in **two layers**, and the engine layer is **fail-close - [ ] Engine at-rest key: `MEFOR_STORE_ENCRYPTION_KEY` (or `[store].encryption_key_file`) supplied from the secret manager, **and** `MEFOR_STORE_REQUIRE_ENCRYPTION=true` so the audited opt-out cannot start the engine keyless ([PHI.md](PHI.md#3-encryption-at-rest) §3). -- [ ] **TLS in transit** everywhere: API TLS, MLLP-over-TLS (or edge-relay), DB `encrypt=true` / +- [ ] **TLS in transit** everywhere: API TLS, MLLP-over-TLS (an edge relay's WAN hop is TLS only with + `tls=True` on its outbound), DB `encrypt=true` / `trust_server_certificate=false`; **`MEFOR_ALLOW_INSECURE_TLS` is NOT set**. - [ ] raw-TCP/X12 are loopback/segmented (the gate refuses a public bind) — none published publicly. - [ ] **Private subnets + PrivateLink**; DB not publicly reachable; **no public MLLP ingress** (edge-relay diff --git a/docs/REMOTE-CONSOLE.md b/docs/REMOTE-CONSOLE.md index f4437a35a5..e1856cd05a 100644 --- a/docs/REMOTE-CONSOLE.md +++ b/docs/REMOTE-CONSOLE.md @@ -38,7 +38,9 @@ switches to `[security]` and setting them in `[api]` is now **refused at config `[api].port`, so editing the TOML does not move the bind. Re-run `install-service.ps1` with the arguments you installed with, plus `-ListenHost` set to the bind address, such as `-ListenHost 10.0.0.12` ([`SERVICE.md`](SERVICE.md#install)). The re-run stops the service and -does not start it again, so start it afterwards. Every TLS rule below applies to an off-box +does not start it again, but if the stop times out it only warns and reconfigures the service while +it runs, and the running engine keeps its old bind. So restart the service afterwards and confirm +it binds the new address. Every TLS rule below applies to an off-box `--host` as it does to `listen_address`. ### How hard is the TLS requirement? From d376dee3838fd09d744ff22d9032c4eddf24eb73 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:23:46 -0600 Subject: [PATCH 15/26] docs: relay hop, bind-guard effect, AOAG DR start steps, TOTP keyless wording PR 3528 review round, findings 1-9, 12 and 13. BACKLOG #2734, #5270. - CLOUD-DEPLOYMENT.md section 5: the cloud engine's off-loopback listener needs tls=True with a certificate; cleartext_accepted is outbound-only, so cleartext over Direct Connect or ExpressRoute binds on the cloud end only by a false attestation. The attestation fits only a hop encrypted end to end. The relay's LAN listener is on a segment, not loopback. The intro no longer calls the link encrypted. - CLOUD-PHI-HIPAA.md: the sender's MLLP ends at the relay, not "stays on the LAN"; the network bullet points at the section 3 bullet. - DEPLOYMENT.md bind-guard summary: start isolates the listener (ADR 0031); check, reload and connection edits refuse the whole config; the exit-2 sentence no longer covers the inbound gates. - AOAG-DEPLOYMENT.md: -ErrorAction Stop and an elevated shell; runbook step 5 makes a non-promotable DR engine promotable and sets automatic start; failback resets promotable, then a new step 4 sets manual start and stops the engine. - ASVS-L2-PHASE0-CHANGES.md TOTP row: keyless only under the audited opt-out, not on a "synthetic instance". Verified-by: tests --- docs/AOAG-DEPLOYMENT.md | 39 +++++++++++++++++++++++++--------- docs/ASVS-L2-PHASE0-CHANGES.md | 2 +- docs/CLOUD-DEPLOYMENT.md | 27 +++++++++++++++++------ docs/CLOUD-PHI-HIPAA.md | 14 +++++++----- docs/DEPLOYMENT.md | 18 ++++++++++------ 5 files changed, 71 insertions(+), 29 deletions(-) diff --git a/docs/AOAG-DEPLOYMENT.md b/docs/AOAG-DEPLOYMENT.md index d6e030044c..714ad4c330 100644 --- a/docs/AOAG-DEPLOYMENT.md +++ b/docs/AOAG-DEPLOYMENT.md @@ -536,12 +536,15 @@ two hospital engines and the DR engine. Give each an **identical config dir** an sets the service to start automatically (`SERVICE_AUTO_START`) on every run, a re-run over an existing service included, so a stopped DR engine starts by itself at its next reboot, against the cold posture. A manual start type lasts only until the installer's next run, so set it again after - every run of the installer: run this on the DR engine VM. It matches + every run of the installer: run this on the DR engine VM, in an elevated PowerShell, because + changing a service's start type needs one. It matches the service by its exact name, as the installer does, because `-Name` also matches a display name; - put your `-ServiceName` in `$n` if you changed it from the default `MessageFoundry`: + put your `-ServiceName` in `$n` if you changed it from the default `MessageFoundry`. If the change + fails, for example in a shell that is not elevated, `-ErrorAction Stop` ends the line at the error, + so it never prints the readback as if the change had been made: ```powershell - if ([Environment]::MachineName -ne '') { Write-Host "STOP this must run on , but this is $([Environment]::MachineName); nothing ran" } else { $n = 'MessageFoundry'; $svc = Get-Service | Where-Object { $_.Name -eq $n }; if (-not $svc) { Write-Host "STOP no service is named $n here; nothing changed" } else { Set-Service -InputObject $svc -StartupType Manual; Get-Service | Where-Object { $_.Name -eq $n } | Select-Object Name, Status, StartType } } + if ([Environment]::MachineName -ne '') { Write-Host "STOP this must run on , but this is $([Environment]::MachineName); nothing ran" } else { $n = 'MessageFoundry'; $svc = Get-Service | Where-Object { $_.Name -eq $n }; if (-not $svc) { Write-Host "STOP no service is named $n here; nothing changed" } else { Set-Service -InputObject $svc -StartupType Manual -ErrorAction Stop; Get-Service | Where-Object { $_.Name -eq $n } | Select-Object Name, Status, StartType } } ``` A manual start type stops only the start at boot. A manual service still starts on demand, so the @@ -550,9 +553,9 @@ two hospital engines and the DR engine. Give each an **identical config dir** an as its next step, and the restart after a re-run of the installer in [REMOTE-CONSOLE.md](REMOTE-CONSOLE.md). While a §6 activation has the DR engine carrying the traffic, a manual start type means a reboot of its VM leaves no engine running: run the same line - with `-StartupType Automatic` once it is up, and with `Manual` again at failback. Setting `Manual` - does not stop the service: failback's engine-side step 2 restarts the DR engine, and it runs on - after that until it is stopped. + with `-StartupType Automatic` once it is up (§6 runbook step 5), and with `Manual` again at + failback. Setting `Manual` does not stop the service: failback's engine-side step 2 restarts the + DR engine, and it runs on after that until engine-side step 4 stops it. - Timing defaults (`[…]` = `[cluster]`, with the invariant `heartbeat < fence < ttl` enforced at config load): `heartbeat_seconds = 10`, `leader_fence_timeout_seconds = 20`, `leader_lease_ttl_seconds = 30`, `node_timeout_seconds = 30`. `[store].pool_size ≥ 2` is @@ -732,7 +735,12 @@ Document which pattern you chose; the §6 runbook's sender-repoint step executes on-promotion `reset_stale_inflight` re-pends in-flight rows. That holds only for a promotable node: a DR engine set `[cluster].promotable = false` (§5.1) never acquires or renews the lease, so this start leaves it a non-leader and, with the hospital engines down, the cluster with no - leader. Repoint senders per the §5.4 pattern: + leader. So if you set it non-promotable, make it promotable before you start it: set + `[cluster].promotable = true` in the service config its service reads (the installer's + `-ServiceConfig`, [SERVICE.md](SERVICE.md)). A node reads that setting once, when it starts, so + on a node that is already running the change waits for its next start. Once the service is up, + set its start type to automatic with the §5.1 line, written with `-StartupType Automatic`, so a + reboot of its VM while it carries the traffic starts it again. Repoint senders per the §5.4 pattern: a global LB / GSLB follows automatically via the health check *once the service is up*; per-DC VIPs execute the sender cutover list; with RHI, **advertise the DR /32** now. 6. **Verify the hospital-side /32 was withdrawn.** If the hospital site advertised the MLLP VIP as a @@ -781,12 +789,23 @@ So **before you RESUME** the old primary: dead-letter rows on promotion). 2. **Cleanly restart the DR engine service.** The clean stop releases the lease immediately, and the primary-DC standby promotes in ≈ one heartbeat. This is §5.3's recovery mechanism, used - deliberately as the failback lever. + deliberately as the failback lever. If you made the DR engine promotable at activation (runbook + step 5), set `[cluster].promotable = false` in its service config again first, so it comes back + from this restart unable to take the lease. 3. Verify the primary-DC node reports `role == "primary"` on `/cluster/nodes`, and that the listener DNS has flipped back to the primary subnet (the step-4 `Resolve-DnsName` check, run from the primary-DC engine VM). -4. Check for stuck `INFLIGHT` rows (§5.3) and confirm dispositions are flowing. -5. Repoint senders back (reverse of the §5.4 cutover, if per-DC VIPs). +4. **Return the DR engine to cold (§5.1).** The restart in step 2 left it running, so set its + start type back to manual and stop it. Run this on the DR engine VM, in an elevated PowerShell, + with the same `$n` as the §5.1 line. If either change fails, `-ErrorAction Stop` ends the line + at that error, so the readback prints only once both are made: + + ```powershell + if ([Environment]::MachineName -ne '') { Write-Host "STOP this must run on , but this is $([Environment]::MachineName); nothing ran" } else { $n = 'MessageFoundry'; $svc = Get-Service | Where-Object { $_.Name -eq $n }; if (-not $svc) { Write-Host "STOP no service is named $n here; nothing changed" } else { Set-Service -InputObject $svc -StartupType Manual -ErrorAction Stop; Stop-Service -InputObject $svc -ErrorAction Stop; Get-Service | Where-Object { $_.Name -eq $n } | Select-Object Name, Status, StartType } } + ``` + +5. Check for stuck `INFLIGHT` rows (§5.3) and confirm dispositions are flowing. +6. Repoint senders back (reverse of the §5.4 cutover, if per-DC VIPs). ### The RPO statement — be honest about it diff --git a/docs/ASVS-L2-PHASE0-CHANGES.md b/docs/ASVS-L2-PHASE0-CHANGES.md index a07d1fe53b..7113f2823c 100644 --- a/docs/ASVS-L2-PHASE0-CHANGES.md +++ b/docs/ASVS-L2-PHASE0-CHANGES.md @@ -344,7 +344,7 @@ re-identifies data. | Key | Generation | Storage and holders | Rotation and destruction | |---|---|---|---| -| **TOTP shared secret** — one per enrolled account, in `users.totp_secret` | minted by the engine in `begin_mfa_enrollment`: 160 bits from `secrets.token_bytes(20)`, base32-encoded (`generate_secret` in [`auth/totp.py`](../messagefoundry/auth/totp.py)). It is the HMAC-SHA-256 key for RFC 6238 codes | a ciphered column, sealed by the store cipher and bound to the user id: under the DEK by default, or inside Transit under `vault_transit`. An unkeyed synthetic instance runs the identity cipher, so there it is plaintext. **Two holders by design:** the engine's store and the user's authenticator. The engine shows the secret once per enrolment: in the JSON response of `POST /me/mfa/enroll`, or on the page `POST /ui/account/mfa/enroll` renders. No later route returns it | no calendar cadence. Enrolling again mints a fresh secret, and the engine refuses to re-enrol while MFA is on. Disabling MFA and an administrator reset both set the column to NULL (`disable_totp`). Under the default `aesgcm` cipher, `rotate-key` re-encrypts it under a new DEK, except on an account whose integrity seal its user re-seal pass refuses, where the secret is left as it is stored (BACKLOG #5611), and discarding the DEK erases it, along with every DR archive that holds an older copy | +| **TOTP shared secret** — one per enrolled account, in `users.totp_secret` | minted by the engine in `begin_mfa_enrollment`: 160 bits from `secrets.token_bytes(20)`, base32-encoded (`generate_secret` in [`auth/totp.py`](../messagefoundry/auth/totp.py)). It is the HMAC-SHA-256 key for RFC 6238 codes | a ciphered column, sealed by the store cipher and bound to the user id: under the DEK by default, or inside Transit under `vault_transit`. A store opened with no key runs the identity cipher, so there it is plaintext; `serve` starts keyless only under the audited at-rest opt-out, on the rule the in-process store-at-rest cipher row above states. **Two holders by design:** the engine's store and the user's authenticator. The engine shows the secret once per enrolment: in the JSON response of `POST /me/mfa/enroll`, or on the page `POST /ui/account/mfa/enroll` renders. No later route returns it | no calendar cadence. Enrolling again mints a fresh secret, and the engine refuses to re-enrol while MFA is on. Disabling MFA and an administrator reset both set the column to NULL (`disable_totp`). Under the default `aesgcm` cipher, `rotate-key` re-encrypts it under a new DEK, except on an account whose integrity seal its user re-seal pass refuses, where the secret is left as it is stored (BACKLOG #5611), and discarding the DEK erases it, along with every DR archive that holds an older copy | | **Anonymizer re-identification salt** — the per-dataset key for the tee `anonymize-captures` export ([ADR 0030](adr/0030-anonymization-test-harness-tee.md) §4) | minted by the operator, not the engine. ADR 0030 requires at least 128 bits from a CSPRNG, and the refusal messages name `secrets.token_urlsafe(24)`. `Keyer` in [`anon/keying.py`](../messagefoundry_toolkit/anon/keying.py) (vendored byte-identical to `tee/anon/keying.py`) refuses a visibly weak salt. That is a screen against a degenerate value, not proof of 128 bits | supplied through the environment (`MEFOR_ANON_SALT` by default; `--salt-env` names another variable) and held only in the export process's memory. ADR 0030 forbids persisting or logging it. It keys a BLAKE2b hash, so anyone holding it and a guessed real value can recompute that value's surrogate. ADR 0030 classes it as PHI-equivalent. **Target: one holder**, the person running the export | discard it when the run ends; a fresh salt per run is ADR 0030's default. A salt pinned to a dataset, so its fixtures regenerate the same way, must be destroyed once that dataset will not be regenerated. Reusing one salt across datasets links their surrogates, so each new dataset gets a new salt | | **Sealed-cache key** — the per-process key that seals the transform-state and reference read-through caches ([`store/sealed_cache.py`](../messagefoundry/store/sealed_cache.py), BACKLOG #1174) | minted by the engine on first use in each process: 256 bits from `os.urandom`, built into an `AESGCM` by `_install_key` in [`store/crypto.py`](../messagefoundry/store/crypto.py), which locks and wipes the mutable key buffer (best effort). The operator supplies nothing | the engine process only, in memory. It is never written to disk, logged, exported or sent to a sandbox child; the child receives decrypted values, never the key. A forked child inherits it and draws a new nonce prefix, so the two never reuse a nonce | never rotated and never recovered: it lives exactly as long as its process and is gone when the process exits. Nothing needs it afterwards, because each start rebuilds the caches from the store under a fresh key. Its nonce counter refuses to wrap, so one key never reuses a nonce | diff --git a/docs/CLOUD-DEPLOYMENT.md b/docs/CLOUD-DEPLOYMENT.md index a6a97e5fff..54f6eecd5e 100644 --- a/docs/CLOUD-DEPLOYMENT.md +++ b/docs/CLOUD-DEPLOYMENT.md @@ -252,7 +252,8 @@ The reference manifest ([`ha-postgres.yaml`](../docker/k8s/ha-postgres.yaml)) se The strongest objection to cloud for HL7 is **connectivity**, not compliance: every MLLP message would cross a WAN to an on-prem EHR, and MLLP has no native TLS. The industry answer — and MessageFoundry's recommended cloud path — is **hybrid**: terminate MLLP **near the EHR** and forward it over a **private -encrypted link** to the cloud engine. +link** to the cloud engine. A private link is not by itself an encrypted one: section 5.1 says when the +engine treats that hop as encrypted, and what each end needs. ### 5.1 The sender's MLLP ends at the edge relay, and the relay's store buffers the WAN @@ -334,13 +335,17 @@ engine's inbound. The relay answers the real cloud objection (a WAN-crossing, TL **without changing the engine** only where its outbound hop is encrypted, as the second bullet says: -- The sender's MLLP ends at the relay, on the **LAN** (loopback-or-segment near the EHR). The - relay's inbound listener is bound off loopback so the EHR can reach it, so under the default +- The sender's MLLP ends at the relay, on the **LAN**, on a segment near the EHR. The relay's + inbound listener is bound off loopback so the EHR can reach it, so under the default enforcement the bind guard refuses it without `tls=True`: at start the engine leaves that listener unbound and starts the rest, and `messagefoundry check` refuses the whole config. What crosses that refusal is `tls=True` with a certificate on the listener, or `tls_hop_attested` with its reason; `serve --allow-insecure-bind` does nothing there - ([Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary)). + ([Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary)). The attestation fits only a + hop that is encrypted end to end by means the engine cannot see: a TLS-terminating proxy or + sidecar in front of the listener, or link-layer encryption on the segment + ([Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested)). A segment + that is only firewalled or isolated carries the feed in cleartext, so do not attest it. - The relay→cloud hop rides a **private link** (VPN / Direct Connect / ExpressRoute). The engine cannot see that link, so it judges the outbound hop on the outbound's own settings, by the rule [`DEPLOYMENT.md`](DEPLOYMENT.md#channel--tls-posture-matrix) and @@ -353,9 +358,17 @@ says: whether the VPN is there or not, and the VPN encrypts the whole hop only where its tunnel runs from the relay to the cloud engine; a leg outside the tunnel, such as one between the relay and a separate VPN gateway, is cleartext. Direct Connect and ExpressRoute do not encrypt by - themselves, so over either without an encrypting layer the honest declaration is - `cleartext_accepted`, and MLLP or TCP then crosses the WAN in cleartext. The cloud host must also - be on the [`[egress]`](CONFIGURATION.md#egress) allow-list. + themselves, so over either, with no encrypting layer, run the hop as `MLLP()` with `tls=True` on + both ends: on the relay's outbound, and on the cloud engine's inbound listener, with a + certificate. The cloud end has its own bind guard. Its listener is bound off loopback so the + load balancer can reach it, so under the default enforcement it is refused without `tls=True`, + on the same rule as the relay's listener in the first bullet. `cleartext_accepted` does not + help there: it is an outbound declaration only, so on the relay it lets a cleartext outbound + send, with a warning, and it never reaches the cloud engine's listener. An inbound `Tcp()` + listener has no TLS option at all. So under the default enforcement a cleartext feed over Direct + Connect or ExpressRoute can be bound on the cloud end only with `tls_hop_attested`, and over that + link the attestation would be false: do not set it. The cloud host must also be on the + [`[egress]`](CONFIGURATION.md#egress) allow-list. - A WAN outage is a **buffered queue**, not lost messages, within the bounds above. The edge relay can be a **single node** (POC/edge SQLite is fine — its job is buffering, and DB-tier HA diff --git a/docs/CLOUD-PHI-HIPAA.md b/docs/CLOUD-PHI-HIPAA.md index bd8d71b01c..2a2b3daf00 100644 --- a/docs/CLOUD-PHI-HIPAA.md +++ b/docs/CLOUD-PHI-HIPAA.md @@ -83,10 +83,12 @@ PHI at rest is protected in **two layers**, and the engine layer is **fail-close hop is **plaintext** and not encrypted by the engine; when `serve` accepts that is [SECURITY.md, Plaintext proxy hop](SECURITY.md#plaintext-proxy-hop). - **MLLP data plane:** **MLLP-over-TLS** (`tls=True` per connection). A non-loopback MLLP listener without - TLS is **refused at wiring time** (`check_mllp_tls_exposure`). For partners that cross a WAN, prefer the - **edge-relay** topology ([`CLOUD-DEPLOYMENT.md`](CLOUD-DEPLOYMENT.md) §5) so MLLP stays on the LAN and - the WAN hop rides a private link. That hop is encrypted only where the relay's outbound sets - `tls=True` or the link itself encrypts it; that section says how the engine judges it. + TLS is **refused** (`check_mllp_tls_exposure`; what the refusal stops is in + [`DEPLOYMENT.md`](DEPLOYMENT.md#bind-guard-behavior-summary)). For partners that cross a WAN, prefer the + **edge-relay** topology ([`CLOUD-DEPLOYMENT.md`](CLOUD-DEPLOYMENT.md) §5), so the sender's MLLP ends on + the LAN, at the relay. The relay's own hop to the cloud engine is MLLP or TCP over a private link, and + it is encrypted only where the relay's outbound and the cloud engine's listener both set `tls=True`, or + the link itself encrypts it; that section says how the engine judges it. - **raw-TCP / X12:** **plaintext-only** (no TLS option), and **exposed-gated** since PR #558 — `check_tcp_tls_exposure` **refuses** a non-loopback raw-TCP/X12 bind at startup, parity with the MLLP/DICOM/HTTP guards. Keep them loopback-bound, OS-firewalled/segmented, or behind a TLS-terminating @@ -120,7 +122,9 @@ PHI at rest is protected in **two layers**, and the engine layer is **fail-close never traverses the public internet even within the provider. - **No public MLLP ingress.** MLLP is never exposed on a public load balancer. Partners reach it via: - the **edge-relay** topology (MLLP terminated on-prem near the EHR, forwarded over a private link, - encrypted only as the bullet above says — the recommended path), or + encrypted only as the *MLLP data plane* bullet in + [section 3](#3-encryption-in-transit--no-phi-on-the-wire-in-cleartext) says — the recommended + path), or - an **internal** L4 NLB reachable only from your private network / VPN (`aws-load-balancer-scheme: internal`), never `internet-facing`. - **Segment the management plane** (console/IDE → API) from the data plane; keep the API off general-user diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 7a5cd98a15..015469671c 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -1068,12 +1068,17 @@ a PHI instance with **no** allow-list populated, and `block_unlisted_outbound` n `[security].web_console_public_address`. The same Plaintext proxy hop section says when each one refuses. - **MLLP inbound** ([`pipeline/wiring_runner.py`](../messagefoundry/pipeline/wiring_runner.py), - `check_mllp_tls_exposure`): a non-loopback MLLP source without `tls=true` raises a `WiringError` at - wiring time (before the engine starts). Override (dev only): `serve --allow-insecure-bind`, under the - same clamp. + `check_mllp_tls_exposure`): a non-loopback MLLP source without `tls=true` raises a `WiringError` + wherever that listener would be bound, and what the refusal stops depends on the path. When the + engine starts, it stops only that listener: the engine records the listener as failed, leaves it + unbound and starts the rest ([ADR 0031](adr/0031-startup-connection-fault-isolation.md)), so `serve` + does not exit over it. At least `messagefoundry check`, a reload and a `messagefoundry connection` + edit run the same gate through the build check, and refuse the whole config while the listener + would be bound. Override (dev only): `serve --allow-insecure-bind`, under the same clamp. - **DICOM C-STORE SCP / HTTP / raw-TCP / X12 inbound** (same module): siblings of the MLLP guard — `check_dimse_tls_exposure`, `check_http_tls_exposure`, and `check_tcp_tls_exposure` (raw-TCP **and** X12, - shipped in PR #558) — each refuses a non-loopback bind without TLS at wiring time. raw-TCP/X12 are + shipped in PR #558) — each refuses a non-loopback bind without TLS, on the same paths and with the + same effect as the MLLP guard: all four run through one function, `check_inbound_tls_exposure`. raw-TCP/X12 are plaintext-only, so for them the supported passes include loopback and `--allow-insecure-bind` (or its config twin `[security].require_encryption_for_remote = false`) under the clamp below. OS firewall/segmentation is still worth doing, but it clears none of these gates. So every inbound @@ -1092,8 +1097,9 @@ a PHI instance with **no** allow-list populated, and `block_unlisted_outbound` n ### Exit codes — a startup-stage refusal exits **3**, not 2 -Every refusal listed above happens in `serve`'s pre-flight, before the web server starts, and exits -**2**. One refusal happens later and exits **3**: the PHI **security-notice deliverability** gate +Every refusal listed above, except the four inbound listener gates, happens in `serve`'s pre-flight, +before the web server starts, and exits **2**. The inbound gates do not end `serve`: at start each +leaves only its own listener unbound, as the MLLP bullet says. One refusal happens later and exits **3**: the PHI **security-notice deliverability** gate ([ADR 0167](adr/0167-phi-security-notification-readiness-gates-on-a-deliverable-address-checked-early-in-the-asgi-lifespan.md)). On an instance under `[security].enforcement = enforce` with security notices switched on and `[alerts].security_notifications_required = true`, it refuses to start when **no enabled From 3708d19dde9a1569f64c31bfe9d4ff557d029da9 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:24:51 -0600 Subject: [PATCH 16/26] docstrings and tests: cluster-vip print bound, cadata message source, TOTP guard PR 3528 review round, findings 6, 10, 14 and 15. BACKLOG #5113, #5230, #5270. - __main__.py _cluster_vip docstring: drops "Prints config only -- never message data (PHI-safe)" and points at _ai_policy's statement of what it prints. No code change. - test_trust_anchor_byte_binding: the leading empty-block refusal text is CPython _ssl.c's, measured on 3.14.7 with OpenSSL 3.5.7, not OpenSSL's; the docstring says why the test is not marked _MEASURED_MARK_RULE. - test_crypto_inventory_doc: "synthetic instance" joins the retired words, with the TOTP row's old sentence in the negative control. Proposed PR title: unchanged (PR 3528). Verified-by: tests --- messagefoundry/__main__.py | 5 ++++- tests/test_crypto_inventory_doc.py | 19 +++++++++++-------- tests/test_trust_anchor_byte_binding.py | 16 ++++++++++++++-- 3 files changed, 29 insertions(+), 11 deletions(-) diff --git a/messagefoundry/__main__.py b/messagefoundry/__main__.py index 49dd61861b..a1a097a03c 100644 --- a/messagefoundry/__main__.py +++ b/messagefoundry/__main__.py @@ -15027,7 +15027,10 @@ def _cluster_vip(args: argparse.Namespace) -> int: installer reads them, so ``test_cli_cluster_vip`` asserts them rather than leaving two fields in a machine contract with no reader at all. - Prints config only -- never message data (PHI-safe). Exit 2 and a ``{"error": ...}`` line on a + What it prints is what :func:`_ai_policy` states it prints, read with ``payload`` below as the + success path's fields: on stdout no message data, and config only as that docstring bounds it, + which on the failure path can still include a value an error's own message quotes; stderr is not + covered. Exit 2 and a ``{"error": ...}`` line on a config that will not load, mirroring ``ai-policy``, so a caller parsing stdout as JSON sees the reason rather than an empty read. ``OSError`` is in the catch, and ``OSError`` is what the catch has to name: a ``--service-config`` that names a DIRECTORY passes ``Path.exists()`` and then diff --git a/tests/test_crypto_inventory_doc.py b/tests/test_crypto_inventory_doc.py index fb2f3b7a19..da9191cfe4 100644 --- a/tests/test_crypto_inventory_doc.py +++ b/tests/test_crypto_inventory_doc.py @@ -269,15 +269,18 @@ def test_review_cadence_ties_to_this_guard() -> None: # class is gone (BACKLOG #1279, ADR 0186) and that spelling is refused at load (ADR 0118). _AT_REST_ROW_PREFIX = "| Store-at-rest cipher — in-process" -# Two words the retired rule's text used that §4 does not otherwise use, matched case-folded over all -# of §4. This catches those two spellings only, not every restatement of the rule. If an accurate new -# sentence needs one of them, narrow the match rather than reword true prose. -_RETIRED_DATA_CLASS_WORDS = ("data_class", "non-phi") - -# The false phrasings the row carried before BACKLOG #5270, plus two planted variants: the opt-out's -# refused environment spelling and a key no settings model has. The negative control below feeds each -# back through the checker, so every arm of the guard is shown to fire. +# Three phrasings the retired rule's text used that §4 does not otherwise use, matched case-folded over +# all of §4. This catches those spellings only, not every restatement of the rule. If an accurate new +# sentence needs one of them, narrow the match rather than reword true prose. "synthetic instance" is +# the TOTP row's old wording; a bare "synthetic" would match true prose, at least ADR 0186's title. +_RETIRED_DATA_CLASS_WORDS = ("data_class", "non-phi", "synthetic instance") + +# The false phrasings the at-rest row carried before BACKLOG #5270, the TOTP row's sentence on the +# same rule, and two planted variants: the opt-out's refused environment spelling and a key no settings +# model has. The negative control below feeds each back through the checker, so every arm of the guard +# is shown to fire. _RETIRED_AT_REST_TEXT = ( + "An unkeyed synthetic instance runs the identity cipher, so there it is plaintext.", "every built-in environment (`dev`/`staging`/`prod`) derives `data_class=phi`", "The identity/plaintext cipher runs only on a **synthetic / non-PHI** instance", "via the loud, audited `[store].allow_unencrypted_phi` opt-out", diff --git a/tests/test_trust_anchor_byte_binding.py b/tests/test_trust_anchor_byte_binding.py index 74d69936aa..2cfe07efdd 100644 --- a/tests/test_trust_anchor_byte_binding.py +++ b/tests/test_trust_anchor_byte_binding.py @@ -872,8 +872,20 @@ def test_an_empty_pem_block_refuses_wherever_it_sits( success. ``cafile=`` refuses the file in every position, and so does the check, naming it. Behind a certificate the read-to-end check finds the stop (:func:`~messagefoundry.auth.trust_anchors._reads_to_the_end`, BACKLOG #5229). In front of - every certificate ``cadata=`` itself raises, and the check refuses with OpenSSL's reason. Both - fixture CAs stand for legitimate anchors here. The controls are in the next test.""" + every certificate ``cadata=`` itself raises, and the check refuses with the error's text. That + text is CPython's, not OpenSSL's: ``_ssl.c`` raises ``no start line: cadata does not contain a + certificate`` whenever a PEM ``cadata=`` load adds no certificate, with no OpenSSL library or + reason on the error (measured on CPython 3.14.7 with OpenSSL 3.5.7, where an empty block, a + block of bad base64 and text with no PEM block at all each raise that same text). Both fixture + CAs stand for legitimate anchors here. The controls are in the next test. + + Not marked :data:`_MEASURED_MARK_RULE`, unlike the byte-order-mark rows. That mark exists + because :func:`~messagefoundry.auth.trust_anchors.anchor_cadata` itself refuses a dropped mark + below the OpenSSL version it names, so those rows load on one version and refuse on another. + This refusal has no version branch: the read-to-end probe runs on every OpenSSL version. + What is version-bound here is only the gap this test records, that ``cadata=`` stops without an + error, measured on OpenSSL 3.5.7. If a later OpenSSL raises instead, this test fails rather + than skips, so the refusal's text and the docs that describe the gap are read again.""" first, second = cas data = {"between": first.pem + empty + second.pem, "after": first.pem + second.pem + empty} data["before"] = empty + first.pem + second.pem From e83b1b9070dc2585f01c919595d9d55696400f01 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:45:23 -0600 Subject: [PATCH 17/26] docs: review round 1 on the relay, bind-guard and AOAG repair Repairs from the xhigh review of d376dee3838 (round-2712842774). BACKLOG #2734. - CLOUD-DEPLOYMENT.md: a loopback relay is the EHR-host case; tls=True needs a TLS-speaking sender or a wrapper; the attestation cases are CONNECTIONS.md's (proxy or sidecar, or link-layer encryption), not "end to end"; the intro says MLLP defines no encryption itself. - CLOUD-PHI-HIPAA.md: the relay hop is encrypted only as MLLP with tls=True at both ends, or by the link; Tcp() has none. The raw-TCP bullet no longer offers firewalling as a pass. - DEPLOYMENT.md: check and connection take no --allow-insecure-bind, only require_encryption_for_remote; the posture rule links the summary instead of "at wiring time". - AOAG-DEPLOYMENT.md: restart, not start, a running DR engine after the promotable edit; acquire_delay_seconds delays the take-over; the routine case and the section 6 row stop the DR engine cold with the step 4 line instead of restarting it. Verified-by: tests --- docs/AOAG-DEPLOYMENT.md | 15 +++++++++------ docs/CLOUD-DEPLOYMENT.md | 19 +++++++++++-------- docs/CLOUD-PHI-HIPAA.md | 12 +++++++----- docs/DEPLOYMENT.md | 10 +++++++--- 4 files changed, 34 insertions(+), 22 deletions(-) diff --git a/docs/AOAG-DEPLOYMENT.md b/docs/AOAG-DEPLOYMENT.md index 714ad4c330..2931b7a0bd 100644 --- a/docs/AOAG-DEPLOYMENT.md +++ b/docs/AOAG-DEPLOYMENT.md @@ -697,7 +697,7 @@ Document which pattern you chose; the §6 runbook's sender-repoint step executes | Failure | Automatic behavior | Operator action | |---|---|---| | **Hypervisor host holding the SQL primary dies** | AG fails over automatically to the local sync secondary. Detection is bounded by the 20–30 s default timeouts plus redo drain, and runs longer if you raised the WSFC thresholds (§7.3), so substitute your own numbers. The engine rides the outage per §5.2, likely a self-fence and listener bounce that self-heals. Anti-affinity guarantees the engine and the other replica were elsewhere. | Verify `/cluster/nodes` and AG dashboard; check for stuck in-flight (§5.3) and restart the active engine service if any; restore host → replica rejoins and catches up. | -| **Hypervisor host holding the active engine dies** | A non-leader acquires the lease after ≤ `leader_lease_ttl_seconds` (30 s) — the **surviving hospital engine or the DR engine, whichever renews first**, unless you have made the DR engine non-promotable (`[cluster].promotable = false`, §5.1); on-promotion recovery re-pends the dead node's in-flight rows (~7 s measured functional failover). VIP/route follows via the TCP health check. Hypervisor HA also restarts the dead VM (minutes, crash-consistent) — it comes back as a non-leader. DB untouched. | **Verify which engine won** (`/cluster/nodes`). With a second hospital engine present, promotion should stay in-hospital — confirm it did. **If the DR engine took the lease while the AG primary is still hospital-local, you now have a cross-WAN active engine** (§5.1/§3.3): execute **engine failback** — clean-restart the DR engine service so a hospital engine re-acquires (§6 *Failback*), then stop the DR engine cold again (§5.1). Confirm the VIP/route followed and dispositions are flowing. | +| **Hypervisor host holding the active engine dies** | A non-leader acquires the lease after ≤ `leader_lease_ttl_seconds` (30 s) — the **surviving hospital engine or the DR engine, whichever renews first**, unless you have made the DR engine non-promotable (`[cluster].promotable = false`, §5.1); on-promotion recovery re-pends the dead node's in-flight rows (~7 s measured functional failover). VIP/route follows via the TCP health check. Hypervisor HA also restarts the dead VM (minutes, crash-consistent) — it comes back as a non-leader. DB untouched. | **Verify which engine won** (`/cluster/nodes`). With a second hospital engine present, promotion should stay in-hospital — confirm it did. **If the DR engine took the lease while the AG primary is still hospital-local, you now have a cross-WAN active engine** (§5.1/§3.3): execute **engine failback** — stop the DR engine cold, with the line in §6 *Failback* engine-side step 4, so its clean stop releases the lease and a hospital engine re-acquires it (§6 *Failback*, routine case). Confirm the VIP/route followed and dispositions are flowing. | | **Planned local AG failover (patching)** | Planned manual failover between R1↔R2, no data loss. Engine sees a short DB outage — §5.2's 10 s case if quick. | Schedule in a quiet window; afterwards check stuck in-flight; drill this quarterly (it doubles as the §5.3 reconnect drill). | | **Local sync secondary lost** (host/storage) | After the ~10 s session timeout the primary marks it `NOT SYNCHRONIZING` and keeps committing (`REQUIRED_SYNCHRONIZED_SECONDARIES_TO_COMMIT = 0`). **Running exposed:** no local automatic failover until it's back and resynchronized. | Alert + restore redundancy promptly. If it's *slow* rather than dead, commits are waiting on it (`HADR_SYNC_COMMIT`) — consider flipping it async while remediating. | | **Both local DB replicas lost, engines alive** (partial site loss — storage/rack; R1 *and* R2 gone, the hospital engines still up) | No automatic failover: with both sync replicas gone the AG has no synchronized local target, and R3 is async (no auto-failover). Ingress commits fail, so the engines stop ACKing and run their store-error retry loops (§5.2); nothing is accepted-and-dropped. | Do **not** let the engines thrash a half-dead AG. In order: **(1) stop the engine services** (both hospital engines) to quiesce commit retries; **(2) force the AG** to R3 (`FORCE_FAILOVER_ALLOW_DATA_LOSS`, forcing quorum first per §4.3/§6 if quorum was lost); **(3) verify via `/cluster/nodes`** that exactly one engine holds the lease, then start it against the now-DR primary — accepting this is cross-WAN operation (§9). RPO per the §6 forced-failover loss statement. | @@ -731,14 +731,15 @@ Document which pattern you chose; the §6 runbook's sender-repoint step executes 5. **Start the DR engine service.** In steady state the DR engine runs **cold** (§5.1), so it is *not* already competing for the lease — **start its NSSM service now**, after (a) confirming the listener resolves to the DR subnet (step 4) and (b) running the **identical-config check** (§5.1) - so promotion does not dead-letter rows. On start it acquires the lease within ≈ one heartbeat and - on-promotion `reset_stale_inflight` re-pends in-flight rows. That holds only for a promotable + so promotion does not dead-letter rows. On start it acquires the lease within ≈ one heartbeat, + after any `[cluster].acquire_delay_seconds` set on it (§5.1), because the dead leader's lease is + an expired one, and on-promotion `reset_stale_inflight` re-pends in-flight rows. That holds only for a promotable node: a DR engine set `[cluster].promotable = false` (§5.1) never acquires or renews the lease, so this start leaves it a non-leader and, with the hospital engines down, the cluster with no leader. So if you set it non-promotable, make it promotable before you start it: set `[cluster].promotable = true` in the service config its service reads (the installer's `-ServiceConfig`, [SERVICE.md](SERVICE.md)). A node reads that setting once, when it starts, so - on a node that is already running the change waits for its next start. Once the service is up, + if its service is already running, restart it rather than start it. Once the service is up, set its start type to automatic with the §5.1 line, written with `-StartupType Automatic`, so a reboot of its VM while it carries the traffic starts it again. Repoint senders per the §5.4 pattern: a global LB / GSLB follows automatically via the health check *once the service is up*; per-DC @@ -761,8 +762,10 @@ engine** (the #2 hospital engine, or worse the DR engine) win the lease while th left the hospital. Nothing on the SQL side moved, so there is nothing to resync — **just move leadership back**: confirm the configs are identical (§5.1), then **cleanly restart the misplaced engine service**. Its clean stop releases the lease immediately and the intended engine promotes in -≈ one heartbeat (§5.3). If the misplaced engine was the **DR** engine, **stop it cold again** -afterward (§5.1). Use this whenever §6's active-engine-death row flags a cross-WAN leader; the full +≈ one heartbeat (§5.3). If the misplaced engine was the **DR** engine, **stop it cold instead of +restarting it**, with the line in engine-side step 4 below, which sets manual start and stops it. Its +clean stop releases the lease the same way, and a stopped engine cannot race for it again; the §5.1 +line alone sets manual start and leaves it running. Use this whenever §6's active-engine-death row flags a cross-WAN leader; the full SQL + engine sequence below applies only after an actual DR *database* activation. **SQL side.** Microsoft's forced-failover doc covers the sequence. In outline: rejoin and resume diff --git a/docs/CLOUD-DEPLOYMENT.md b/docs/CLOUD-DEPLOYMENT.md index 54f6eecd5e..1ae1a73208 100644 --- a/docs/CLOUD-DEPLOYMENT.md +++ b/docs/CLOUD-DEPLOYMENT.md @@ -250,7 +250,8 @@ The reference manifest ([`ha-postgres.yaml`](../docker/k8s/ha-postgres.yaml)) se ## 5. Hybrid edge-relay topology (the realistic on-prem-adopter cloud path) The strongest objection to cloud for HL7 is **connectivity**, not compliance: every MLLP message would -cross a WAN to an on-prem EHR, and MLLP has no native TLS. The industry answer — and MessageFoundry's +cross a WAN to an on-prem EHR, and MLLP itself defines no encryption, so many senders speak it only in +cleartext (MessageFoundry runs MLLP over TLS where both ends set it up). The industry answer — and MessageFoundry's recommended cloud path — is **hybrid**: terminate MLLP **near the EHR** and forward it over a **private link** to the cloud engine. A private link is not by itself an encrypted one: section 5.1 says when the engine treats that hop as encrypted, and what each end needs. @@ -335,17 +336,19 @@ engine's inbound. The relay answers the real cloud objection (a WAN-crossing, TL **without changing the engine** only where its outbound hop is encrypted, as the second bullet says: -- The sender's MLLP ends at the relay, on the **LAN**, on a segment near the EHR. The relay's - inbound listener is bound off loopback so the EHR can reach it, so under the default +- The sender's MLLP ends at the relay, on the **LAN** near the EHR. Only a relay on the EHR's own + host can bind its inbound listener to loopback, which the bind guard does not check. Anywhere + else the listener is bound off loopback so the EHR can reach it, so under the default enforcement the bind guard refuses it without `tls=True`: at start the engine leaves that listener unbound and starts the rest, and `messagefoundry check` refuses the whole config. What crosses that refusal is `tls=True` with a certificate on the listener, or `tls_hop_attested` with its reason; `serve --allow-insecure-bind` does nothing there - ([Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary)). The attestation fits only a - hop that is encrypted end to end by means the engine cannot see: a TLS-terminating proxy or - sidecar in front of the listener, or link-layer encryption on the segment - ([Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested)). A segment - that is only firewalled or isolated carries the feed in cleartext, so do not attest it. + ([Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary)). `tls=True` needs a sender + that speaks TLS, or a TLS wrapper on the sender's side. The attestation fits only the cases + [Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested) names, a + TLS-terminating proxy or sidecar in front of the listener, or a segment with its own link-layer + encryption. A segment with no encryption of its own, however firewalled, is not one of them, so + do not attest it. - The relay→cloud hop rides a **private link** (VPN / Direct Connect / ExpressRoute). The engine cannot see that link, so it judges the outbound hop on the outbound's own settings, by the rule [`DEPLOYMENT.md`](DEPLOYMENT.md#channel--tls-posture-matrix) and diff --git a/docs/CLOUD-PHI-HIPAA.md b/docs/CLOUD-PHI-HIPAA.md index 2a2b3daf00..4f89d389a7 100644 --- a/docs/CLOUD-PHI-HIPAA.md +++ b/docs/CLOUD-PHI-HIPAA.md @@ -87,12 +87,14 @@ PHI at rest is protected in **two layers**, and the engine layer is **fail-close [`DEPLOYMENT.md`](DEPLOYMENT.md#bind-guard-behavior-summary)). For partners that cross a WAN, prefer the **edge-relay** topology ([`CLOUD-DEPLOYMENT.md`](CLOUD-DEPLOYMENT.md) §5), so the sender's MLLP ends on the LAN, at the relay. The relay's own hop to the cloud engine is MLLP or TCP over a private link, and - it is encrypted only where the relay's outbound and the cloud engine's listener both set `tls=True`, or - the link itself encrypts it; that section says how the engine judges it. + it is encrypted only where it is MLLP with `tls=True` on both the relay's outbound and the cloud + engine's listener, or the link itself encrypts it (`Tcp()` has no TLS option); that section says how + the engine judges it. - **raw-TCP / X12:** **plaintext-only** (no TLS option), and **exposed-gated** since PR #558 — - `check_tcp_tls_exposure` **refuses** a non-loopback raw-TCP/X12 bind at startup, parity with the - MLLP/DICOM/HTTP guards. Keep them loopback-bound, OS-firewalled/segmented, or behind a TLS-terminating - TCP proxy. **Do not** publish them publicly. + `check_tcp_tls_exposure` **refuses** a non-loopback raw-TCP/X12 bind, with the same effect as the + MLLP/DICOM/HTTP guards. Keep them loopback-bound, or behind a TLS-terminating TCP proxy with + [`tls_hop_attested`](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested). Firewalling and + segmenting them is still worth doing, but it clears no gate. **Do not** publish them publicly. - **Store DB connection:** `[store].encrypt = true` (default) + `[store].trust_server_certificate = false` (default) — TLS-verified to the managed Postgres. Give the DB a CA-trusted cert; **never** set `MEFOR_ALLOW_INSECURE_TLS` in production. diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 015469671c..454881fe30 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -269,8 +269,10 @@ address. **Fail-closed rule (ADR 0002 §0):** a non-loopback **API** bind is *refused at startup* without a certificate (`[api].tls_cert_file`), and a certificate alone does not start one; [SECURITY.md, Enforcement model](SECURITY.md#enforcement-model) states the rule. Every inbound -**listen** type — MLLP, HTTP, DICOM C-STORE SCP, raw TCP/X12 — is refused off-loopback without TLS at -wiring time. +**listen** type — MLLP, HTTP, DICOM C-STORE SCP, raw TCP/X12 — is refused off-loopback in cleartext +(raw TCP/X12 have no TLS option), with the effect +[Bind-guard behavior](#bind-guard-behavior-summary) states: at engine start only that listener stays +unbound. **The API refusal is not about cleartext.** With no certificate configured, the engine still serves TLS: it mints a self-signed placeholder on first run @@ -1074,7 +1076,9 @@ a PHI instance with **no** allow-list populated, and `block_unlisted_outbound` n unbound and starts the rest ([ADR 0031](adr/0031-startup-connection-fault-isolation.md)), so `serve` does not exit over it. At least `messagefoundry check`, a reload and a `messagefoundry connection` edit run the same gate through the build check, and refuse the whole config while the listener - would be bound. Override (dev only): `serve --allow-insecure-bind`, under the same clamp. + would be bound. Override (dev only): `serve --allow-insecure-bind`, under the same clamp. `check` + and `connection` take no such flag: they read only its config twin, + `[security].require_encryption_for_remote = false`, under the same clamp. - **DICOM C-STORE SCP / HTTP / raw-TCP / X12 inbound** (same module): siblings of the MLLP guard — `check_dimse_tls_exposure`, `check_http_tls_exposure`, and `check_tcp_tls_exposure` (raw-TCP **and** X12, shipped in PR #558) — each refuses a non-loopback bind without TLS, on the same paths and with the From 55e4ab9fce0fc4060000e49951a417f95b38eb54 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 16:45:57 -0600 Subject: [PATCH 18/26] docstrings: review round 1 on the cluster-vip and cadata wording Repairs from the xhigh review of 3708d19dde9 (round-2712842774). BACKLOG #5113, #5230. - __main__.py _cluster_vip: points at _ai_policy's statement without restating its bound. No code change. - test_trust_anchor_byte_binding: the version-bound part names CPython's message text in the before rows as well as the OpenSSL gap. Verified-by: tests --- messagefoundry/__main__.py | 6 ++---- tests/test_trust_anchor_byte_binding.py | 8 +++++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/messagefoundry/__main__.py b/messagefoundry/__main__.py index a1a097a03c..866e2b0a48 100644 --- a/messagefoundry/__main__.py +++ b/messagefoundry/__main__.py @@ -15027,10 +15027,8 @@ def _cluster_vip(args: argparse.Namespace) -> int: installer reads them, so ``test_cli_cluster_vip`` asserts them rather than leaving two fields in a machine contract with no reader at all. - What it prints is what :func:`_ai_policy` states it prints, read with ``payload`` below as the - success path's fields: on stdout no message data, and config only as that docstring bounds it, - which on the failure path can still include a value an error's own message quotes; stderr is not - covered. Exit 2 and a ``{"error": ...}`` line on a + What it prints, and what that does not cover, is what :func:`_ai_policy` states for itself, with + ``payload`` below as the success path's fields. Exit 2 and a ``{"error": ...}`` line on a config that will not load, mirroring ``ai-policy``, so a caller parsing stdout as JSON sees the reason rather than an empty read. ``OSError`` is in the catch, and ``OSError`` is what the catch has to name: a ``--service-config`` that names a DIRECTORY passes ``Path.exists()`` and then diff --git a/tests/test_trust_anchor_byte_binding.py b/tests/test_trust_anchor_byte_binding.py index 2cfe07efdd..e5c0bed55a 100644 --- a/tests/test_trust_anchor_byte_binding.py +++ b/tests/test_trust_anchor_byte_binding.py @@ -883,9 +883,11 @@ def test_an_empty_pem_block_refuses_wherever_it_sits( because :func:`~messagefoundry.auth.trust_anchors.anchor_cadata` itself refuses a dropped mark below the OpenSSL version it names, so those rows load on one version and refuse on another. This refusal has no version branch: the read-to-end probe runs on every OpenSSL version. - What is version-bound here is only the gap this test records, that ``cadata=`` stops without an - error, measured on OpenSSL 3.5.7. If a later OpenSSL raises instead, this test fails rather - than skips, so the refusal's text and the docs that describe the gap are read again.""" + What is version-bound here is what this test records of the libraries: the gap, that + ``cadata=`` stops without an error, measured on OpenSSL 3.5.7, and in the ``before`` rows + CPython's message text, measured on 3.14.7. If a later OpenSSL raises instead, or a later + CPython rewords the message, this test fails rather than skips, so the refusal's text and the + docs that describe the gap are read again.""" first, second = cas data = {"between": first.pem + empty + second.pem, "after": first.pem + second.pem + empty} data["before"] = empty + first.pem + second.pem From 45bad2e5d6a1566a2ab8b217b784b2ba93f2892f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 17:05:19 -0600 Subject: [PATCH 19/26] docs: review round 2 on the relay, bind-guard and AOAG repair Repairs from the xhigh review of 55e4ab9fce0 (round-eacbfe4e37). BACKLOG #2734. - AOAG-DEPLOYMENT.md: full failback stops the DR engine cold in step 2, after confirming a running promotable primary-DC engine, instead of restarting it; the routine case and the section 6 row point at that line. Step 5: acquire_delay_seconds counts from the lease's expiry on the database clock; MEFOR_CLUSTER_PROMOTABLE wins over the file; confirm promotable on /cluster/nodes. - CLOUD-DEPLOYMENT.md: a same-host sidecar lets the relay listener bind loopback with no attestation; the cloud end's bind guard and the tls=True remedy apply to any link that does not encrypt the whole hop, VPN included. - CLOUD-PHI-HIPAA.md: raw TCP behind a same-host proxy stays loopback; attestation only in the cases CONNECTIONS.md names. - DEPLOYMENT.md: tls_hop_attested crosses check and connection too; the posture rule and the exit-code paragraph link the summary rather than restating it. Verified-by: tests --- docs/AOAG-DEPLOYMENT.md | 52 ++++++++++++++++++++++------------------ docs/CLOUD-DEPLOYMENT.md | 31 +++++++++++++----------- docs/CLOUD-PHI-HIPAA.md | 8 ++++--- docs/DEPLOYMENT.md | 14 +++++------ 4 files changed, 58 insertions(+), 47 deletions(-) diff --git a/docs/AOAG-DEPLOYMENT.md b/docs/AOAG-DEPLOYMENT.md index 2931b7a0bd..07a7be5297 100644 --- a/docs/AOAG-DEPLOYMENT.md +++ b/docs/AOAG-DEPLOYMENT.md @@ -554,8 +554,8 @@ two hospital engines and the DR engine. Give each an **identical config dir** an [REMOTE-CONSOLE.md](REMOTE-CONSOLE.md). While a §6 activation has the DR engine carrying the traffic, a manual start type means a reboot of its VM leaves no engine running: run the same line with `-StartupType Automatic` once it is up (§6 runbook step 5), and with `Manual` again at - failback. Setting `Manual` does not stop the service: failback's engine-side step 2 restarts the - DR engine, and it runs on after that until engine-side step 4 stops it. + failback. Setting `Manual` does not stop the service; the line in failback's engine-side step 2 + sets it and stops the service. - Timing defaults (`[…]` = `[cluster]`, with the invariant `heartbeat < fence < ttl` enforced at config load): `heartbeat_seconds = 10`, `leader_fence_timeout_seconds = 20`, `leader_lease_ttl_seconds = 30`, `node_timeout_seconds = 30`. `[store].pool_size ≥ 2` is @@ -697,7 +697,7 @@ Document which pattern you chose; the §6 runbook's sender-repoint step executes | Failure | Automatic behavior | Operator action | |---|---|---| | **Hypervisor host holding the SQL primary dies** | AG fails over automatically to the local sync secondary. Detection is bounded by the 20–30 s default timeouts plus redo drain, and runs longer if you raised the WSFC thresholds (§7.3), so substitute your own numbers. The engine rides the outage per §5.2, likely a self-fence and listener bounce that self-heals. Anti-affinity guarantees the engine and the other replica were elsewhere. | Verify `/cluster/nodes` and AG dashboard; check for stuck in-flight (§5.3) and restart the active engine service if any; restore host → replica rejoins and catches up. | -| **Hypervisor host holding the active engine dies** | A non-leader acquires the lease after ≤ `leader_lease_ttl_seconds` (30 s) — the **surviving hospital engine or the DR engine, whichever renews first**, unless you have made the DR engine non-promotable (`[cluster].promotable = false`, §5.1); on-promotion recovery re-pends the dead node's in-flight rows (~7 s measured functional failover). VIP/route follows via the TCP health check. Hypervisor HA also restarts the dead VM (minutes, crash-consistent) — it comes back as a non-leader. DB untouched. | **Verify which engine won** (`/cluster/nodes`). With a second hospital engine present, promotion should stay in-hospital — confirm it did. **If the DR engine took the lease while the AG primary is still hospital-local, you now have a cross-WAN active engine** (§5.1/§3.3): execute **engine failback** — stop the DR engine cold, with the line in §6 *Failback* engine-side step 4, so its clean stop releases the lease and a hospital engine re-acquires it (§6 *Failback*, routine case). Confirm the VIP/route followed and dispositions are flowing. | +| **Hypervisor host holding the active engine dies** | A non-leader acquires the lease after ≤ `leader_lease_ttl_seconds` (30 s) — the **surviving hospital engine or the DR engine, whichever renews first**, unless you have made the DR engine non-promotable (`[cluster].promotable = false`, §5.1); on-promotion recovery re-pends the dead node's in-flight rows (~7 s measured functional failover). VIP/route follows via the TCP health check. Hypervisor HA also restarts the dead VM (minutes, crash-consistent) — it comes back as a non-leader. DB untouched. | **Verify which engine won** (`/cluster/nodes`). With a second hospital engine present, promotion should stay in-hospital — confirm it did. **If the DR engine took the lease while the AG primary is still hospital-local, you now have a cross-WAN active engine** (§5.1/§3.3): execute **engine failback** — stop the DR engine cold, with the line in §6 *Failback* engine-side step 2, so its clean stop releases the lease and a hospital engine re-acquires it (§6 *Failback*, routine case). Confirm the VIP/route followed and dispositions are flowing. | | **Planned local AG failover (patching)** | Planned manual failover between R1↔R2, no data loss. Engine sees a short DB outage — §5.2's 10 s case if quick. | Schedule in a quiet window; afterwards check stuck in-flight; drill this quarterly (it doubles as the §5.3 reconnect drill). | | **Local sync secondary lost** (host/storage) | After the ~10 s session timeout the primary marks it `NOT SYNCHRONIZING` and keeps committing (`REQUIRED_SYNCHRONIZED_SECONDARIES_TO_COMMIT = 0`). **Running exposed:** no local automatic failover until it's back and resynchronized. | Alert + restore redundancy promptly. If it's *slow* rather than dead, commits are waiting on it (`HADR_SYNC_COMMIT`) — consider flipping it async while remediating. | | **Both local DB replicas lost, engines alive** (partial site loss — storage/rack; R1 *and* R2 gone, the hospital engines still up) | No automatic failover: with both sync replicas gone the AG has no synchronized local target, and R3 is async (no auto-failover). Ingress commits fail, so the engines stop ACKing and run their store-error retry loops (§5.2); nothing is accepted-and-dropped. | Do **not** let the engines thrash a half-dead AG. In order: **(1) stop the engine services** (both hospital engines) to quiesce commit retries; **(2) force the AG** to R3 (`FORCE_FAILOVER_ALLOW_DATA_LOSS`, forcing quorum first per §4.3/§6 if quorum was lost); **(3) verify via `/cluster/nodes`** that exactly one engine holds the lease, then start it against the now-DR primary — accepting this is cross-WAN operation (§9). RPO per the §6 forced-failover loss statement. | @@ -731,15 +731,20 @@ Document which pattern you chose; the §6 runbook's sender-repoint step executes 5. **Start the DR engine service.** In steady state the DR engine runs **cold** (§5.1), so it is *not* already competing for the lease — **start its NSSM service now**, after (a) confirming the listener resolves to the DR subnet (step 4) and (b) running the **identical-config check** (§5.1) - so promotion does not dead-letter rows. On start it acquires the lease within ≈ one heartbeat, - after any `[cluster].acquire_delay_seconds` set on it (§5.1), because the dead leader's lease is - an expired one, and on-promotion `reset_stale_inflight` re-pends in-flight rows. That holds only for a promotable + so promotion does not dead-letter rows. On start it acquires the lease within ≈ one heartbeat + and on-promotion `reset_stale_inflight` re-pends in-flight rows. Any + `[cluster].acquire_delay_seconds` set on it (§5.1) counts from when the dead leader's lease + expired, on the database's clock, not from this start: if the lease expired less than that delay + ago, the claim waits out the remainder. Lower it in the same edit as below if that is too long. + The claim holds only for a promotable node: a DR engine set `[cluster].promotable = false` (§5.1) never acquires or renews the lease, so this start leaves it a non-leader and, with the hospital engines down, the cluster with no leader. So if you set it non-promotable, make it promotable before you start it: set `[cluster].promotable = true` in the service config its service reads (the installer's - `-ServiceConfig`, [SERVICE.md](SERVICE.md)). A node reads that setting once, when it starts, so - if its service is already running, restart it rather than start it. Once the service is up, + `-ServiceConfig`, [SERVICE.md](SERVICE.md)). A `MEFOR_CLUSTER_PROMOTABLE` variable in the + service's environment wins over the file, so change or remove it there if one is set, and after + the start confirm the node shows `promotable: true` on `/cluster/nodes`. A node reads that setting + once, when it starts, so if its service is already running, restart it rather than start it. Once the service is up, set its start type to automatic with the §5.1 line, written with `-StartupType Automatic`, so a reboot of its VM while it carries the traffic starts it again. Repoint senders per the §5.4 pattern: a global LB / GSLB follows automatically via the health check *once the service is up*; per-DC @@ -763,7 +768,7 @@ left the hospital. Nothing on the SQL side moved, so there is nothing to resync leadership back**: confirm the configs are identical (§5.1), then **cleanly restart the misplaced engine service**. Its clean stop releases the lease immediately and the intended engine promotes in ≈ one heartbeat (§5.3). If the misplaced engine was the **DR** engine, **stop it cold instead of -restarting it**, with the line in engine-side step 4 below, which sets manual start and stops it. Its +restarting it**, with the line in engine-side step 2 below, which sets manual start and stops it. Its clean stop releases the lease the same way, and a stopped engine cannot race for it again; the §5.1 line alone sets manual start and leaves it running. Use this whenever §6's active-engine-death row flags a cross-WAN leader; the full SQL + engine sequence below applies only after an actual DR *database* activation. @@ -790,25 +795,26 @@ So **before you RESUME** the old primary: 1. Confirm the two engine configs are **identical** before promoting (§5.1; a divergent config can dead-letter rows on promotion). -2. **Cleanly restart the DR engine service.** The clean stop releases the lease immediately, and - the primary-DC standby promotes in ≈ one heartbeat. This is §5.3's recovery mechanism, used - deliberately as the failback lever. If you made the DR engine promotable at activation (runbook - step 5), set `[cluster].promotable = false` in its service config again first, so it comes back - from this restart unable to take the lease. -3. Verify the primary-DC node reports `role == "primary"` on `/cluster/nodes`, and that the - listener DNS has flipped back to the primary subnet (the step-4 `Resolve-DnsName` check, run - from the primary-DC engine VM). -4. **Return the DR engine to cold (§5.1).** The restart in step 2 left it running, so set its - start type back to manual and stop it. Run this on the DR engine VM, in an elevated PowerShell, - with the same `$n` as the §5.1 line. If either change fails, `-ErrorAction Stop` ends the line - at that error, so the readback prints only once both are made: +2. **Stop the DR engine cold (§5.1).** First confirm on `/cluster/nodes` that a primary-DC engine + is running and promotable: with none, stopping the DR engine leaves the cluster with no leader. + If you made the DR engine promotable at activation (runbook step 5), set `[cluster].promotable = + false` in its service config again, so a later stray start cannot take the lease. Then run this + on the DR engine VM, in an elevated PowerShell, with the same `$n` as the §5.1 line. It sets the + start type back to manual and stops the service. The clean stop releases the lease immediately, + and the primary-DC standby promotes in ≈ one heartbeat: this is §5.3's recovery mechanism, used + deliberately as the failback lever. A stopped engine cannot race for the lease again, as a + restarted one can. If either change fails, `-ErrorAction Stop` ends the line at that error, so + the readback prints only once both are made: ```powershell if ([Environment]::MachineName -ne '') { Write-Host "STOP this must run on , but this is $([Environment]::MachineName); nothing ran" } else { $n = 'MessageFoundry'; $svc = Get-Service | Where-Object { $_.Name -eq $n }; if (-not $svc) { Write-Host "STOP no service is named $n here; nothing changed" } else { Set-Service -InputObject $svc -StartupType Manual -ErrorAction Stop; Stop-Service -InputObject $svc -ErrorAction Stop; Get-Service | Where-Object { $_.Name -eq $n } | Select-Object Name, Status, StartType } } ``` -5. Check for stuck `INFLIGHT` rows (§5.3) and confirm dispositions are flowing. -6. Repoint senders back (reverse of the §5.4 cutover, if per-DC VIPs). +3. Verify the primary-DC node reports `role == "primary"` on `/cluster/nodes`, and that the + listener DNS has flipped back to the primary subnet (the step-4 `Resolve-DnsName` check, run + from the primary-DC engine VM). +4. Check for stuck `INFLIGHT` rows (§5.3) and confirm dispositions are flowing. +5. Repoint senders back (reverse of the §5.4 cutover, if per-DC VIPs). ### The RPO statement — be honest about it diff --git a/docs/CLOUD-DEPLOYMENT.md b/docs/CLOUD-DEPLOYMENT.md index 1ae1a73208..239d579c8e 100644 --- a/docs/CLOUD-DEPLOYMENT.md +++ b/docs/CLOUD-DEPLOYMENT.md @@ -336,9 +336,11 @@ engine's inbound. The relay answers the real cloud objection (a WAN-crossing, TL **without changing the engine** only where its outbound hop is encrypted, as the second bullet says: -- The sender's MLLP ends at the relay, on the **LAN** near the EHR. Only a relay on the EHR's own - host can bind its inbound listener to loopback, which the bind guard does not check. Anywhere - else the listener is bound off loopback so the EHR can reach it, so under the default +- The sender's MLLP ends at the relay, on the **LAN** near the EHR. The bind guard does not check + a loopback bind, and the relay's inbound listener can bind loopback where what the EHR connects + to runs on the relay's host: at least a relay on the EHR's own host, and a TLS-terminating + sidecar on the relay's host that forwards to the listener, which then needs no attestation. + Otherwise the listener is bound off loopback so the EHR can reach it, so under the default enforcement the bind guard refuses it without `tls=True`: at start the engine leaves that listener unbound and starts the rest, and `messagefoundry check` refuses the whole config. What crosses that refusal is `tls=True` with a certificate on the listener, or `tls_hop_attested` with @@ -361,17 +363,18 @@ says: whether the VPN is there or not, and the VPN encrypts the whole hop only where its tunnel runs from the relay to the cloud engine; a leg outside the tunnel, such as one between the relay and a separate VPN gateway, is cleartext. Direct Connect and ExpressRoute do not encrypt by - themselves, so over either, with no encrypting layer, run the hop as `MLLP()` with `tls=True` on - both ends: on the relay's outbound, and on the cloud engine's inbound listener, with a - certificate. The cloud end has its own bind guard. Its listener is bound off loopback so the - load balancer can reach it, so under the default enforcement it is refused without `tls=True`, - on the same rule as the relay's listener in the first bullet. `cleartext_accepted` does not - help there: it is an outbound declaration only, so on the relay it lets a cleartext outbound - send, with a warning, and it never reaches the cloud engine's listener. An inbound `Tcp()` - listener has no TLS option at all. So under the default enforcement a cleartext feed over Direct - Connect or ExpressRoute can be bound on the cloud end only with `tls_hop_attested`, and over that - link the attestation would be false: do not set it. The cloud host must also be on the - [`[egress]`](CONFIGURATION.md#egress) allow-list. + themselves. Wherever the link does not encrypt the whole hop, over any of the three, run the + hop as `MLLP()` with `tls=True` on both ends: on the relay's outbound, and on the cloud engine's + inbound listener, with a certificate. The cloud end has its own bind guard. Its listener is + bound off loopback so the load balancer can reach it, so under the default enforcement it is + refused without `tls=True`, on the same rule as the relay's listener in the first bullet. + `cleartext_accepted` does not help there: it is an outbound declaration only, so on the relay it + lets a cleartext outbound send, with a warning, and it never reaches the cloud engine's + listener. An inbound `Tcp()` listener has no TLS option at all. So under the default enforcement + a cleartext relay hop can be bound on the cloud end only with `tls_hop_attested`, which is true + only where the link encrypts the whole hop. Over Direct Connect or ExpressRoute with no + encrypting layer, or a VPN leg outside the tunnel, it would be false: do not set it. The cloud + host must also be on the [`[egress]`](CONFIGURATION.md#egress) allow-list. - A WAN outage is a **buffered queue**, not lost messages, within the bounds above. The edge relay can be a **single node** (POC/edge SQLite is fine — its job is buffering, and DB-tier HA diff --git a/docs/CLOUD-PHI-HIPAA.md b/docs/CLOUD-PHI-HIPAA.md index 4f89d389a7..8249f12e11 100644 --- a/docs/CLOUD-PHI-HIPAA.md +++ b/docs/CLOUD-PHI-HIPAA.md @@ -92,9 +92,11 @@ PHI at rest is protected in **two layers**, and the engine layer is **fail-close the engine judges it. - **raw-TCP / X12:** **plaintext-only** (no TLS option), and **exposed-gated** since PR #558 — `check_tcp_tls_exposure` **refuses** a non-loopback raw-TCP/X12 bind, with the same effect as the - MLLP/DICOM/HTTP guards. Keep them loopback-bound, or behind a TLS-terminating TCP proxy with - [`tls_hop_attested`](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested). Firewalling and - segmenting them is still worth doing, but it clears no gate. **Do not** publish them publicly. + MLLP/DICOM/HTTP guards. Keep them loopback-bound, with a TLS-terminating TCP proxy on the same host + in front where the senders are remote. An off-loopback listener crosses the gate only with + [`tls_hop_attested`](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested), in the cases that + section names. Firewalling and segmenting them is still worth doing, but it clears no gate. + **Do not** publish them publicly. - **Store DB connection:** `[store].encrypt = true` (default) + `[store].trust_server_certificate = false` (default) — TLS-verified to the managed Postgres. Give the DB a CA-trusted cert; **never** set `MEFOR_ALLOW_INSECURE_TLS` in production. diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 454881fe30..f14dfca75e 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -270,9 +270,8 @@ address. certificate (`[api].tls_cert_file`), and a certificate alone does not start one; [SECURITY.md, Enforcement model](SECURITY.md#enforcement-model) states the rule. Every inbound **listen** type — MLLP, HTTP, DICOM C-STORE SCP, raw TCP/X12 — is refused off-loopback in cleartext -(raw TCP/X12 have no TLS option), with the effect -[Bind-guard behavior](#bind-guard-behavior-summary) states: at engine start only that listener stays -unbound. +(raw TCP/X12 have no TLS option); [Bind-guard behavior](#bind-guard-behavior-summary) says what the +refusal stops. **The API refusal is not about cleartext.** With no certificate configured, the engine still serves TLS: it mints a self-signed placeholder on first run @@ -1077,8 +1076,9 @@ a PHI instance with **no** allow-list populated, and `block_unlisted_outbound` n does not exit over it. At least `messagefoundry check`, a reload and a `messagefoundry connection` edit run the same gate through the build check, and refuse the whole config while the listener would be bound. Override (dev only): `serve --allow-insecure-bind`, under the same clamp. `check` - and `connection` take no such flag: they read only its config twin, - `[security].require_encryption_for_remote = false`, under the same clamp. + and `connection` take no such flag; in its place they read only its config twin, + `[security].require_encryption_for_remote = false`, under the same clamp. The per-connection + `tls_hop_attested` (the clamp bullet below) crosses the refusal on every one of these paths. - **DICOM C-STORE SCP / HTTP / raw-TCP / X12 inbound** (same module): siblings of the MLLP guard — `check_dimse_tls_exposure`, `check_http_tls_exposure`, and `check_tcp_tls_exposure` (raw-TCP **and** X12, shipped in PR #558) — each refuses a non-loopback bind without TLS, on the same paths and with the @@ -1102,8 +1102,8 @@ a PHI instance with **no** allow-list populated, and `block_unlisted_outbound` n ### Exit codes — a startup-stage refusal exits **3**, not 2 Every refusal listed above, except the four inbound listener gates, happens in `serve`'s pre-flight, -before the web server starts, and exits **2**. The inbound gates do not end `serve`: at start each -leaves only its own listener unbound, as the MLLP bullet says. One refusal happens later and exits **3**: the PHI **security-notice deliverability** gate +before the web server starts, and exits **2**. The inbound gates do not end `serve`, as the MLLP +bullet says. One refusal happens later and exits **3**: the PHI **security-notice deliverability** gate ([ADR 0167](adr/0167-phi-security-notification-readiness-gates-on-a-deliverable-address-checked-early-in-the-asgi-lifespan.md)). On an instance under `[security].enforcement = enforce` with security notices switched on and `[alerts].security_notifications_required = true`, it refuses to start when **no enabled From fe4f3b02d3b87e4eb91eafe3ca00b70584e9169d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 17:32:40 -0600 Subject: [PATCH 20/26] docs: point the cloud docs at the bind-guard and attestation sources of record BACKLOG #2734. CLOUD-DEPLOYMENT.md section 5.1 and CLOUD-PHI-HIPAA.md sections 3, 5 and 8 restated what the inbound bind guard admits and when tls_hop_attested fits, each time with a closed list that missed a case (warn mode with the flag, require_encryption_for_remote = false, a loopback listener behind a same-host front). Those sentences are gone; each place now links to DEPLOYMENT.md "Bind-guard behavior (summary)" or CONNECTIONS.md "Attesting a hop secure", and keeps only the deployment advice: MLLP with tls=True on both ends of the relay hop, a certificate on the cloud listener, MLLP or a same-host TLS front where Tcp() has no TLS, no attestation of a hop that is not secure, and the cloud host on [egress]. DEPLOYMENT.md's summary now says that the four inbound TLS gates match the bind host against the literal set _LOOPBACK_HOSTS, so a 127.0.0.2 bind is judged off loopback, and that HTTP's peer-control gate uses the CIDR-aware is_loopback_hop_host. CONNECTIONS.md's attestation section names its cases as "at least". Verified-by: tests --- docs/CLOUD-DEPLOYMENT.md | 64 ++++++++++++++++------------------------ docs/CLOUD-PHI-HIPAA.md | 38 +++++++++++++----------- docs/CONNECTIONS.md | 4 +-- docs/DEPLOYMENT.md | 7 ++++- 4 files changed, 53 insertions(+), 60 deletions(-) diff --git a/docs/CLOUD-DEPLOYMENT.md b/docs/CLOUD-DEPLOYMENT.md index 239d579c8e..df5b8d6438 100644 --- a/docs/CLOUD-DEPLOYMENT.md +++ b/docs/CLOUD-DEPLOYMENT.md @@ -253,8 +253,8 @@ The strongest objection to cloud for HL7 is **connectivity**, not compliance: ev cross a WAN to an on-prem EHR, and MLLP itself defines no encryption, so many senders speak it only in cleartext (MessageFoundry runs MLLP over TLS where both ends set it up). The industry answer — and MessageFoundry's recommended cloud path — is **hybrid**: terminate MLLP **near the EHR** and forward it over a **private -link** to the cloud engine. A private link is not by itself an encrypted one: section 5.1 says when the -engine treats that hop as encrypted, and what each end needs. +link** to the cloud engine. A private link is not by itself an encrypted one: section 5.1 says what +each end of that hop needs. ### 5.1 The sender's MLLP ends at the edge relay, and the relay's store buffers the WAN @@ -307,7 +307,7 @@ flowchart TB Two other docs own the settings behind these hops. [`CONNECTIONS.md`](CONNECTIONS.md) lists, for `MLLP()` and for `Tcp()`, when the connector counts a send as delivered. [`DEPLOYMENT.md`](DEPLOYMENT.md), -in its TLS posture matrix, says which hops the engine refuses to start in plaintext off loopback. +in its TLS posture matrix, says which hops the engine refuses in plaintext off loopback. [Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested) covers a hop that is secure by means the engine cannot see. @@ -336,45 +336,31 @@ engine's inbound. The relay answers the real cloud objection (a WAN-crossing, TL **without changing the engine** only where its outbound hop is encrypted, as the second bullet says: -- The sender's MLLP ends at the relay, on the **LAN** near the EHR. The bind guard does not check - a loopback bind, and the relay's inbound listener can bind loopback where what the EHR connects - to runs on the relay's host: at least a relay on the EHR's own host, and a TLS-terminating - sidecar on the relay's host that forwards to the listener, which then needs no attestation. - Otherwise the listener is bound off loopback so the EHR can reach it, so under the default - enforcement the bind guard refuses it without `tls=True`: at start the engine leaves that - listener unbound and starts the rest, and `messagefoundry check` refuses the whole config. What - crosses that refusal is `tls=True` with a certificate on the listener, or `tls_hop_attested` with - its reason; `serve --allow-insecure-bind` does nothing there - ([Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary)). `tls=True` needs a sender - that speaks TLS, or a TLS wrapper on the sender's side. The attestation fits only the cases - [Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested) names, a - TLS-terminating proxy or sidecar in front of the listener, or a segment with its own link-layer - encryption. A segment with no encryption of its own, however firewalled, is not one of them, so - do not attest it. +- The sender's MLLP ends at the relay, on the **LAN** near the EHR. The relay's inbound listener + meets the bind guard, and [Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary) says + what it refuses, what crosses it, what it counts as loopback, and what a refusal stops. Run the + listener as `MLLP()` with `tls=True` and a certificate; that needs a sender that speaks TLS, or a + TLS wrapper on the sender's side. A TLS-terminating front on the relay's host can instead forward + to a listener bound to loopback. Do not attest a hop that is not secure: + [Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested) says when + `tls_hop_attested` fits, and a firewalled segment with no encryption of its own is not secure. - The relay→cloud hop rides a **private link** (VPN / Direct Connect / ExpressRoute). The engine cannot see that link, so it judges the outbound hop on the outbound's own settings, by the rule [`DEPLOYMENT.md`](DEPLOYMENT.md#channel--tls-posture-matrix) and - [`CONNECTIONS.md`](CONNECTIONS.md#declaring-a-cleartext-hop-cleartext_accepted) state once. Its - on-box carve-out covers only the relay's loopback (`127.0.0.0/8`, `::1`, `localhost`), so the - relay's own LAN address counts as off-box. An outbound `MLLP()` with `tls=True` to an off-box - host must also pass the [revocation guard](DEPLOYMENT.md#revocation-guard-behavior). - [`tls_hop_attested`](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested) fits only a link that - encrypts the whole hop. The engine judges a hop over a site-to-site VPN on the same settings - whether the VPN is there or not, and the VPN encrypts the whole hop only where its tunnel runs - from the relay to the cloud engine; a leg outside the tunnel, such as one between the relay and - a separate VPN gateway, is cleartext. Direct Connect and ExpressRoute do not encrypt by - themselves. Wherever the link does not encrypt the whole hop, over any of the three, run the - hop as `MLLP()` with `tls=True` on both ends: on the relay's outbound, and on the cloud engine's - inbound listener, with a certificate. The cloud end has its own bind guard. Its listener is - bound off loopback so the load balancer can reach it, so under the default enforcement it is - refused without `tls=True`, on the same rule as the relay's listener in the first bullet. - `cleartext_accepted` does not help there: it is an outbound declaration only, so on the relay it - lets a cleartext outbound send, with a warning, and it never reaches the cloud engine's - listener. An inbound `Tcp()` listener has no TLS option at all. So under the default enforcement - a cleartext relay hop can be bound on the cloud end only with `tls_hop_attested`, which is true - only where the link encrypts the whole hop. Over Direct Connect or ExpressRoute with no - encrypting layer, or a VPN leg outside the tunnel, it would be false: do not set it. The cloud - host must also be on the [`[egress]`](CONFIGURATION.md#egress) allow-list. + [`CONNECTIONS.md`](CONNECTIONS.md#declaring-a-cleartext-hop-cleartext_accepted) state. Direct + Connect and ExpressRoute do not encrypt by themselves, and a VPN leaves cleartext any leg outside + its tunnel, such as one between the relay and a separate VPN gateway. Run the hop as `MLLP()` + with `tls=True` on both ends: on the relay's outbound, and on the cloud engine's inbound listener, + with a certificate on the cloud listener. An outbound `MLLP()` with `tls=True` to an off-box host + must also pass the [revocation guard](DEPLOYMENT.md#revocation-guard-behavior). The cloud + engine's listener meets its own bind guard, by the same + [Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary). `cleartext_accepted` is an + outbound declaration, so it never reaches that listener. An inbound `Tcp()` listener has no TLS + option, so use `MLLP()` for this hop, or put a TLS-terminating front on the cloud engine's host so + the listener binds loopback; the relay's outbound `Tcp()` has no TLS option either, so its side + then needs a TLS wrapper of its own. Do not attest a hop that is not secure + ([Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested)). The cloud host + must also be on the [`[egress]`](CONFIGURATION.md#egress) allow-list. - A WAN outage is a **buffered queue**, not lost messages, within the bounds above. The edge relay can be a **single node** (POC/edge SQLite is fine — its job is buffering, and DB-tier HA diff --git a/docs/CLOUD-PHI-HIPAA.md b/docs/CLOUD-PHI-HIPAA.md index 8249f12e11..dcc23fd285 100644 --- a/docs/CLOUD-PHI-HIPAA.md +++ b/docs/CLOUD-PHI-HIPAA.md @@ -83,19 +83,20 @@ PHI at rest is protected in **two layers**, and the engine layer is **fail-close hop is **plaintext** and not encrypted by the engine; when `serve` accepts that is [SECURITY.md, Plaintext proxy hop](SECURITY.md#plaintext-proxy-hop). - **MLLP data plane:** **MLLP-over-TLS** (`tls=True` per connection). A non-loopback MLLP listener without - TLS is **refused** (`check_mllp_tls_exposure`; what the refusal stops is in - [`DEPLOYMENT.md`](DEPLOYMENT.md#bind-guard-behavior-summary)). For partners that cross a WAN, prefer the + TLS meets the bind guard (`check_mllp_tls_exposure`); + [`DEPLOYMENT.md`, Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary) says what it + refuses, what crosses it and what a refusal stops. For partners that cross a WAN, prefer the **edge-relay** topology ([`CLOUD-DEPLOYMENT.md`](CLOUD-DEPLOYMENT.md) §5), so the sender's MLLP ends on - the LAN, at the relay. The relay's own hop to the cloud engine is MLLP or TCP over a private link, and - it is encrypted only where it is MLLP with `tls=True` on both the relay's outbound and the cloud - engine's listener, or the link itself encrypts it (`Tcp()` has no TLS option); that section says how - the engine judges it. + the LAN, at the relay. Run the relay's hop to the cloud engine as `MLLP()` with `tls=True` on both + ends, with a certificate on the cloud listener; that section says why a private link alone does not + do, and what to do with `Tcp()`, which has no TLS option. - **raw-TCP / X12:** **plaintext-only** (no TLS option), and **exposed-gated** since PR #558 — - `check_tcp_tls_exposure` **refuses** a non-loopback raw-TCP/X12 bind, with the same effect as the - MLLP/DICOM/HTTP guards. Keep them loopback-bound, with a TLS-terminating TCP proxy on the same host - in front where the senders are remote. An off-loopback listener crosses the gate only with - [`tls_hop_attested`](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested), in the cases that - section names. Firewalling and segmenting them is still worth doing, but it clears no gate. + `check_tcp_tls_exposure` is their bind guard, as + [`DEPLOYMENT.md`, Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary) says. Keep them + loopback-bound, with a TLS-terminating TCP proxy on the same host in front where the senders are + remote. Do not attest a hop that is not secure + ([Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested)). Firewalling and + segmenting them is still worth doing; the engine cannot see either. **Do not** publish them publicly. - **Store DB connection:** `[store].encrypt = true` (default) + `[store].trust_server_certificate = false` (default) — TLS-verified to the managed Postgres. Give the DB a CA-trusted cert; **never** set @@ -125,10 +126,10 @@ PHI at rest is protected in **two layers**, and the engine layer is **fail-close - **PrivateLink / private endpoints** for the managed-DB and secret-manager connections, so that traffic never traverses the public internet even within the provider. - **No public MLLP ingress.** MLLP is never exposed on a public load balancer. Partners reach it via: - - the **edge-relay** topology (MLLP terminated on-prem near the EHR, forwarded over a private link, - encrypted only as the *MLLP data plane* bullet in - [section 3](#3-encryption-in-transit--no-phi-on-the-wire-in-cleartext) says — the recommended - path), or + - the **edge-relay** topology (MLLP terminated on-prem near the EHR, forwarded over a private link; + the *MLLP data plane* bullet in + [section 3](#3-encryption-in-transit--no-phi-on-the-wire-in-cleartext) says what that hop needs — + the recommended path), or - an **internal** L4 NLB reachable only from your private network / VPN (`aws-load-balancer-scheme: internal`), never `internet-facing`. - **Segment the management plane** (console/IDE → API) from the data plane; keep the API off general-user @@ -189,10 +190,11 @@ PHI at rest is protected in **two layers**, and the engine layer is **fail-close - [ ] Engine at-rest key: `MEFOR_STORE_ENCRYPTION_KEY` (or `[store].encryption_key_file`) supplied from the secret manager, **and** `MEFOR_STORE_REQUIRE_ENCRYPTION=true` so the audited opt-out cannot start the engine keyless ([PHI.md](PHI.md#3-encryption-at-rest) §3). -- [ ] **TLS in transit** everywhere: API TLS, MLLP-over-TLS (an edge relay's WAN hop is TLS only with - `tls=True` on its outbound), DB `encrypt=true` / +- [ ] **TLS in transit** everywhere: API TLS, MLLP-over-TLS (an edge relay's WAN hop with `tls=True` on + both ends, [CLOUD-DEPLOYMENT.md](CLOUD-DEPLOYMENT.md) §5), DB `encrypt=true` / `trust_server_certificate=false`; **`MEFOR_ALLOW_INSECURE_TLS` is NOT set**. -- [ ] raw-TCP/X12 are loopback/segmented (the gate refuses a public bind) — none published publicly. +- [ ] raw-TCP/X12 are loopback-bound, behind a TLS-terminating proxy on the same host where senders are + remote ([bind guard](DEPLOYMENT.md#bind-guard-behavior-summary)) — none published publicly. - [ ] **Private subnets + PrivateLink**; DB not publicly reachable; **no public MLLP ingress** (edge-relay or internal NLB only). - [ ] **Region-pinned**: DB, compute, KMS keys, backups, secrets all in the approved region. diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index e7405f8c03..c1b1269063 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -4510,8 +4510,8 @@ an operator declaring it on every destination, and the engine does not try to. ## Attesting a hop secure (`tls_hop_attested`) `tls_hop_attested = true` with a mandatory `tls_hop_attested_reason` says a hop **is** secure, by means -the engine cannot see. A TLS-terminating proxy or sidecar in front of the connection is the usual case. -An isolated segment with its own link-layer encryption is the other. An enforcing refusal of a +the engine cannot see. The cases include at least a TLS-terminating proxy or sidecar in front of the +connection, and an isolated segment with its own link-layer encryption. An enforcing refusal of a cleartext or verify-off hop then **ALLOWs** it ([ADR 0092](adr/0092-posture-keyed-transport-hop-refusal-refuse-the-insecure-phi-hop.md), owner ruling 2026-09-24). That covers at least a non-loopback inbound bind without TLS, a cleartext egress hop, a diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index f14dfca75e..cd26f2eaf6 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -1082,7 +1082,12 @@ a PHI instance with **no** allow-list populated, and `block_unlisted_outbound` n - **DICOM C-STORE SCP / HTTP / raw-TCP / X12 inbound** (same module): siblings of the MLLP guard — `check_dimse_tls_exposure`, `check_http_tls_exposure`, and `check_tcp_tls_exposure` (raw-TCP **and** X12, shipped in PR #558) — each refuses a non-loopback bind without TLS, on the same paths and with the - same effect as the MLLP guard: all four run through one function, `check_inbound_tls_exposure`. raw-TCP/X12 are + same effect as the MLLP guard: all four run through one function, `check_inbound_tls_exposure`. + All four treat a bind host as loopback by matching it against the literal set `_LOOPBACK_HOSTS` + in that module, which holds at least `127.0.0.1`, `localhost`, `::1` and `::ffff:127.0.0.1`, not + against an address range, so, for example, an MLLP or HTTP bind on `127.0.0.2` is judged off + loopback; HTTP's separate peer-control gate, `check_http_intake_auth`, uses the CIDR-aware + `is_loopback_hop_host` instead. raw-TCP/X12 are plaintext-only, so for them the supported passes include loopback and `--allow-insecure-bind` (or its config twin `[security].require_encryption_for_remote = false`) under the clamp below. OS firewall/segmentation is still worth doing, but it clears none of these gates. So every inbound From c48a53a1200da91a97b7a954516d1dcf5c13c0d4 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 17:33:35 -0600 Subject: [PATCH 21/26] docs: AOAG failback steps name their preconditions and undo the activation edits BACKLOG #2734. The section 6 active-engine-death row and the routine failback case now send the operator to engine-side step 2 with its /cluster/nodes check first, not straight to its line. Step 2 says what to do when no primary-DC engine runs (start one and wait until it shows promotable), and undoes a MEFOR_CLUSTER_PROMOTABLE or lowered acquire_delay_seconds set at activation. Runbook step 5 says where to lower acquire_delay_seconds, including the MEFOR_CLUSTER_ACQUIRE_DELAY_SECONDS variable, which wins over the file (settings.py _env_overrides). Proposed PR title: unchanged from PR 3528. Verified-by: tests --- docs/AOAG-DEPLOYMENT.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/AOAG-DEPLOYMENT.md b/docs/AOAG-DEPLOYMENT.md index 07a7be5297..5816cd304e 100644 --- a/docs/AOAG-DEPLOYMENT.md +++ b/docs/AOAG-DEPLOYMENT.md @@ -697,7 +697,7 @@ Document which pattern you chose; the §6 runbook's sender-repoint step executes | Failure | Automatic behavior | Operator action | |---|---|---| | **Hypervisor host holding the SQL primary dies** | AG fails over automatically to the local sync secondary. Detection is bounded by the 20–30 s default timeouts plus redo drain, and runs longer if you raised the WSFC thresholds (§7.3), so substitute your own numbers. The engine rides the outage per §5.2, likely a self-fence and listener bounce that self-heals. Anti-affinity guarantees the engine and the other replica were elsewhere. | Verify `/cluster/nodes` and AG dashboard; check for stuck in-flight (§5.3) and restart the active engine service if any; restore host → replica rejoins and catches up. | -| **Hypervisor host holding the active engine dies** | A non-leader acquires the lease after ≤ `leader_lease_ttl_seconds` (30 s) — the **surviving hospital engine or the DR engine, whichever renews first**, unless you have made the DR engine non-promotable (`[cluster].promotable = false`, §5.1); on-promotion recovery re-pends the dead node's in-flight rows (~7 s measured functional failover). VIP/route follows via the TCP health check. Hypervisor HA also restarts the dead VM (minutes, crash-consistent) — it comes back as a non-leader. DB untouched. | **Verify which engine won** (`/cluster/nodes`). With a second hospital engine present, promotion should stay in-hospital — confirm it did. **If the DR engine took the lease while the AG primary is still hospital-local, you now have a cross-WAN active engine** (§5.1/§3.3): execute **engine failback** — stop the DR engine cold, with the line in §6 *Failback* engine-side step 2, so its clean stop releases the lease and a hospital engine re-acquires it (§6 *Failback*, routine case). Confirm the VIP/route followed and dispositions are flowing. | +| **Hypervisor host holding the active engine dies** | A non-leader acquires the lease after ≤ `leader_lease_ttl_seconds` (30 s) — the **surviving hospital engine or the DR engine, whichever renews first**, unless you have made the DR engine non-promotable (`[cluster].promotable = false`, §5.1); on-promotion recovery re-pends the dead node's in-flight rows (~7 s measured functional failover). VIP/route follows via the TCP health check. Hypervisor HA also restarts the dead VM (minutes, crash-consistent) — it comes back as a non-leader. DB untouched. | **Verify which engine won** (`/cluster/nodes`). With a second hospital engine present, promotion should stay in-hospital — confirm it did. **If the DR engine took the lease while the AG primary is still hospital-local, you now have a cross-WAN active engine** (§5.1/§3.3): execute **engine failback** — stop the DR engine cold, with §6 *Failback* engine-side step 2, its `/cluster/nodes` check first, so its clean stop releases the lease and a hospital engine re-acquires it (§6 *Failback*, routine case). Confirm the VIP/route followed and dispositions are flowing. | | **Planned local AG failover (patching)** | Planned manual failover between R1↔R2, no data loss. Engine sees a short DB outage — §5.2's 10 s case if quick. | Schedule in a quiet window; afterwards check stuck in-flight; drill this quarterly (it doubles as the §5.3 reconnect drill). | | **Local sync secondary lost** (host/storage) | After the ~10 s session timeout the primary marks it `NOT SYNCHRONIZING` and keeps committing (`REQUIRED_SYNCHRONIZED_SECONDARIES_TO_COMMIT = 0`). **Running exposed:** no local automatic failover until it's back and resynchronized. | Alert + restore redundancy promptly. If it's *slow* rather than dead, commits are waiting on it (`HADR_SYNC_COMMIT`) — consider flipping it async while remediating. | | **Both local DB replicas lost, engines alive** (partial site loss — storage/rack; R1 *and* R2 gone, the hospital engines still up) | No automatic failover: with both sync replicas gone the AG has no synchronized local target, and R3 is async (no auto-failover). Ingress commits fail, so the engines stop ACKing and run their store-error retry loops (§5.2); nothing is accepted-and-dropped. | Do **not** let the engines thrash a half-dead AG. In order: **(1) stop the engine services** (both hospital engines) to quiesce commit retries; **(2) force the AG** to R3 (`FORCE_FAILOVER_ALLOW_DATA_LOSS`, forcing quorum first per §4.3/§6 if quorum was lost); **(3) verify via `/cluster/nodes`** that exactly one engine holds the lease, then start it against the now-DR primary — accepting this is cross-WAN operation (§9). RPO per the §6 forced-failover loss statement. | @@ -735,7 +735,8 @@ Document which pattern you chose; the §6 runbook's sender-repoint step executes and on-promotion `reset_stale_inflight` re-pends in-flight rows. Any `[cluster].acquire_delay_seconds` set on it (§5.1) counts from when the dead leader's lease expired, on the database's clock, not from this start: if the lease expired less than that delay - ago, the claim waits out the remainder. Lower it in the same edit as below if that is too long. + ago, the claim waits out the remainder. If that is too long, lower it before the start, in its service config, or in its + `MEFOR_CLUSTER_ACQUIRE_DELAY_SECONDS` if one is set, which wins over the file. The claim holds only for a promotable node: a DR engine set `[cluster].promotable = false` (§5.1) never acquires or renews the lease, so this start leaves it a non-leader and, with the hospital engines down, the cluster with no @@ -768,7 +769,7 @@ left the hospital. Nothing on the SQL side moved, so there is nothing to resync leadership back**: confirm the configs are identical (§5.1), then **cleanly restart the misplaced engine service**. Its clean stop releases the lease immediately and the intended engine promotes in ≈ one heartbeat (§5.3). If the misplaced engine was the **DR** engine, **stop it cold instead of -restarting it**, with the line in engine-side step 2 below, which sets manual start and stops it. Its +restarting it**, with engine-side step 2 below, its `/cluster/nodes` check first; its line sets manual start and stops it. Its clean stop releases the lease the same way, and a stopped engine cannot race for it again; the §5.1 line alone sets manual start and leaves it running. Use this whenever §6's active-engine-death row flags a cross-WAN leader; the full SQL + engine sequence below applies only after an actual DR *database* activation. @@ -796,9 +797,11 @@ So **before you RESUME** the old primary: 1. Confirm the two engine configs are **identical** before promoting (§5.1; a divergent config can dead-letter rows on promotion). 2. **Stop the DR engine cold (§5.1).** First confirm on `/cluster/nodes` that a primary-DC engine - is running and promotable: with none, stopping the DR engine leaves the cluster with no leader. + is running and promotable: with none, stopping the DR engine leaves the cluster with no leader, + so start one first and wait until `/cluster/nodes` shows it promotable. If you made the DR engine promotable at activation (runbook step 5), set `[cluster].promotable = - false` in its service config again, so a later stray start cannot take the lease. Then run this + false` in its service config again, so a later stray start cannot take the lease, and undo any + `MEFOR_CLUSTER_PROMOTABLE` or lowered `acquire_delay_seconds` you changed then. Then run this on the DR engine VM, in an elevated PowerShell, with the same `$n` as the §5.1 line. It sets the start type back to manual and stops the service. The clean stop releases the lease immediately, and the primary-DC standby promotes in ≈ one heartbeat: this is §5.3's recovery mechanism, used From a86daa27731678d5a708617eec8505d58a4f0af8 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 17:48:13 -0600 Subject: [PATCH 22/26] docs: review round 1; the cloud docs' bind-guard sentences go back to main's text BACKLOG #2734. Review round 1 found new unsafe-direction advice in CLOUD-DEPLOYMENT.md (a TLS front on every cloud replica passes the load balancer's TCP check on standbys; a local TLS wrapper on the relay's Tcp() outbound takes the delivery point off the WAN buffer) and in CLOUD-PHI-HIPAA.md (firewalling described as something the engine cannot see, next to the attestation's own definition). Under the batch's stop rule, those files' bind-guard and attestation sentences are back to their origin/main text, with only the pointers to DEPLOYMENT.md "Bind-guard behavior (summary)" and CONNECTIONS.md "Attesting a hop secure" added. The relay-hop advice (MLLP with tls=True on both ends, a certificate on the cloud listener, the cloud host on [egress]) stays. DEPLOYMENT.md: the loopback clause says the match is as written, so a localhost bind passes whatever the name resolves to. CONNECTIONS.md: the open list is tied to means that make the hop secure. AOAG: the acquire_delay_seconds edit names the file first and the variable as the override; the activation undo no longer sits inside the promotable conditional; the step 2 "start one first" line is withdrawn (it ran ahead of step 3's listener DNS check), so R3-10 is owed. Verified-by: tests --- docs/AOAG-DEPLOYMENT.md | 13 +++++++------ docs/CLOUD-DEPLOYMENT.md | 24 ++++++++---------------- docs/CLOUD-PHI-HIPAA.md | 29 +++++++++++++---------------- docs/CONNECTIONS.md | 5 +++-- docs/DEPLOYMENT.md | 10 +++++----- 5 files changed, 36 insertions(+), 45 deletions(-) diff --git a/docs/AOAG-DEPLOYMENT.md b/docs/AOAG-DEPLOYMENT.md index 5816cd304e..1a85a015ec 100644 --- a/docs/AOAG-DEPLOYMENT.md +++ b/docs/AOAG-DEPLOYMENT.md @@ -735,8 +735,9 @@ Document which pattern you chose; the §6 runbook's sender-repoint step executes and on-promotion `reset_stale_inflight` re-pends in-flight rows. Any `[cluster].acquire_delay_seconds` set on it (§5.1) counts from when the dead leader's lease expired, on the database's clock, not from this start: if the lease expired less than that delay - ago, the claim waits out the remainder. If that is too long, lower it before the start, in its service config, or in its - `MEFOR_CLUSTER_ACQUIRE_DELAY_SECONDS` if one is set, which wins over the file. + ago, the claim waits out the remainder. If that is too long, lower it in its service config before the start; a + `MEFOR_CLUSTER_ACQUIRE_DELAY_SECONDS` in the service's environment wins over the file, so change + or remove it there if one is set. The claim holds only for a promotable node: a DR engine set `[cluster].promotable = false` (§5.1) never acquires or renews the lease, so this start leaves it a non-leader and, with the hospital engines down, the cluster with no @@ -797,11 +798,11 @@ So **before you RESUME** the old primary: 1. Confirm the two engine configs are **identical** before promoting (§5.1; a divergent config can dead-letter rows on promotion). 2. **Stop the DR engine cold (§5.1).** First confirm on `/cluster/nodes` that a primary-DC engine - is running and promotable: with none, stopping the DR engine leaves the cluster with no leader, - so start one first and wait until `/cluster/nodes` shows it promotable. + is running and promotable: with none, stopping the DR engine leaves the cluster with no leader. If you made the DR engine promotable at activation (runbook step 5), set `[cluster].promotable = - false` in its service config again, so a later stray start cannot take the lease, and undo any - `MEFOR_CLUSTER_PROMOTABLE` or lowered `acquire_delay_seconds` you changed then. Then run this + false` in its service config again, so a later stray start cannot take the lease. Undo any + `MEFOR_CLUSTER_PROMOTABLE` or `acquire_delay_seconds` change you made at activation, in the file + or the service's environment, whether or not you changed `promotable`. Then run this on the DR engine VM, in an elevated PowerShell, with the same `$n` as the §5.1 line. It sets the start type back to manual and stops the service. The clean stop releases the lease immediately, and the primary-DC standby promotes in ≈ one heartbeat: this is §5.3's recovery mechanism, used diff --git a/docs/CLOUD-DEPLOYMENT.md b/docs/CLOUD-DEPLOYMENT.md index df5b8d6438..5118000901 100644 --- a/docs/CLOUD-DEPLOYMENT.md +++ b/docs/CLOUD-DEPLOYMENT.md @@ -307,7 +307,7 @@ flowchart TB Two other docs own the settings behind these hops. [`CONNECTIONS.md`](CONNECTIONS.md) lists, for `MLLP()` and for `Tcp()`, when the connector counts a send as delivered. [`DEPLOYMENT.md`](DEPLOYMENT.md), -in its TLS posture matrix, says which hops the engine refuses in plaintext off loopback. +in its TLS posture matrix, says which hops the engine refuses to start in plaintext off loopback. [Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested) covers a hop that is secure by means the engine cannot see. @@ -336,14 +336,10 @@ engine's inbound. The relay answers the real cloud objection (a WAN-crossing, TL **without changing the engine** only where its outbound hop is encrypted, as the second bullet says: -- The sender's MLLP ends at the relay, on the **LAN** near the EHR. The relay's inbound listener - meets the bind guard, and [Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary) says - what it refuses, what crosses it, what it counts as loopback, and what a refusal stops. Run the - listener as `MLLP()` with `tls=True` and a certificate; that needs a sender that speaks TLS, or a - TLS wrapper on the sender's side. A TLS-terminating front on the relay's host can instead forward - to a listener bound to loopback. Do not attest a hop that is not secure: - [Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested) says when - `tls_hop_attested` fits, and a firewalled segment with no encryption of its own is not secure. +- MLLP stays on the **LAN** (loopback-or-segment near the EHR), so it never crosses the WAN in cleartext. + The relay's inbound listener meets the bind guard: + [Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary) and + [Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested). - The relay→cloud hop rides a **private link** (VPN / Direct Connect / ExpressRoute). The engine cannot see that link, so it judges the outbound hop on the outbound's own settings, by the rule [`DEPLOYMENT.md`](DEPLOYMENT.md#channel--tls-posture-matrix) and @@ -353,13 +349,9 @@ says: with `tls=True` on both ends: on the relay's outbound, and on the cloud engine's inbound listener, with a certificate on the cloud listener. An outbound `MLLP()` with `tls=True` to an off-box host must also pass the [revocation guard](DEPLOYMENT.md#revocation-guard-behavior). The cloud - engine's listener meets its own bind guard, by the same - [Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary). `cleartext_accepted` is an - outbound declaration, so it never reaches that listener. An inbound `Tcp()` listener has no TLS - option, so use `MLLP()` for this hop, or put a TLS-terminating front on the cloud engine's host so - the listener binds loopback; the relay's outbound `Tcp()` has no TLS option either, so its side - then needs a TLS wrapper of its own. Do not attest a hop that is not secure - ([Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested)). The cloud host + engine's listener meets its own bind guard: + [Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary) and + [Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested). The cloud host must also be on the [`[egress]`](CONFIGURATION.md#egress) allow-list. - A WAN outage is a **buffered queue**, not lost messages, within the bounds above. diff --git a/docs/CLOUD-PHI-HIPAA.md b/docs/CLOUD-PHI-HIPAA.md index dcc23fd285..c3ab373ba4 100644 --- a/docs/CLOUD-PHI-HIPAA.md +++ b/docs/CLOUD-PHI-HIPAA.md @@ -83,21 +83,18 @@ PHI at rest is protected in **two layers**, and the engine layer is **fail-close hop is **plaintext** and not encrypted by the engine; when `serve` accepts that is [SECURITY.md, Plaintext proxy hop](SECURITY.md#plaintext-proxy-hop). - **MLLP data plane:** **MLLP-over-TLS** (`tls=True` per connection). A non-loopback MLLP listener without - TLS meets the bind guard (`check_mllp_tls_exposure`); - [`DEPLOYMENT.md`, Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary) says what it - refuses, what crosses it and what a refusal stops. For partners that cross a WAN, prefer the - **edge-relay** topology ([`CLOUD-DEPLOYMENT.md`](CLOUD-DEPLOYMENT.md) §5), so the sender's MLLP ends on - the LAN, at the relay. Run the relay's hop to the cloud engine as `MLLP()` with `tls=True` on both - ends, with a certificate on the cloud listener; that section says why a private link alone does not - do, and what to do with `Tcp()`, which has no TLS option. + TLS is **refused at wiring time** (`check_mllp_tls_exposure`; + [`DEPLOYMENT.md`, Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary)). For partners that + cross a WAN, prefer the **edge-relay** topology ([`CLOUD-DEPLOYMENT.md`](CLOUD-DEPLOYMENT.md) §5), so + the sender's MLLP ends on the LAN, at the relay. Run the relay's hop to the cloud engine as `MLLP()` + with `tls=True` on both ends, with a certificate on the cloud listener; that section says why a + private link alone does not do. - **raw-TCP / X12:** **plaintext-only** (no TLS option), and **exposed-gated** since PR #558 — - `check_tcp_tls_exposure` is their bind guard, as - [`DEPLOYMENT.md`, Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary) says. Keep them - loopback-bound, with a TLS-terminating TCP proxy on the same host in front where the senders are - remote. Do not attest a hop that is not secure - ([Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested)). Firewalling and - segmenting them is still worth doing; the engine cannot see either. - **Do not** publish them publicly. + `check_tcp_tls_exposure` **refuses** a non-loopback raw-TCP/X12 bind at startup, parity with the + MLLP/DICOM/HTTP guards ([`DEPLOYMENT.md`, Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary); + [Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested)). Keep them + loopback-bound, OS-firewalled/segmented, or behind a TLS-terminating TCP proxy. **Do not** publish + them publicly. - **Store DB connection:** `[store].encrypt = true` (default) + `[store].trust_server_certificate = false` (default) — TLS-verified to the managed Postgres. Give the DB a CA-trusted cert; **never** set `MEFOR_ALLOW_INSECURE_TLS` in production. @@ -193,8 +190,8 @@ PHI at rest is protected in **two layers**, and the engine layer is **fail-close - [ ] **TLS in transit** everywhere: API TLS, MLLP-over-TLS (an edge relay's WAN hop with `tls=True` on both ends, [CLOUD-DEPLOYMENT.md](CLOUD-DEPLOYMENT.md) §5), DB `encrypt=true` / `trust_server_certificate=false`; **`MEFOR_ALLOW_INSECURE_TLS` is NOT set**. -- [ ] raw-TCP/X12 are loopback-bound, behind a TLS-terminating proxy on the same host where senders are - remote ([bind guard](DEPLOYMENT.md#bind-guard-behavior-summary)) — none published publicly. +- [ ] raw-TCP/X12 are loopback/segmented (the gate refuses a public bind; + [bind guard](DEPLOYMENT.md#bind-guard-behavior-summary)) — none published publicly. - [ ] **Private subnets + PrivateLink**; DB not publicly reachable; **no public MLLP ingress** (edge-relay or internal NLB only). - [ ] **Region-pinned**: DB, compute, KMS keys, backups, secrets all in the approved region. diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index c1b1269063..994a4dd649 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -4510,8 +4510,9 @@ an operator declaring it on every destination, and the engine does not try to. ## Attesting a hop secure (`tls_hop_attested`) `tls_hop_attested = true` with a mandatory `tls_hop_attested_reason` says a hop **is** secure, by means -the engine cannot see. The cases include at least a TLS-terminating proxy or sidecar in front of the -connection, and an isolated segment with its own link-layer encryption. An enforcing refusal of a +the engine cannot see. The means that make a hop secure this way include at least a TLS-terminating +proxy or sidecar in front of the connection, and an isolated segment with its own link-layer +encryption. An enforcing refusal of a cleartext or verify-off hop then **ALLOWs** it ([ADR 0092](adr/0092-posture-keyed-transport-hop-refusal-refuse-the-insecure-phi-hop.md), owner ruling 2026-09-24). That covers at least a non-loopback inbound bind without TLS, a cleartext egress hop, a diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index cd26f2eaf6..88cba6adfe 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -1083,11 +1083,11 @@ a PHI instance with **no** allow-list populated, and `block_unlisted_outbound` n `check_dimse_tls_exposure`, `check_http_tls_exposure`, and `check_tcp_tls_exposure` (raw-TCP **and** X12, shipped in PR #558) — each refuses a non-loopback bind without TLS, on the same paths and with the same effect as the MLLP guard: all four run through one function, `check_inbound_tls_exposure`. - All four treat a bind host as loopback by matching it against the literal set `_LOOPBACK_HOSTS` - in that module, which holds at least `127.0.0.1`, `localhost`, `::1` and `::ffff:127.0.0.1`, not - against an address range, so, for example, an MLLP or HTTP bind on `127.0.0.2` is judged off - loopback; HTTP's separate peer-control gate, `check_http_intake_auth`, uses the CIDR-aware - `is_loopback_hop_host` instead. raw-TCP/X12 are + All four treat a bind host as loopback by matching it, as written, against the literal set + `_LOOPBACK_HOSTS` in that module, which holds at least `127.0.0.1`, `localhost`, `::1` and + `::ffff:127.0.0.1`. So, for example, an MLLP or HTTP bind on `127.0.0.2` is judged off loopback, + and a bind on `localhost` passes whatever that name resolves to. HTTP's separate peer-control + gate, `check_http_intake_auth`, uses the CIDR-aware `is_loopback_hop_host` instead. raw-TCP/X12 are plaintext-only, so for them the supported passes include loopback and `--allow-insecure-bind` (or its config twin `[security].require_encryption_for_remote = false`) under the clamp below. OS firewall/segmentation is still worth doing, but it clears none of these gates. So every inbound From ff924496c1ec66e9e13f1f6bca09935bffb56bbd Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 17:59:30 -0600 Subject: [PATCH 23/26] docs: review round 2; CONNECTIONS attestation pair back to its closed form BACKLOG #2734. Review rounds 1 and 2 both rated the "at least" change to CONNECTIONS.md "Attesting a hop secure" as unsafe in direction: it opens the list of means that lift an enforcing refusal, drops "point-to-point", and leaves SECURITY-LOOSENING.md's closed pair as a second, disagreeing source. The pair is back to its earlier text; the conflict with the brief's step 4 goes to the Manager. DEPLOYMENT.md: the loopback clause names the set without an "at least" list, so its 127.0.0.2 example follows. AOAG: step 5 says the delay is read once, at start; step 2's undo names both variables and the file key without hanging off the promotable condition. Verified-by: tests --- docs/AOAG-DEPLOYMENT.md | 9 +++++---- docs/CONNECTIONS.md | 5 ++--- docs/DEPLOYMENT.md | 8 ++++---- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/AOAG-DEPLOYMENT.md b/docs/AOAG-DEPLOYMENT.md index 1a85a015ec..8b37a90e9e 100644 --- a/docs/AOAG-DEPLOYMENT.md +++ b/docs/AOAG-DEPLOYMENT.md @@ -735,7 +735,8 @@ Document which pattern you chose; the §6 runbook's sender-repoint step executes and on-promotion `reset_stale_inflight` re-pends in-flight rows. Any `[cluster].acquire_delay_seconds` set on it (§5.1) counts from when the dead leader's lease expired, on the database's clock, not from this start: if the lease expired less than that delay - ago, the claim waits out the remainder. If that is too long, lower it in its service config before the start; a + ago, the claim waits out the remainder. If that is too long, lower it in its service config before the start, since a node reads it once, + at start; a `MEFOR_CLUSTER_ACQUIRE_DELAY_SECONDS` in the service's environment wins over the file, so change or remove it there if one is set. The claim holds only for a promotable @@ -800,9 +801,9 @@ So **before you RESUME** the old primary: 2. **Stop the DR engine cold (§5.1).** First confirm on `/cluster/nodes` that a primary-DC engine is running and promotable: with none, stopping the DR engine leaves the cluster with no leader. If you made the DR engine promotable at activation (runbook step 5), set `[cluster].promotable = - false` in its service config again, so a later stray start cannot take the lease. Undo any - `MEFOR_CLUSTER_PROMOTABLE` or `acquire_delay_seconds` change you made at activation, in the file - or the service's environment, whether or not you changed `promotable`. Then run this + false` in its service config again, so a later stray start cannot take the lease. Also undo + any activation change to `acquire_delay_seconds` in the file, and to `MEFOR_CLUSTER_PROMOTABLE` + or `MEFOR_CLUSTER_ACQUIRE_DELAY_SECONDS` in the service's environment. Then run this on the DR engine VM, in an elevated PowerShell, with the same `$n` as the §5.1 line. It sets the start type back to manual and stops the service. The clean stop releases the lease immediately, and the primary-DC standby promotes in ≈ one heartbeat: this is §5.3's recovery mechanism, used diff --git a/docs/CONNECTIONS.md b/docs/CONNECTIONS.md index 994a4dd649..e7405f8c03 100644 --- a/docs/CONNECTIONS.md +++ b/docs/CONNECTIONS.md @@ -4510,9 +4510,8 @@ an operator declaring it on every destination, and the engine does not try to. ## Attesting a hop secure (`tls_hop_attested`) `tls_hop_attested = true` with a mandatory `tls_hop_attested_reason` says a hop **is** secure, by means -the engine cannot see. The means that make a hop secure this way include at least a TLS-terminating -proxy or sidecar in front of the connection, and an isolated segment with its own link-layer -encryption. An enforcing refusal of a +the engine cannot see. A TLS-terminating proxy or sidecar in front of the connection is the usual case. +An isolated segment with its own link-layer encryption is the other. An enforcing refusal of a cleartext or verify-off hop then **ALLOWs** it ([ADR 0092](adr/0092-posture-keyed-transport-hop-refusal-refuse-the-insecure-phi-hop.md), owner ruling 2026-09-24). That covers at least a non-loopback inbound bind without TLS, a cleartext egress hop, a diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 88cba6adfe..eb90c4b271 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -1084,10 +1084,10 @@ a PHI instance with **no** allow-list populated, and `block_unlisted_outbound` n shipped in PR #558) — each refuses a non-loopback bind without TLS, on the same paths and with the same effect as the MLLP guard: all four run through one function, `check_inbound_tls_exposure`. All four treat a bind host as loopback by matching it, as written, against the literal set - `_LOOPBACK_HOSTS` in that module, which holds at least `127.0.0.1`, `localhost`, `::1` and - `::ffff:127.0.0.1`. So, for example, an MLLP or HTTP bind on `127.0.0.2` is judged off loopback, - and a bind on `localhost` passes whatever that name resolves to. HTTP's separate peer-control - gate, `check_http_intake_auth`, uses the CIDR-aware `is_loopback_hop_host` instead. raw-TCP/X12 are + `_LOOPBACK_HOSTS` in that module, not against an address range. So, for example, an MLLP or HTTP + bind on `127.0.0.2` is judged off loopback, and a bind on `localhost`, which the set holds, passes + whatever that name resolves to. HTTP's separate peer-control gate, `check_http_intake_auth`, uses + the CIDR-aware `is_loopback_hop_host` instead. raw-TCP/X12 are plaintext-only, so for them the supported passes include loopback and `--allow-insecure-bind` (or its config twin `[security].require_encryption_for_remote = false`) under the clamp below. OS firewall/segmentation is still worth doing, but it clears none of these gates. So every inbound From e6fc6fb298fb5d89836519403c754a365150bc35 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 18:49:45 -0600 Subject: [PATCH 24/26] docs: cloud docs back to main, with only the encrypted-link deletions PR 3528 final repair (P-a). docs/CLOUD-DEPLOYMENT.md and docs/CLOUD-PHI-HIPAA.md go back to origin/main's text, which drops every bind-guard and attestation sentence the earlier repair rounds added. Only deletions that add no claim are re-applied on top: - "encrypted" leaves "private encrypted link" in the section 5 lead, the mermaid WAN node, the 5.1 relay bullet, and CLOUD-PHI-HIPAA's MLLP data plane bullet and edge-relay bullet: a VPN, Direct Connect or ExpressRoute link is not by itself an encrypted one. - "(or edge-relay)" leaves the CLOUD-PHI-HIPAA checklist's TLS in transit line, which offered the relay as a substitute for TLS. - "additionally" and "for defense in depth" leave the 5.1 tls=True sentence, which no longer rests on an encrypted link. - "nothing is dropped" becomes "a row that uses up its retries is dead-lettered, replayable", matching the retry-budget paragraph above it. Verified-by: tests --- docs/CLOUD-DEPLOYMENT.md | 37 ++++++++----------------------------- docs/CLOUD-PHI-HIPAA.md | 27 +++++++++------------------ 2 files changed, 17 insertions(+), 47 deletions(-) diff --git a/docs/CLOUD-DEPLOYMENT.md b/docs/CLOUD-DEPLOYMENT.md index 5118000901..a9b9c96b13 100644 --- a/docs/CLOUD-DEPLOYMENT.md +++ b/docs/CLOUD-DEPLOYMENT.md @@ -250,11 +250,9 @@ The reference manifest ([`ha-postgres.yaml`](../docker/k8s/ha-postgres.yaml)) se ## 5. Hybrid edge-relay topology (the realistic on-prem-adopter cloud path) The strongest objection to cloud for HL7 is **connectivity**, not compliance: every MLLP message would -cross a WAN to an on-prem EHR, and MLLP itself defines no encryption, so many senders speak it only in -cleartext (MessageFoundry runs MLLP over TLS where both ends set it up). The industry answer — and MessageFoundry's +cross a WAN to an on-prem EHR, and MLLP has no native TLS. The industry answer — and MessageFoundry's recommended cloud path — is **hybrid**: terminate MLLP **near the EHR** and forward it over a **private -link** to the cloud engine. A private link is not by itself an encrypted one: section 5.1 says what -each end of that hop needs. +link** to the cloud engine. ### 5.1 The sender's MLLP ends at the edge relay, and the relay's store buffers the WAN @@ -327,33 +325,14 @@ MLLP/TCP connectors** verbatim. **Why the staged store is the selling point.** The relay's **at-least-once staged store** ([ADR 0001](adr/0001-staged-pipeline-architecture.md)) is the **WAN buffer**: a WAN blip queues outbound rows in -the relay's durable store, and they drain on reconnect while each row still has retry attempts left. -A row that uses them up during a long outage is dead-lettered, not dropped, and an operator can replay -it, as the retry-budget paragraph above says, until `[retention].dead_letter_days` purges its body, -or the outbound's own `dead_letter_days`, which overrides that key for the rows it dead-letters. -Either way the count-and-log invariant holds end to end. The same property protects the cloud -engine's inbound. The relay answers the real cloud objection (a WAN-crossing, TLS-less MLLP feed) -**without changing the engine** only where its outbound hop is encrypted, as the second bullet -says: +the relay's durable store and **drains on reconnect** — a row that uses up its retries is dead-lettered, replayable (the count-and-log invariant +holds end to end). The same property protects the cloud engine's inbound. This sidesteps the real cloud +objection (a WAN-crossing, TLS-less MLLP feed) **without changing the engine**: - MLLP stays on the **LAN** (loopback-or-segment near the EHR), so it never crosses the WAN in cleartext. - The relay's inbound listener meets the bind guard: - [Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary) and - [Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested). -- The relay→cloud hop rides a **private link** (VPN / Direct Connect / ExpressRoute). The engine - cannot see that link, so it judges the outbound hop on the outbound's own settings, by the rule - [`DEPLOYMENT.md`](DEPLOYMENT.md#channel--tls-posture-matrix) and - [`CONNECTIONS.md`](CONNECTIONS.md#declaring-a-cleartext-hop-cleartext_accepted) state. Direct - Connect and ExpressRoute do not encrypt by themselves, and a VPN leaves cleartext any leg outside - its tunnel, such as one between the relay and a separate VPN gateway. Run the hop as `MLLP()` - with `tls=True` on both ends: on the relay's outbound, and on the cloud engine's inbound listener, - with a certificate on the cloud listener. An outbound `MLLP()` with `tls=True` to an off-box host - must also pass the [revocation guard](DEPLOYMENT.md#revocation-guard-behavior). The cloud - engine's listener meets its own bind guard: - [Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary) and - [Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested). The cloud host - must also be on the [`[egress]`](CONFIGURATION.md#egress) allow-list. -- A WAN outage is a **buffered queue**, not lost messages, within the bounds above. +- The relay→cloud hop rides the **private link** (VPN / Direct Connect / ExpressRoute) — and you + can run the relay's outbound MLLP with `tls=True` (MLLP-over-TLS). +- A WAN outage is a **buffered queue**, not lost messages. The edge relay can be a **single node** (POC/edge SQLite is fine — its job is buffering, and DB-tier HA lives at the cloud engine), or itself an HA pair on-prem if the edge must survive a node loss. Its diff --git a/docs/CLOUD-PHI-HIPAA.md b/docs/CLOUD-PHI-HIPAA.md index c3ab373ba4..015609fc5c 100644 --- a/docs/CLOUD-PHI-HIPAA.md +++ b/docs/CLOUD-PHI-HIPAA.md @@ -83,18 +83,13 @@ PHI at rest is protected in **two layers**, and the engine layer is **fail-close hop is **plaintext** and not encrypted by the engine; when `serve` accepts that is [SECURITY.md, Plaintext proxy hop](SECURITY.md#plaintext-proxy-hop). - **MLLP data plane:** **MLLP-over-TLS** (`tls=True` per connection). A non-loopback MLLP listener without - TLS is **refused at wiring time** (`check_mllp_tls_exposure`; - [`DEPLOYMENT.md`, Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary)). For partners that - cross a WAN, prefer the **edge-relay** topology ([`CLOUD-DEPLOYMENT.md`](CLOUD-DEPLOYMENT.md) §5), so - the sender's MLLP ends on the LAN, at the relay. Run the relay's hop to the cloud engine as `MLLP()` - with `tls=True` on both ends, with a certificate on the cloud listener; that section says why a - private link alone does not do. + TLS is **refused at wiring time** (`check_mllp_tls_exposure`). For partners that cross a WAN, prefer the + **edge-relay** topology ([`CLOUD-DEPLOYMENT.md`](CLOUD-DEPLOYMENT.md) §5) so MLLP stays on the LAN and + the WAN hop rides a private link. - **raw-TCP / X12:** **plaintext-only** (no TLS option), and **exposed-gated** since PR #558 — `check_tcp_tls_exposure` **refuses** a non-loopback raw-TCP/X12 bind at startup, parity with the - MLLP/DICOM/HTTP guards ([`DEPLOYMENT.md`, Bind-guard behavior](DEPLOYMENT.md#bind-guard-behavior-summary); - [Attesting a hop secure](CONNECTIONS.md#attesting-a-hop-secure-tls_hop_attested)). Keep them - loopback-bound, OS-firewalled/segmented, or behind a TLS-terminating TCP proxy. **Do not** publish - them publicly. + MLLP/DICOM/HTTP guards. Keep them loopback-bound, OS-firewalled/segmented, or behind a TLS-terminating + TCP proxy. **Do not** publish them publicly. - **Store DB connection:** `[store].encrypt = true` (default) + `[store].trust_server_certificate = false` (default) — TLS-verified to the managed Postgres. Give the DB a CA-trusted cert; **never** set `MEFOR_ALLOW_INSECURE_TLS` in production. @@ -123,10 +118,8 @@ PHI at rest is protected in **two layers**, and the engine layer is **fail-close - **PrivateLink / private endpoints** for the managed-DB and secret-manager connections, so that traffic never traverses the public internet even within the provider. - **No public MLLP ingress.** MLLP is never exposed on a public load balancer. Partners reach it via: - - the **edge-relay** topology (MLLP terminated on-prem near the EHR, forwarded over a private link; - the *MLLP data plane* bullet in - [section 3](#3-encryption-in-transit--no-phi-on-the-wire-in-cleartext) says what that hop needs — - the recommended path), or + - the **edge-relay** topology (MLLP terminated on-prem near the EHR, forwarded over a private + link — the recommended path), or - an **internal** L4 NLB reachable only from your private network / VPN (`aws-load-balancer-scheme: internal`), never `internet-facing`. - **Segment the management plane** (console/IDE → API) from the data plane; keep the API off general-user @@ -187,11 +180,9 @@ PHI at rest is protected in **two layers**, and the engine layer is **fail-close - [ ] Engine at-rest key: `MEFOR_STORE_ENCRYPTION_KEY` (or `[store].encryption_key_file`) supplied from the secret manager, **and** `MEFOR_STORE_REQUIRE_ENCRYPTION=true` so the audited opt-out cannot start the engine keyless ([PHI.md](PHI.md#3-encryption-at-rest) §3). -- [ ] **TLS in transit** everywhere: API TLS, MLLP-over-TLS (an edge relay's WAN hop with `tls=True` on - both ends, [CLOUD-DEPLOYMENT.md](CLOUD-DEPLOYMENT.md) §5), DB `encrypt=true` / +- [ ] **TLS in transit** everywhere: API TLS, MLLP-over-TLS, DB `encrypt=true` / `trust_server_certificate=false`; **`MEFOR_ALLOW_INSECURE_TLS` is NOT set**. -- [ ] raw-TCP/X12 are loopback/segmented (the gate refuses a public bind; - [bind guard](DEPLOYMENT.md#bind-guard-behavior-summary)) — none published publicly. +- [ ] raw-TCP/X12 are loopback/segmented (the gate refuses a public bind) — none published publicly. - [ ] **Private subnets + PrivateLink**; DB not publicly reachable; **no public MLLP ingress** (edge-relay or internal NLB only). - [ ] **Region-pinned**: DB, compute, KMS keys, backups, secrets all in the approved region. From 611a67e2b804a3bbabc15002c54017f33bcc11fc Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 18:50:15 -0600 Subject: [PATCH 25/26] docs: AOAG DR start step points at the service environment recipe PR 3528 final repair (P-a). Section 6 runbook step 5 tells an operator to change or remove a MEFOR_CLUSTER_* variable in the DR engine's service environment. Two lines now say how: edit it with the read, edit and write-back steps in docs/SERVICE.md, since nssm set AppEnvironmentExtra replaces the whole list, and restart a running service after the change, since it reads its environment only at start. Proposed PR title (PR 3528, unchanged scope): Batch 20053 docs: relay hop, AOAG DR start steps, cluster-vip and cadata wording, TOTP keyless wording Proposed vault banner text: unchanged from PR 3528's body. Verified-by: tests --- docs/AOAG-DEPLOYMENT.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/AOAG-DEPLOYMENT.md b/docs/AOAG-DEPLOYMENT.md index 8b37a90e9e..9ccb539337 100644 --- a/docs/AOAG-DEPLOYMENT.md +++ b/docs/AOAG-DEPLOYMENT.md @@ -739,6 +739,9 @@ Document which pattern you chose; the §6 runbook's sender-repoint step executes at start; a `MEFOR_CLUSTER_ACQUIRE_DELAY_SECONDS` in the service's environment wins over the file, so change or remove it there if one is set. + Edit the service's environment with the read, edit and write-back steps in + [SERVICE.md](SERVICE.md#start--stop--status), because `nssm set AppEnvironmentExtra` replaces the whole list. + A service reads its environment only when it starts, so if it is running, restart it after you change it. The claim holds only for a promotable node: a DR engine set `[cluster].promotable = false` (§5.1) never acquires or renews the lease, so this start leaves it a non-leader and, with the hospital engines down, the cluster with no From 4870a537f5eb629b7ffed2f92a1739d90020d174 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 1 Dec 2026 19:08:58 -0600 Subject: [PATCH 26/26] docs: review round 1 on the final head; deletions and one pointer only PR 3528 final repair (P-a), round 1 of the final-head review. Each change deletes text or adds a pointer; no new wording. - CLOUD-DEPLOYMENT 5.1: "you can" leaves the tls=True sentence, so the relay's outbound MLLP is told to run with tls=True rather than offered it, now that the link is no longer called encrypted. - CLOUD-PHI-HIPAA MLLP data plane bullet: the clause "so MLLP stays on the LAN and the WAN hop rides a private link" goes; the bullet now points at CLOUD-DEPLOYMENT section 5, which says what the hop runs. - DEPLOYMENT exit codes: "four" leaves "the four inbound listener gates", since the HTTP intake-auth gate named above also degrades the connection rather than ending serve. - AOAG failback step 2: a pointer to SERVICE.md beside the service environment edit, as runbook step 5 has. Verified-by: tests --- docs/AOAG-DEPLOYMENT.md | 3 ++- docs/CLOUD-DEPLOYMENT.md | 4 ++-- docs/CLOUD-PHI-HIPAA.md | 3 +-- docs/DEPLOYMENT.md | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/AOAG-DEPLOYMENT.md b/docs/AOAG-DEPLOYMENT.md index 9ccb539337..a2aa2192c7 100644 --- a/docs/AOAG-DEPLOYMENT.md +++ b/docs/AOAG-DEPLOYMENT.md @@ -806,7 +806,8 @@ So **before you RESUME** the old primary: If you made the DR engine promotable at activation (runbook step 5), set `[cluster].promotable = false` in its service config again, so a later stray start cannot take the lease. Also undo any activation change to `acquire_delay_seconds` in the file, and to `MEFOR_CLUSTER_PROMOTABLE` - or `MEFOR_CLUSTER_ACQUIRE_DELAY_SECONDS` in the service's environment. Then run this + or `MEFOR_CLUSTER_ACQUIRE_DELAY_SECONDS` in the service's environment + ([SERVICE.md](SERVICE.md#start--stop--status)). Then run this on the DR engine VM, in an elevated PowerShell, with the same `$n` as the §5.1 line. It sets the start type back to manual and stops the service. The clean stop releases the lease immediately, and the primary-DC standby promotes in ≈ one heartbeat: this is §5.3's recovery mechanism, used diff --git a/docs/CLOUD-DEPLOYMENT.md b/docs/CLOUD-DEPLOYMENT.md index a9b9c96b13..50079a2e77 100644 --- a/docs/CLOUD-DEPLOYMENT.md +++ b/docs/CLOUD-DEPLOYMENT.md @@ -330,8 +330,8 @@ holds end to end). The same property protects the cloud engine's inbound. This s objection (a WAN-crossing, TLS-less MLLP feed) **without changing the engine**: - MLLP stays on the **LAN** (loopback-or-segment near the EHR), so it never crosses the WAN in cleartext. -- The relay→cloud hop rides the **private link** (VPN / Direct Connect / ExpressRoute) — and you - can run the relay's outbound MLLP with `tls=True` (MLLP-over-TLS). +- The relay→cloud hop rides the **private link** (VPN / Direct Connect / ExpressRoute) — and + run the relay's outbound MLLP with `tls=True` (MLLP-over-TLS). - A WAN outage is a **buffered queue**, not lost messages. The edge relay can be a **single node** (POC/edge SQLite is fine — its job is buffering, and DB-tier HA diff --git a/docs/CLOUD-PHI-HIPAA.md b/docs/CLOUD-PHI-HIPAA.md index 015609fc5c..9f6dcccb31 100644 --- a/docs/CLOUD-PHI-HIPAA.md +++ b/docs/CLOUD-PHI-HIPAA.md @@ -84,8 +84,7 @@ PHI at rest is protected in **two layers**, and the engine layer is **fail-close [SECURITY.md, Plaintext proxy hop](SECURITY.md#plaintext-proxy-hop). - **MLLP data plane:** **MLLP-over-TLS** (`tls=True` per connection). A non-loopback MLLP listener without TLS is **refused at wiring time** (`check_mllp_tls_exposure`). For partners that cross a WAN, prefer the - **edge-relay** topology ([`CLOUD-DEPLOYMENT.md`](CLOUD-DEPLOYMENT.md) §5) so MLLP stays on the LAN and - the WAN hop rides a private link. + **edge-relay** topology ([`CLOUD-DEPLOYMENT.md`](CLOUD-DEPLOYMENT.md) §5). - **raw-TCP / X12:** **plaintext-only** (no TLS option), and **exposed-gated** since PR #558 — `check_tcp_tls_exposure` **refuses** a non-loopback raw-TCP/X12 bind at startup, parity with the MLLP/DICOM/HTTP guards. Keep them loopback-bound, OS-firewalled/segmented, or behind a TLS-terminating diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index eb90c4b271..a2004d7252 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -1106,7 +1106,7 @@ a PHI instance with **no** allow-list populated, and `block_unlisted_outbound` n ### Exit codes — a startup-stage refusal exits **3**, not 2 -Every refusal listed above, except the four inbound listener gates, happens in `serve`'s pre-flight, +Every refusal listed above, except the inbound listener gates, happens in `serve`'s pre-flight, before the web server starts, and exits **2**. The inbound gates do not end `serve`, as the MLLP bullet says. One refusal happens later and exits **3**: the PHI **security-notice deliverability** gate ([ADR 0167](adr/0167-phi-security-notification-readiness-gates-on-a-deliverable-address-checked-early-in-the-asgi-lifespan.md)).