From 4df3b25ca79ec2b14bc2719cbf93cf07bfff3f20 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 09:42:17 -0600 Subject: [PATCH 01/28] Key custody S3 slice B3c, installer part: host-provider account refusal, add-file grant, provision-admin --service-account step Vault BACKLOG #3411 slice B3c (items 6 and 13, part of item 21). install-service.ps1 reads [store].key_provider from the settings file it registers (as text, never by running the install's interpreter), or from MEFOR_STORE_KEY_PROVIDER in the service's own environment on a rerun. Under 'host' it: - refuses -AllowLocalSystem, and a -ServiceAccount that is SYSTEM, LOCAL SERVICE or NETWORK SERVICE, before anything acts (Manager decision d20261105T144832834-1567f8); - grants the service account add-file on the secrets directory alone, read back, so the first start can write master.key from the handoff; - prints the provision-admin --service-account command, naming the registered secrets directory (#8119 item 9), unless a key file is there. docs/SERVICE.md says so in one paragraph. Proposed PR title: Key custody S3 slice B3c (installer): host-provider account refusal, secrets-directory add-file grant, provision-admin --service-account step --- docs/SERVICE.md | 9 ++ scripts/service/install-service.ps1 | 132 ++++++++++++++- tests/test_file_path_join_census.py | 5 +- tests/test_install_service_custody.py | 223 ++++++++++++++++++++++++++ 4 files changed, 365 insertions(+), 4 deletions(-) create mode 100644 tests/test_install_service_custody.py diff --git a/docs/SERVICE.md b/docs/SERVICE.md index a463f01331..f2717a40a1 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -245,6 +245,15 @@ Administrator from an elevated shell on the host: messagefoundry provision-admin --username --email
--db C:\ProgramData\MessageFoundry\messagefoundry.db ``` +When the settings file names `[store].key_provider = 'host'` (vault BACKLOG #3411), skip step 1: +that provider refuses a second store key source beside it, so leave `MEFOR_STORE_ENCRYPTION_KEY` +unset. `provision-admin` mints the store key instead. When the install script reads that setting +(its `Get-SettingsKeyProvider` says in which forms), it prints the command for step 2, with `--service-account` naming the service's account and the secrets directory the +service was registered with. The script also lets that account add files to the secrets directory, +where the service writes its own key file at its first start. It refuses `-AllowLocalSystem`, and +at least the SYSTEM, LOCAL SERVICE and NETWORK SERVICE spellings of `-ServiceAccount`, because that +provider refuses those accounts and the service would not start. + If the service started first, at the shipped posture it refuses to start. Once the earlier start checks pass (the store key and `[alerts]` among them), that refusal names `provision-admin` in the log; run the command, then restart the service. In the data directory the install script hardens, diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index 7a5f5fa801..220831011f 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -1003,8 +1003,13 @@ function Set-SecretsDirAcl { anything left over is a refusal, not a warning. The engine refuses only the known broad groups at start, so an entry for some other account would go unnoticed there and could read every secret in the directory. + + -AddFile ALSO LETS THE ACCOUNT ADD A FILE TO THE DIRECTORY ITSELF (vault BACKLOG #3411, key + custody S3 slice B3c). Under [store].key_provider = 'host' the directory holds the store key, + and the service's first start writes its own key file there from the handoff provision-admin + left. The grant is on the directory alone, not inherited by its files, and is read back. #> - param([Parameter(Mandatory)][string]$Path, [string]$Account) + param([Parameter(Mandatory)][string]$Path, [string]$Account, [switch]$AddFile) $remedy = "Restrict it as docs/CONFIGURATION.md 'The secrets directory' shows, and re-run the installer." # Read again here, not only when -SecretsDir was judged: icacls follows a junction to its # target, and the path, or a folder above it, may have become one since. @@ -1031,6 +1036,13 @@ function Set-SecretsDirAcl { $problems += ("'$Account' could not be granted read (icacls exit $LASTEXITCODE), so the " + "service could not read the directory") } + if ($AddFile) { + & icacls $Path /grant "${Account}:(WD)" | Out-Null + if ($LASTEXITCODE -ne 0) { + $problems += ("'$Account' could not be granted the right to add a file (icacls exit " + + "$LASTEXITCODE), so the service could not write its store key file there") + } + } } # The same well-known broad set Set-SecureDataDirAcl removes, for the reasons it gives. $broad = Get-WellKnownBroadSids @@ -1067,6 +1079,18 @@ function Set-SecretsDirAcl { $(try { $_.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value -eq $accountSid } catch { $false }) }) if (-not $held) { $problems += "'$Account' holds no read on it, so the service could not read it" } + if ($AddFile) { + $add = [System.Security.AccessControl.FileSystemRights]::CreateFiles + $adds = @($acl.Access | Where-Object { + $_.AccessControlType -eq [Security.AccessControl.AccessControlType]::Allow -and + -not ($_.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) -and + ($_.FileSystemRights -band $add) -eq $add -and + $(try { $_.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value -eq $accountSid } + catch { $false }) }) + if (-not $adds) { + $problems += "'$Account' cannot add a file to it, so the service could not write its store key file" + } + } } } catch { $problems += "its access list could not be read back ($($_.Exception.Message))" @@ -1136,6 +1160,67 @@ function Get-RegisteredEnvironmentValue { return Get-EnvironmentListValue -List $key.GetValue('AppEnvironmentExtra', $null) -Name $Name } +function Get-SettingsKeyProvider { + <# + The [store].key_provider the settings file $Path names, or $null when this reader finds none + (vault BACKLOG #3411, key custody S3 slice B3c). + + READ AS TEXT. Running the install's interpreter would run its code from this elevated prompt, + which the interpreter check below declines to do. So this reads at least a key_provider line in + a [store] table, a top-level store.key_provider dotted key, and a one-line store inline table, + each holding a one-line string with no escape. Any other form reads as $null. What the installer + does with the answer is an early refusal and a printed step: the engine applies its own key + custody refusals at start whatever this returns. + #> + param([Parameter(Mandatory)][string]$Path) + $value = '(?:"(?[^"\\]*)"|''(?[^'']*)'')' + $key = '(?:key_provider|"key_provider"|''key_provider'')' + $store = '(?:store|"store"|''store'')' + $tail = '\s*(?:#.*)?$' + $table = "" + $found = $null + foreach ($line in [IO.File]::ReadAllLines($Path)) { + $line = $line.TrimStart([char]0xFEFF) + if ($line -match '^\s*\[\[') { $table = "[[]]"; continue } + if ($line -match ('^\s*\[(?[^\]]*)\]' + $tail)) { + $table = $Matches.t -replace '[\s"'']', '' + continue + } + # A [store] line; a top-level dotted key; a top-level one-line inline table. + if (($table -eq "store" -and $line -match ('^\s*' + $key + '\s*=\s*' + $value + $tail)) -or + ($table -eq "" -and $line -match ('^\s*' + $store + '\s*(?:\.\s*' + $key + '\s*=\s*' + + $value + $tail + '|=\s*\{(?:.*[,{\s])?' + $key + '\s*=\s*' + $value + ')'))) { + $found = $Matches.v + } + } + return $found +} + +function Get-HostCustodyAccountProblem { + <# + Why the service cannot run as the account this install would give it under + [store].key_provider = 'host', or "" when this check finds no reason (vault BACKLOG #3411, key + custody S3 slice B3c; Manager decision d20261105T144832834-1567f8). The host provider refuses + at least SYSTEM, LOCAL SERVICE and NETWORK SERVICE as the engine account, so a service that runs + as one of them refuses to start. This names them before anything acts. An explicit + -ServiceAccount wins over -AllowLocalSystem, as it does when the account is set. + #> + param([string]$ServiceAccount, [switch]$AllowLocalSystem) + if (-not $ServiceAccount) { + if ($AllowLocalSystem) { return "-AllowLocalSystem would run the service as LocalSystem" } + return "" + } + $shared = '^(\.\\)?LocalSystem$|^(NT AUTHORITY\\)?(SYSTEM|LocalService|NetworkService|LOCAL SERVICE|NETWORK SERVICE)$|^\*?S-1-5-(18|19|20)$' + # By SID too, so a spelling the pattern misses still counts once the name resolves. + $sid = try { + ([Security.Principal.NTAccount]$ServiceAccount.Trim()).Translate([Security.Principal.SecurityIdentifier]).Value + } catch { "" } + if ($ServiceAccount.Trim() -match $shared -or $sid -match '^S-1-5-(18|19|20)$') { + return "-ServiceAccount '$ServiceAccount' is SYSTEM, LOCAL SERVICE or NETWORK SERVICE" + } + return "" +} + function Set-ServiceEnvironmentValue { <# Set one variable in the service's NSSM environment (AppEnvironmentExtra under its Parameters @@ -2772,6 +2857,24 @@ if ($ServiceConfig -and -not (Test-Path -LiteralPath $ServiceConfig -PathType Le throw "Service settings file not found at: $ServiceConfig" } +# --- key custody: [store].key_provider = 'host' (vault BACKLOG #3411, S3 slice B3c) -------------------- +# The service's own environment overrides the settings file, as it does at start, so on a rerun a +# MEFOR_STORE_KEY_PROVIDER already registered for the service is what counts. Refused before +# anything acts. Get-SettingsKeyProvider says what it reads, and why the engine's own refusal at +# start does not rest on it. +$RegisteredKeyProvider = Get-RegisteredEnvironmentValue -ServiceName $ServiceName -Name "MEFOR_STORE_KEY_PROVIDER" +$HostCustody = if ($null -ne $RegisteredKeyProvider) { $RegisteredKeyProvider -ceq "host" } + else { (Get-SettingsKeyProvider -Path $ServiceConfig) -ceq "host" } +if ($HostCustody) { + $custodyAccountProblem = Get-HostCustodyAccountProblem -ServiceAccount $ServiceAccount -AllowLocalSystem:$AllowLocalSystem + if ($custodyAccountProblem) { + throw ("$custodyAccountProblem, and the service's settings name [store].key_provider = " + + "'host', whose key custody refuses that account, so the service would not start. Leave " + + "out -AllowLocalSystem to run as the virtual account 'NT SERVICE\$ServiceName', or pass a " + + "-ServiceAccount of the service's own (docs/SERVICE.md 'Least-privilege service account').") + } +} + # An install that builds its root (vault BACKLOG #2626) resolves NSSM first. Resolve-Nssm's # refusals, at least a -NssmPath off the pin, an -NssmDir others can write and a failed download, # need no engine root, and one after the build would leave a built root that -EngineWheel then @@ -3204,7 +3307,7 @@ Set-DataDirOwner -Path $DataDir # setting. The service is told where it is through its environment, which holds only the path. # A directory left unrestricted is a refusal, and the service is registered by now, so it is # disabled first, as the other refusals after registration are. -try { Set-SecretsDirAcl -Path $SecretsDir -Account $ServiceAccount } +try { Set-SecretsDirAcl -Path $SecretsDir -Account $ServiceAccount -AddFile:$HostCustody } catch { throw "$($_.Exception.Message) $(Disable-RefusedService -ServiceName $ServiceName -Consequence 'it cannot start with a secrets directory others can read')" } @@ -3360,6 +3463,31 @@ Write-Host " Logs : $StdoutLog" Write-Host " $StderrLog" Write-Host "" Write-Host "Next steps:" +# Key custody (vault BACKLOG #3411, S3 slice B3c): under the host provider the service starts only +# once its store key is minted, and provision-admin mints it as the handoff the service converts on +# its first start. The installer does not run it: it would run the install's code from this +# elevated prompt, and it asks for a password and the recovery key at the terminal. So the command +# is printed, naming the account, the settings file, the store path and the secrets directory the +# service was registered with, so the shell and the service read one directory (vault BACKLOG #8119 +# item 9). Not printed when a store key file is already in that directory. +if ($HostCustody) { + $custodyFile = "master.key", "handoff.key" | ForEach-Object { Join-Path $SecretsDir $_ } | + Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 + if ($custodyFile) { + Write-Host (" Store key: '$custodyFile' is already there ([store].key_provider = " + + "'host'), so provision-admin mints no key over it.") + } else { + $q = { param($s) "'" + ($s -replace "'", "''") + "'" } + Write-Host (" Before the first start, mint the store key for '$RunAsObjectName' " + + "([store].key_provider = 'host'), in an elevated PowerShell:") + Write-Host " `$env:MEFOR_SECRETS_DIRECTORY = $(& $q $SecretsDir)" + Write-Host (" & $(& $q $PythonExe) $EngineInterpreterOptions -m messagefoundry provision-admin " + + "--username --email
--service-config $(& $q $ServiceConfig) " + + "--db $(& $q $DbPath) --service-account $(& $q $RunAsObjectName)") + Write-Host (" It shows the store's recovery key once and asks for it back. Keep it off this " + + "host: with neither this host nor that key, the store cannot be opened.") + } +} # Start-Service needs no nssm.exe, so an operator following this never runs a copy nobody checked # (BACKLOG #2364). Write-Host " Start-Service '$ServiceName'" diff --git a/tests/test_file_path_join_census.py b/tests/test_file_path_join_census.py index a169f020d7..34ec5765d4 100644 --- a/tests/test_file_path_join_census.py +++ b/tests/test_file_path_join_census.py @@ -1256,14 +1256,15 @@ def derived_script_sites() -> dict[str, int]: 7, OPERATOR, "Fixed names under the repo root, the helper source and the install directory." ), "scripts/service/install-service.ps1": Site( - 44, + 45, OPERATOR, "Fixed names, and a folder named from a fresh GUID under the Windows temp folder, under " "paths the operator passes or the script derives (repo root, install " "root and its site-packages, dist-info, wheelhouse and buildtemp folders, the engine " "wheel's folder, " "the base interpreter's folder and the one above it, " - "project root, data directory and the folder above it, ProgramData, NSSM directory, temp), " + "project root, data directory and the folder above it, secrets directory, ProgramData, NSSM " + "directory, temp), " "the data directory's own leaf name with -secrets after it, the leaf name of the engine wheel " "the operator passes, which must match messagefoundry--*.whl, plus registry keys " "named after the service's own images, and the fixed Parameters key under each key the " diff --git a/tests/test_install_service_custody.py b/tests/test_install_service_custody.py new file mode 100644 index 0000000000..f3a195c57c --- /dev/null +++ b/tests/test_install_service_custody.py @@ -0,0 +1,223 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""install-service.ps1 under ``[store].key_provider = 'host'`` (vault BACKLOG #3411, key custody S3 +slice B3c). + +The installer refuses the accounts the host provider refuses as the engine account, before +anything acts; lets the service account add a file to the secrets directory, where the service's +first start writes its key file from the handoff; and prints the ``provision-admin +--service-account`` step. Behaviour runs the script's own functions, extracted by AST, through +``pwsh``; the call sites are read by AST, since no test runs the script body. +""" + +from __future__ import annotations + +import json +import tomllib +import uuid +from pathlib import Path + +import pytest + +from tests.test_service_install_manifest import ( + _SCRIPT, + _extract, + _ok, + _preflight_facts, + _psq, + _run, + _script_text, + _sole_call, + _windows_only, +) + +pytestmark = pytest.mark.skipif( + _SCRIPT is None, + reason="install-service.ps1 not locatable (off-repo / non-editable install)", +) + +# (settings file text, what the installer must read as [store].key_provider) +_SETTINGS: list[tuple[str, str | None]] = [ + ('[store]\nkey_provider = "host"\n', "host"), + ("[store]\nkey_provider = 'host' # the custody provider\n", "host"), + ('[api]\nport = 1\n\n[ store ]\nbackend = "sqlite"\n key_provider="host"\n', "host"), + ('[store]\n"key_provider" = "host"\n', "host"), + ('store.key_provider = "host"\n[api]\nport = 1\n', "host"), + ('store = { backend = "sqlite", key_provider = "host" }\n', "host"), + ('[store]\nkey_provider = "host"\n', "host"), + ('[store]\nkey_provider = "auto"\n', "auto"), + ('[store]\nbackend = "sqlite"\n', None), + ('[store.tls]\nkey_provider = "host"\n', None), + ('[api]\nkey_provider = "host"\n', None), + ('[store]\n[[alerts.sinks]]\nkey_provider = "host"\n', None), + ('[store]\n# key_provider = "host"\n', None), + ('[store]\nother_key_provider = "host"\n', None), + ("", None), +] + + +def test_the_settings_reader_finds_the_key_provider(tmp_path: Path) -> None: + """Every positive case parses to the same value under Python's own TOML reader, so the cases + are real settings files and not text the reader merely happens to match.""" + assert _SCRIPT is not None + for text, expected in _SETTINGS: + parsed = tomllib.loads(text.lstrip("")) + store = parsed.get("store", {}) + assert store.get("key_provider") == expected or expected is None, text + paths = [] + for i, (text, _) in enumerate(_SETTINGS): + p = tmp_path / f"settings-{i}.toml" + p.write_bytes(text.encode("utf-8")) + paths.append(str(p)) + body = ( + " $out = @(foreach ($p in @(" + + ", ".join(_psq(p) for p in paths) + + ")) { $v = Get-SettingsKeyProvider -Path $p; if ($null -eq $v) { '' } else { $v } })\n" + " ConvertTo-Json -InputObject $out -Compress\n" + ) + got = json.loads(_ok(_extract(_SCRIPT, ["Get-SettingsKeyProvider"], body), tmp_path)) + want = ["" if e is None else e for _, e in _SETTINGS] + assert got == want, list(zip([t for t, _ in _SETTINGS], got, want, strict=True)) + + +# (-ServiceAccount, -AllowLocalSystem, refused) +_ACCOUNTS: list[tuple[str, bool, bool]] = [ + ("", True, True), + ("", False, False), + (r"NT SERVICE\MessageFoundry", False, False), + (r"NT SERVICE\MessageFoundry", True, False), # an explicit -ServiceAccount wins + (r"CONTOSO\svc-mefor$", False, False), + ("LocalSystem", False, True), + (r".\LocalSystem", False, True), + (r"NT AUTHORITY\SYSTEM", False, True), + ("SYSTEM", False, True), + (r"nt authority\localservice", False, True), + (r"NT AUTHORITY\LOCAL SERVICE", False, True), + (r"NT AUTHORITY\NetworkService", False, True), + (r"NT AUTHORITY\NETWORK SERVICE", False, True), + ("*S-1-5-18", False, True), + ("S-1-5-20", False, True), +] + + +def test_the_host_provider_refuses_the_shared_accounts(tmp_path: Path) -> None: + """One pwsh run for every case: the function is pure.""" + assert _SCRIPT is not None + calls = "\n".join( + f" $out += [string](Get-HostCustodyAccountProblem -ServiceAccount {_psq(account)} " + f"-AllowLocalSystem:{'$true' if allow else '$false'})" + for account, allow, _ in _ACCOUNTS + ) + body = f" $out = @()\n{calls}\n ConvertTo-Json -InputObject $out -Compress\n" + got = json.loads(_ok(_extract(_SCRIPT, ["Get-HostCustodyAccountProblem"], body), tmp_path)) + assert [bool(p) for p in got] == [r for _, _, r in _ACCOUNTS], list( + zip(_ACCOUNTS, got, strict=False) + ) + + +def test_the_installer_refuses_before_anything_acts_and_wires_the_custody_steps( + tmp_path: Path, +) -> None: + """CALL-SITE guard: the refusal reads the settings file the service is registered with, the + service's own environment first, and throws before NSSM is resolved or the install is built; + the secrets directory's grant follows the same reading; and the printed step names + --service-account.""" + facts = _preflight_facts(tmp_path) + text = _script_text().replace("\r\n", "\n") + reader = _sole_call(facts, "Get-SettingsKeyProvider") + assert "-Path $ServiceConfig" in reader["text"], reader["text"] + problem = _sole_call(facts, "Get-HostCustodyAccountProblem") + assert "-ServiceAccount $ServiceAccount" in problem["text"], problem["text"] + assert "-AllowLocalSystem:$AllowLocalSystem" in problem["text"], problem["text"] + registered = next( + c + for c in facts["commands"] + if c["name"] == "Get-RegisteredEnvironmentValue" and "MEFOR_STORE_KEY_PROVIDER" in c["text"] + ) + assert registered["start"] < reader["start"] + refusal = text.index("$custodyAccountProblem, and the service's settings name") + for later in ( + "if ($BuildsInstall) {\n # AFTER the normalization", + "if (-not $BuildsInstall) { $NssmPath = Resolve-Nssm", + "New-Item -ItemType Directory -Force -Path $DataDir", + ): + assert refusal < text.index(later), later + # The settings file is known to exist before it is read. + assert text.index("Service settings file not found at: $ServiceConfig") < refusal + lock = _sole_call(facts, "Set-SecretsDirAcl") + assert "-AddFile:$HostCustody" in lock["text"], lock["text"] + assert "--service-account $(& $q $RunAsObjectName)" in text + assert "$env:MEFOR_SECRETS_DIRECTORY = $(& $q $SecretsDir)" in text + + +@_windows_only +def test_add_file_lets_the_account_add_a_file_to_the_directory_alone(tmp_path: Path) -> None: + """Set-SecretsDirAcl -AddFile gives the account CreateFiles on the directory, not inherited by + its files, and the engine's own check still accepts the directory. Without the switch the + account gets no such right (the control). Unelevated, the owner change is refused, and the + function refuses for that alone, as in the lockdown test beside it.""" + from messagefoundry.restricted_file import broad_access_problem + + assert _SCRIPT is not None + results = {} + for add in (True, False): + secrets = tmp_path / f"sd-{uuid.uuid4().hex[:8]}" / "secrets" + secrets.mkdir(parents=True) + switch = "$true" if add else "$false" + body = rf""" + $me = [Security.Principal.WindowsIdentity]::GetCurrent().Name + $mySid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value + $dir = {_psq(str(secrets))} + $refusal = '' + try {{ Set-SecretsDirAcl -Path $dir -Account $me -AddFile:{switch} }} catch {{ $refusal = $_.Exception.Message }} + $acl = Get-Acl $dir + $add = [System.Security.AccessControl.FileSystemRights]::CreateFiles + $mine = @($acl.Access | Where-Object {{ + try {{ $_.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value -eq $mySid }} + catch {{ $false }} }}) + [pscustomobject]@{{ + refusal = $refusal + dirAdd = @($mine | Where-Object {{ ($_.FileSystemRights -band $add) -eq $add -and + -not ($_.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) }}).Count + inheritedAdd = @($mine | Where-Object {{ ($_.FileSystemRights -band $add) -eq $add -and + ($_.InheritanceFlags -ne [Security.AccessControl.InheritanceFlags]::None) }}).Count + text = (& icacls $dir | Out-String) + }} | ConvertTo-Json -Depth 4 -Compress +""" + try: + got = json.loads( + _ok( + _extract( + _SCRIPT, + [ + "Set-SecretsDirAcl", + "Get-WellKnownBroadSids", + "Get-BroadAclResidue", + "Get-ReparsePointAncestor", + ], + body, + ), + tmp_path, + ) + .strip() + .splitlines()[-1] + ) + got["engine"] = broad_access_problem(secrets, directory=True) + finally: + restore = rf""" + $me = [Security.Principal.WindowsIdentity]::GetCurrent().Name + & icacls {_psq(str(secrets))} /inheritance:e /grant "${{me}}:(OI)(CI)F" | Out-Null +""" + _run(_extract(_SCRIPT, [], restore), tmp_path) + results[add] = got + on, off = results[True], results[False] + assert on["engine"] is None, on + assert on["dirAdd"] >= 1 and on["inheritedAdd"] == 0, on["text"] + assert off["dirAdd"] == 0, ( + f"CONTROL FAILED: the account could add a file without -AddFile\n{off['text']}" + ) + for got in (on, off): + refusal = got["refusal"] + assert not refusal or ( + "owner" in refusal and "add a file" not in refusal and "grants access" not in refusal + ), refusal From 74d9b48ccc2852c271dcdcfeeb9f4bf334fc8f2b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 10:18:45 -0600 Subject: [PATCH 02/28] Key custody B3c repair round 1: keep only the account refusal; read TOML names case-sensitively Vault BACKLOG #3411 slice B3c, review round-4be4461e2a. Removed the secrets-directory add-file grant and the printed provision-admin --service-account step. A standing engine write on the secrets directory is a design choice the row leaves open (it lets the engine plant secret-class files), and the printed step fails without it, so both go to the Manager. The settings reader now compares table and key names case-sensitively, as TOML does, and ignores a key_provider nested inside the store inline table. The refusal names which source set the host provider: the service's own environment or the settings file. docs/SERVICE.md states the refusal alone, with -AllowLocalSystem refused only when no -ServiceAccount is passed. Tests check every case against tomllib, including the new negatives. --- docs/SERVICE.md | 14 ++-- scripts/service/install-service.ps1 | 81 ++++-------------- tests/test_file_path_join_census.py | 5 +- tests/test_install_service_custody.py | 116 ++++---------------------- 4 files changed, 44 insertions(+), 172 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index f2717a40a1..771fd8aa6a 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -245,14 +245,12 @@ Administrator from an elevated shell on the host: messagefoundry provision-admin --username --email
--db C:\ProgramData\MessageFoundry\messagefoundry.db ``` -When the settings file names `[store].key_provider = 'host'` (vault BACKLOG #3411), skip step 1: -that provider refuses a second store key source beside it, so leave `MEFOR_STORE_ENCRYPTION_KEY` -unset. `provision-admin` mints the store key instead. When the install script reads that setting -(its `Get-SettingsKeyProvider` says in which forms), it prints the command for step 2, with `--service-account` naming the service's account and the secrets directory the -service was registered with. The script also lets that account add files to the secrets directory, -where the service writes its own key file at its first start. It refuses `-AllowLocalSystem`, and -at least the SYSTEM, LOCAL SERVICE and NETWORK SERVICE spellings of `-ServiceAccount`, because that -provider refuses those accounts and the service would not start. +Under `[store].key_provider = 'host'` (vault BACKLOG #3411) the service cannot run as SYSTEM, +LOCAL SERVICE or NETWORK SERVICE: that provider refuses them as the engine account. When the +install script reads that setting, from the settings file in the forms its +`Get-SettingsKeyProvider` lists or from `MEFOR_STORE_KEY_PROVIDER` in the service's own +environment, it refuses such an account before it changes anything: `-AllowLocalSystem` with no +`-ServiceAccount`, and at least the usual spellings of those accounts as `-ServiceAccount`. If the service started first, at the shipped posture it refuses to start. Once the earlier start checks pass (the store key and `[alerts]` among them), that refusal names `provision-admin` in the diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index 220831011f..e50ab9ad82 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -1003,13 +1003,8 @@ function Set-SecretsDirAcl { anything left over is a refusal, not a warning. The engine refuses only the known broad groups at start, so an entry for some other account would go unnoticed there and could read every secret in the directory. - - -AddFile ALSO LETS THE ACCOUNT ADD A FILE TO THE DIRECTORY ITSELF (vault BACKLOG #3411, key - custody S3 slice B3c). Under [store].key_provider = 'host' the directory holds the store key, - and the service's first start writes its own key file there from the handoff provision-admin - left. The grant is on the directory alone, not inherited by its files, and is read back. #> - param([Parameter(Mandatory)][string]$Path, [string]$Account, [switch]$AddFile) + param([Parameter(Mandatory)][string]$Path, [string]$Account) $remedy = "Restrict it as docs/CONFIGURATION.md 'The secrets directory' shows, and re-run the installer." # Read again here, not only when -SecretsDir was judged: icacls follows a junction to its # target, and the path, or a folder above it, may have become one since. @@ -1036,13 +1031,6 @@ function Set-SecretsDirAcl { $problems += ("'$Account' could not be granted read (icacls exit $LASTEXITCODE), so the " + "service could not read the directory") } - if ($AddFile) { - & icacls $Path /grant "${Account}:(WD)" | Out-Null - if ($LASTEXITCODE -ne 0) { - $problems += ("'$Account' could not be granted the right to add a file (icacls exit " + - "$LASTEXITCODE), so the service could not write its store key file there") - } - } } # The same well-known broad set Set-SecureDataDirAcl removes, for the reasons it gives. $broad = Get-WellKnownBroadSids @@ -1079,18 +1067,6 @@ function Set-SecretsDirAcl { $(try { $_.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value -eq $accountSid } catch { $false }) }) if (-not $held) { $problems += "'$Account' holds no read on it, so the service could not read it" } - if ($AddFile) { - $add = [System.Security.AccessControl.FileSystemRights]::CreateFiles - $adds = @($acl.Access | Where-Object { - $_.AccessControlType -eq [Security.AccessControl.AccessControlType]::Allow -and - -not ($_.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) -and - ($_.FileSystemRights -band $add) -eq $add -and - $(try { $_.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value -eq $accountSid } - catch { $false }) }) - if (-not $adds) { - $problems += "'$Account' cannot add a file to it, so the service could not write its store key file" - } - } } } catch { $problems += "its access list could not be read back ($($_.Exception.Message))" @@ -1167,10 +1143,11 @@ function Get-SettingsKeyProvider { READ AS TEXT. Running the install's interpreter would run its code from this elevated prompt, which the interpreter check below declines to do. So this reads at least a key_provider line in - a [store] table, a top-level store.key_provider dotted key, and a one-line store inline table, - each holding a one-line string with no escape. Any other form reads as $null. What the installer - does with the answer is an early refusal and a printed step: the engine applies its own key - custody refusals at start whatever this returns. + a [store] table, a top-level store.key_provider dotted key, and a one-line store inline table + with no table nested before the key, each holding a one-line string with no escape. Names + compare case-sensitively, as TOML's do. Any other form reads as $null. What the installer does + with the answer is an early refusal: the engine applies its own key custody refusals at start + whatever this returns. #> param([Parameter(Mandatory)][string]$Path) $value = '(?:"(?[^"\\]*)"|''(?[^'']*)'')' @@ -1181,15 +1158,15 @@ function Get-SettingsKeyProvider { $found = $null foreach ($line in [IO.File]::ReadAllLines($Path)) { $line = $line.TrimStart([char]0xFEFF) - if ($line -match '^\s*\[\[') { $table = "[[]]"; continue } - if ($line -match ('^\s*\[(?[^\]]*)\]' + $tail)) { - $table = $Matches.t -replace '[\s"'']', '' + if ($line -cmatch '^\s*\[\[') { $table = "[[]]"; continue } + if ($line -cmatch ('^\s*\[(?[^\]]*)\]' + $tail)) { + $table = $Matches.t -creplace '[\s"'']', '' continue } # A [store] line; a top-level dotted key; a top-level one-line inline table. - if (($table -eq "store" -and $line -match ('^\s*' + $key + '\s*=\s*' + $value + $tail)) -or - ($table -eq "" -and $line -match ('^\s*' + $store + '\s*(?:\.\s*' + $key + '\s*=\s*' + - $value + $tail + '|=\s*\{(?:.*[,{\s])?' + $key + '\s*=\s*' + $value + ')'))) { + if (($table -ceq "store" -and $line -cmatch ('^\s*' + $key + '\s*=\s*' + $value + $tail)) -or + ($table -ceq "" -and $line -cmatch ('^\s*' + $store + '\s*(?:\.\s*' + $key + '\s*=\s*' + + $value + $tail + '|=\s*\{(?:[^{]*[,\s])?' + $key + '\s*=\s*' + $value + ')'))) { $found = $Matches.v } } @@ -2868,8 +2845,11 @@ $HostCustody = if ($null -ne $RegisteredKeyProvider) { $RegisteredKeyProvider -c if ($HostCustody) { $custodyAccountProblem = Get-HostCustodyAccountProblem -ServiceAccount $ServiceAccount -AllowLocalSystem:$AllowLocalSystem if ($custodyAccountProblem) { - throw ("$custodyAccountProblem, and the service's settings name [store].key_provider = " + - "'host', whose key custody refuses that account, so the service would not start. Leave " + + $namedBy = if ($null -ne $RegisteredKeyProvider) { + "the service's own environment sets MEFOR_STORE_KEY_PROVIDER=host" + } else { "the settings file '$ServiceConfig' names [store].key_provider = 'host'" } + throw ("$custodyAccountProblem, and $namedBy, a key provider whose custody refuses that " + + "account, so the service would not start. Leave " + "out -AllowLocalSystem to run as the virtual account 'NT SERVICE\$ServiceName', or pass a " + "-ServiceAccount of the service's own (docs/SERVICE.md 'Least-privilege service account').") } @@ -3307,7 +3287,7 @@ Set-DataDirOwner -Path $DataDir # setting. The service is told where it is through its environment, which holds only the path. # A directory left unrestricted is a refusal, and the service is registered by now, so it is # disabled first, as the other refusals after registration are. -try { Set-SecretsDirAcl -Path $SecretsDir -Account $ServiceAccount -AddFile:$HostCustody } +try { Set-SecretsDirAcl -Path $SecretsDir -Account $ServiceAccount } catch { throw "$($_.Exception.Message) $(Disable-RefusedService -ServiceName $ServiceName -Consequence 'it cannot start with a secrets directory others can read')" } @@ -3463,31 +3443,6 @@ Write-Host " Logs : $StdoutLog" Write-Host " $StderrLog" Write-Host "" Write-Host "Next steps:" -# Key custody (vault BACKLOG #3411, S3 slice B3c): under the host provider the service starts only -# once its store key is minted, and provision-admin mints it as the handoff the service converts on -# its first start. The installer does not run it: it would run the install's code from this -# elevated prompt, and it asks for a password and the recovery key at the terminal. So the command -# is printed, naming the account, the settings file, the store path and the secrets directory the -# service was registered with, so the shell and the service read one directory (vault BACKLOG #8119 -# item 9). Not printed when a store key file is already in that directory. -if ($HostCustody) { - $custodyFile = "master.key", "handoff.key" | ForEach-Object { Join-Path $SecretsDir $_ } | - Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 - if ($custodyFile) { - Write-Host (" Store key: '$custodyFile' is already there ([store].key_provider = " + - "'host'), so provision-admin mints no key over it.") - } else { - $q = { param($s) "'" + ($s -replace "'", "''") + "'" } - Write-Host (" Before the first start, mint the store key for '$RunAsObjectName' " + - "([store].key_provider = 'host'), in an elevated PowerShell:") - Write-Host " `$env:MEFOR_SECRETS_DIRECTORY = $(& $q $SecretsDir)" - Write-Host (" & $(& $q $PythonExe) $EngineInterpreterOptions -m messagefoundry provision-admin " + - "--username --email
--service-config $(& $q $ServiceConfig) " + - "--db $(& $q $DbPath) --service-account $(& $q $RunAsObjectName)") - Write-Host (" It shows the store's recovery key once and asks for it back. Keep it off this " + - "host: with neither this host nor that key, the store cannot be opened.") - } -} # Start-Service needs no nssm.exe, so an operator following this never runs a copy nobody checked # (BACKLOG #2364). Write-Host " Start-Service '$ServiceName'" diff --git a/tests/test_file_path_join_census.py b/tests/test_file_path_join_census.py index 34ec5765d4..a169f020d7 100644 --- a/tests/test_file_path_join_census.py +++ b/tests/test_file_path_join_census.py @@ -1256,15 +1256,14 @@ def derived_script_sites() -> dict[str, int]: 7, OPERATOR, "Fixed names under the repo root, the helper source and the install directory." ), "scripts/service/install-service.ps1": Site( - 45, + 44, OPERATOR, "Fixed names, and a folder named from a fresh GUID under the Windows temp folder, under " "paths the operator passes or the script derives (repo root, install " "root and its site-packages, dist-info, wheelhouse and buildtemp folders, the engine " "wheel's folder, " "the base interpreter's folder and the one above it, " - "project root, data directory and the folder above it, secrets directory, ProgramData, NSSM " - "directory, temp), " + "project root, data directory and the folder above it, ProgramData, NSSM directory, temp), " "the data directory's own leaf name with -secrets after it, the leaf name of the engine wheel " "the operator passes, which must match messagefoundry--*.whl, plus registry keys " "named after the service's own images, and the fixed Parameters key under each key the " diff --git a/tests/test_install_service_custody.py b/tests/test_install_service_custody.py index f3a195c57c..8c20b8b2ab 100644 --- a/tests/test_install_service_custody.py +++ b/tests/test_install_service_custody.py @@ -4,17 +4,14 @@ slice B3c). The installer refuses the accounts the host provider refuses as the engine account, before -anything acts; lets the service account add a file to the secrets directory, where the service's -first start writes its key file from the handoff; and prints the ``provision-admin ---service-account`` step. Behaviour runs the script's own functions, extracted by AST, through -``pwsh``; the call sites are read by AST, since no test runs the script body. +anything acts. Behaviour runs the script's own functions, extracted by AST, through ``pwsh``; the +call sites are read by AST, since no test runs the script body. """ from __future__ import annotations import json import tomllib -import uuid from pathlib import Path import pytest @@ -25,10 +22,8 @@ _ok, _preflight_facts, _psq, - _run, _script_text, _sole_call, - _windows_only, ) pytestmark = pytest.mark.skipif( @@ -36,6 +31,8 @@ reason="install-service.ps1 not locatable (off-repo / non-editable install)", ) +_BOM = "\N{ZERO WIDTH NO-BREAK SPACE}" + # (settings file text, what the installer must read as [store].key_provider) _SETTINGS: list[tuple[str, str | None]] = [ ('[store]\nkey_provider = "host"\n', "host"), @@ -44,7 +41,7 @@ ('[store]\n"key_provider" = "host"\n', "host"), ('store.key_provider = "host"\n[api]\nport = 1\n', "host"), ('store = { backend = "sqlite", key_provider = "host" }\n', "host"), - ('[store]\nkey_provider = "host"\n', "host"), + (_BOM + '[store]\nkey_provider = "host"\n', "host"), ('[store]\nkey_provider = "auto"\n', "auto"), ('[store]\nbackend = "sqlite"\n', None), ('[store.tls]\nkey_provider = "host"\n', None), @@ -52,18 +49,21 @@ ('[store]\n[[alerts.sinks]]\nkey_provider = "host"\n', None), ('[store]\n# key_provider = "host"\n', None), ('[store]\nother_key_provider = "host"\n', None), + # TOML names are case-sensitive, and a key in a nested inline table is not [store]'s. + ('[STORE]\nkey_provider = "host"\n', None), + ('[store]\nKEY_PROVIDER = "host"\n', None), + ('store = { tls = { key_provider = "host" } }\n', None), ("", None), ] def test_the_settings_reader_finds_the_key_provider(tmp_path: Path) -> None: - """Every positive case parses to the same value under Python's own TOML reader, so the cases - are real settings files and not text the reader merely happens to match.""" + """Every case is a real settings file whose [store].key_provider, under Python's own TOML + reader, is the value the installer must read.""" assert _SCRIPT is not None for text, expected in _SETTINGS: - parsed = tomllib.loads(text.lstrip("")) - store = parsed.get("store", {}) - assert store.get("key_provider") == expected or expected is None, text + store = tomllib.loads(text.removeprefix(_BOM)).get("store", {}) + assert store.get("key_provider") == expected, text paths = [] for i, (text, _) in enumerate(_SETTINGS): p = tmp_path / f"settings-{i}.toml" @@ -115,13 +115,10 @@ def test_the_host_provider_refuses_the_shared_accounts(tmp_path: Path) -> None: ) -def test_the_installer_refuses_before_anything_acts_and_wires_the_custody_steps( - tmp_path: Path, -) -> None: - """CALL-SITE guard: the refusal reads the settings file the service is registered with, the - service's own environment first, and throws before NSSM is resolved or the install is built; - the secrets directory's grant follows the same reading; and the printed step names - --service-account.""" +def test_the_installer_refuses_before_anything_acts(tmp_path: Path) -> None: + """CALL-SITE guard: the refusal reads the service's own environment first, then the settings + file the service is registered with, and throws before NSSM is resolved or the install is + built.""" facts = _preflight_facts(tmp_path) text = _script_text().replace("\r\n", "\n") reader = _sole_call(facts, "Get-SettingsKeyProvider") @@ -135,7 +132,7 @@ def test_the_installer_refuses_before_anything_acts_and_wires_the_custody_steps( if c["name"] == "Get-RegisteredEnvironmentValue" and "MEFOR_STORE_KEY_PROVIDER" in c["text"] ) assert registered["start"] < reader["start"] - refusal = text.index("$custodyAccountProblem, and the service's settings name") + refusal = text.index('throw ("$custodyAccountProblem, and $namedBy') for later in ( "if ($BuildsInstall) {\n # AFTER the normalization", "if (-not $BuildsInstall) { $NssmPath = Resolve-Nssm", @@ -144,80 +141,3 @@ def test_the_installer_refuses_before_anything_acts_and_wires_the_custody_steps( assert refusal < text.index(later), later # The settings file is known to exist before it is read. assert text.index("Service settings file not found at: $ServiceConfig") < refusal - lock = _sole_call(facts, "Set-SecretsDirAcl") - assert "-AddFile:$HostCustody" in lock["text"], lock["text"] - assert "--service-account $(& $q $RunAsObjectName)" in text - assert "$env:MEFOR_SECRETS_DIRECTORY = $(& $q $SecretsDir)" in text - - -@_windows_only -def test_add_file_lets_the_account_add_a_file_to_the_directory_alone(tmp_path: Path) -> None: - """Set-SecretsDirAcl -AddFile gives the account CreateFiles on the directory, not inherited by - its files, and the engine's own check still accepts the directory. Without the switch the - account gets no such right (the control). Unelevated, the owner change is refused, and the - function refuses for that alone, as in the lockdown test beside it.""" - from messagefoundry.restricted_file import broad_access_problem - - assert _SCRIPT is not None - results = {} - for add in (True, False): - secrets = tmp_path / f"sd-{uuid.uuid4().hex[:8]}" / "secrets" - secrets.mkdir(parents=True) - switch = "$true" if add else "$false" - body = rf""" - $me = [Security.Principal.WindowsIdentity]::GetCurrent().Name - $mySid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value - $dir = {_psq(str(secrets))} - $refusal = '' - try {{ Set-SecretsDirAcl -Path $dir -Account $me -AddFile:{switch} }} catch {{ $refusal = $_.Exception.Message }} - $acl = Get-Acl $dir - $add = [System.Security.AccessControl.FileSystemRights]::CreateFiles - $mine = @($acl.Access | Where-Object {{ - try {{ $_.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value -eq $mySid }} - catch {{ $false }} }}) - [pscustomobject]@{{ - refusal = $refusal - dirAdd = @($mine | Where-Object {{ ($_.FileSystemRights -band $add) -eq $add -and - -not ($_.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) }}).Count - inheritedAdd = @($mine | Where-Object {{ ($_.FileSystemRights -band $add) -eq $add -and - ($_.InheritanceFlags -ne [Security.AccessControl.InheritanceFlags]::None) }}).Count - text = (& icacls $dir | Out-String) - }} | ConvertTo-Json -Depth 4 -Compress -""" - try: - got = json.loads( - _ok( - _extract( - _SCRIPT, - [ - "Set-SecretsDirAcl", - "Get-WellKnownBroadSids", - "Get-BroadAclResidue", - "Get-ReparsePointAncestor", - ], - body, - ), - tmp_path, - ) - .strip() - .splitlines()[-1] - ) - got["engine"] = broad_access_problem(secrets, directory=True) - finally: - restore = rf""" - $me = [Security.Principal.WindowsIdentity]::GetCurrent().Name - & icacls {_psq(str(secrets))} /inheritance:e /grant "${{me}}:(OI)(CI)F" | Out-Null -""" - _run(_extract(_SCRIPT, [], restore), tmp_path) - results[add] = got - on, off = results[True], results[False] - assert on["engine"] is None, on - assert on["dirAdd"] >= 1 and on["inheritedAdd"] == 0, on["text"] - assert off["dirAdd"] == 0, ( - f"CONTROL FAILED: the account could add a file without -AddFile\n{off['text']}" - ) - for got in (on, off): - refusal = got["refusal"] - assert not refusal or ( - "owner" in refusal and "add a file" not in refusal and "grants access" not in refusal - ), refusal From 2516efd89f8e98782b38cce29c3a75290c3efb1c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 10:45:33 -0600 Subject: [PATCH 03/28] Key custody B3c repair round 2: the settings reader skips multi-line strings, comments and array elements; SERVICE.md states the host path is not complete Vault BACKLOG #3411 slice B3c, review round-63bd861ddc. Get-SettingsKeyProvider skips lines inside a multi-line string, takes a header only when it names a table by bare or quoted keys, and in a store inline table ignores text in a string value or after the table. The refusal's remedy names -ServiceAccount when that is what was passed, and the comment no longer claims to match the engine's environment reading beyond the service's NSSM list. docs/SERVICE.md now says the steps do not yet cover the host provider (step 1's key is refused; the service's first start cannot write its key file with the read-only grant), and that the script does not check the non-local account refusal under enforce. --- docs/SERVICE.md | 10 +++++++++- scripts/service/install-service.ps1 | 27 ++++++++++++++++++--------- tests/test_install_service_custody.py | 12 ++++++++++-- 3 files changed, 37 insertions(+), 12 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index 771fd8aa6a..36b7013c57 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -250,7 +250,15 @@ LOCAL SERVICE or NETWORK SERVICE: that provider refuses them as the engine accou install script reads that setting, from the settings file in the forms its `Get-SettingsKeyProvider` lists or from `MEFOR_STORE_KEY_PROVIDER` in the service's own environment, it refuses such an account before it changes anything: `-AllowLocalSystem` with no -`-ServiceAccount`, and at least the usual spellings of those accounts as `-ServiceAccount`. +`-ServiceAccount`, and at least the usual spellings of those accounts as `-ServiceAccount`. Under +`[security].enforcement = 'enforce'` the provider also refuses an account that is not local to +this host, such as a domain user or a gMSA, and the script does not check for that. + +The steps above do not yet cover that provider. It refuses a store key set beside it, so step 1's +key makes `provision-admin` refuse; and it mints the store key, which `--service-account` mints for +the service's account rather than yours. The script grants that account read only on the secrets +directory, where the service's first start must write its own key file, so a service the script +installs under this provider does not start yet (vault BACKLOG #3411). If the service started first, at the shipped posture it refuses to start. Once the earlier start checks pass (the store key and `[alerts]` among them), that refusal names `provision-admin` in the diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index e50ab9ad82..30d68e83cc 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -1156,17 +1156,25 @@ function Get-SettingsKeyProvider { $tail = '\s*(?:#.*)?$' $table = "" $found = $null + $inString = $false foreach ($line in [IO.File]::ReadAllLines($Path)) { $line = $line.TrimStart([char]0xFEFF) + # A line inside a multi-line string is never a header or a key; an odd count of + # triple quotes opens or closes one. + $wasInString = $inString + if (([regex]::Matches($line, '"""|''''''').Count % 2) -eq 1) { $inString = -not $inString } + if ($wasInString -or $inString) { continue } if ($line -cmatch '^\s*\[\[') { $table = "[[]]"; continue } - if ($line -cmatch ('^\s*\[(?[^\]]*)\]' + $tail)) { + # A header names a table by bare or quoted keys, so an array element such as ["a", "b"] + # is not one. + if ($line -cmatch ('^\s*\[(?[A-Za-z0-9_.\-"'' ]+)\]' + $tail)) { $table = $Matches.t -creplace '[\s"'']', '' continue } # A [store] line; a top-level dotted key; a top-level one-line inline table. if (($table -ceq "store" -and $line -cmatch ('^\s*' + $key + '\s*=\s*' + $value + $tail)) -or ($table -ceq "" -and $line -cmatch ('^\s*' + $store + '\s*(?:\.\s*' + $key + '\s*=\s*' + - $value + $tail + '|=\s*\{(?:[^{]*[,\s])?' + $key + '\s*=\s*' + $value + ')'))) { + $value + $tail + '|=\s*\{(?:(?:[^{}"''#]|"[^"\\]*"|''[^'']*'')*[,\s])?' + $key + '\s*=\s*' + $value + ')'))) { $found = $Matches.v } } @@ -2835,10 +2843,10 @@ if ($ServiceConfig -and -not (Test-Path -LiteralPath $ServiceConfig -PathType Le } # --- key custody: [store].key_provider = 'host' (vault BACKLOG #3411, S3 slice B3c) -------------------- -# The service's own environment overrides the settings file, as it does at start, so on a rerun a -# MEFOR_STORE_KEY_PROVIDER already registered for the service is what counts. Refused before -# anything acts. Get-SettingsKeyProvider says what it reads, and why the engine's own refusal at -# start does not rest on it. +# On a rerun, a MEFOR_STORE_KEY_PROVIDER in the service's NSSM environment (AppEnvironmentExtra) +# wins over the settings file, as an environment variable does at start. No other environment is +# read here, the machine's included. Refused before anything acts. Get-SettingsKeyProvider says +# what it reads, and why the engine's own refusal at start does not rest on it. $RegisteredKeyProvider = Get-RegisteredEnvironmentValue -ServiceName $ServiceName -Name "MEFOR_STORE_KEY_PROVIDER" $HostCustody = if ($null -ne $RegisteredKeyProvider) { $RegisteredKeyProvider -ceq "host" } else { (Get-SettingsKeyProvider -Path $ServiceConfig) -ceq "host" } @@ -2848,10 +2856,11 @@ if ($HostCustody) { $namedBy = if ($null -ne $RegisteredKeyProvider) { "the service's own environment sets MEFOR_STORE_KEY_PROVIDER=host" } else { "the settings file '$ServiceConfig' names [store].key_provider = 'host'" } + $remedy = if ($ServiceAccount) { "Pass a -ServiceAccount of the service's own, or leave it and -AllowLocalSystem out" } + else { "Leave out -AllowLocalSystem" } throw ("$custodyAccountProblem, and $namedBy, a key provider whose custody refuses that " + - "account, so the service would not start. Leave " + - "out -AllowLocalSystem to run as the virtual account 'NT SERVICE\$ServiceName', or pass a " + - "-ServiceAccount of the service's own (docs/SERVICE.md 'Least-privilege service account').") + "account, so the service would not start. $remedy to run as the virtual account " + + "'NT SERVICE\$ServiceName' (docs/SERVICE.md 'Least-privilege service account').") } } diff --git a/tests/test_install_service_custody.py b/tests/test_install_service_custody.py index 8c20b8b2ab..d82d9c36e6 100644 --- a/tests/test_install_service_custody.py +++ b/tests/test_install_service_custody.py @@ -3,8 +3,9 @@ """install-service.ps1 under ``[store].key_provider = 'host'`` (vault BACKLOG #3411, key custody S3 slice B3c). -The installer refuses the accounts the host provider refuses as the engine account, before -anything acts. Behaviour runs the script's own functions, extracted by AST, through ``pwsh``; the +The installer refuses SYSTEM, LOCAL SERVICE and NETWORK SERVICE, which the host provider refuses as +the engine account, before anything acts. It does not check the provider's refusal of a non-local +account under enforce. Behaviour runs the script's own functions, extracted by AST, through ``pwsh``; the call sites are read by AST, since no test runs the script body. """ @@ -53,6 +54,13 @@ ('[STORE]\nkey_provider = "host"\n', None), ('[store]\nKEY_PROVIDER = "host"\n', None), ('store = { tls = { key_provider = "host" } }\n', None), + # Text that only looks like the key: a comment, a string value, a multi-line string. + ('store = { backend = "sqlite" } # was key_provider = "host"\n', None), + ('store = { backend = "sqlite", note = "x key_provider = \'host\'" }\n', None), + ('[api]\nnote = """\n[store]\nkey_provider = "host"\n"""\n', None), + # Lines that only look like a table header do not move the reader out of [store]. + ('[store]\npairs = [\n ["a", "b"]\n]\nkey_provider = "host"\n', "host"), + ('[store]\nnote = """\n[api]\n"""\nkey_provider = "host"\n', "host"), ("", None), ] From 2ed4bbbd136c2a45b3ab5eb1f63f1584aaef8b08 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 11:15:24 -0600 Subject: [PATCH 04/28] Key custody B3c: text only, the reader's docstring states its triple-quote limit and the refusal names the real SERVICE.md heading Vault BACKLOG #3411 slice B3c, after review round-7269978c8a; no code changed. --- docs/SERVICE.md | 4 ++-- scripts/service/install-service.ps1 | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index 36b7013c57..eaa081a154 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -247,8 +247,8 @@ messagefoundry provision-admin --username --email
--db C:\Progr Under `[store].key_provider = 'host'` (vault BACKLOG #3411) the service cannot run as SYSTEM, LOCAL SERVICE or NETWORK SERVICE: that provider refuses them as the engine account. When the -install script reads that setting, from the settings file in the forms its -`Get-SettingsKeyProvider` lists or from `MEFOR_STORE_KEY_PROVIDER` in the service's own +install script reads that setting, from the settings file as its `Get-SettingsKeyProvider` +describes, or from `MEFOR_STORE_KEY_PROVIDER` in the service's own environment, it refuses such an account before it changes anything: `-AllowLocalSystem` with no `-ServiceAccount`, and at least the usual spellings of those accounts as `-ServiceAccount`. Under `[security].enforcement = 'enforce'` the provider also refuses an account that is not local to diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index 30d68e83cc..c051ccf875 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -1145,7 +1145,9 @@ function Get-SettingsKeyProvider { which the interpreter check below declines to do. So this reads at least a key_provider line in a [store] table, a top-level store.key_provider dotted key, and a one-line store inline table with no table nested before the key, each holding a one-line string with no escape. Names - compare case-sensitively, as TOML's do. Any other form reads as $null. What the installer does + compare case-sensitively, as TOML's do. Any other form reads as $null. A triple quote in a + comment or a one-line string, or a multi-line string holding the other delimiter, can make + it misread every line after it, either way. What the installer does with the answer is an early refusal: the engine applies its own key custody refusals at start whatever this returns. #> @@ -2860,7 +2862,7 @@ if ($HostCustody) { else { "Leave out -AllowLocalSystem" } throw ("$custodyAccountProblem, and $namedBy, a key provider whose custody refuses that " + "account, so the service would not start. $remedy to run as the virtual account " + - "'NT SERVICE\$ServiceName' (docs/SERVICE.md 'Least-privilege service account').") + "'NT SERVICE\$ServiceName' (docs/SERVICE.md 'Run as a least-privilege account').") } } From 6edc3b962595d92da61cc673abc3f38f1635d0d3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 14:09:18 -0600 Subject: [PATCH 05/28] Key custody B3c: the settings reader skips lines inside a multi-line array; the custody test is classified as tooling Vault BACKLOG #3411 slice B3c, from the Manager's tail review of 2ed4bbbd136. A one-element nested array line such as ["store"] or [1] is no longer read as a table header, in [store] or outside it. tests/test_install_service_custody.py imports no engine module and its subject is scripts/service/install-service.ps1, so it joins tests/tooling_manifest.txt. --- scripts/service/install-service.ps1 | 20 +++++++++++++++----- tests/test_install_service_custody.py | 5 +++++ tests/tooling_manifest.txt | 1 + 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index c051ccf875..f867a0da55 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -1144,8 +1144,9 @@ function Get-SettingsKeyProvider { READ AS TEXT. Running the install's interpreter would run its code from this elevated prompt, which the interpreter check below declines to do. So this reads at least a key_provider line in a [store] table, a top-level store.key_provider dotted key, and a one-line store inline table - with no table nested before the key, each holding a one-line string with no escape. Names - compare case-sensitively, as TOML's do. Any other form reads as $null. A triple quote in a + with no table nested before the key, each holding a one-line string with no escape. Lines + inside a multi-line array or string are skipped. Names compare case-sensitively, as TOML's + do. Any other form reads as $null. A triple quote in a comment or a one-line string, or a multi-line string holding the other delimiter, can make it misread every line after it, either way. What the installer does with the answer is an early refusal: the engine applies its own key custody refusals at start @@ -1159,6 +1160,7 @@ function Get-SettingsKeyProvider { $table = "" $found = $null $inString = $false + $arrayDepth = 0 foreach ($line in [IO.File]::ReadAllLines($Path)) { $line = $line.TrimStart([char]0xFEFF) # A line inside a multi-line string is never a header or a key; an odd count of @@ -1166,11 +1168,19 @@ function Get-SettingsKeyProvider { $wasInString = $inString if (([regex]::Matches($line, '"""|''''''').Count % 2) -eq 1) { $inString = -not $inString } if ($wasInString -or $inString) { continue } - if ($line -cmatch '^\s*\[\[') { $table = "[[]]"; continue } - # A header names a table by bare or quoted keys, so an array element such as ["a", "b"] - # is not one. + # A line inside a multi-line array is an element, never a header or a key, even one shaped + # like a header such as ["store"] or [1]. The depth counts the brackets left open, outside + # strings and comments, by the lines before this one. + $inArray = $arrayDepth -gt 0 + $code = ($line -creplace '"(?:[^"\\]|\\.)*"|''[^'']*''', '""') -creplace '#.*$', '' + $arrayDepth = [Math]::Max(0, $arrayDepth + ([regex]::Matches($code, '\[').Count - + [regex]::Matches($code, '\]').Count)) + if ($inArray) { continue } + if ($line -cmatch '^\s*\[\[') { $table = "[[]]"; $arrayDepth = 0; continue } + # A header names a table by bare or quoted keys. if ($line -cmatch ('^\s*\[(?[A-Za-z0-9_.\-"'' ]+)\]' + $tail)) { $table = $Matches.t -creplace '[\s"'']', '' + $arrayDepth = 0 continue } # A [store] line; a top-level dotted key; a top-level one-line inline table. diff --git a/tests/test_install_service_custody.py b/tests/test_install_service_custody.py index d82d9c36e6..dafcba9932 100644 --- a/tests/test_install_service_custody.py +++ b/tests/test_install_service_custody.py @@ -60,6 +60,11 @@ ('[api]\nnote = """\n[store]\nkey_provider = "host"\n"""\n', None), # Lines that only look like a table header do not move the reader out of [store]. ('[store]\npairs = [\n ["a", "b"]\n]\nkey_provider = "host"\n', "host"), + # A one-element nested array line has a header's shape, inside [store] and outside it. + ('[store]\nretired = [\n ["k1"]\n]\nkey_provider = "host"\n', "host"), + ('[store]\nn = [\n [1],\n [2]\n]\nkey_provider = "host"\n', "host"), + ('[api]\nhosts = [\n ["store"]\n]\nkey_provider = "host"\n', None), + ('[api]\nhosts = [ # "]"\n ["store"]\n]\nkey_provider = "host"\n', None), ('[store]\nnote = """\n[api]\n"""\nkey_provider = "host"\n', "host"), ("", None), ] diff --git a/tests/tooling_manifest.txt b/tests/tooling_manifest.txt index 143f3a3a19..4f5e82d803 100644 --- a/tests/tooling_manifest.txt +++ b/tests/tooling_manifest.txt @@ -289,3 +289,4 @@ tests/test_dashboard_collect_metrics.py tests/test_dashboard_to_rows.py tests/test_dashboard_render_html.py tests/test_dashboard_ps_scripts.py +tests/test_install_service_custody.py From b9299afc2bb295b6a7dac70d810742af29ea7df7 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 14:30:29 -0600 Subject: [PATCH 06/28] Key custody B3c: text only, the settings reader's docstring drops its completeness claim Vault BACKLOG #3411 slice B3c, after review round-7130f3afc9; no code changed. --- scripts/service/install-service.ps1 | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index f867a0da55..c63bf66c6d 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -1146,9 +1146,10 @@ function Get-SettingsKeyProvider { a [store] table, a top-level store.key_provider dotted key, and a one-line store inline table with no table nested before the key, each holding a one-line string with no escape. Lines inside a multi-line array or string are skipped. Names compare case-sensitively, as TOML's - do. Any other form reads as $null. A triple quote in a - comment or a one-line string, or a multi-line string holding the other delimiter, can make - it misread every line after it, either way. What the installer does + do. Other forms can misread either way: at least a header it does not recognize (a tab, or a + quoted key with a space or punctuation) leaves the lines after it credited to the table + before it, and a triple quote in a comment or a one-line string, or a multi-line string + holding the other delimiter, can make it misread every line after it. What the installer does with the answer is an early refusal: the engine applies its own key custody refusals at start whatever this returns. #> From 1291264aa8fd55642cfd5ce04ad2433ab1163b90 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 14:33:45 -0600 Subject: [PATCH 07/28] Key custody B3c: the custody installer test imports messagefoundry.service and stays on the engine legs Vault BACKLOG #3411 slice B3c, Manager ruling on review round-7130f3afc9 finding 2: it takes the script path from messagefoundry.service as its sibling tests do, and leaves tests/tooling_manifest.txt. Imports and the manifest line only. --- tests/test_install_service_custody.py | 4 +++- tests/tooling_manifest.txt | 1 - 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/test_install_service_custody.py b/tests/test_install_service_custody.py index dafcba9932..5e39308fb7 100644 --- a/tests/test_install_service_custody.py +++ b/tests/test_install_service_custody.py @@ -17,8 +17,8 @@ import pytest +import messagefoundry.service as svc from tests.test_service_install_manifest import ( - _SCRIPT, _extract, _ok, _preflight_facts, @@ -27,6 +27,8 @@ _sole_call, ) +_SCRIPT = svc.install_script_path() + pytestmark = pytest.mark.skipif( _SCRIPT is None, reason="install-service.ps1 not locatable (off-repo / non-editable install)", diff --git a/tests/tooling_manifest.txt b/tests/tooling_manifest.txt index 4f5e82d803..143f3a3a19 100644 --- a/tests/tooling_manifest.txt +++ b/tests/tooling_manifest.txt @@ -289,4 +289,3 @@ tests/test_dashboard_collect_metrics.py tests/test_dashboard_to_rows.py tests/test_dashboard_render_html.py tests/test_dashboard_ps_scripts.py -tests/test_install_service_custody.py From 181484380e14f36cb155e1c836811a0e257dae9d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 15:37:06 -0600 Subject: [PATCH 08/28] Key custody: the host provider reads a custody directory of its own Vault BACKLOG #3411 slice B3c, design note 1. MEFOR_CUSTODY_DIRECTORY, an absolute path, names the directory that holds master.key and handoff.key, in place of MEFOR_SECRETS_DIRECTORY or a SQLite store's data directory, which stay the fallbacks. Before a read or a mint the engine applies the secrets directory's check (broad_access_problem with directory) to it, at every enforcement setting, so a broad group's right to read it, add a file or delete one is refused; one account's add-file right is not. With the variable set, a key file found only in the secrets directory refuses the read rather than reading as no key minted. The refusal and remedy texts that name the custody directory's variable (keep_the_key_step, the unusable-directory refusal, provision-admin's already-exists refusal and its where-the-key-went line) name the new one when it is set. Tests: the precedence, a mint into the directory, a broad grant refused with its control, the left-in-secrets refusal, and a first start that converts the handoff in a directory where this account holds only read and add-file. --- messagefoundry/__main__.py | 27 +++-- messagefoundry/engine_secrets.py | 7 ++ messagefoundry/store/custody_host.py | 158 ++++++++++++++++++++----- tests/test_store_custody_host.py | 169 +++++++++++++++++++++++++++ 4 files changed, 324 insertions(+), 37 deletions(-) diff --git a/messagefoundry/__main__.py b/messagefoundry/__main__.py index 41d9aed6f2..e98ec7c425 100644 --- a/messagefoundry/__main__.py +++ b/messagefoundry/__main__.py @@ -10586,8 +10586,9 @@ async def server_store_found() -> Literal["none", "empty", "held"]: raise HostCustodyRefused( f"the store already {held}, and {missing}. A new key cannot open a store " "another key made: run with the custody directory that holds the store's host " - "blob, MEFOR_SECRETS_DIRECTORY set as the store's service has it, or unset for " - "a SQLite store whose blob sits beside its file. If that blob is lost, the " + "blob, MEFOR_CUSTODY_DIRECTORY and MEFOR_SECRETS_DIRECTORY set as the store's " + "service has them, or both unset for a SQLite store whose blob sits beside " + "its file. If that blob is lost, the " f"store stays in place. {step}" ) from missing absent, exists = True, None @@ -10915,13 +10916,23 @@ def refused_write(exc: Exception) -> int: # named as a literal: this text reaches stderr (keep_the_key_step says why). import os - from messagefoundry.engine_secrets import SECRETS_DIRECTORY_VARIABLE - - where = ( - f"MEFOR_SECRETS_DIRECTORY set to {minted.path.parent}" - if os.environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip() - else "MEFOR_SECRETS_DIRECTORY unset, so that it looks beside the SQLite store file" + from messagefoundry.engine_secrets import ( + CUSTODY_DIRECTORY_VARIABLE, + SECRETS_DIRECTORY_VARIABLE, ) + + if os.environ.get(CUSTODY_DIRECTORY_VARIABLE, "").strip(): + where = f"MEFOR_CUSTODY_DIRECTORY set to {minted.path.parent}" + elif os.environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip(): + where = ( + f"MEFOR_SECRETS_DIRECTORY set to {minted.path.parent}, with " + "MEFOR_CUSTODY_DIRECTORY unset" + ) + else: + where = ( + "MEFOR_CUSTODY_DIRECTORY and MEFOR_SECRETS_DIRECTORY unset, so that it looks " + "beside the SQLite store file" + ) print( f"The store key was written to {minted.path}. The service looks for it in the custody " f"directory its own environment names; here that came from {where}. A service whose " diff --git a/messagefoundry/engine_secrets.py b/messagefoundry/engine_secrets.py index f6388d7832..133054588b 100644 --- a/messagefoundry/engine_secrets.py +++ b/messagefoundry/engine_secrets.py @@ -24,6 +24,7 @@ retired keys, is refused. The key custody host blob and its handoff (:data:`CUSTODY_FILE_NAMES`) may sit here, and the listing passes over them: the ``host`` key provider reads them itself (:mod:`messagefoundry.store.custody_host`, vault BACKLOG #3411), checking each as a key file. + :data:`CUSTODY_DIRECTORY_VARIABLE`, when set, names another directory for them. **What this slice does not do**, at least: refuse a secret found in the environment (slice B later made the NSSM reading in :mod:`messagefoundry.serviceenv` refuse one in the service's own @@ -50,6 +51,7 @@ from typing import Final __all__ = [ + "CUSTODY_DIRECTORY_VARIABLE", "CUSTODY_FILE_NAMES", "DIRECTORY_SETTING_NAMES", "KEY_CLASS_NAMES", @@ -103,6 +105,11 @@ #: in this directory when it is set, so the listing passes over them. CUSTODY_FILE_NAMES: Final[tuple[str, str]] = ("master.key", "handoff.key") +#: The variable that names a custody directory of its own for those two files (vault BACKLOG +#: #3411, ADR 0214's 2026-11-22 amendment). Set, it wins over this directory for them. A path, not +#: a secret. +CUSTODY_DIRECTORY_VARIABLE: Final = "MEFOR_CUSTODY_DIRECTORY" + #: The prefix of an ``env()`` value's variable, ``MEFOR_VALUE_``. A file in the directory with #: this prefix supplies that value. ``config.environments.VALUE_ENV_PREFIX`` is this constant. VALUE_PREFIX: Final = "MEFOR_VALUE_" diff --git a/messagefoundry/store/custody_host.py b/messagefoundry/store/custody_host.py index 389c9b1807..57cc4d2e2b 100644 --- a/messagefoundry/store/custody_host.py +++ b/messagefoundry/store/custody_host.py @@ -8,7 +8,8 @@ once to the person at the terminal, who enters it back; nothing is written until that entry has opened the recovery wrap, so every blob written here records its recovery key as proved. * **Where the blob goes.** A fixed name in the custody directory (:func:`custody_directory`): the - directory ``MEFOR_SECRETS_DIRECTORY`` names, or else a SQLite store's own data directory. + directory ``MEFOR_CUSTODY_DIRECTORY`` names, else the one ``MEFOR_SECRETS_DIRECTORY`` names, or + else a SQLite store's own data directory. :data:`HOST_FILE_NAME` is the host blob in the engine account's own scope, written by an account minting for itself; :data:`HANDOFF_FILE_NAME` is the machine-scope handoff an administrator writes for the service account (Windows only). A second mint over either is ``FileExistsError``. @@ -57,6 +58,7 @@ record_key_custody, ) from messagefoundry.engine_secrets import ( + CUSTODY_DIRECTORY_VARIABLE, CUSTODY_FILE_NAMES, KEY_CLASS_NAMES, SECRETS_DIRECTORY_VARIABLE, @@ -150,25 +152,57 @@ def custody_directory( ) -> Path | None: """The directory the host blob and the handoff live in, or ``None`` when there is none. - The directory ``MEFOR_SECRETS_DIRECTORY`` names when it is set (an absolute path, or + The directory ``MEFOR_CUSTODY_DIRECTORY`` names when it is set, else the one + ``MEFOR_SECRETS_DIRECTORY`` names when that is set (either an absolute path, or :class:`HostCustodyRefused`); otherwise a SQLite store's data directory, the one that holds the database file. A server store, or an in-memory one, has no data directory.""" from messagefoundry.config.settings import StoreBackend environ = os.environ if environ is None else environ - raw = environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip() - if raw: - path = Path(raw) + variable = _directory_variable(environ) + if variable is not None: + path = Path(environ[variable].strip()) if not path.is_absolute(): - raise _recorded_as( - HostCustodyRefused, f"{SECRETS_DIRECTORY_VARIABLE} must be an absolute path" - ) + raise _recorded_as(HostCustodyRefused, f"{variable} must be an absolute path") return path if settings.backend is StoreBackend.SQLITE and settings.path != ":memory:": return Path(settings.path).resolve().parent return None +def _directory_variable(environ: Mapping[str, str]) -> str | None: + """The variable that names the custody directory, or ``None`` when neither is set.""" + for variable in (CUSTODY_DIRECTORY_VARIABLE, SECRETS_DIRECTORY_VARIABLE): + if environ.get(variable, "").strip(): + return variable + return None + + +def _own_directory_refusal(environ: Mapping[str, str]) -> str | None: + """Why the custody directory ``MEFOR_CUSTODY_DIRECTORY`` names must not be used, or ``None`` + when that variable is unset, names a path with nothing there yet, or names a directory that + passes. It is judged by the check a secrets directory gets + (:func:`~messagefoundry.restricted_file.broad_access_problem` with ``directory``), so a known + broad group's right to read it, add a file to it or delete one in it is refused, as is a + link, and the folder that holds it is read by the holder rule. One account's right to add a + file, the service's, is not refused. A directory ``MEFOR_SECRETS_DIRECTORY`` names is judged + where the settings load reads it, and a SQLite store's data directory is not judged here.""" + raw = environ.get(CUSTODY_DIRECTORY_VARIABLE, "").strip() + if not raw or not os.path.lexists(raw): + # Nothing there: a read finds no file, and a mint refuses the missing directory itself. + return None + from messagefoundry.restricted_file import broad_access_problem + + problem = broad_access_problem(Path(raw), directory=True) + if problem is None: + return None + return ( + f"the custody directory {CUSTODY_DIRECTORY_VARIABLE} names is not restricted: {problem}. " + "Restrict it to SYSTEM and Administrators, with the account the engine runs as allowed " + "to read it and add a file to it (docs/SERVICE.md)" + ) + + def _custody_paths(directory: Path) -> tuple[Path, Path]: return directory / HOST_FILE_NAME, directory / HANDOFF_FILE_NAME @@ -230,7 +264,7 @@ def foreign_custody_refusal( "set [store].key_provider = 'host' and remove every other store key setting, with " "[store].cipher_provider = 'aesgcm', which that provider needs. The engine cannot tell " "whether the blob holds this store's key, so it " - f"leaves the file in place. {keep_the_key_step(settings, new_store=False)}" + f"leaves the file in place. {keep_the_key_step(settings, new_store=False, environ=environ)}" ) @@ -369,8 +403,9 @@ def custody_refusal_at_open(exc: BaseException) -> HostCustodyRefused: chain and then flushes the replaced class's log line (BACKLOG #4882).""" return _read_refusal( "the store's key custody could not be read or checked at the open: check " - f"[store].key_provider, the custody directory ({SECRETS_DIRECTORY_VARIABLE}, or else a " - "SQLite store's data directory) and the host file and handoff in it", + f"[store].key_provider, the custody directory ({CUSTODY_DIRECTORY_VARIABLE}, else " + f"{SECRETS_DIRECTORY_VARIABLE}, else a SQLite store's data directory) and the host file " + "and handoff in it", exc, ) @@ -580,6 +615,33 @@ def _left_behind(done: str, handoff: Path) -> HostCustodyRefused: ) +def _left_in_the_secrets_directory( + directory: Path, environ: Mapping[str, str] | None +) -> str | None: + """Why a read that found neither file in ``directory``, the one ``MEFOR_CUSTODY_DIRECTORY`` + names, must not report that no key was minted, or ``None``: a host file or a handoff sits in + the directory ``MEFOR_SECRETS_DIRECTORY`` names, where a mint run without + ``MEFOR_CUSTODY_DIRECTORY`` writes it. A command told that no key was minted could mint a + second one, which does not open a store the first one made.""" + environ = os.environ if environ is None else environ + if _directory_variable(environ) != CUSTODY_DIRECTORY_VARIABLE: + return None + raw = environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip() + if not raw or not os.path.isabs(raw): + return None + found = [p for p in _custody_paths(Path(raw)) if os.path.lexists(p)] + if not found or found[0].parent == directory: + return None + return ( + f"no host blob or handoff is in the custody directory {directory}, which " + f"{CUSTODY_DIRECTORY_VARIABLE} names, but {' and '.join(str(p) for p in found)} is in the " + f"directory {SECRETS_DIRECTORY_VARIABLE} names, which this provider does not read while " + f"{CUSTODY_DIRECTORY_VARIABLE} is set. If it holds this store's key, move it into " + f"{directory} as an administrator, on the same volume so it keeps its own access list, " + "and start again; a key minted now would not open a store that key made" + ) + + def _missing(host: Path, handoff: Path) -> HostCustodyMissing: """Neither ``host`` nor ``handoff`` is there.""" return _recorded_as( @@ -593,7 +655,8 @@ def check_host_custody_settings( settings: StoreSettings, *, environ: Mapping[str, str] | None = None ) -> tuple[Path, Path]: """The host blob's and the handoff's paths, once the settings pass: no other store key source - beside the blob, the ``aesgcm`` cipher, and a custody directory. Raises + beside the blob, the ``aesgcm`` cipher, a custody directory, and one ``MEFOR_CUSTODY_DIRECTORY`` + names passing :func:`_own_directory_refusal`. Raises :class:`HostCustodyRefused` otherwise. A blob a minting command passes in is held to the same settings a read is.""" environ = os.environ if environ is None else environ @@ -605,8 +668,12 @@ def check_host_custody_settings( raise _recorded_as( HostCustodyRefused, "[store].key_provider = 'host' needs a directory for the host blob: set " - f"{SECRETS_DIRECTORY_VARIABLE}, since this store has no data directory of its own", + f"{CUSTODY_DIRECTORY_VARIABLE} or {SECRETS_DIRECTORY_VARIABLE}, since this store has " + "no data directory of its own", ) + refusal = _own_directory_refusal(environ) + if refusal is not None: + raise _recorded_as(HostCustodyRefused, refusal) return _custody_paths(directory) @@ -675,6 +742,9 @@ def load_host_custody( if not (os.path.lexists(host) or os.path.lexists(handoff)): # Before the account is judged: no key is here for any account, and a command that mints # one for another account (provision-admin --service-account) must learn that first. + stray = _left_in_the_secrets_directory(host.parent, environ) + if stray is not None: + raise _recorded_as(HostCustodyRefused, stray) raise _missing(host, handoff) try: try: @@ -749,25 +819,44 @@ async def store_holds_data(store: Store) -> bool: def keep_the_key_step( - settings: StoreSettings, *, new_store: bool, service_account: str | None = None + settings: StoreSettings, + *, + new_store: bool, + service_account: str | None = None, + environ: Mapping[str, str] | None = None, ) -> str: """A fallback way on, after a caller's own remedy, at least for the paths that meet a key file or store they cannot tie to this store (PR 2804 fifth and sixth holds). It advises changing no existing file, key, blob or store: it asks for a new custody directory, and with ``new_store`` a - new store location, which changes the settings that name them. Names no path and no key.""" + new store location, which changes the settings that name them. Names no path and no key. + ``environ`` is read for which variable names the custody directory now.""" from messagefoundry.config.settings import SchemaManagement, StoreBackend server = settings.backend is not StoreBackend.SQLITE + own = _directory_variable(os.environ if environ is None else environ) == ( + CUSTODY_DIRECTORY_VARIABLE + ) # The variable is named here as a literal, not through SECRETS_DIRECTORY_VARIABLE: this text # can reach stderr, and CodeQL's name heuristic reads that constant as a secret (alert 315). text = ( - "To go on without it, give this store a custody directory of its own: a new directory, " - "restricted and writable by the service as a secrets directory must be, which the engine " - "checks at start, named by MEFOR_SECRETS_DIRECTORY here and in this store's own service " - "environment, never in one that another store's service also reads, since that store " - "would then look for its key there. Copy into it every secret file the current secrets " - f"directory holds other than {HOST_FILE_NAME} and {HANDOFF_FILE_NAME}, if one is set, " - "since the service reads its other secrets from there too" + ( + # A directory of its own holds no other secret, so nothing is copied into it. + "To go on without it, give this store a custody directory of its own: a new directory, " + "restricted as docs/SERVICE.md says, which the engine checks at start, named by " + "MEFOR_CUSTODY_DIRECTORY here and in this store's own service environment, never in one " + "that another store's service also reads, since that store would then look for its key " + "there" + ) + if own + else ( + "To go on without it, give this store a custody directory of its own: a new directory, " + "restricted and writable by the service as a secrets directory must be, which the engine " + "checks at start, named by MEFOR_SECRETS_DIRECTORY here and in this store's own service " + "environment, never in one that another store's service also reads, since that store " + "would then look for its key there. Copy into it every secret file the current secrets " + f"directory holds other than {HOST_FILE_NAME} and {HANDOFF_FILE_NAME}, if one is set, " + "since the service reads its other secrets from there too" + ) ) if new_store: text += ". Point [store] at a store location of its own: " + ( @@ -856,7 +945,9 @@ def mint_target( f"{path} already exists, so a store key was already minted here; a second mint " "is never made over it. The engine cannot tell whose key it holds, so it leaves " "it in place. " - f"{keep_the_key_step(settings, new_store=False, service_account=service_account)}" + + keep_the_key_step( + settings, new_store=False, service_account=service_account, environ=environ + ) ) if service_account is None: # What the write refuses for this account, asked now: the shared and non-local accounts @@ -886,21 +977,21 @@ def mint_target( _refuse_an_unusable_directory( target.parent, service_account=service_account, - named=bool(environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip()), + named=_directory_variable(environ), ) return target def _refuse_an_unusable_directory( - directory: Path, *, service_account: str | None, named: bool + directory: Path, *, service_account: str | None, named: str | None ) -> None: """Refuse, before any recovery key is shown, a custody directory the key file's write would refuse only after the ceremony, at least: one that is missing or not a directory, one this account cannot add a file to (PR 2804 twelfth hold, item 4), and one whose volume fails :func:`~messagefoundry.restricted_file.write_restricted_file`'s local-volume rule, asked through - that rule's own check (PR 2804 eleventh hold). ``named`` is whether ``MEFOR_SECRETS_DIRECTORY`` - names the directory, rather than a SQLite store's own data directory, so each refusal names - the setting that moves it.""" + that rule's own check (PR 2804 eleventh hold). ``named`` is the variable that names the + directory, ``None`` for a SQLite store's own data directory, so each refusal names the setting + that moves it.""" from messagefoundry.restricted_file import can_add_a_file, key_directory_volume_problem none_shown = "so no store key was minted and no recovery key was shown" @@ -911,11 +1002,20 @@ def _refuse_an_unusable_directory( writers = "this account" + ( "" if service_account is None else f' and the service account "{service_account}"' ) - secrets_directory = "restricted as a secrets directory must be and writable by " + writers + own = named == CUSTODY_DIRECTORY_VARIABLE + secrets_directory = ( + "restricted as docs/SERVICE.md says for a custody directory, and writable by " + if own + else "restricted as a secrets directory must be and writable by " + ) + writers def move_on(to: str) -> str: # The variable is named as a literal: this text reaches stderr (keep_the_key_step says # why). + if own: + return ( + f"set MEFOR_CUSTODY_DIRECTORY, here and in the service's own environment, to {to}" + ) variable = ( "set MEFOR_SECRETS_DIRECTORY, here and in the service's own environment, to " f"{to}, and copy into it every other secret file the current secrets directory " diff --git a/tests/test_store_custody_host.py b/tests/test_store_custody_host.py index e08c093482..a70aa3e953 100644 --- a/tests/test_store_custody_host.py +++ b/tests/test_store_custody_host.py @@ -75,6 +75,7 @@ def _clean(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: "MEFOR_STORE_ENCRYPTION_KEY", "MEFOR_STORE_ENCRYPTION_KEYS_RETIRED", "MEFOR_SECRETS_DIRECTORY", + "MEFOR_CUSTODY_DIRECTORY", ): monkeypatch.delenv(name, raising=False) if sys.platform == "win32": @@ -193,6 +194,174 @@ def test_the_custody_directory_is_the_secrets_directory_or_the_data_directory( load_host_custody(server, enforcing=True, environ={}) +# --- a custody directory of its own (vault BACKLOG #3411, ADR 0214's 2026-11-22 amendment) -------- + + +def _own_custody_directory(path: Path) -> Path: + """A directory no broad group reaches: mode 0700 on POSIX; on Windows pytest's own, which + inherits SYSTEM, Administrators and this account from the user's temporary folder.""" + path.mkdir(mode=0o700) + return path + + +def test_a_custody_directory_of_its_own_wins_over_the_secrets_directory(tmp_path: Path) -> None: + settings = _settings(tmp_path) + custody_dir, secrets = tmp_path / "custody", tmp_path / "secrets" + both = {"MEFOR_CUSTODY_DIRECTORY": str(custody_dir), "MEFOR_SECRETS_DIRECTORY": str(secrets)} + assert custody_host.custody_directory(settings, environ=both) == custody_dir + # A blank one is unset, as the secrets directory's is. + blank = {**both, "MEFOR_CUSTODY_DIRECTORY": " "} + assert custody_host.custody_directory(settings, environ=blank) == secrets + with pytest.raises(HostCustodyRefused, match="MEFOR_CUSTODY_DIRECTORY must be an absolute"): + custody_host.custody_directory(settings, environ={"MEFOR_CUSTODY_DIRECTORY": "rel"}) + server = settings.model_copy(update={"backend": StoreBackend.POSTGRES}) + assert ( + custody_host.custody_directory( + server, environ={"MEFOR_CUSTODY_DIRECTORY": str(custody_dir)} + ) + == custody_dir + ) + + +@host_file_platforms +def test_a_mint_writes_into_the_custody_directory_of_its_own(tmp_path: Path) -> None: + """The host file goes where MEFOR_CUSTODY_DIRECTORY points, not to the secrets directory or + beside the store, and a read finds it there.""" + custody_dir = _own_custody_directory(tmp_path / "custody") + secrets = _own_custody_directory(tmp_path / "secrets") + environ = {"MEFOR_CUSTODY_DIRECTORY": str(custody_dir), "MEFOR_SECRETS_DIRECTORY": str(secrets)} + settings = _settings(tmp_path) + minted = mint_host_custody( + settings, service_account=None, enforcing=True, terminal=_Console(), environ=environ + ) + assert minted.path == custody_dir / "master.key" + assert not (secrets / "master.key").exists() and not (tmp_path / "master.key").exists() + assert load_host_custody(settings, enforcing=True, environ=environ) == minted.blob + + +def _grant(path: Path, *grants: str, reset: bool = False) -> None: + import subprocess + + argv = ["icacls", str(path)] + if reset: + argv += ["/inheritance:r"] + subprocess.run([*argv, "/grant:r", *grants], check=True, capture_output=True) + + +def _me() -> str: + """This token's own SID, never a name from the environment.""" + sid = custody_host._engine_sid() + assert sid is not None + return f"*{sid}" + + +def test_a_custody_directory_of_its_own_that_a_broad_group_reaches_is_refused( + tmp_path: Path, +) -> None: + """The secrets directory's check, applied to the custody directory: a broad group's right to + add a file there is refused, before a read and before a mint. The control is the same + directory without that right, which passes the check and finds no key.""" + custody_dir = _own_custody_directory(tmp_path / "custody") + environ = {"MEFOR_CUSTODY_DIRECTORY": str(custody_dir)} + settings = _settings(tmp_path) + with pytest.raises(HostCustodyMissing): + load_host_custody(settings, enforcing=True, environ=environ) + if sys.platform == "win32": + _grant(custody_dir, "*S-1-5-32-545:(WD)") # Users may add a file + else: + custody_dir.chmod(0o733) # other may add a file + try: + with pytest.raises( + HostCustodyRefused, match="MEFOR_CUSTODY_DIRECTORY names is not restricted" + ): + load_host_custody(settings, enforcing=True, environ=environ) + with pytest.raises(HostCustodyRefused, match="is not restricted"): + mint_target(settings, service_account=None, enforcing=True, environ=environ) + finally: + if sys.platform == "win32": + import subprocess + + subprocess.run( + ["icacls", str(custody_dir), "/remove:g", "*S-1-5-32-545"], + check=True, + capture_output=True, + ) + else: + custody_dir.chmod(0o700) + + +def test_a_key_file_left_in_the_secrets_directory_is_not_taken_for_no_key(tmp_path: Path) -> None: + """With MEFOR_CUSTODY_DIRECTORY set, a handoff a mint without it left in the secrets directory + refuses the read, rather than reading as no key minted, which would lead to a second key.""" + custody_dir = _own_custody_directory(tmp_path / "custody") + secrets = _own_custody_directory(tmp_path / "secrets") + (secrets / "handoff.key").write_bytes(b"not read") + environ = {"MEFOR_CUSTODY_DIRECTORY": str(custody_dir), "MEFOR_SECRETS_DIRECTORY": str(secrets)} + with pytest.raises(HostCustodyRefused, match="move it into") as refused: + load_host_custody(_settings(tmp_path), enforcing=True, environ=environ) + assert not isinstance(refused.value, HostCustodyMissing) + assert str(secrets / "handoff.key") in str(refused.value) + # The control: without the variable the secrets directory is the custody directory, and the + # same file is read there (and refused as no handoff). + with pytest.raises(HostCustodyRefused) as read: + load_host_custody( + _settings(tmp_path), enforcing=True, environ={"MEFOR_SECRETS_DIRECTORY": str(secrets)} + ) + assert "move it into" not in str(read.value) + + +def test_the_way_on_names_the_custody_directory_of_its_own(tmp_path: Path) -> None: + environ = {"MEFOR_CUSTODY_DIRECTORY": str(tmp_path / "custody")} + step = custody_host.keep_the_key_step(_settings(tmp_path), new_store=False, environ=environ) + assert "named by MEFOR_CUSTODY_DIRECTORY here" in step, step + # No other secret lives there, so none is to be copied, and the secrets directory is not named. + assert "Copy into it" not in step and "MEFOR_SECRETS_DIRECTORY" not in step, step + secrets = custody_host.keep_the_key_step(_settings(tmp_path), new_store=False, environ={}) + assert "named by MEFOR_SECRETS_DIRECTORY here" in secrets, secrets + + +@windows_only +async def test_the_first_start_converts_into_a_directory_it_may_only_read_and_add_a_file_to( + tmp_path: Path, +) -> None: + """The installer's grant, measured: an engine account holding only read and add-file on its + custody directory converts the handoff there, writing master.key and deleting the handoff + through the handle it read it with. Nothing lands in the secrets directory.""" + custody_dir = _own_custody_directory(tmp_path / "custody") + secrets = _own_custody_directory(tmp_path / "secrets") + data = tmp_path / "data" + data.mkdir() + settings = _settings(data) + blob = _proved_blob() + _WRAPS[blob.store_id.value] = wrap_master_key( + blob.master_key, RecoveryKey.mint(), blob.store_id + ) + await _create(settings, blob) + _handoff(custody_dir / "handoff.key", blob) + _grant( + custody_dir, + "*S-1-5-18:(OI)F", + "*S-1-5-32-544:(OI)F", + f"{_me()}:(RX,WD)", + reset=True, + ) + try: + # The grant took: this account may add a file there. + assert restricted_file.can_add_a_file(custody_dir) is True + env = {"MEFOR_CUSTODY_DIRECTORY": str(custody_dir), "MEFOR_SECRETS_DIRECTORY": str(secrets)} + with pytest.MonkeyPatch.context() as patch: + for name, value in env.items(): + patch.setenv(name, value) + store = await open_store(settings) # the service's first start + await store.close() + assert not (custody_dir / "handoff.key").exists() + assert custody.read_host_file(custody_dir / "master.key") == blob + assert not list(secrets.iterdir()) + finally: + # The owner keeps the right to change the list, so pytest can remove the directory. + _grant(custody_dir, f"{_me()}:(OI)(CI)F") + + @pytest.mark.parametrize( ("update", "environ", "named"), [ From 9ec2beb2c0ec7b5393a328392eace2d85cd2eff3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 15:38:03 -0600 Subject: [PATCH 09/28] Key custody: the installer makes the custody directory under the host provider Vault BACKLOG #3411 slice B3c, design note 1. Under [store].key_provider = 'host', install-service.ps1 resolves -CustodyDir, else the service's MEFOR_CUSTODY_DIRECTORY, else -custody; judges it before anything acts by the secrets directory's rules with that directory added; makes it restricted in one step and empty; then, once the account resolves, sets owner Administrators, inheritance off, SYSTEM and Administrators full control, and the service account read and add-file on the directory alone (Set-CustodyDirAcl, read back by Get-CustodyGrantProblem), and names it to the service. -CustodyDir without that provider is refused. The secrets directory's sharer check also reads other services' MEFOR_CUSTODY_DIRECTORY. docs/SERVICE.md gains the custody directory section and default; ADR 0214 gains the 2026-11-22 amendment. Proposed PR title: Key custody B3c: a custody directory of its own for the host key provider, made by the installer and checked by the engine Proposed banner (#3411): PARTIAL. B3c design note 1 built: separate custody directory (MEFOR_CUSTODY_DIRECTORY), installer grant of read and add-file, engine check. Left: step 1's store key refusing provision-admin under host, the printed provision-admin --service-account step, uninstall's removal of the custody grant. --- docs/SERVICE.md | 40 ++- ...-for-the-engine-s-secret-class-settings.md | 19 ++ scripts/service/install-service.ps1 | 252 +++++++++++++++++- tests/test_install_service_custody.py | 164 ++++++++++++ tests/test_service_install_manifest.py | 18 +- 5 files changed, 479 insertions(+), 14 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index eaa081a154..d81bb8b1c4 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -170,6 +170,7 @@ Defaults: | Message store | `\messagefoundry.db` | | Logs | `\logs\service.out.log`, `service.err.log` | | Secrets directory (`-SecretsDir`) | the one the service already names, else `-secrets`; named to the service as `MEFOR_SECRETS_DIRECTORY` | +| Custody directory (`-CustodyDir`), under `[store].key_provider = 'host'` only | the one the service already names, else `-custody`; named to the service as `MEFOR_CUSTODY_DIRECTORY` ([The custody directory](#the-custody-directory-under-the-host-key-provider)) | | Bind | `127.0.0.1:8765` | | Log level | `INFO` | @@ -256,9 +257,42 @@ this host, such as a domain user or a gMSA, and the script does not check for th The steps above do not yet cover that provider. It refuses a store key set beside it, so step 1's key makes `provision-admin` refuse; and it mints the store key, which `--service-account` mints for -the service's account rather than yours. The script grants that account read only on the secrets -directory, where the service's first start must write its own key file, so a service the script -installs under this provider does not start yet (vault BACKLOG #3411). +the service's account rather than yours (vault BACKLOG #3411). + +#### The custody directory under the host key provider + +The host key provider keeps two files, `handoff.key`, which `provision-admin --service-account` +writes, and `master.key`, which the service's first start writes from it and then reads at every +start. The service must be able to add a file where they live, and the secrets directory gives it +read only, since administrators write that directory (ADR 0214). So when the install script reads +`[store].key_provider = 'host'` it also makes a **custody directory** of its own for those two +files, `-CustodyDir`, else the one the service already names, else `-custody`, and names +it to the service as `MEFOR_CUSTODY_DIRECTORY`. It is judged before anything acts by the secrets +directory's rules, made restricted in one step, and then given this list: + +- owner: Administrators, with inheritance off; +- SYSTEM and Administrators: full control, inherited by the files in it; +- the service account: read and add-file on the directory itself, inherited by nothing. + +The script replaces any other grant the service account holds there and removes every other +account's entry. It refuses, and disables the service, when what it reads back has another owner, +still inherits, still has an entry for another account, or gives the service account more or less +than that grant. When the script does not read that provider, it refuses `-CustodyDir`. + +**The engine.** When `MEFOR_CUSTODY_DIRECTORY` is set, the host provider reads and writes the two +files there, in place of the directory `MEFOR_SECRETS_DIRECTORY` names or the store's own data +directory. Before it reads or mints, it checks that directory as it checks a secrets directory: a +known broad group's right to read it, add a file to it or delete one in it is refused, and so is a +link, at any enforcement setting. It does not refuse one account's add-file right, the service's. +While the variable is set, a key file found only in the secrets directory is refused rather than +taken for no key at all, so a mint run without the variable does not lead to a second key. + +**Minting.** Set the variable in the elevated shell that runs `provision-admin --service-account`, +to the same path, so the handoff lands where the service looks: + +```powershell +$env:MEFOR_CUSTODY_DIRECTORY = 'C:\ProgramData\MessageFoundry-custody' +``` If the service started first, at the shipped posture it refuses to start. Once the earlier start checks pass (the store key and `[alerts]` among them), that refusal names `provision-admin` in the diff --git a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md index d2f6f9a89a..d5a651df75 100644 --- a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md +++ b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md @@ -153,6 +153,25 @@ names ADR 0019 declared and nobody built. Also not moved: the store key's own re ## Amendments +- **2026-11-22, the host key provider's files get a custody directory of their own (vault + BACKLOG #3411).** Under `[store].key_provider = 'host'` the service's first start writes its own + key file, `master.key`, beside the `handoff.key` an administrator's `provision-admin + --service-account` left. Decision 5 and slice C keep this directory administrator-written, with + the service at read only, and a service right to add a file here would let it supply a + secret-class setting. So those two files move to a directory of their own when + `MEFOR_CUSTODY_DIRECTORY` names one, an absolute path, which wins over `MEFOR_SECRETS_DIRECTORY` + for them; unset, they stay where they were, in this directory or beside a SQLite store. Before + a read or a mint, the engine applies decision 4's check to the directory that variable names, + `broad_access_problem` with `directory`, at every enforcement setting; it does not refuse one + account's right to add a file there. A host file or handoff found only in this directory while + the variable is set refuses the read, so a mint made without the variable is not taken for no + key. `install-service.ps1` makes the directory only when it reads that provider: `-CustodyDir`, + else the one the service names, else `-custody`, judged by slice C's rules with this + directory added to the paths it must not be, hold or sit inside, made restricted in one step, + and restricted to Administrators as owner, SYSTEM and Administrators with full control, and the + service account with read and add-file on the directory alone, which it reads back. It names + the directory to the service as `MEFOR_CUSTODY_DIRECTORY`. docs/SERVICE.md, *The custody + directory under the host key provider*, is the operator's text. - **2026-11-17, the Windows holder is read where the path resolves to (vault BACKLOG #5657).** This replaces parts of the 2026-11-13 amendment below. `_windows_surroundings_problem` still walks `full.parent`, except for a drive root such as `S:\`, whose own path it walks, so a diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index c63bf66c6d..491c8d9e1b 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -78,6 +78,12 @@ param( # the service as MEFOR_SECRETS_DIRECTORY in its NSSM environment. Default: the directory the # service already names, else -secrets, beside the data directory. [string]$SecretsDir, + # The custody directory (vault BACKLOG #3411, ADR 0214's 2026-11-22 amendment), made only under + # [store].key_provider = 'host'. Created owned by Administrators, with the service account allowed + # to read it and add a file to it and nothing else, and named to the service as + # MEFOR_CUSTODY_DIRECTORY in its NSSM environment. Default: the directory the service already + # names, else -custody, beside the data directory. + [string]$CustodyDir, [string]$ListenHost = "127.0.0.1", [int]$Port = 8765, # Least-privilege service account (DEPLOY-1). Override the default run-as with a specific account - @@ -951,7 +957,8 @@ function New-RestrictedDirectory { would hand this call their folder. The owner and the protection are read back to catch that. $OwnerSid is a parameter so the unelevated tests can make a folder they own. #> - param([Parameter(Mandatory)][string]$Path, [string]$OwnerSid = "S-1-5-32-544") + param([Parameter(Mandatory)][string]$Path, [string]$OwnerSid = "S-1-5-32-544", + [string]$What = "the secrets directory") $sec = New-Object System.Security.AccessControl.DirectorySecurity $sec.SetOwner([Security.Principal.SecurityIdentifier]$OwnerSid) $sec.SetAccessRuleProtection($true, $false) @@ -979,7 +986,7 @@ function New-RestrictedDirectory { # Read again after the create, as Set-SecretsDirAcl does: a folder above may have become a # junction since the preflight judged the path. $above = Get-ReparsePointAncestor -Path $Path - if ($above) { throw "'$Path' cannot be the secrets directory: $above." } + if ($above) { throw "'$Path' cannot be ${What}: $above." } } function Set-SecretsDirAcl { @@ -1094,6 +1101,112 @@ function Get-SecretsDirHeldProblem { "old access list") } +function Get-CustodyGrantProblem { + <# + Why the access list $Acl does not give the account $AccountSid exactly what the custody + directory grants it, or "" when it does (vault BACKLOG #3411, ADR 0214's 2026-11-22 + amendment): read and add-file on the directory itself, inherited by nothing. A right beyond + those, or an allow entry that files or folders inside inherit, is a problem, and so is a + missing read or add-file. Deny entries grant nothing and are not read. + + WHY ADD-FILE AND NOTHING MORE. The service's first start writes its own key file, master.key, + into this directory, so it must add a file there. It deletes the handoff through the handle it + read it with, which the handoff's own access list allows, so it needs no right to delete a file + in the directory, or to change the directory's list. + #> + param([Parameter(Mandatory)][System.Security.AccessControl.FileSystemSecurity]$Acl, + [Parameter(Mandatory)][string]$AccountSid) + $rights = [System.Security.AccessControl.FileSystemRights] + $read = $rights::ReadAndExecute + $add = $rights::CreateFiles + $allowed = [int64]($read -bor $add -bor $rights::Synchronize) + $held = [int64]0 + foreach ($rule in @($Acl.Access)) { + if ($rule.AccessControlType -ne [Security.AccessControl.AccessControlType]::Allow) { continue } + $sid = try { $rule.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value } + catch { "$($rule.IdentityReference)" } + if ($sid -ne $AccountSid) { continue } + if ($rule.InheritanceFlags -ne [Security.AccessControl.InheritanceFlags]::None) { + return "an entry for it is inherited by what the directory holds ($($rule.FileSystemRights))" + } + $mask = [int64]$rule.FileSystemRights + if ($mask -band -bnot $allowed) { + return "it holds $($rule.FileSystemRights), more than read and add-file" + } + $held = $held -bor $mask + } + if (($held -band [int64]$read) -ne [int64]$read) { return "it cannot read the directory" } + if (($held -band [int64]$add) -ne [int64]$add) { return "it cannot add a file to the directory" } + return "" +} + +function Set-CustodyDirAcl { + <# + Restrict the custody directory (vault BACKLOG #3411, ADR 0214's 2026-11-22 amendment): + Administrators as the owner, inheritance off, SYSTEM and Administrators full control inherited + by the files in it, and the service account read and add-file on the directory alone + (Get-CustodyGrantProblem says why no more). The engine applies the secrets directory's check + to it at start. + + THE ACCOUNT'S GRANT IS REPLACED, unlike the secrets directory's: no route needs more, so a + rerun takes back any wider grant. Every entry for another account is removed. The owner goes + first, for the reason Set-SecretsDirAcl gives. Throws when the result is not that. + #> + param([Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][string]$Account) + $item = Get-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue + if (-not $item -or -not $item.PSIsContainer -or ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) { + throw ("The custody directory '$Path' is no longer a plain folder, so its access list was not " + + "changed. Check what is at that path, and re-run the installer.") + } + $above = Get-ReparsePointAncestor -Path $Path + if ($above) { + throw ("The custody directory '$Path' was not restricted: $above. Check what is at that path, " + + "and re-run the installer.") + } + $problems = @() + & icacls $Path /setowner "*S-1-5-32-544" | Out-Null + if ($LASTEXITCODE -ne 0) { $problems += "Administrators could not be made its owner (icacls exit $LASTEXITCODE)" } + & icacls $Path /inheritance:r /grant:r "*S-1-5-18:(OI)F" "*S-1-5-32-544:(OI)F" | Out-Null + if ($LASTEXITCODE -ne 0) { + $problems += "inheritance could not be turned off with SYSTEM and Administrators granted (icacls exit $LASTEXITCODE)" + } + # No inheritance flag: the grant is on the directory, and the key files carry their own lists. + & icacls $Path /grant:r "${Account}:(RX,WD)" | Out-Null + if ($LASTEXITCODE -ne 0) { + $problems += "'$Account' could not be granted read and add-file (icacls exit $LASTEXITCODE)" + } + $broad = Get-WellKnownBroadSids + & icacls $Path /remove:g @broad | Out-Null + foreach ($holder in @(Get-BroadAclResidue -Path $Path -Account $Account)) { + $spelled = if ($holder -match '^S-1-') { "*$holder" } else { $holder } + & icacls $Path /remove:g $spelled | Out-Null + } + try { + $acl = Get-Acl -LiteralPath $Path + $owner = $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value + if ($owner -ne "S-1-5-32-544" -and $owner -ne "S-1-5-18") { $problems += "its owner is still $owner" } + if (-not $acl.AreAccessRulesProtected) { $problems += "it still inherits entries from the folder above" } + $residue = @(Get-BroadAclResidue -Path $Path -Account $Account -Acl $acl) + if ($residue) { $problems += "it still grants access to: $($residue -join ', ')" } + $accountSid = $null + try { $accountSid = ([Security.Principal.NTAccount]$Account).Translate([Security.Principal.SecurityIdentifier]).Value } + catch [System.Security.Principal.IdentityNotMappedException] { + $problems += "'$Account' does not resolve to an account, so its grant could not be checked" + } + if ($accountSid) { + $grant = Get-CustodyGrantProblem -Acl $acl -AccountSid $accountSid + if ($grant) { $problems += "'$Account': $grant" } + } + } catch { + $problems += "its access list could not be read back ($($_.Exception.Message))" + } + if ($problems) { + throw ("The custody directory '$Path' is not restricted as the host key provider needs: " + + "$($problems -join '; '). The service's first start writes its store key file there. " + + "Check the directory's access list, and re-run the installer.") + } +} + function Get-MergedEnvironmentList { <# $Existing, an NSSM environment list of NAME=value entries, with every entry for $Name replaced @@ -2793,13 +2906,17 @@ $secretsProblem = if (Test-Path -LiteralPath $SecretsDir -PathType Leaf) { "it i else { Get-LockPathProblem -Path $SecretsDir -Holds $SecretsHolds -NotWithin $SecretsNotWithin -OnlyFolders @() -AllowMissing } if (-not $secretsProblem) { $secretsProblem = Get-ReparsePointAncestor -Path $SecretsDir } if (-not $secretsProblem) { - $SecretsDirSharers = @(Get-OtherServiceNamingPath -ServiceName $ServiceName -Name "MEFOR_SECRETS_DIRECTORY" -Path $SecretsDir) + # Another service's custody directory too (vault BACKLOG #3411): this lockdown would strip the + # add-file grant its first start needs. + $SecretsDirSharers = @(foreach ($named in @("MEFOR_SECRETS_DIRECTORY", "MEFOR_CUSTODY_DIRECTORY")) { + Get-OtherServiceNamingPath -ServiceName $ServiceName -Name $named -Path $SecretsDir }) | + Select-Object -Unique if ($SecretsDirSharers) { - $secretsProblem = ("the service(s) $($SecretsDirSharers -join ', ') name it, a folder inside " + + $secretsProblem = ("the service(s) $(@($SecretsDirSharers) -join ', ') name it, a folder inside " + "it, a folder around it, or a path this installer cannot compare with it, as their secrets " + - "directory, and the lockdown here could reach theirs. Pass -SecretsDir with a folder for " + + "or custody directory, and the lockdown here could reach theirs. Pass -SecretsDir with a folder for " + "this service. A path this installer cannot compare is refused whatever -SecretsDir names, " + - "so correct that service's MEFOR_SECRETS_DIRECTORY instead") + "so correct that service's MEFOR_SECRETS_DIRECTORY or MEFOR_CUSTODY_DIRECTORY instead") } } # Does the service already name this directory? Then it is a rerun's own directory, and its files @@ -2877,6 +2994,90 @@ if ($HostCustody) { } } +# --- the custody directory (vault BACKLOG #3411, ADR 0214's 2026-11-22 amendment) -------------------- +# Under the host provider the service's first start writes its own key file, master.key, beside the +# handoff provision-admin leaves, so it must add a file where those two live. The secrets directory +# is administrator-written (ADR 0214), so they get a directory of their own, named to the service as +# MEFOR_CUSTODY_DIRECTORY, which the engine reads in place of MEFOR_SECRETS_DIRECTORY for them. +# Judged here, before anything acts, by the secrets directory's rules, and made before the service +# is registered; restricted (Set-CustodyDirAcl) once the account resolves. +$CustodyDirNamed = $false +if (-not $HostCustody) { + if ($CustodyDir) { + throw ("-CustodyDir is used only under [store].key_provider = 'host', which this install " + + "did not read from the service's environment or the settings file '$ServiceConfig'. " + + "Leave -CustodyDir out, or set that provider first.") + } +} else { + $RegisteredCustodyDir = Get-RegisteredEnvironmentValue -ServiceName $ServiceName -Name "MEFOR_CUSTODY_DIRECTORY" + if ($RegisteredCustodyDir) { $RegisteredCustodyDir = ConvertTo-EngineStripped $RegisteredCustodyDir } + if ($RegisteredCustodyDir -and ($RegisteredCustodyDir -match '^([A-Za-z]:[\\/]|[\\/]{2}[^\\/])')) { + $normal = ConvertTo-NormalPath $RegisteredCustodyDir + if (-not $normal) { + throw ("The service's MEFOR_CUSTODY_DIRECTORY, '$RegisteredCustodyDir', is not a usable path. " + + "Pass -CustodyDir with the directory to use.") + } + $RegisteredCustodyDir = $normal + } + if ($CustodyDir) { + $normal = ConvertTo-NormalPath (Resolve-AbsolutePath $CustodyDir) + if (-not $normal) { throw "-CustodyDir '$CustodyDir' is not a usable path." } + $CustodyDir = $normal + } + elseif ($RegisteredCustodyDir) { + if ($RegisteredCustodyDir -notmatch '^([A-Za-z]:\\|\\\\[^\\])') { + throw ("The service's MEFOR_CUSTODY_DIRECTORY, '$RegisteredCustodyDir', is not an absolute " + + "path, and the engine refuses it. Pass -CustodyDir with the directory to use.") + } + $CustodyDir = $RegisteredCustodyDir + } else { + $DataParent = Split-Path -Parent $DataDir + if (-not $DataParent) { + throw "-DataDir '$DataDir' is a volume root, so the custody directory has no default. Pass -CustodyDir." + } + $CustodyDir = Join-Path $DataParent "$(Split-Path -Leaf $DataDir)-custody" + } + Assert-NoNssmExpansion $CustodyDir + # The secrets directory's rules, with that directory added to what it must not be, hold or sit in. + $custodyProblem = if (Test-Path -LiteralPath $CustodyDir -PathType Leaf) { "it is a file" } + else { + Get-LockPathProblem -Path $CustodyDir -Holds (@($SecretsHolds) + $SecretsDir) ` + -NotWithin (@($SecretsNotWithin) + $SecretsDir) -OnlyFolders @() -AllowMissing + } + if (-not $custodyProblem) { $custodyProblem = Get-ReparsePointAncestor -Path $CustodyDir } + if (-not $custodyProblem) { + # Another service's custody or secrets directory: the lockdown here would strip its grants. + $custodySharers = @(foreach ($named in @("MEFOR_CUSTODY_DIRECTORY", "MEFOR_SECRETS_DIRECTORY")) { + Get-OtherServiceNamingPath -ServiceName $ServiceName -Name $named -Path $CustodyDir }) + if ($custodySharers) { + $custodyProblem = ("the service(s) $(@($custodySharers | Select-Object -Unique) -join ', ') " + + "name it, a folder inside it, a folder around it, or a path this installer cannot " + + "compare with it, as their custody or secrets directory, and the lockdown here could " + + "reach theirs. Pass -CustodyDir with a folder for this service") + } + } + # Refused, not adopted, when it exists and the service does not name it, as the secrets + # directory is, for the reason given there. + $CustodyDirNamed = [bool]$RegisteredCustodyDir -and ($RegisteredCustodyDir.TrimEnd('\') -eq $CustodyDir.TrimEnd('\')) + if (-not $custodyProblem -and (Test-Path -LiteralPath $CustodyDir)) { + if (-not $CustodyDirNamed) { + $custodyProblem = ("it already exists and the service does not name it. Remove it, check " + + "who made it, and re-run the installer, which then makes it restricted") + } else { + $owner = (Get-Acl -LiteralPath $CustodyDir).GetOwner([Security.Principal.SecurityIdentifier]).Value + if ($owner -ne "S-1-5-32-544" -and $owner -ne "S-1-5-18") { + $custodyProblem = ("the service names it, but its owner is now $owner, not the " + + "Administrators each install sets, so it may not be the folder the install made. " + + "Check who made it") + } + } + } + if ($custodyProblem) { + throw ("-CustodyDir '$CustodyDir' cannot be the custody directory: $custodyProblem. Point it " + + "at a folder of its own, such as the default '-custody'.") + } +} + # An install that builds its root (vault BACKLOG #2626) resolves NSSM first. Resolve-Nssm's # refusals, at least a -NssmPath off the pin, an -NssmDir others can write and a failed download, # need no engine root, and one after the build would leave a built root that -EngineWheel then @@ -2926,6 +3127,21 @@ if (-not $SecretsDirNamed -or -not (Test-Path -LiteralPath $SecretsDir)) { $heldProblem = Get-SecretsDirHeldProblem -Path $SecretsDir if ($heldProblem) { throw "-SecretsDir '$SecretsDir' cannot be the secrets directory: $heldProblem." } } +# The custody directory the same way (vault BACKLOG #3411): made restricted in one step, and then +# empty, since a key file in it that this install did not see made would be read as the store's. +if ($HostCustody) { + $CustodyParent = Split-Path -Parent $CustodyDir + if (-not (Test-Path -LiteralPath $CustodyParent)) { New-AdminOnlyFolder -Path $CustodyParent } + if (-not $CustodyDirNamed -or -not (Test-Path -LiteralPath $CustodyDir)) { + New-RestrictedDirectory -Path $CustodyDir -What "the custody directory" + $custodyHeld = @(Get-ChildItem -LiteralPath $CustodyDir -Force -ErrorAction Stop) + if ($custodyHeld.Count -ne 0) { + throw ("-CustodyDir '$CustodyDir' cannot be the custody directory: it holds " + + "$($custodyHeld.Count) item(s) the installer did not put there, such as " + + "'$($custodyHeld[0].Name)'. Remove the directory, check who wrote them, and re-run the installer.") + } + } +} # NB the data-dir + config-dir ACL lockdown is applied LATER, AFTER the service is registered and its # ObjectName (run-as account) is set - see "ACLs" below. The default run-as is now a per-service VIRTUAL # account (NT SERVICE\, #224), whose SID does NOT resolve for icacls until the service @@ -3328,6 +3544,30 @@ try { "($($_.Exception.Message)). Add MEFOR_SECRETS_DIRECTORY=$SecretsDir to its AppEnvironmentExtra " + "by hand, keeping the entries already there.") } +# The custody directory (vault BACKLOG #3411, ADR 0214's 2026-11-22 amendment): the service's own +# grant there is read and add-file, so its first start can write master.key. A directory left +# otherwise is a refusal, and the service is disabled first, as above. +if ($HostCustody) { + try { Set-CustodyDirAcl -Path $CustodyDir -Account $ServiceAccount } + catch { + throw "$($_.Exception.Message) $(Disable-RefusedService -ServiceName $ServiceName -Consequence 'its first start cannot write its store key file as the custody directory needs')" + } + try { + $replacedCustodyDir = Set-ServiceEnvironmentValue -ServiceName $ServiceName -Name "MEFOR_CUSTODY_DIRECTORY" -Value $CustodyDir + if ($replacedCustodyDir -and -not $CustodyDirNamed) { + Write-Warning ("The service's MEFOR_CUSTODY_DIRECTORY named '$replacedCustodyDir' and now " + + "names '$CustodyDir', as -CustodyDir asked. The engine reads no key file from the old " + + "directory: if master.key or handoff.key is there, move it into the new one as an " + + "administrator, on the same volume so it keeps its own access list.") + } + Write-Host " Custody: '$CustodyDir', named to the service as MEFOR_CUSTODY_DIRECTORY (docs/SERVICE.md)." + } catch { + Write-Warning ("Could not name the custody directory in the service's environment " + + "($($_.Exception.Message)). Add MEFOR_CUSTODY_DIRECTORY=$CustodyDir to its AppEnvironmentExtra " + + "by hand, keeping the entries already there; without it the service looks for its key " + + "file in the secrets directory, where it cannot write one.") + } +} # The lockdown above removes Users and Authenticated Users, so a named account writes the data # directory through its own grant. That grant is read back on the two directories the service must # write (vault BACKLOG #2702). LocalSystem has no named grant: it writes through the SYSTEM entry. diff --git a/tests/test_install_service_custody.py b/tests/test_install_service_custody.py index 5e39308fb7..85cd38dc0b 100644 --- a/tests/test_install_service_custody.py +++ b/tests/test_install_service_custody.py @@ -23,8 +23,11 @@ _ok, _preflight_facts, _psq, + _run, _script_text, _sole_call, + _sole_call_on, + _windows_only, ) _SCRIPT = svc.install_script_path() @@ -156,3 +159,164 @@ def test_the_installer_refuses_before_anything_acts(tmp_path: Path) -> None: assert refusal < text.index(later), later # The settings file is known to exist before it is read. assert text.index("Service settings file not found at: $ServiceConfig") < refusal + + +# --- the custody directory (ADR 0214's 2026-11-22 amendment) -------------------------------------- + +#: (the service account's grant, as icacls spells it, whether Get-CustodyGrantProblem passes it) +_GRANTS: list[tuple[str, bool]] = [ + ("(RX,WD)", True), + ("(RX)", False), # no add-file: the first start could not write master.key + ("(WD)", False), # no read + ("(OI)(RX,WD)", False), # inherited by the files in it + ("(RX,WD,DC)", False), # may delete any file in it + ("(RX,WD,WDAC)", False), # may change its list + ("M", False), + ("F", False), + ("(GR,WD)", False), # a generic right is not read as the rights it maps to +] + + +@_windows_only +def test_the_custody_grant_rule(tmp_path: Path) -> None: + """Get-CustodyGrantProblem on a real directory's list, one per grant. A deny entry is not a + grant, so it neither widens nor narrows the verdict.""" + assert _SCRIPT is not None + dirs = [] + for i, (grant, _) in enumerate(_GRANTS): + d = tmp_path / f"g{i}" + d.mkdir() + dirs.append((str(d), grant)) + cases = "\n".join( + f' & icacls {_psq(d)} /inheritance:r /grant:r "*${{mySid}}:{grant}" ' + f"'*S-1-5-32-544:(OI)F' | Out-Null\n" + f" & icacls {_psq(d)} /deny '*S-1-5-32-545:(WD)' | Out-Null\n" + f" $out += [string](Get-CustodyGrantProblem -Acl (Get-Acl -LiteralPath {_psq(d)}) " + "-AccountSid $mySid)" + for d, grant in dirs + ) + body = ( + " $mySid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value\n" + f" $out = @()\n{cases}\n ConvertTo-Json -InputObject $out -Compress\n" + ) + try: + got = json.loads(_ok(_extract(_SCRIPT, ["Get-CustodyGrantProblem"], body), tmp_path)) + finally: + restore = "\n".join( + f' & icacls {_psq(d)} /inheritance:e /grant "*$([Security.Principal.WindowsIdentity]' + '::GetCurrent().User.Value):(OI)(CI)F" | Out-Null' + for d, _ in dirs + ) + _run(_extract(_SCRIPT, [], restore), tmp_path) + assert [not p for p in got] == [ok for _, ok in _GRANTS], list(zip(_GRANTS, got, strict=True)) + + +@_windows_only +def test_the_custody_directory_lockdown_grants_exactly_read_and_add_file(tmp_path: Path) -> None: + """Set-CustodyDirAcl on a directory that inherits Users read and the account's Modify. The + account ends with read and add-file on the directory alone, nothing inherited, and the engine's + own check of a custody directory passes it, where it refused the directory before. Unelevated, + the owner change is refused, and the function refuses for that alone.""" + from messagefoundry.store import custody_host + + assert _SCRIPT is not None + parent = tmp_path / "cd" + custody = parent / "custody" + custody.mkdir(parents=True) + pre = rf""" + $me = [Security.Principal.WindowsIdentity]::GetCurrent().Name + & icacls {_psq(str(parent))} /grant '*S-1-5-32-545:(OI)(CI)RX' "${{me}}:(OI)(CI)M" | Out-Null +""" + _ok(_extract(_SCRIPT, [], pre), tmp_path) + environ = {"MEFOR_CUSTODY_DIRECTORY": str(custody)} + assert custody_host._own_directory_refusal(environ) is not None, ( + "CONTROL FAILED: the engine accepted the directory before the lockdown" + ) + lock = rf""" + $me = [Security.Principal.WindowsIdentity]::GetCurrent().Name + $mySid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value + $dir = {_psq(str(custody))} + $refusal = '' + try {{ Set-CustodyDirAcl -Path $dir -Account $me }} catch {{ $refusal = $_.Exception.Message }} + $acl = Get-Acl -LiteralPath $dir + $mine = @($acl.Access | Where-Object {{ + try {{ $_.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value -eq $mySid }} + catch {{ $false }} }}) + [pscustomobject]@{{ + refusal = $refusal + inherited = @($acl.Access | Where-Object {{ $_.IsInherited }}).Count + protected = $acl.AreAccessRulesProtected + mine = @($mine | ForEach-Object {{ [pscustomobject]@{{ + type = "$($_.AccessControlType)"; rights = [int64]$_.FileSystemRights; + inherit = "$($_.InheritanceFlags)" }} }}) + grant = (Get-CustodyGrantProblem -Acl $acl -AccountSid $mySid) + text = (& icacls $dir | Out-String) + }} | ConvertTo-Json -Depth 4 -Compress +""" + names = [ + "Set-CustodyDirAcl", + "Get-CustodyGrantProblem", + "Get-WellKnownBroadSids", + "Get-BroadAclResidue", + "Get-ReparsePointAncestor", + ] + try: + got = json.loads(_ok(_extract(_SCRIPT, names, lock), tmp_path).strip().splitlines()[-1]) + after = custody_host._own_directory_refusal(environ) + finally: + restore = rf""" + $me = [Security.Principal.WindowsIdentity]::GetCurrent().Name + & icacls {_psq(str(custody))} /inheritance:e /grant "${{me}}:(OI)(CI)F" | Out-Null +""" + _run(_extract(_SCRIPT, [], restore), tmp_path) + assert after is None, f"the engine refuses the locked directory: {after}\n{got['text']}" + assert got["protected"] and got["inherited"] == 0, got["text"] + mine = got["mine"] if isinstance(got["mine"], list) else [got["mine"]] + # ReadAndExecute | CreateFiles | Synchronize, in one allow entry inherited by nothing. + assert mine == [{"type": "Allow", "rights": 0x1200AB, "inherit": "None"}], got["text"] + assert not got["grant"], got["grant"] + refusal = got["refusal"] + assert not refusal or ( + "owner" in refusal + and "grants access" not in refusal + and "inherits" not in refusal + and "more than" not in refusal + ), f"a clean lockdown must find nothing but the owner; got {refusal}" + + +def test_the_installer_makes_and_names_the_custody_directory_under_the_host_provider( + tmp_path: Path, +) -> None: + """CALL-SITE guard: the custody directory is judged with the secrets directory's rules before + NSSM is resolved, made restricted before the service is registered, restricted after the + secrets directory once the account resolves, and named to the service. Each step sits under + the host provider's branch, and -CustodyDir is refused without it.""" + facts = _preflight_facts(tmp_path) + # Read by line: the call offsets count the file's own line endings, which read_text folds. + text = _script_text() + check = _sole_call_on(facts, "Get-LockPathProblem", "-Path $CustodyDir") + assert "-AllowMissing" in check["text"] and "$SecretsDir" in check["text"], check["text"] + sharers = _sole_call_on(facts, "Get-OtherServiceNamingPath", "-Path $CustodyDir") + creates = _sole_call_on(facts, "New-RestrictedDirectory", "-Path $CustodyDir") + lock = _sole_call(facts, "Set-CustodyDirAcl") + assert "-Path $CustodyDir" in lock["text"] and "-Account $ServiceAccount" in lock["text"] + secrets_lock = _sole_call(facts, "Set-SecretsDirAcl") + named = _sole_call_on(facts, "Set-ServiceEnvironmentValue", "$CustodyDir") + assert "MEFOR_CUSTODY_DIRECTORY" in named["text"], named["text"] + nssm = min(c["start"] for c in facts["commands"] if c["name"] == "Resolve-Nssm") + registered = min( + c["start"] + for c in facts["commands"] + if c["name"] == "Invoke-Nssm" and "install" in c["text"] + ) + host = _sole_call(facts, "Get-HostCustodyAccountProblem") + assert host["start"] < check["start"] < sharers["start"] < nssm + assert creates["start"] < registered < secrets_lock["start"] < lock["start"] < named["start"] + # Each act is inside an `if ($HostCustody)` block. + lines = text.splitlines() + for call in (creates, lock, named): + at = call["line"] - 1 # 1-based in the parser's extent + head = max(i for i in range(at) if lines[i].startswith("if ($HostCustody) {")) + end = next(i for i in range(head, len(lines)) if lines[i] == "}") + assert head < at < end, call["text"] + assert "-CustodyDir is used only under [store].key_provider = 'host'" in text diff --git a/tests/test_service_install_manifest.py b/tests/test_service_install_manifest.py index e88cf50ceb..7c8cb63678 100644 --- a/tests/test_service_install_manifest.py +++ b/tests/test_service_install_manifest.py @@ -1231,6 +1231,14 @@ def _sole_call(facts: dict, name: str) -> dict: return hits[0] +def _sole_call_on(facts: dict, name: str, needle: str) -> dict: + """The one ``name`` call whose text holds ``needle``, for a command called on more than one + directory.""" + hits = [c for c in facts["commands"] if c["name"] == name and needle in c["text"]] + assert len(hits) == 1, f"expected exactly one {name} call holding {needle}, found {len(hits)}" + return hits[0] + + def test_every_path_parameter_is_absolute_before_anything_consumes_it(tmp_path: Path) -> None: """Each of -DataDir, -AppExe, -Config, -DbPath is finalised BEFORE the Resolve-Nssm call. @@ -4018,8 +4026,9 @@ def test_the_installer_creates_and_names_the_secrets_directory(tmp_path: Path) - lock = _sole_call(facts, "Set-SecretsDirAcl") assert "-Account $ServiceAccount" in lock["text"], lock["text"] assert lock["start"] > data["start"], "the secrets directory is restricted before the data dir" - named = _sole_call(facts, "Set-ServiceEnvironmentValue") - assert "MEFOR_SECRETS_DIRECTORY" in named["text"] and "$SecretsDir" in named["text"] + # The custody directory (vault BACKLOG #3411) has calls of its own, on $CustodyDir. + named = _sole_call_on(facts, "Set-ServiceEnvironmentValue", "$SecretsDir") + assert "MEFOR_SECRETS_DIRECTORY" in named["text"], named["text"] assert "AppEnvironmentExtra" not in " ".join( c["text"] for c in facts["commands"] if c["name"] == "Invoke-Nssm" ), "an `nssm set AppEnvironmentExtra` would replace the operator's whole list" @@ -4033,8 +4042,7 @@ def test_the_installer_creates_and_names_the_secrets_directory(tmp_path: Path) - assert "-AllowMissing" in check["text"] and "-OnlyFolders @()" in check["text"], check["text"] # Made in one step with its owner and list (New-RestrictedDirectory), never New-Item then icacls, # which leaves a window where the folder inherits Users' create right. - creates = _sole_call(facts, "New-RestrictedDirectory") - assert "-Path $SecretsDir" in creates["text"], creates["text"] + creates = _sole_call_on(facts, "New-RestrictedDirectory", "-Path $SecretsDir") assert not [ c for c in facts["commands"] @@ -4045,7 +4053,7 @@ def test_the_installer_creates_and_names_the_secrets_directory(tmp_path: Path) - for c in facts["commands"] if c["name"] == "Get-ReparsePointAncestor" and "-Path $SecretsDir" in c["text"] ) - sharers = _sole_call(facts, "Get-OtherServiceNamingPath") + sharers = _sole_call_on(facts, "Get-OtherServiceNamingPath", "-Path $SecretsDir") empty = _sole_call(facts, "Get-SecretsDirHeldProblem") registered = min( c["start"] From 033d49e39b4ce8c3396e81acec573739b1b9c879 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 16:16:42 -0600 Subject: [PATCH 10/28] Key custody: repair round 1, custody directory review round-058d7b7c0e Vault BACKLOG #3411 slice B3c, design note 1. - The check that refuses another key provider beside a host file now looks in every directory the host provider may read, the custody directory and the one it reads without it, so setting MEFOR_CUSTODY_DIRECTORY no longer hides a key file in the secrets directory, and a relative one no longer turns the check off. - The left-behind refusal reads the SQLite data directory fallback too. - The installer removes a deny the service account holds on the custody directory, and the read-back refuses one that takes away read or add-file. - The refusal's remedy names a POSIX rule off Windows. - SERVICE.md, the ADR amendment and the docstring no longer imply the engine refuses other single accounts' entries; the read-back list is an at-least list. - The first-start test drops the Administrators entry, so an elevated runner still measures read and add-file alone. The path-join census counts the -custody join. --- docs/SERVICE.md | 21 ++-- ...-for-the-engine-s-secret-class-settings.md | 10 +- messagefoundry/store/custody_host.py | 102 +++++++++++------- scripts/service/install-service.ps1 | 19 +++- tests/test_file_path_join_census.py | 9 +- tests/test_install_service_custody.py | 33 +++--- tests/test_store_custody_host.py | 43 ++++++-- 7 files changed, 159 insertions(+), 78 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index d81bb8b1c4..62e946646a 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -274,18 +274,21 @@ directory's rules, made restricted in one step, and then given this list: - SYSTEM and Administrators: full control, inherited by the files in it; - the service account: read and add-file on the directory itself, inherited by nothing. -The script replaces any other grant the service account holds there and removes every other -account's entry. It refuses, and disables the service, when what it reads back has another owner, -still inherits, still has an entry for another account, or gives the service account more or less -than that grant. When the script does not read that provider, it refuses `-CustodyDir`. +The script replaces any other grant or deny the service account holds there and removes every +other account's entry. It then reads the list back, and refuses, disabling the service, at least +when it has another owner, still inherits, still has an entry for another account, or gives the +service account more than that grant or, through a missing entry or a deny, less. When the script +does not read that provider, it refuses `-CustodyDir`. **The engine.** When `MEFOR_CUSTODY_DIRECTORY` is set, the host provider reads and writes the two files there, in place of the directory `MEFOR_SECRETS_DIRECTORY` names or the store's own data -directory. Before it reads or mints, it checks that directory as it checks a secrets directory: a -known broad group's right to read it, add a file to it or delete one in it is refused, and so is a -link, at any enforcement setting. It does not refuse one account's add-file right, the service's. -While the variable is set, a key file found only in the secrets directory is refused rather than -taken for no key at all, so a mint run without the variable does not lead to a second key. +directory. Before it reads or mints, it checks that directory as it checks a secrets directory, at +any enforcement setting: a known broad group's right to read it, add a file to it or delete one in +it is refused, and so is a link. That check reads known broad groups only, so it refuses no entry +for one account, the service's or any other; the list the script sets is what leaves other +accounts no entry. While the variable is set, a key file found where the provider would look without it, the +secrets directory or beside a SQLite store, is refused rather than taken for no key at all, so a +mint run without the variable does not lead to a second key. **Minting.** Set the variable in the elevated shell that runs `provision-admin --service-account`, to the same path, so the handoff lands where the service looks: diff --git a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md index d5a651df75..67a53b1884 100644 --- a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md +++ b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md @@ -162,10 +162,12 @@ names ADR 0019 declared and nobody built. Also not moved: the store key's own re `MEFOR_CUSTODY_DIRECTORY` names one, an absolute path, which wins over `MEFOR_SECRETS_DIRECTORY` for them; unset, they stay where they were, in this directory or beside a SQLite store. Before a read or a mint, the engine applies decision 4's check to the directory that variable names, - `broad_access_problem` with `directory`, at every enforcement setting; it does not refuse one - account's right to add a file there. A host file or handoff found only in this directory while - the variable is set refuses the read, so a mint made without the variable is not taken for no - key. `install-service.ps1` makes the directory only when it reads that provider: `-CustodyDir`, + `broad_access_problem` with `directory`, at every enforcement setting; like decision 4's check, + it reads known broad groups only, so it refuses no entry for one account, the service's add-file + right included. While the variable is set, a host file or handoff found only where the provider + reads without it, this directory or beside a SQLite store, refuses the read, so a mint made + without the variable is not taken for no key; and the check that refuses another key provider + beside a host file or handoff looks in both places. `install-service.ps1` makes the directory only when it reads that provider: `-CustodyDir`, else the one the service names, else `-custody`, judged by slice C's rules with this directory added to the paths it must not be, hold or sit inside, made restricted in one step, and restricted to Administrators as owner, SYSTEM and Administrators with full control, and the diff --git a/messagefoundry/store/custody_host.py b/messagefoundry/store/custody_host.py index 57cc4d2e2b..e0ad1b04e4 100644 --- a/messagefoundry/store/custody_host.py +++ b/messagefoundry/store/custody_host.py @@ -184,9 +184,10 @@ def _own_directory_refusal(environ: Mapping[str, str]) -> str | None: passes. It is judged by the check a secrets directory gets (:func:`~messagefoundry.restricted_file.broad_access_problem` with ``directory``), so a known broad group's right to read it, add a file to it or delete one in it is refused, as is a - link, and the folder that holds it is read by the holder rule. One account's right to add a - file, the service's, is not refused. A directory ``MEFOR_SECRETS_DIRECTORY`` names is judged - where the settings load reads it, and a SQLite store's data directory is not judged here.""" + link, and the folder that holds it is read by the holder rule. It reads known broad groups + only, so an entry for one account, the service's or another's, is not refused. A directory + ``MEFOR_SECRETS_DIRECTORY`` names is judged where the settings load reads it, and a SQLite + store's data directory is not judged here.""" raw = environ.get(CUSTODY_DIRECTORY_VARIABLE, "").strip() if not raw or not os.path.lexists(raw): # Nothing there: a read finds no file, and a mint refuses the missing directory itself. @@ -196,10 +197,16 @@ def _own_directory_refusal(environ: Mapping[str, str]) -> str | None: problem = broad_access_problem(Path(raw), directory=True) if problem is None: return None + remedy = ( + "Restrict it to SYSTEM and Administrators, with the account the engine runs as allowed to " + "read it and add a file to it, as docs/SERVICE.md shows" + if sys.platform == "win32" + else "Make it owned by the account the engine runs as, mode 0700, in a folder only that " + "account or root may write" + ) return ( f"the custody directory {CUSTODY_DIRECTORY_VARIABLE} names is not restricted: {problem}. " - "Restrict it to SYSTEM and Administrators, with the account the engine runs as allowed " - "to read it and add a file to it (docs/SERVICE.md)" + f"{remedy}" ) @@ -207,6 +214,27 @@ def _custody_paths(directory: Path) -> tuple[Path, Path]: return directory / HOST_FILE_NAME, directory / HANDOFF_FILE_NAME +def _key_file_directories(settings: StoreSettings, environ: Mapping[str, str]) -> list[Path]: + """Each directory a host file or handoff for this store may sit in, first the one the host + provider reads now: the one ``MEFOR_CUSTODY_DIRECTORY`` names, then the one it reads without + that variable, ``MEFOR_SECRETS_DIRECTORY``'s or else a SQLite store's data directory. A + variable that is not an absolute path names none here; :func:`custody_directory` refuses it.""" + from messagefoundry.config.settings import StoreBackend + + found: list[Path] = [] + for variable in (CUSTODY_DIRECTORY_VARIABLE, SECRETS_DIRECTORY_VARIABLE): + raw = environ.get(variable, "").strip() + if raw and Path(raw).is_absolute(): + found.append(Path(raw)) + if ( + not environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip() + and settings.backend is StoreBackend.SQLITE + and settings.path != ":memory:" + ): + found.append(Path(settings.path).resolve().parent) + return list(dict.fromkeys(found)) + + def _key_sources_beside(settings: StoreSettings, environ: Mapping[str, str]) -> list[str]: """Every other store key source that is set: the settings' own and the key-class variables.""" named = [] @@ -243,21 +271,22 @@ def foreign_custody_refusal( settings: StoreSettings, *, environ: Mapping[str, str] | None = None ) -> str | None: """Why a store under any key provider but ``host`` must not open, or ``None``: a host blob or a - handoff sits in its custody directory, so the store's key would be taken from somewhere other - than the blob minted for it. An unusable directory setting is left for the reader of that - setting to refuse.""" + handoff sits in a directory the ``host`` provider would read it from + (:func:`_key_file_directories`), so the store's key would be taken from somewhere other than + the blob minted for it. A directory setting that is not an absolute path is passed over here, + and the directories the other setting names are still looked in.""" environ = os.environ if environ is None else environ - try: - directory = custody_directory(settings, environ=environ) - except HostCustodyRefused: - return None - if directory is None: - return None - found = [p.name for p in _custody_paths(directory) if os.path.lexists(p)] + found = [ + p + for directory in _key_file_directories(settings, environ) + for p in _custody_paths(directory) + if os.path.lexists(p) + ] if not found: return None return ( - f"{' and '.join(found)} is in {directory}, but [store].key_provider is " + f"{' and '.join(p.name for p in found)} is in " + f"{' and '.join(dict.fromkeys(str(p.parent) for p in found))}, but [store].key_provider is " f"{settings.key_provider!r}. A store with a host blob takes its key from that blob only: " "if it holds this store's key, keep a copy of each key setting's value first, somewhere " "as protected as where it is now, since it may be the only copy of a store key, and then " @@ -615,30 +644,31 @@ def _left_behind(done: str, handoff: Path) -> HostCustodyRefused: ) -def _left_in_the_secrets_directory( - directory: Path, environ: Mapping[str, str] | None +def _left_outside_the_custody_directory( + settings: StoreSettings, directory: Path, environ: Mapping[str, str] | None ) -> str | None: - """Why a read that found neither file in ``directory``, the one ``MEFOR_CUSTODY_DIRECTORY`` - names, must not report that no key was minted, or ``None``: a host file or a handoff sits in - the directory ``MEFOR_SECRETS_DIRECTORY`` names, where a mint run without - ``MEFOR_CUSTODY_DIRECTORY`` writes it. A command told that no key was minted could mint a - second one, which does not open a store the first one made.""" + """Why a read that found neither file in ``directory``, the custody directory, must not report + that no key was minted, or ``None``: a host file or a handoff sits in another directory + :func:`_key_file_directories` names, where a mint run without ``MEFOR_CUSTODY_DIRECTORY`` + writes it. A command told that no key was minted could mint a second one, which does not open + a store the first one made.""" environ = os.environ if environ is None else environ - if _directory_variable(environ) != CUSTODY_DIRECTORY_VARIABLE: - return None - raw = environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip() - if not raw or not os.path.isabs(raw): - return None - found = [p for p in _custody_paths(Path(raw)) if os.path.lexists(p)] - if not found or found[0].parent == directory: + found = [ + p + for other in _key_file_directories(settings, environ) + if other != directory + for p in _custody_paths(other) + if os.path.lexists(p) + ] + if not found: return None return ( f"no host blob or handoff is in the custody directory {directory}, which " - f"{CUSTODY_DIRECTORY_VARIABLE} names, but {' and '.join(str(p) for p in found)} is in the " - f"directory {SECRETS_DIRECTORY_VARIABLE} names, which this provider does not read while " - f"{CUSTODY_DIRECTORY_VARIABLE} is set. If it holds this store's key, move it into " - f"{directory} as an administrator, on the same volume so it keeps its own access list, " - "and start again; a key minted now would not open a store that key made" + f"{CUSTODY_DIRECTORY_VARIABLE} names, but {' and '.join(str(p) for p in found)} is in a " + f"directory this provider reads only while {CUSTODY_DIRECTORY_VARIABLE} is unset. If it " + f"holds this store's key, move it into {directory} as an administrator, on the same " + "volume so it keeps its own access list, and start again; a key minted now would not open " + "a store that key made" ) @@ -742,7 +772,7 @@ def load_host_custody( if not (os.path.lexists(host) or os.path.lexists(handoff)): # Before the account is judged: no key is here for any account, and a command that mints # one for another account (provision-admin --service-account) must learn that first. - stray = _left_in_the_secrets_directory(host.parent, environ) + stray = _left_outside_the_custody_directory(settings, host.parent, environ) if stray is not None: raise _recorded_as(HostCustodyRefused, stray) raise _missing(host, handoff) diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index 491c8d9e1b..6ce34d2ad8 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -1105,9 +1105,9 @@ function Get-CustodyGrantProblem { <# Why the access list $Acl does not give the account $AccountSid exactly what the custody directory grants it, or "" when it does (vault BACKLOG #3411, ADR 0214's 2026-11-22 - amendment): read and add-file on the directory itself, inherited by nothing. A right beyond - those, or an allow entry that files or folders inside inherit, is a problem, and so is a - missing read or add-file. Deny entries grant nothing and are not read. + amendment): read and add-file on the directory itself, inherited by nothing. At least a right + beyond those, an allow entry that files or folders inside inherit, a missing read or add-file, + and a deny entry for the account that takes away part of either, are problems. WHY ADD-FILE AND NOTHING MORE. The service's first start writes its own key file, master.key, into this directory, so it must add a file there. It deletes the handoff through the handle it @@ -1122,10 +1122,16 @@ function Get-CustodyGrantProblem { $allowed = [int64]($read -bor $add -bor $rights::Synchronize) $held = [int64]0 foreach ($rule in @($Acl.Access)) { - if ($rule.AccessControlType -ne [Security.AccessControl.AccessControlType]::Allow) { continue } $sid = try { $rule.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value } catch { "$($rule.IdentityReference)" } if ($sid -ne $AccountSid) { continue } + if ($rule.AccessControlType -ne [Security.AccessControl.AccessControlType]::Allow) { + # A deny is read before an allow, so one that reaches read or add-file takes it away. + if ([int64]$rule.FileSystemRights -band ([int64]$read -bor [int64]$add)) { + return "a deny entry for it takes away $($rule.FileSystemRights)" + } + continue + } if ($rule.InheritanceFlags -ne [Security.AccessControl.InheritanceFlags]::None) { return "an entry for it is inherited by what the directory holds ($($rule.FileSystemRights))" } @@ -1170,6 +1176,8 @@ function Set-CustodyDirAcl { if ($LASTEXITCODE -ne 0) { $problems += "inheritance could not be turned off with SYSTEM and Administrators granted (icacls exit $LASTEXITCODE)" } + # A deny for the account would outrank its grant; /grant:r leaves one in place. + & icacls $Path /remove:d $Account | Out-Null # No inheritance flag: the grant is on the directory, and the key files carry their own lists. & icacls $Path /grant:r "${Account}:(RX,WD)" | Out-Null if ($LASTEXITCODE -ne 0) { @@ -3558,7 +3566,8 @@ if ($HostCustody) { Write-Warning ("The service's MEFOR_CUSTODY_DIRECTORY named '$replacedCustodyDir' and now " + "names '$CustodyDir', as -CustodyDir asked. The engine reads no key file from the old " + "directory: if master.key or handoff.key is there, move it into the new one as an " + - "administrator, on the same volume so it keeps its own access list.") + "administrator, on the same volume so it keeps its own access list. Then remove the " + + "service account's grant on the old directory.") } Write-Host " Custody: '$CustodyDir', named to the service as MEFOR_CUSTODY_DIRECTORY (docs/SERVICE.md)." } catch { diff --git a/tests/test_file_path_join_census.py b/tests/test_file_path_join_census.py index a169f020d7..d8760ebf4f 100644 --- a/tests/test_file_path_join_census.py +++ b/tests/test_file_path_join_census.py @@ -955,8 +955,8 @@ def derived_script_sites() -> dict[str, int]: "messagefoundry/store/custody_host.py::_custody_paths": Site( 2, OPERATOR, - "The two fixed custody file names under the directory MEFOR_SECRETS_DIRECTORY names, or " - "the operator's [store].path directory.", + "The two fixed custody file names under the directory MEFOR_CUSTODY_DIRECTORY or " + "MEFOR_SECRETS_DIRECTORY names, or the operator's [store].path directory.", ), "messagefoundry/store/store.py::MessageStore._db_size_bytes": Site( 1, OPERATOR, _SQLITE_SIDECARS @@ -1256,7 +1256,7 @@ def derived_script_sites() -> dict[str, int]: 7, OPERATOR, "Fixed names under the repo root, the helper source and the install directory." ), "scripts/service/install-service.ps1": Site( - 44, + 45, OPERATOR, "Fixed names, and a folder named from a fresh GUID under the Windows temp folder, under " "paths the operator passes or the script derives (repo root, install " @@ -1264,7 +1264,8 @@ def derived_script_sites() -> dict[str, int]: "wheel's folder, " "the base interpreter's folder and the one above it, " "project root, data directory and the folder above it, ProgramData, NSSM directory, temp), " - "the data directory's own leaf name with -secrets after it, the leaf name of the engine wheel " + "the data directory's own leaf name with -secrets or -custody after it, the leaf name of " + "the engine wheel " "the operator passes, which must match messagefoundry--*.whl, plus registry keys " "named after the service's own images, and the fixed Parameters key under each key the " "registry lists below Services.", diff --git a/tests/test_install_service_custody.py b/tests/test_install_service_custody.py index 85cd38dc0b..85c9fde926 100644 --- a/tests/test_install_service_custody.py +++ b/tests/test_install_service_custody.py @@ -174,26 +174,30 @@ def test_the_installer_refuses_before_anything_acts(tmp_path: Path) -> None: ("M", False), ("F", False), ("(GR,WD)", False), # a generic right is not read as the rights it maps to + ("(RX,WD)+deny(WD)", False), # a deny for the account itself takes add-file away ] @_windows_only def test_the_custody_grant_rule(tmp_path: Path) -> None: - """Get-CustodyGrantProblem on a real directory's list, one per grant. A deny entry is not a - grant, so it neither widens nor narrows the verdict.""" + """Get-CustodyGrantProblem on a real directory's list, one per grant. A deny entry for another + account, here Users, neither widens nor narrows the verdict; one for the account itself that + reaches add-file is refused.""" assert _SCRIPT is not None dirs = [] - for i, (grant, _) in enumerate(_GRANTS): + for i, (spelled, _) in enumerate(_GRANTS): d = tmp_path / f"g{i}" d.mkdir() - dirs.append((str(d), grant)) + grant, _, deny = spelled.partition("+deny") + dirs.append((str(d), grant, deny)) cases = "\n".join( f' & icacls {_psq(d)} /inheritance:r /grant:r "*${{mySid}}:{grant}" ' f"'*S-1-5-32-544:(OI)F' | Out-Null\n" f" & icacls {_psq(d)} /deny '*S-1-5-32-545:(WD)' | Out-Null\n" - f" $out += [string](Get-CustodyGrantProblem -Acl (Get-Acl -LiteralPath {_psq(d)}) " + + (f' & icacls {_psq(d)} /deny "*${{mySid}}:{deny}" | Out-Null\n' if deny else "") + + f" $out += [string](Get-CustodyGrantProblem -Acl (Get-Acl -LiteralPath {_psq(d)}) " "-AccountSid $mySid)" - for d, grant in dirs + for d, grant, deny in dirs ) body = ( " $mySid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value\n" @@ -203,9 +207,10 @@ def test_the_custody_grant_rule(tmp_path: Path) -> None: got = json.loads(_ok(_extract(_SCRIPT, ["Get-CustodyGrantProblem"], body), tmp_path)) finally: restore = "\n".join( - f' & icacls {_psq(d)} /inheritance:e /grant "*$([Security.Principal.WindowsIdentity]' - '::GetCurrent().User.Value):(OI)(CI)F" | Out-Null' - for d, _ in dirs + " $s = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value\n" + f' & icacls {_psq(d)} /remove:d "*$s" | Out-Null\n' + f' & icacls {_psq(d)} /inheritance:e /grant "*${{s}}:(OI)(CI)F" | Out-Null' + for d, _, _ in dirs ) _run(_extract(_SCRIPT, [], restore), tmp_path) assert [not p for p in got] == [ok for _, ok in _GRANTS], list(zip(_GRANTS, got, strict=True)) @@ -213,10 +218,11 @@ def test_the_custody_grant_rule(tmp_path: Path) -> None: @_windows_only def test_the_custody_directory_lockdown_grants_exactly_read_and_add_file(tmp_path: Path) -> None: - """Set-CustodyDirAcl on a directory that inherits Users read and the account's Modify. The - account ends with read and add-file on the directory alone, nothing inherited, and the engine's - own check of a custody directory passes it, where it refused the directory before. Unelevated, - the owner change is refused, and the function refuses for that alone.""" + """Set-CustodyDirAcl on a directory that inherits Users read and the account's Modify, and + denies the account add-file. The account ends with read and add-file on the directory alone, + nothing inherited and no deny, and the engine's own check of a custody directory passes it, + where it refused the directory before. Unelevated, the owner change is refused, and the + function refuses for that alone.""" from messagefoundry.store import custody_host assert _SCRIPT is not None @@ -226,6 +232,7 @@ def test_the_custody_directory_lockdown_grants_exactly_read_and_add_file(tmp_pat pre = rf""" $me = [Security.Principal.WindowsIdentity]::GetCurrent().Name & icacls {_psq(str(parent))} /grant '*S-1-5-32-545:(OI)(CI)RX' "${{me}}:(OI)(CI)M" | Out-Null + & icacls {_psq(str(custody))} /deny "${{me}}:(WD)" | Out-Null """ _ok(_extract(_SCRIPT, [], pre), tmp_path) environ = {"MEFOR_CUSTODY_DIRECTORY": str(custody)} diff --git a/tests/test_store_custody_host.py b/tests/test_store_custody_host.py index a70aa3e953..fff1daceec 100644 --- a/tests/test_store_custody_host.py +++ b/tests/test_store_custody_host.py @@ -308,6 +308,39 @@ def test_a_key_file_left_in_the_secrets_directory_is_not_taken_for_no_key(tmp_pa _settings(tmp_path), enforcing=True, environ={"MEFOR_SECRETS_DIRECTORY": str(secrets)} ) assert "move it into" not in str(read.value) + # With no secrets directory, beside a SQLite store, where a mint with neither variable writes. + (secrets / "handoff.key").unlink() + beside = tmp_path / "handoff.key" + beside.write_bytes(b"not read") + with pytest.raises(HostCustodyRefused, match="move it into") as refused: + load_host_custody( + _settings(tmp_path), + enforcing=True, + environ={"MEFOR_CUSTODY_DIRECTORY": str(custody_dir)}, + ) + assert str(beside) in str(refused.value) + + +@pytest.mark.parametrize("where", ["custody", "secrets", "beside the store"]) +def test_a_host_blob_anywhere_the_host_provider_reads_refuses_every_other_key_provider( + tmp_path: Path, where: str +) -> None: + """Rule 13 reads the custody directory of its own and the directory the host provider reads + without it, so a key file left in either refuses another provider. A custody variable that is + not an absolute path does not turn the check off.""" + custody_dir = _own_custody_directory(tmp_path / "custody") + secrets = _own_custody_directory(tmp_path / "secrets") + target = {"custody": custody_dir, "secrets": secrets, "beside the store": tmp_path}[where] + (target / "master.key").write_bytes(b"not read") + settings = _settings(tmp_path, key_provider="auto", encryption_key_file="k.bin") + environ = {"MEFOR_CUSTODY_DIRECTORY": str(custody_dir)} + if where != "beside the store": + environ["MEFOR_SECRETS_DIRECTORY"] = str(secrets) + refusal = foreign_custody_refusal(settings, environ=environ) + assert refusal is not None and str(target) in refusal, refusal + if where != "custody": + unusable = {**environ, "MEFOR_CUSTODY_DIRECTORY": "relative"} + assert foreign_custody_refusal(settings, environ=unusable) is not None def test_the_way_on_names_the_custody_directory_of_its_own(tmp_path: Path) -> None: @@ -338,13 +371,9 @@ async def test_the_first_start_converts_into_a_directory_it_may_only_read_and_ad ) await _create(settings, blob) _handoff(custody_dir / "handoff.key", blob) - _grant( - custody_dir, - "*S-1-5-18:(OI)F", - "*S-1-5-32-544:(OI)F", - f"{_me()}:(RX,WD)", - reset=True, - ) + # No Administrators entry, unlike the installer's list: on an elevated runner it would give + # this token full control, and the case would no longer measure read and add-file alone. + _grant(custody_dir, "*S-1-5-18:(OI)F", f"{_me()}:(RX,WD)", reset=True) try: # The grant took: this account may add a file there. assert restricted_file.can_add_a_file(custody_dir) is True From 055009afa7900c817b0752f37048262de5945811 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 16:48:26 -0600 Subject: [PATCH 11/28] Key custody: repair round 2, custody directory review round-e6602f0088 Vault BACKLOG #3411 slice B3c, design note 1. - The installer removes every deny entry on the custody directory, and the read-back refuses any deny that applies to the directory: one for a group the service account is in binds it as one for the account does. Tests cover a Users deny and an inherit-only one. - The directories a key file may sit in now include a SQLite store's data directory whether or not a variable is set, so the left-behind refusal reads beside the store for an installer-made service; mint_target applies that refusal before anything is minted. The data-directory rule is read through custody_directory, not repeated. - The installer's refusal of an existing, unnamed custody directory no longer says to remove it outright: it says to move any key file out first. - SERVICE.md and the ADR amendment state what the read-back covers, deny entries included, and the sharer sentence names MEFOR_CUSTODY_DIRECTORY; the module docstring's precedence line matches the code. - -CustodyDir joins the absolute-before-use guard, and the call-site test refuses a New-Item made custody directory. --- docs/SERVICE.md | 19 ++--- ...-for-the-engine-s-secret-class-settings.md | 6 +- messagefoundry/store/custody_host.py | 70 ++++++++++--------- scripts/service/install-service.ps1 | 33 ++++++--- tests/test_install_service_custody.py | 26 ++++--- tests/test_service_install_manifest.py | 1 + tests/test_store_custody_host.py | 11 +++ 7 files changed, 103 insertions(+), 63 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index 62e946646a..15f63f21ec 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -274,11 +274,12 @@ directory's rules, made restricted in one step, and then given this list: - SYSTEM and Administrators: full control, inherited by the files in it; - the service account: read and add-file on the directory itself, inherited by nothing. -The script replaces any other grant or deny the service account holds there and removes every -other account's entry. It then reads the list back, and refuses, disabling the service, at least -when it has another owner, still inherits, still has an entry for another account, or gives the -service account more than that grant or, through a missing entry or a deny, less. When the script -does not read that provider, it refuses `-CustodyDir`. +The script replaces any other grant the service account holds there, and removes every other +account's allow entry and every deny entry, whoever it names. It then reads the list back, and +refuses, disabling the service, at least when it has another owner, still inherits, still has an +allow entry for another account or a deny entry on the directory, or gives the service account +more or less than that grant. When the script does not read that provider, it refuses +`-CustodyDir`. **The engine.** When `MEFOR_CUSTODY_DIRECTORY` is set, the host provider reads and writes the two files there, in place of the directory `MEFOR_SECRETS_DIRECTORY` names or the store's own data @@ -286,9 +287,9 @@ directory. Before it reads or mints, it checks that directory as it checks a sec any enforcement setting: a known broad group's right to read it, add a file to it or delete one in it is refused, and so is a link. That check reads known broad groups only, so it refuses no entry for one account, the service's or any other; the list the script sets is what leaves other -accounts no entry. While the variable is set, a key file found where the provider would look without it, the -secrets directory or beside a SQLite store, is refused rather than taken for no key at all, so a -mint run without the variable does not lead to a second key. +accounts no entry. While the variable is set and neither file is there, a key file in the secrets +directory or beside a SQLite store refuses a read and a mint, rather than being taken for no key at +all, so a mint run without the variable does not lead to a second key. **Minting.** Set the variable in the elevated shell that runs `provision-admin --service-account`, to the same path, so the handoff lands where the service looks: @@ -726,7 +727,7 @@ NSSM environment. file or a folder holding a folder, that sits below a junction, or that is, holds or sits inside at least the data, log, store, config, value-file and settings-file folders, NSSM's folder, the engine install, the checkout, the Windows folder and Program Files. It refuses a path another - service already names as its `MEFOR_SECRETS_DIRECTORY`, or a folder inside or around one, so a second service on the same + service already names as its `MEFOR_SECRETS_DIRECTORY` or `MEFOR_CUSTODY_DIRECTORY`, or a folder inside or around one, so a second service on the same `-DataDir` needs its own `-SecretsDir`. The installer makes the directory with its owner and access list in one step. The directory starts empty: as an administrator, create or copy in one file per setting, named as its variable, and restart the service. Do not move a file in: a diff --git a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md index 67a53b1884..bd5a00d5ef 100644 --- a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md +++ b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md @@ -164,10 +164,10 @@ names ADR 0019 declared and nobody built. Also not moved: the store key's own re a read or a mint, the engine applies decision 4's check to the directory that variable names, `broad_access_problem` with `directory`, at every enforcement setting; like decision 4's check, it reads known broad groups only, so it refuses no entry for one account, the service's add-file - right included. While the variable is set, a host file or handoff found only where the provider - reads without it, this directory or beside a SQLite store, refuses the read, so a mint made + right included. While the variable is set and neither file is in that directory, a host file or + handoff in this directory or beside a SQLite store refuses a read and a mint, so one made without the variable is not taken for no key; and the check that refuses another key provider - beside a host file or handoff looks in both places. `install-service.ps1` makes the directory only when it reads that provider: `-CustodyDir`, + beside a host file or handoff looks in all three places. `install-service.ps1` makes the directory only when it reads that provider: `-CustodyDir`, else the one the service names, else `-custody`, judged by slice C's rules with this directory added to the paths it must not be, hold or sit inside, made restricted in one step, and restricted to Administrators as owner, SYSTEM and Administrators with full control, and the diff --git a/messagefoundry/store/custody_host.py b/messagefoundry/store/custody_host.py index e0ad1b04e4..bdca029f41 100644 --- a/messagefoundry/store/custody_host.py +++ b/messagefoundry/store/custody_host.py @@ -22,7 +22,8 @@ (:class:`~messagefoundry.store.store.StorePin`): a new store's genesis record is written with the current id, and an existing store's must name one the blob names. * **Precedence.** A host blob is never read beside another store key source, and a host blob or a - handoff in the custody directory refuses every other key provider (rules 2 and 13). + handoff in a directory this provider may read refuses every other key provider (rules 2 and 13; + :func:`foreign_custody_refusal`). * **The account.** SYSTEM, LOCAL SERVICE and NETWORK SERVICE are refused always, and on Linux root and nobody (the custody primitives refuse them). An account that is not local to this host, at least a domain user or a group managed service account, is refused under ``enforce`` and named as @@ -215,26 +216,35 @@ def _custody_paths(directory: Path) -> tuple[Path, Path]: def _key_file_directories(settings: StoreSettings, environ: Mapping[str, str]) -> list[Path]: - """Each directory a host file or handoff for this store may sit in, first the one the host - provider reads now: the one ``MEFOR_CUSTODY_DIRECTORY`` names, then the one it reads without - that variable, ``MEFOR_SECRETS_DIRECTORY``'s or else a SQLite store's data directory. A - variable that is not an absolute path names none here; :func:`custody_directory` refuses it.""" - from messagefoundry.config.settings import StoreBackend - + """Each directory a host file or handoff for this store may sit in: the ones + ``MEFOR_CUSTODY_DIRECTORY`` and ``MEFOR_SECRETS_DIRECTORY`` name, and a SQLite store's data + directory, where a mint run with neither variable writes, whether or not a variable is set + here. A variable that is not an absolute path names none here; :func:`custody_directory` + refuses it.""" found: list[Path] = [] for variable in (CUSTODY_DIRECTORY_VARIABLE, SECRETS_DIRECTORY_VARIABLE): raw = environ.get(variable, "").strip() if raw and Path(raw).is_absolute(): found.append(Path(raw)) - if ( - not environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip() - and settings.backend is StoreBackend.SQLITE - and settings.path != ":memory:" - ): - found.append(Path(settings.path).resolve().parent) + beside = custody_directory(settings, environ={}) + if beside is not None: + found.append(beside) return list(dict.fromkeys(found)) +def _key_files_outside( + settings: StoreSettings, directory: Path | None, environ: Mapping[str, str] +) -> list[Path]: + """The host files and handoffs in :func:`_key_file_directories` other than ``directory``.""" + return [ + p + for other in _key_file_directories(settings, environ) + if other != directory + for p in _custody_paths(other) + if os.path.lexists(p) + ] + + def _key_sources_beside(settings: StoreSettings, environ: Mapping[str, str]) -> list[str]: """Every other store key source that is set: the settings' own and the key-class variables.""" named = [] @@ -271,17 +281,12 @@ def foreign_custody_refusal( settings: StoreSettings, *, environ: Mapping[str, str] | None = None ) -> str | None: """Why a store under any key provider but ``host`` must not open, or ``None``: a host blob or a - handoff sits in a directory the ``host`` provider would read it from + handoff sits in a directory where a ``host`` mint may have written it (:func:`_key_file_directories`), so the store's key would be taken from somewhere other than the blob minted for it. A directory setting that is not an absolute path is passed over here, and the directories the other setting names are still looked in.""" environ = os.environ if environ is None else environ - found = [ - p - for directory in _key_file_directories(settings, environ) - for p in _custody_paths(directory) - if os.path.lexists(p) - ] + found = _key_files_outside(settings, None, environ) if not found: return None return ( @@ -647,19 +652,14 @@ def _left_behind(done: str, handoff: Path) -> HostCustodyRefused: def _left_outside_the_custody_directory( settings: StoreSettings, directory: Path, environ: Mapping[str, str] | None ) -> str | None: - """Why a read that found neither file in ``directory``, the custody directory, must not report - that no key was minted, or ``None``: a host file or a handoff sits in another directory - :func:`_key_file_directories` names, where a mint run without ``MEFOR_CUSTODY_DIRECTORY`` - writes it. A command told that no key was minted could mint a second one, which does not open - a store the first one made.""" + """Why a read or a mint that found neither file in ``directory``, the custody directory + ``MEFOR_CUSTODY_DIRECTORY`` names, must not go on as if no key was minted, or ``None``: a host + file or a handoff sits in another directory :func:`_key_file_directories` names, where a mint + run without that variable writes it. A second key would not open a store the first one made.""" environ = os.environ if environ is None else environ - found = [ - p - for other in _key_file_directories(settings, environ) - if other != directory - for p in _custody_paths(other) - if os.path.lexists(p) - ] + if _directory_variable(environ) != CUSTODY_DIRECTORY_VARIABLE: + return None # without it the provider reads where it did before the variable existed + found = _key_files_outside(settings, directory, environ) if not found: return None return ( @@ -667,7 +667,7 @@ def _left_outside_the_custody_directory( f"{CUSTODY_DIRECTORY_VARIABLE} names, but {' and '.join(str(p) for p in found)} is in a " f"directory this provider reads only while {CUSTODY_DIRECTORY_VARIABLE} is unset. If it " f"holds this store's key, move it into {directory} as an administrator, on the same " - "volume so it keeps its own access list, and start again; a key minted now would not open " + "volume so it keeps its own access list, and try again; a key minted now would not open " "a store that key made" ) @@ -979,6 +979,10 @@ def mint_target( settings, new_store=False, service_account=service_account, environ=environ ) ) + # A key file a mint without MEFOR_CUSTODY_DIRECTORY left elsewhere stops a second one too. + stray = _left_outside_the_custody_directory(settings, host.parent, environ) + if stray is not None: + raise _recorded_as(HostCustodyRefused, stray) if service_account is None: # What the write refuses for this account, asked now: the shared and non-local accounts # (and on Linux root and nobody). diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index 6ce34d2ad8..c6415cc263 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -1107,7 +1107,7 @@ function Get-CustodyGrantProblem { directory grants it, or "" when it does (vault BACKLOG #3411, ADR 0214's 2026-11-22 amendment): read and add-file on the directory itself, inherited by nothing. At least a right beyond those, an allow entry that files or folders inside inherit, a missing read or add-file, - and a deny entry for the account that takes away part of either, are problems. + and any deny entry that applies to the directory itself, whoever it names, are problems. WHY ADD-FILE AND NOTHING MORE. The service's first start writes its own key file, master.key, into this directory, so it must add a file there. It deletes the handoff through the handle it @@ -1124,14 +1124,16 @@ function Get-CustodyGrantProblem { foreach ($rule in @($Acl.Access)) { $sid = try { $rule.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value } catch { "$($rule.IdentityReference)" } - if ($sid -ne $AccountSid) { continue } if ($rule.AccessControlType -ne [Security.AccessControl.AccessControlType]::Allow) { - # A deny is read before an allow, so one that reaches read or add-file takes it away. - if ([int64]$rule.FileSystemRights -band ([int64]$read -bor [int64]$add)) { - return "a deny entry for it takes away $($rule.FileSystemRights)" + # A deny is read before an allow, and one for a group the account is in, such as + # Users, binds it as one for the account does. Which groups it is in is not read here, + # so any deny that applies to the directory itself is refused. + if (-not ($rule.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly)) { + return "a deny entry for $($rule.IdentityReference) applies to the directory ($($rule.FileSystemRights))" } continue } + if ($sid -ne $AccountSid) { continue } if ($rule.InheritanceFlags -ne [Security.AccessControl.InheritanceFlags]::None) { return "an entry for it is inherited by what the directory holds ($($rule.FileSystemRights))" } @@ -1176,8 +1178,17 @@ function Set-CustodyDirAcl { if ($LASTEXITCODE -ne 0) { $problems += "inheritance could not be turned off with SYSTEM and Administrators granted (icacls exit $LASTEXITCODE)" } - # A deny for the account would outrank its grant; /grant:r leaves one in place. - & icacls $Path /remove:d $Account | Out-Null + # A deny for the account, or for a group it is in, would outrank its grant, and /grant:r and + # /remove:g leave every deny in place, so each one goes. The read-back refuses any left. + $denied = @(try { (Get-Acl -LiteralPath $Path).Access } catch { @() }) | Where-Object { + $_.AccessControlType -eq [Security.AccessControl.AccessControlType]::Deny -and -not $_.IsInherited } + foreach ($holder in @($denied | ForEach-Object { + $who = $_.IdentityReference + try { $who.Translate([Security.Principal.SecurityIdentifier]).Value } catch { "$who" } + } | Select-Object -Unique)) { + $spelled = if ($holder -match '^S-1-') { "*$holder" } else { $holder } + & icacls $Path /remove:d $spelled | Out-Null + } # No inheritance flag: the grant is on the directory, and the key files carry their own lists. & icacls $Path /grant:r "${Account}:(RX,WD)" | Out-Null if ($LASTEXITCODE -ne 0) { @@ -3069,8 +3080,12 @@ if (-not $HostCustody) { $CustodyDirNamed = [bool]$RegisteredCustodyDir -and ($RegisteredCustodyDir.TrimEnd('\') -eq $CustodyDir.TrimEnd('\')) if (-not $custodyProblem -and (Test-Path -LiteralPath $CustodyDir)) { if (-not $CustodyDirNamed) { - $custodyProblem = ("it already exists and the service does not name it. Remove it, check " + - "who made it, and re-run the installer, which then makes it restricted") + $custodyProblem = ("it already exists and the service does not name it. Check who made " + + "it. If it holds master.key or handoff.key, that may be the only copy of a store's key " + + "on this host: do not delete it. Move each such file, as an administrator, to a folder " + + "only administrators can read on the same volume, so it keeps its own access list. Then " + + "remove the directory, re-run the installer, which makes it restricted, and move the " + + "files back into it") } else { $owner = (Get-Acl -LiteralPath $CustodyDir).GetOwner([Security.Principal.SecurityIdentifier]).Value if ($owner -ne "S-1-5-32-544" -and $owner -ne "S-1-5-18") { diff --git a/tests/test_install_service_custody.py b/tests/test_install_service_custody.py index 85c9fde926..37607b6bb4 100644 --- a/tests/test_install_service_custody.py +++ b/tests/test_install_service_custody.py @@ -174,15 +174,16 @@ def test_the_installer_refuses_before_anything_acts(tmp_path: Path) -> None: ("M", False), ("F", False), ("(GR,WD)", False), # a generic right is not read as the rights it maps to - ("(RX,WD)+deny(WD)", False), # a deny for the account itself takes add-file away + ("(RX,WD)+deny${me}:(WD)", False), # a deny for the account itself takes add-file away + # One for a group it is in binds it too, and the groups are not read, so any deny is refused. + ("(RX,WD)+deny*S-1-5-32-545:(WD)", False), + ("(RX,WD)+deny*S-1-5-32-545:(OI)(IO)(WD)", True), # inherit-only: not on the directory ] @_windows_only def test_the_custody_grant_rule(tmp_path: Path) -> None: - """Get-CustodyGrantProblem on a real directory's list, one per grant. A deny entry for another - account, here Users, neither widens nor narrows the verdict; one for the account itself that - reaches add-file is refused.""" + """Get-CustodyGrantProblem on a real directory's list, one per grant and deny.""" assert _SCRIPT is not None dirs = [] for i, (spelled, _) in enumerate(_GRANTS): @@ -193,14 +194,14 @@ def test_the_custody_grant_rule(tmp_path: Path) -> None: cases = "\n".join( f' & icacls {_psq(d)} /inheritance:r /grant:r "*${{mySid}}:{grant}" ' f"'*S-1-5-32-544:(OI)F' | Out-Null\n" - f" & icacls {_psq(d)} /deny '*S-1-5-32-545:(WD)' | Out-Null\n" - + (f' & icacls {_psq(d)} /deny "*${{mySid}}:{deny}" | Out-Null\n' if deny else "") + + (f' & icacls {_psq(d)} /deny "{deny}" | Out-Null\n' if deny else "") + f" $out += [string](Get-CustodyGrantProblem -Acl (Get-Acl -LiteralPath {_psq(d)}) " "-AccountSid $mySid)" for d, grant, deny in dirs ) body = ( " $mySid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value\n" + ' $me = "*$mySid"\n' f" $out = @()\n{cases}\n ConvertTo-Json -InputObject $out -Compress\n" ) try: @@ -208,7 +209,7 @@ def test_the_custody_grant_rule(tmp_path: Path) -> None: finally: restore = "\n".join( " $s = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value\n" - f' & icacls {_psq(d)} /remove:d "*$s" | Out-Null\n' + f' & icacls {_psq(d)} /remove:d "*$s" "*S-1-5-32-545" | Out-Null\n' f' & icacls {_psq(d)} /inheritance:e /grant "*${{s}}:(OI)(CI)F" | Out-Null' for d, _, _ in dirs ) @@ -219,7 +220,7 @@ def test_the_custody_grant_rule(tmp_path: Path) -> None: @_windows_only def test_the_custody_directory_lockdown_grants_exactly_read_and_add_file(tmp_path: Path) -> None: """Set-CustodyDirAcl on a directory that inherits Users read and the account's Modify, and - denies the account add-file. The account ends with read and add-file on the directory alone, + denies the account and Users add-file. The account ends with read and add-file on the directory alone, nothing inherited and no deny, and the engine's own check of a custody directory passes it, where it refused the directory before. Unelevated, the owner change is refused, and the function refuses for that alone.""" @@ -232,7 +233,7 @@ def test_the_custody_directory_lockdown_grants_exactly_read_and_add_file(tmp_pat pre = rf""" $me = [Security.Principal.WindowsIdentity]::GetCurrent().Name & icacls {_psq(str(parent))} /grant '*S-1-5-32-545:(OI)(CI)RX' "${{me}}:(OI)(CI)M" | Out-Null - & icacls {_psq(str(custody))} /deny "${{me}}:(WD)" | Out-Null + & icacls {_psq(str(custody))} /deny "${{me}}:(WD)" '*S-1-5-32-545:(WD)' | Out-Null """ _ok(_extract(_SCRIPT, [], pre), tmp_path) environ = {"MEFOR_CUSTODY_DIRECTORY": str(custody)} @@ -252,6 +253,7 @@ def test_the_custody_directory_lockdown_grants_exactly_read_and_add_file(tmp_pat [pscustomobject]@{{ refusal = $refusal inherited = @($acl.Access | Where-Object {{ $_.IsInherited }}).Count + denies = @($acl.Access | Where-Object {{ "$($_.AccessControlType)" -eq 'Deny' }}).Count protected = $acl.AreAccessRulesProtected mine = @($mine | ForEach-Object {{ [pscustomobject]@{{ type = "$($_.AccessControlType)"; rights = [int64]$_.FileSystemRights; @@ -278,6 +280,7 @@ def test_the_custody_directory_lockdown_grants_exactly_read_and_add_file(tmp_pat _run(_extract(_SCRIPT, [], restore), tmp_path) assert after is None, f"the engine refuses the locked directory: {after}\n{got['text']}" assert got["protected"] and got["inherited"] == 0, got["text"] + assert got["denies"] == 0, f"a deny survived the lockdown:\n{got['text']}" mine = got["mine"] if isinstance(got["mine"], list) else [got["mine"]] # ReadAndExecute | CreateFiles | Synchronize, in one allow entry inherited by nothing. assert mine == [{"type": "Allow", "rights": 0x1200AB, "inherit": "None"}], got["text"] @@ -305,6 +308,11 @@ def test_the_installer_makes_and_names_the_custody_directory_under_the_host_prov assert "-AllowMissing" in check["text"] and "$SecretsDir" in check["text"], check["text"] sharers = _sole_call_on(facts, "Get-OtherServiceNamingPath", "-Path $CustodyDir") creates = _sole_call_on(facts, "New-RestrictedDirectory", "-Path $CustodyDir") + assert not [ + c + for c in facts["commands"] + if c["name"] in ("New-AdminOnlyFolder", "New-Item") and "-Path $CustodyDir" in c["text"] + ], "the custody directory itself must not be made by New-Item" lock = _sole_call(facts, "Set-CustodyDirAcl") assert "-Path $CustodyDir" in lock["text"] and "-Account $ServiceAccount" in lock["text"] secrets_lock = _sole_call(facts, "Set-SecretsDirAcl") diff --git a/tests/test_service_install_manifest.py b/tests/test_service_install_manifest.py index 7c8cb63678..6b4df2f6d3 100644 --- a/tests/test_service_install_manifest.py +++ b/tests/test_service_install_manifest.py @@ -1139,6 +1139,7 @@ def at(name_starts: str) -> int: "ProjectRoot", "DbPath", "SecretsDir", + "CustodyDir", # vault BACKLOG #3411 # -EngineWheel's inputs (vault BACKLOG #2626), read before the build acts. "EngineWheel", "RequirementsLock", diff --git a/tests/test_store_custody_host.py b/tests/test_store_custody_host.py index fff1daceec..cbfa90bfa4 100644 --- a/tests/test_store_custody_host.py +++ b/tests/test_store_custody_host.py @@ -319,6 +319,17 @@ def test_a_key_file_left_in_the_secrets_directory_is_not_taken_for_no_key(tmp_pa environ={"MEFOR_CUSTODY_DIRECTORY": str(custody_dir)}, ) assert str(beside) in str(refused.value) + # A mint is stopped the same way, before anything is minted. + with pytest.raises(HostCustodyRefused, match="move it into"): + mint_target( + _settings(tmp_path), + service_account=None, + enforcing=True, + environ={ + "MEFOR_CUSTODY_DIRECTORY": str(custody_dir), + "MEFOR_SECRETS_DIRECTORY": str(secrets), + }, + ) @pytest.mark.parametrize("where", ["custody", "secrets", "beside the store"]) From 104122bf83bc5f5ee5cd8dbe059d1656b49d8176 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 17:26:35 -0600 Subject: [PATCH 12/28] Key custody: round-232ff851bf's four items, the uninstaller and the naming refusal Vault BACKLOG #3411 slice B3c, design note 1, as the Manager directed. - Set-CustodyDirAcl removes every allow entry for the account before its grant, so a wider entry with other inheritance flags cannot survive; the header and SERVICE.md now hold. The lockdown test seeds such an entry. - The custody tests make the Windows directory without a mode, which on Python 3.13 and later writes SYSTEM, Administrators and OWNER RIGHTS entries, and the first-start reset removes those three; the test now checks the list is SYSTEM and the account's read and add-file alone. - The other-provider check looks beside a SQLite store only when MEFOR_SECRETS_DIRECTORY is unset, as before the custody variable, so its remedy can clear it; the left-behind check still looks there. - _key_file_directories says "at least" and names what it misses. - The uninstaller reads MEFOR_CUSTODY_DIRECTORY, names the directory in its notice, and removes the account's entry under -RemoveAccountAces. - A custody variable the installer cannot write refuses and disables the service instead of warning. --- ...-for-the-engine-s-secret-class-settings.md | 3 +- messagefoundry/store/custody_host.py | 36 ++++++++---- scripts/service/install-service.ps1 | 36 +++++++----- scripts/service/uninstall-service.ps1 | 34 +++++++++++ tests/test_install_service_custody.py | 28 ++++++++- tests/test_service_install_manifest.py | 12 +++- tests/test_store_custody_host.py | 57 +++++++++++++++++-- 7 files changed, 171 insertions(+), 35 deletions(-) diff --git a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md index bd5a00d5ef..ed9777e283 100644 --- a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md +++ b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md @@ -167,7 +167,8 @@ names ADR 0019 declared and nobody built. Also not moved: the store key's own re right included. While the variable is set and neither file is in that directory, a host file or handoff in this directory or beside a SQLite store refuses a read and a mint, so one made without the variable is not taken for no key; and the check that refuses another key provider - beside a host file or handoff looks in all three places. `install-service.ps1` makes the directory only when it reads that provider: `-CustodyDir`, + beside a host file or handoff looks in that directory and in the one the provider reads without + it. `install-service.ps1` makes the directory only when it reads that provider: `-CustodyDir`, else the one the service names, else `-custody`, judged by slice C's rules with this directory added to the paths it must not be, hold or sit inside, made restricted in one step, and restricted to Administrators as owner, SYSTEM and Administrators with full control, and the diff --git a/messagefoundry/store/custody_host.py b/messagefoundry/store/custody_host.py index bdca029f41..9256894513 100644 --- a/messagefoundry/store/custody_host.py +++ b/messagefoundry/store/custody_host.py @@ -215,30 +215,40 @@ def _custody_paths(directory: Path) -> tuple[Path, Path]: return directory / HOST_FILE_NAME, directory / HANDOFF_FILE_NAME -def _key_file_directories(settings: StoreSettings, environ: Mapping[str, str]) -> list[Path]: - """Each directory a host file or handoff for this store may sit in: the ones +def _key_file_directories( + settings: StoreSettings, environ: Mapping[str, str], *, always_beside_store: bool +) -> list[Path]: + """At least these directories a host file or handoff for this store may sit in: the ones ``MEFOR_CUSTODY_DIRECTORY`` and ``MEFOR_SECRETS_DIRECTORY`` name, and a SQLite store's data - directory, where a mint run with neither variable writes, whether or not a variable is set - here. A variable that is not an absolute path names none here; :func:`custody_directory` - refuses it.""" + directory, where a mint run with neither variable writes. The data directory is named only when + ``MEFOR_SECRETS_DIRECTORY`` is unset, unless ``always_beside_store``. Not named, at least: a + custody directory an earlier setting named. A variable that is not an absolute path names none + here; :func:`custody_directory` refuses it.""" found: list[Path] = [] for variable in (CUSTODY_DIRECTORY_VARIABLE, SECRETS_DIRECTORY_VARIABLE): raw = environ.get(variable, "").strip() if raw and Path(raw).is_absolute(): found.append(Path(raw)) - beside = custody_directory(settings, environ={}) - if beside is not None: - found.append(beside) + if always_beside_store or not environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip(): + beside = custody_directory(settings, environ={}) + if beside is not None: + found.append(beside) return list(dict.fromkeys(found)) def _key_files_outside( - settings: StoreSettings, directory: Path | None, environ: Mapping[str, str] + settings: StoreSettings, + directory: Path | None, + environ: Mapping[str, str], + *, + always_beside_store: bool, ) -> list[Path]: """The host files and handoffs in :func:`_key_file_directories` other than ``directory``.""" return [ p - for other in _key_file_directories(settings, environ) + for other in _key_file_directories( + settings, environ, always_beside_store=always_beside_store + ) if other != directory for p in _custody_paths(other) if os.path.lexists(p) @@ -286,7 +296,9 @@ def foreign_custody_refusal( the blob minted for it. A directory setting that is not an absolute path is passed over here, and the directories the other setting names are still looked in.""" environ = os.environ if environ is None else environ - found = _key_files_outside(settings, None, environ) + # Beside the store only where the provider would read it now: the remedy, a new directory + # named by a variable, must be able to clear the refusal. + found = _key_files_outside(settings, None, environ, always_beside_store=False) if not found: return None return ( @@ -659,7 +671,7 @@ def _left_outside_the_custody_directory( environ = os.environ if environ is None else environ if _directory_variable(environ) != CUSTODY_DIRECTORY_VARIABLE: return None # without it the provider reads where it did before the variable existed - found = _key_files_outside(settings, directory, environ) + found = _key_files_outside(settings, directory, environ, always_beside_store=True) if not found: return None return ( diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index c6415cc263..819f7a6178 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -1189,6 +1189,9 @@ function Set-CustodyDirAcl { $spelled = if ($holder -match '^S-1-') { "*$holder" } else { $holder } & icacls $Path /remove:d $spelled | Out-Null } + # /grant:r replaces only an entry with the same inheritance flags, so every allow entry for the + # account goes first, and a wider one cannot survive beside the grant. + & icacls $Path /remove:g $Account | Out-Null # No inheritance flag: the grant is on the directory, and the key files carry their own lists. & icacls $Path /grant:r "${Account}:(RX,WD)" | Out-Null if ($LASTEXITCODE -ne 0) { @@ -3575,22 +3578,27 @@ if ($HostCustody) { catch { throw "$($_.Exception.Message) $(Disable-RefusedService -ServiceName $ServiceName -Consequence 'its first start cannot write its store key file as the custody directory needs')" } + # A refusal, not a warning: without the variable the service reads the secrets directory, where + # it cannot write its key file, and a mint made as SERVICE.md says lands where it does not look. + $custodyNamingError = $null + $replacedCustodyDir = $null try { $replacedCustodyDir = Set-ServiceEnvironmentValue -ServiceName $ServiceName -Name "MEFOR_CUSTODY_DIRECTORY" -Value $CustodyDir - if ($replacedCustodyDir -and -not $CustodyDirNamed) { - Write-Warning ("The service's MEFOR_CUSTODY_DIRECTORY named '$replacedCustodyDir' and now " + - "names '$CustodyDir', as -CustodyDir asked. The engine reads no key file from the old " + - "directory: if master.key or handoff.key is there, move it into the new one as an " + - "administrator, on the same volume so it keeps its own access list. Then remove the " + - "service account's grant on the old directory.") - } - Write-Host " Custody: '$CustodyDir', named to the service as MEFOR_CUSTODY_DIRECTORY (docs/SERVICE.md)." - } catch { - Write-Warning ("Could not name the custody directory in the service's environment " + - "($($_.Exception.Message)). Add MEFOR_CUSTODY_DIRECTORY=$CustodyDir to its AppEnvironmentExtra " + - "by hand, keeping the entries already there; without it the service looks for its key " + - "file in the secrets directory, where it cannot write one.") - } + } catch { $custodyNamingError = $_.Exception.Message } + if ($null -ne $custodyNamingError) { + throw ("Could not name the custody directory in the service's environment " + + "($custodyNamingError), and without MEFOR_CUSTODY_DIRECTORY the service looks for its " + + "key file in the secrets directory, where it cannot write one. Re-run the installer. " + + "$(Disable-RefusedService -ServiceName $ServiceName -Consequence 'it would not find its custody directory')") + } + if ($replacedCustodyDir -and -not $CustodyDirNamed) { + Write-Warning ("The service's MEFOR_CUSTODY_DIRECTORY named '$replacedCustodyDir' and now " + + "names '$CustodyDir', as -CustodyDir asked. The engine reads no key file from the old " + + "directory: if master.key or handoff.key is there, move it into the new one as an " + + "administrator, on the same volume so it keeps its own access list. Then remove the " + + "service account's grant on the old directory.") + } + Write-Host " Custody: '$CustodyDir', named to the service as MEFOR_CUSTODY_DIRECTORY (docs/SERVICE.md)." } # The lockdown above removes Users and Authenticated Users, so a named account writes the data # directory through its own grant. That grant is read back on the two directories the service must diff --git a/scripts/service/uninstall-service.ps1 b/scripts/service/uninstall-service.ps1 index e31c468d22..5e18e5c878 100644 --- a/scripts/service/uninstall-service.ps1 +++ b/scripts/service/uninstall-service.ps1 @@ -279,6 +279,9 @@ function Get-UninstallResidueNotice { # The secrets directory read off the registration's MEFOR_SECRETS_DIRECTORY (vault BACKLOG # #2595 slice C). The installer grants the run-as account read there, with inheritance off. [string]$SecretsDir, + # The custody directory read off MEFOR_CUSTODY_DIRECTORY (vault BACKLOG #3411). The installer + # grants the run-as account read and add-file there, under the host key provider only. + [string]$CustodyDir, # Measured from the config dir's own ACL, not assumed from a switch this script never saw. [switch]$ConfigInheritanceStripped, # Path of the nssm.exe the registration starts, only when it is actually on disk. @@ -297,6 +300,7 @@ function Get-UninstallResidueNotice { [switch]$DataAceRemoved, [switch]$ConfigAceRemoved, [switch]$SecretsAceRemoved, + [switch]$CustodyAceRemoved, # Read AFTER the removal: the service's registry key is still there. Windows has only marked # the service for deletion, and the key holds the SID type and the privilege list the # installer set (vault BACKLOG #2702). @@ -346,6 +350,14 @@ function Get-UninstallResidueNotice { $lines += " Delete them once nothing needs them." } + if ($CustodyDir) { + $lines += " Custody dir $CustodyDir" + $lines += " The custody directory the service read under the host key" + $lines += " provider. master.key in it holds the store's key, and may be its" + $lines += " only copy on this host. This script leaves it and its files." + $lines += " Keep it while the store is kept." + } + if ($CachedNssm) { $lines += " NSSM binary $CachedNssm" $lines += " The copy the service was registered with. Any other service" @@ -382,6 +394,16 @@ function Get-UninstallResidueNotice { } } + if ($CustodyDir) { + if ($CustodyAceRemoved) { + $lines += " Custody entry REMOVED - '$ServiceAccount' no longer has an entry on $CustodyDir." + } else { + $lines += " Custody entry '$ServiceAccount' still has read and add-file on $CustodyDir." + $lines += " Remove it with:" + $lines += " icacls `"$CustodyDir`" /remove:g `"$acePrincipal`"" + } + } + if ($LogonRightRemoved) { $lines += " Logon right REMOVED - '$ServiceAccount' no longer holds 'Log on as a service'." } elseif ($LogonRightUnproven) { @@ -744,6 +766,7 @@ $appParameters = "" $appExe = "" $appStdout = "" $secretsDir = "" +$custodyDir = "" $svcKey = "HKLM:\SYSTEM\CurrentControlSet\Services\$ServiceName" try { $objectName = [string](Get-ItemProperty -LiteralPath $svcKey -Name ObjectName -ErrorAction Stop).ObjectName @@ -763,6 +786,11 @@ try { $_ -and ([string]$_).StartsWith("MEFOR_SECRETS_DIRECTORY=", [StringComparison]::OrdinalIgnoreCase) }) | Select-Object -Last 1 if ($secretsEntry) { $secretsDir = $secretsEntry.Substring("MEFOR_SECRETS_DIRECTORY=".Length) } + # The custody directory it names under the host key provider (vault BACKLOG #3411), the same way. + $custodyEntry = @($params.AppEnvironmentExtra | Where-Object { + $_ -and ([string]$_).StartsWith("MEFOR_CUSTODY_DIRECTORY=", [StringComparison]::OrdinalIgnoreCase) }) | + Select-Object -Last 1 + if ($custodyEntry) { $custodyDir = $custodyEntry.Substring("MEFOR_CUSTODY_DIRECTORY=".Length) } } catch { $unreadable += ("the registered command line of '$ServiceName' ($($_.Exception.Message)) - so " + "the config directory and the data directory below could not be checked against it") @@ -934,6 +962,7 @@ $script:LogonRightUnproven = $false $dataAceRemoved = $false $configAceRemoved = $false $secretsAceRemoved = $false +$custodyAceRemoved = $false if ($RemoveLogonRight) { if (-not $hasAccount) { @@ -969,6 +998,9 @@ if ($RemoveAccountAces) { if ($secretsDir) { $secretsAceRemoved = Remove-AccountAce -Path $secretsDir -Principal $acePrincipal -What "secrets directory" } + if ($custodyDir) { + $custodyAceRemoved = Remove-AccountAce -Path $custodyDir -Principal $acePrincipal -What "custody directory" + } } } @@ -979,6 +1011,7 @@ Get-UninstallResidueNotice ` -ServiceAccountSid $accountSid ` -ConfigDir $configDir ` -SecretsDir $secretsDir ` + -CustodyDir $custodyDir ` -ConfigInheritanceStripped:$configProtected ` -CachedNssm $cachedNssm ` -WerImages $werImages ` @@ -988,6 +1021,7 @@ Get-UninstallResidueNotice ` -DataAceRemoved:$dataAceRemoved ` -ConfigAceRemoved:$configAceRemoved ` -SecretsAceRemoved:$secretsAceRemoved ` + -CustodyAceRemoved:$custodyAceRemoved ` -RegistrationPending:$registrationPending ` -Unreadable $unreadable | ForEach-Object { Write-Host $_ } diff --git a/tests/test_install_service_custody.py b/tests/test_install_service_custody.py index 37607b6bb4..489d132af1 100644 --- a/tests/test_install_service_custody.py +++ b/tests/test_install_service_custody.py @@ -220,7 +220,7 @@ def test_the_custody_grant_rule(tmp_path: Path) -> None: @_windows_only def test_the_custody_directory_lockdown_grants_exactly_read_and_add_file(tmp_path: Path) -> None: """Set-CustodyDirAcl on a directory that inherits Users read and the account's Modify, and - denies the account and Users add-file. The account ends with read and add-file on the directory alone, + denies the account and Users add-file, and grants the account Modify itself. The account ends with read and add-file on the directory alone, nothing inherited and no deny, and the engine's own check of a custody directory passes it, where it refused the directory before. Unelevated, the owner change is refused, and the function refuses for that alone.""" @@ -234,6 +234,8 @@ def test_the_custody_directory_lockdown_grants_exactly_read_and_add_file(tmp_pat $me = [Security.Principal.WindowsIdentity]::GetCurrent().Name & icacls {_psq(str(parent))} /grant '*S-1-5-32-545:(OI)(CI)RX' "${{me}}:(OI)(CI)M" | Out-Null & icacls {_psq(str(custody))} /deny "${{me}}:(WD)" '*S-1-5-32-545:(WD)' | Out-Null + # An explicit wider grant, with other inheritance flags than the one the lockdown writes. + & icacls {_psq(str(custody))} /grant "${{me}}:(OI)(CI)M" | Out-Null """ _ok(_extract(_SCRIPT, [], pre), tmp_path) environ = {"MEFOR_CUSTODY_DIRECTORY": str(custody)} @@ -335,3 +337,27 @@ def test_the_installer_makes_and_names_the_custody_directory_under_the_host_prov end = next(i for i in range(head, len(lines)) if lines[i] == "}") assert head < at < end, call["text"] assert "-CustodyDir is used only under [store].key_provider = 'host'" in text + # A custody variable the installer could not write refuses and disables the service, as a + # lockdown failure does: without it the service reads the secrets directory for its key file. + flat = " ".join(text.split()) + refusal = flat.index('throw ("Could not name the custody directory') + assert "Disable-RefusedService" in flat[refusal : refusal + 600], flat[refusal : refusal + 600] + assert 'Write-Warning ("Could not name the custody directory' not in flat + + +def test_the_uninstaller_names_the_custody_directory_and_removes_its_grant( + tmp_path: Path, +) -> None: + """CALL-SITE guard: the uninstaller reads MEFOR_CUSTODY_DIRECTORY off the registration, + removes the account's entry there under -RemoveAccountAces, and hands both to the notice, + whose lines tests/test_service_install_manifest.py checks.""" + from tests.test_service_install_manifest import _UNINSTALL + + assert _UNINSTALL is not None + facts = _preflight_facts(tmp_path, _UNINSTALL) + remove = _sole_call_on(facts, "Remove-AccountAce", "-Path $custodyDir") + assert "-Principal $acePrincipal" in remove["text"], remove["text"] + notice = _sole_call(facts, "Get-UninstallResidueNotice") + assert "-CustodyDir $custodyDir" in notice["text"], notice["text"] + assert "-CustodyAceRemoved:$custodyAceRemoved" in notice["text"], notice["text"] + assert 'StartsWith("MEFOR_CUSTODY_DIRECTORY="' in _UNINSTALL.read_text(encoding="utf-8") diff --git a/tests/test_service_install_manifest.py b/tests/test_service_install_manifest.py index 6b4df2f6d3..90cc05ac34 100644 --- a/tests/test_service_install_manifest.py +++ b/tests/test_service_install_manifest.py @@ -2752,6 +2752,8 @@ def test_a_script_that_does_not_parse_is_refused_not_read(tmp_path: Path) -> Non "ServiceAccountSid": "S-1-5-80-4001", "ConfigDir": r"D:\mefor\config", "SecretsDir": r"C:\ProgramData\MessageFoundry-secrets", + # Under the host key provider only (vault BACKLOG #3411). + "CustodyDir": r"C:\ProgramData\MessageFoundry-custody", "ConfigInheritanceStripped": True, "CachedNssm": r"C:\ProgramData\MessageFoundry\bin\nssm.exe", "WerImages": ["messagefoundry.exe", "python.exe"], @@ -2766,6 +2768,8 @@ def test_a_script_that_does_not_parse_is_refused_not_read(tmp_path: Path) -> Non "config_ace": "Config dir entry", "secrets_dir": "Secrets dir ", "secrets_ace": "Secrets entry", + "custody_dir": "Custody dir ", + "custody_ace": "Custody entry", "logon_right": "Log on as a service", "config_inheritance": "/inheritance:e", "wer": "Windows Error Reporting", @@ -2923,10 +2927,11 @@ def test_a_cleared_residue_is_reported_as_cleared_not_as_remaining(tmp_path: Pat "DataAceRemoved": True, "ConfigAceRemoved": True, "SecretsAceRemoved": True, + "CustodyAceRemoved": True, } ) text = _notice(tmp_path, facts) - assert text.count("REMOVED") >= 4, ( + assert text.count("REMOVED") >= 5, ( f"the notice must report what this run actually took back:\n{text}" ) assert "/remove:g" not in text, ( @@ -3753,8 +3758,9 @@ def test_both_switches_are_declared_and_wired(tmp_path: Path) -> None: assert names.count(_SECEDIT_FN) == 1, ( f"expected one {_SECEDIT_FN} call, found {names.count(_SECEDIT_FN)}" ) - assert names.count(_ACE_FN) == 3, ( - "the account's entry is written on the data dir, the config dir and the secrets dir, so " + assert names.count(_ACE_FN) == 4, ( + "the account's entry is written on the data dir, the config dir, the secrets dir and, " + "under the host key provider, the custody dir (vault BACKLOG #3411), so " f"each must be removable; found {names.count(_ACE_FN)} {_ACE_FN} calls" ) notice = [c for c in cmds if c["name"] == "Get-UninstallResidueNotice"] diff --git a/tests/test_store_custody_host.py b/tests/test_store_custody_host.py index cbfa90bfa4..8644b2a312 100644 --- a/tests/test_store_custody_host.py +++ b/tests/test_store_custody_host.py @@ -198,9 +198,13 @@ def test_the_custody_directory_is_the_secrets_directory_or_the_data_directory( def _own_custody_directory(path: Path) -> Path: - """A directory no broad group reaches: mode 0700 on POSIX; on Windows pytest's own, which - inherits SYSTEM, Administrators and this account from the user's temporary folder.""" - path.mkdir(mode=0o700) + """A directory no broad group reaches: mode 0700 on POSIX. On Windows it is made with no mode, + since there Python 3.13 and later turn a mode into explicit SYSTEM, Administrators and OWNER + RIGHTS full-control entries; it inherits the list of pytest's temporary folder instead.""" + if sys.platform == "win32": + path.mkdir() + else: + path.mkdir(mode=0o700) return path @@ -244,6 +248,13 @@ def _grant(path: Path, *grants: str, reset: bool = False) -> None: argv = ["icacls", str(path)] if reset: + # Explicit entries survive /inheritance:r and /grant:r, so SYSTEM, Administrators and + # OWNER RIGHTS, the ones a mode would have written, go first. + subprocess.run( + [*argv, "/remove:g", "*S-1-5-18", "*S-1-5-32-544", "*S-1-3-4"], + check=True, + capture_output=True, + ) argv += ["/inheritance:r"] subprocess.run([*argv, "/grant:r", *grants], check=True, capture_output=True) @@ -354,6 +365,33 @@ def test_a_host_blob_anywhere_the_host_provider_reads_refuses_every_other_key_pr assert foreign_custody_refusal(settings, environ=unusable) is not None +def test_another_provider_is_not_refused_for_a_file_beside_the_store_it_would_not_read( + tmp_path: Path, +) -> None: + """With MEFOR_SECRETS_DIRECTORY set, the host provider would not read beside the store, so a + file there does not refuse another provider, as before MEFOR_CUSTODY_DIRECTORY existed. The + refusal's own remedy, a new directory named by a variable, can then clear it. The left-behind + check, which stops a second key, still looks there.""" + secrets = _own_custody_directory(tmp_path / "secrets") + (tmp_path / "master.key").write_bytes(b"not read") + settings = _settings(tmp_path, key_provider="auto", encryption_key_file="k.bin") + for environ in ( + {"MEFOR_SECRETS_DIRECTORY": str(secrets)}, + {"MEFOR_SECRETS_DIRECTORY": str(secrets), "MEFOR_CUSTODY_DIRECTORY": str(secrets)}, + ): + assert foreign_custody_refusal(settings, environ=environ) is None, environ + custody_dir = _own_custody_directory(tmp_path / "custody") + with pytest.raises(HostCustodyRefused, match="move it into"): + load_host_custody( + _settings(tmp_path), + enforcing=True, + environ={ + "MEFOR_CUSTODY_DIRECTORY": str(custody_dir), + "MEFOR_SECRETS_DIRECTORY": str(secrets), + }, + ) + + def test_the_way_on_names_the_custody_directory_of_its_own(tmp_path: Path) -> None: environ = {"MEFOR_CUSTODY_DIRECTORY": str(tmp_path / "custody")} step = custody_host.keep_the_key_step(_settings(tmp_path), new_store=False, environ=environ) @@ -386,8 +424,19 @@ async def test_the_first_start_converts_into_a_directory_it_may_only_read_and_ad # this token full control, and the case would no longer measure read and add-file alone. _grant(custody_dir, "*S-1-5-18:(OI)F", f"{_me()}:(RX,WD)", reset=True) try: - # The grant took: this account may add a file there. + # The grant took: this account may add a file there, and holds nothing more through any + # entry: SYSTEM's full control and this account's read and add-file are the whole list. assert restricted_file.can_add_a_file(custody_dir) is True + import subprocess + + listed = subprocess.run( + ["icacls", str(custody_dir)], check=True, capture_output=True, text=True + ).stdout + entries = [line.strip() for line in listed.splitlines()[:-1] if line.strip()] + entries[0] = entries[0].removeprefix(str(custody_dir)).strip() + assert len(entries) == 2, listed + assert any(e.endswith(":(OI)(F)") and "SYSTEM" in e for e in entries), listed + assert any(e.endswith(":(RX,WD)") for e in entries), listed env = {"MEFOR_CUSTODY_DIRECTORY": str(custody_dir), "MEFOR_SECRETS_DIRECTORY": str(secrets)} with pytest.MonkeyPatch.context() as patch: for name, value in env.items(): From 88e7fe3cb57d537d70cd84603df6eaf1b26a6405 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 17:47:21 -0600 Subject: [PATCH 13/28] Key custody: the other-provider check reads beside the store again, with a clearable way on Vault BACKLOG #3411 slice B3c, design note 1, under the Manager's decisions of 2026-11-22. - foreign_custody_refusal looks beside a SQLite store whatever is set, wherever a host mint could have written; a relative secrets variable counts as unset. Its way on names each file and says to move it out as an administrator, keeping it, in place of naming a new custody directory, which would not clear it. A test moves the file and the refusal clears; the fifth-hold guard allows that one move. - The installer's two custody refusals say how to go on: add the variable by hand, or remove the directory and re-run, since a rerun refuses a directory the service does not name. - The uninstaller's help, parameter comment and notice name handoff.key, say master.key keeps its own entry for the account, and warn that a reinstall refuses the kept directory; SERVICE.md's left-behind table gains the custody row. - The first-start test reads the custody list by SID through Get-Acl. --- docs/SERVICE.md | 1 + ...-for-the-engine-s-secret-class-settings.md | 5 +- messagefoundry/store/custody_host.py | 65 ++++++++-------- scripts/service/install-service.ps1 | 11 ++- scripts/service/uninstall-service.ps1 | 17 ++++- tests/test_install_service_custody.py | 18 +++++ tests/test_store_custody_host.py | 76 +++++++++++-------- 7 files changed, 121 insertions(+), 72 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index 15f63f21ec..aa48171805 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -1286,6 +1286,7 @@ list below says what it covers. | The `DataDir` tree — logs and message store | Your data | Delete it yourself once you are sure you are not reinstalling. `DataDir` is a PHI sink — dispose of it the way [PHI.md](PHI.md) describes | | The service's `nssm.exe`, in the installer's `-NssmDir` (`C:\Program Files\MessageFoundry\nssm` by default) | The copy the service ran; the inventory names the one it was registered with | Delete it yourself only when no other service installed with the same `-NssmDir` remains and you are not reinstalling | | An access-control entry for the run-as account on `DataDir` **and** on the config directory | The installer grants both so the service can read config and write logs | `-RemoveAccountAces`, or `icacls "" /remove:g "*"` | +| Under `[store].key_provider = 'host'`, the custody directory `MEFOR_CUSTODY_DIRECTORY` names, with `master.key` (and `handoff.key` before the first start), and the run-as account's read and add-file entry on it | The files hold the store's key, maybe its only copy on this host. `master.key` keeps its own entry for the account, which the directory's removal does not touch. A reinstall refuses the kept directory while the new service does not name it | Keep the files while the store is kept. `-RemoveAccountAces` removes the directory's entry. To reinstall, move the key files out as an administrator, on the same volume, remove the directory, re-run the installer, and move them back | | The `SeServiceLogonRight` ("Log on as a service") grant | Setting the service's run-as account does not grant it, so the installer does | `-RemoveLogonRight`, or secpol.msc under Local Policies, User Rights Assignment | | Inheritance turned off on `DataDir`, and (with `-LockConfigDir`) on the config directory plus its owner moved to Administrators | See below | `icacls "" /inheritance:e`, by hand | | Windows Error Reporting keys, when you installed with `-SuppressCrashDumps` — **two** surfaces, `ExcludedApplications` and `LocalDumps`, reported separately because Windows evaluates them independently | [Stated above](#suppress-windows-crash-dumps-of-the-engine-adr-0152-phase-0) — removing them switches PHI-carrying dumps back on | By hand, under that registry path | diff --git a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md index ed9777e283..cf264c652a 100644 --- a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md +++ b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md @@ -167,8 +167,9 @@ names ADR 0019 declared and nobody built. Also not moved: the store key's own re right included. While the variable is set and neither file is in that directory, a host file or handoff in this directory or beside a SQLite store refuses a read and a mint, so one made without the variable is not taken for no key; and the check that refuses another key provider - beside a host file or handoff looks in that directory and in the one the provider reads without - it. `install-service.ps1` makes the directory only when it reads that provider: `-CustodyDir`, + beside a host file or handoff looks in the custody directory, in this directory and beside a + SQLite store, whatever is set, and its way on is to move the file out rather than to name a new + directory. `install-service.ps1` makes the directory only when it reads that provider: `-CustodyDir`, else the one the service names, else `-custody`, judged by slice C's rules with this directory added to the paths it must not be, hold or sit inside, made restricted in one step, and restricted to Administrators as owner, SYSTEM and Administrators with full control, and the diff --git a/messagefoundry/store/custody_host.py b/messagefoundry/store/custody_host.py index 9256894513..13583448af 100644 --- a/messagefoundry/store/custody_host.py +++ b/messagefoundry/store/custody_host.py @@ -22,8 +22,8 @@ (:class:`~messagefoundry.store.store.StorePin`): a new store's genesis record is written with the current id, and an existing store's must name one the blob names. * **Precedence.** A host blob is never read beside another store key source, and a host blob or a - handoff in a directory this provider may read refuses every other key provider (rules 2 and 13; - :func:`foreign_custody_refusal`). + handoff in a directory :func:`_key_file_directories` names refuses every other key provider + (rules 2 and 13; :func:`foreign_custody_refusal`). * **The account.** SYSTEM, LOCAL SERVICE and NETWORK SERVICE are refused always, and on Linux root and nobody (the custody primitives refuse them). An account that is not local to this host, at least a domain user or a group managed service account, is refused under ``enforce`` and named as @@ -215,40 +215,30 @@ def _custody_paths(directory: Path) -> tuple[Path, Path]: return directory / HOST_FILE_NAME, directory / HANDOFF_FILE_NAME -def _key_file_directories( - settings: StoreSettings, environ: Mapping[str, str], *, always_beside_store: bool -) -> list[Path]: - """At least these directories a host file or handoff for this store may sit in: the ones - ``MEFOR_CUSTODY_DIRECTORY`` and ``MEFOR_SECRETS_DIRECTORY`` name, and a SQLite store's data - directory, where a mint run with neither variable writes. The data directory is named only when - ``MEFOR_SECRETS_DIRECTORY`` is unset, unless ``always_beside_store``. Not named, at least: a - custody directory an earlier setting named. A variable that is not an absolute path names none - here; :func:`custody_directory` refuses it.""" +def _key_file_directories(settings: StoreSettings, environ: Mapping[str, str]) -> list[Path]: + """At least these directories a ``host`` mint could have written a host file or handoff for + this store in: the ones ``MEFOR_CUSTODY_DIRECTORY`` and ``MEFOR_SECRETS_DIRECTORY`` name, and a + SQLite store's data directory, where a mint run with neither variable writes, whatever is set + here. Not named, at least: a custody directory an earlier setting named. A variable that is not + an absolute path counts as unset here; :func:`custody_directory` refuses it.""" found: list[Path] = [] for variable in (CUSTODY_DIRECTORY_VARIABLE, SECRETS_DIRECTORY_VARIABLE): raw = environ.get(variable, "").strip() if raw and Path(raw).is_absolute(): found.append(Path(raw)) - if always_beside_store or not environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip(): - beside = custody_directory(settings, environ={}) - if beside is not None: - found.append(beside) + beside = custody_directory(settings, environ={}) + if beside is not None: + found.append(beside) return list(dict.fromkeys(found)) def _key_files_outside( - settings: StoreSettings, - directory: Path | None, - environ: Mapping[str, str], - *, - always_beside_store: bool, + settings: StoreSettings, directory: Path | None, environ: Mapping[str, str] ) -> list[Path]: """The host files and handoffs in :func:`_key_file_directories` other than ``directory``.""" return [ p - for other in _key_file_directories( - settings, environ, always_beside_store=always_beside_store - ) + for other in _key_file_directories(settings, environ) if other != directory for p in _custody_paths(other) if os.path.lexists(p) @@ -294,26 +284,37 @@ def foreign_custody_refusal( handoff sits in a directory where a ``host`` mint may have written it (:func:`_key_file_directories`), so the store's key would be taken from somewhere other than the blob minted for it. A directory setting that is not an absolute path is passed over here, - and the directories the other setting names are still looked in.""" + and the directories the other setting names are still looked in. + + The way on names each file, and a step that clears the refusal whatever the variables say: + moving the file out of the directories this check reads. A new custody directory would not, + since the secrets directory and the data directory are read whatever names it.""" environ = os.environ if environ is None else environ - # Beside the store only where the provider would read it now: the remedy, a new directory - # named by a variable, must be able to clear the refusal. - found = _key_files_outside(settings, None, environ, always_beside_store=False) + found = _key_files_outside(settings, None, environ) if not found: return None + named = " and ".join(str(p) for p in found) return ( - f"{' and '.join(p.name for p in found)} is in " - f"{' and '.join(dict.fromkeys(str(p.parent) for p in found))}, but [store].key_provider is " + f"{named} is there, but [store].key_provider is " f"{settings.key_provider!r}. A store with a host blob takes its key from that blob only: " "if it holds this store's key, keep a copy of each key setting's value first, somewhere " "as protected as where it is now, since it may be the only copy of a store key, and then " "set [store].key_provider = 'host' and remove every other store key setting, with " "[store].cipher_provider = 'aesgcm', which that provider needs. The engine cannot tell " - "whether the blob holds this store's key, so it " - f"leaves the file in place. {keep_the_key_step(settings, new_store=False, environ=environ)}" + f"whether the blob holds this store's key, so it leaves the file in place. {_MOVE_OUT_STEP}" ) +#: The step that clears :func:`foreign_custody_refusal` when the file holds no key this store +#: needs (Manager decision 2026-11-22 on vault BACKLOG #3411). A move, never a delete: the file +#: may be another store's only key. +_MOVE_OUT_STEP = ( + "If it holds no key this store needs, move it as an administrator out of that directory, to a " + "folder only administrators can read on the same volume so it keeps its own access list, and " + "start again; it may be another store's only key, so keep it" +) + + # --- the account ---------------------------------------------------------------------------------- @@ -671,7 +672,7 @@ def _left_outside_the_custody_directory( environ = os.environ if environ is None else environ if _directory_variable(environ) != CUSTODY_DIRECTORY_VARIABLE: return None # without it the provider reads where it did before the variable existed - found = _key_files_outside(settings, directory, environ, always_beside_store=True) + found = _key_files_outside(settings, directory, environ) if not found: return None return ( diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index 819f7a6178..0be2fe83ac 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -1225,7 +1225,10 @@ function Set-CustodyDirAcl { if ($problems) { throw ("The custody directory '$Path' is not restricted as the host key provider needs: " + "$($problems -join '; '). The service's first start writes its store key file there. " + - "Check the directory's access list, and re-run the installer.") + "Check the directory's access list, then re-run the installer. When the service does " + + "not name the directory yet, as on a first install, remove the directory first, if it " + + "holds no master.key or handoff.key, since a rerun refuses a directory it finds and " + + "the service does not name.") } } @@ -3588,7 +3591,11 @@ if ($HostCustody) { if ($null -ne $custodyNamingError) { throw ("Could not name the custody directory in the service's environment " + "($custodyNamingError), and without MEFOR_CUSTODY_DIRECTORY the service looks for its " + - "key file in the secrets directory, where it cannot write one. Re-run the installer. " + + "key file in the secrets directory, where it cannot write one. Add " + + "MEFOR_CUSTODY_DIRECTORY=$CustodyDir to the service's AppEnvironmentExtra by hand, keeping " + + "the entries already there, then re-enable the service; or remove the empty directory " + + "'$CustodyDir' and re-run the installer, since a rerun refuses a directory the service " + + "does not name. " + "$(Disable-RefusedService -ServiceName $ServiceName -Consequence 'it would not find its custody directory')") } if ($replacedCustodyDir -and -not $CustodyDirNamed) { diff --git a/scripts/service/uninstall-service.ps1 b/scripts/service/uninstall-service.ps1 index 5e18e5c878..f34aa18726 100644 --- a/scripts/service/uninstall-service.ps1 +++ b/scripts/service/uninstall-service.ps1 @@ -23,7 +23,9 @@ Two of them can be taken back on request, because both need elevation an operator may not have later: -RemoveLogonRight drops the "Log on as a service" right, and -RemoveAccountAces drops - the run-as account's entry from the data and config directories. + the run-as account's entry from the data and config directories, and from the secrets and + custody directories the service names (vault BACKLOG #3411). On the custody directory that is + the directory's own entry: master.key there keeps its own list, which names the account. The service SID type and the privilege list the installer sets are part of the registration, so they go with it. The script looks for the service's registry key after the removal, and the @@ -54,7 +56,8 @@ param( # installer's default per-service virtual account, whose SID belongs to this service alone. [switch]$RemoveLogonRight, # Opt-in: remove the run-as account's access-control entry from the data directory and the - # config directory. The account is gone once the registration is, so the entry is orphaned - + # config directory, and from the secrets and custody directories the registration names. The + # account is gone once the registration is, so the entry is orphaned - # but removing it is still a permission change on directories that may outlive this service. [switch]$RemoveAccountAces ) @@ -354,8 +357,14 @@ function Get-UninstallResidueNotice { $lines += " Custody dir $CustodyDir" $lines += " The custody directory the service read under the host key" $lines += " provider. master.key in it holds the store's key, and may be its" - $lines += " only copy on this host. This script leaves it and its files." - $lines += " Keep it while the store is kept." + $lines += " only copy on this host; handoff.key, there until the service's" + $lines += " first start, holds it too. This script leaves the directory and" + $lines += " its files. Keep them while the store is kept. master.key keeps" + $lines += " its own entry for '$ServiceAccount', whatever happens to the" + $lines += " directory's. A reinstall refuses this directory while the new" + $lines += " service does not name it: move the key files out as an" + $lines += " administrator, on the same volume, remove the directory, re-run" + $lines += " the installer, and move them back." } if ($CachedNssm) { diff --git a/tests/test_install_service_custody.py b/tests/test_install_service_custody.py index 489d132af1..6677cd29d1 100644 --- a/tests/test_install_service_custody.py +++ b/tests/test_install_service_custody.py @@ -361,3 +361,21 @@ def test_the_uninstaller_names_the_custody_directory_and_removes_its_grant( assert "-CustodyDir $custodyDir" in notice["text"], notice["text"] assert "-CustodyAceRemoved:$custodyAceRemoved" in notice["text"], notice["text"] assert 'StartsWith("MEFOR_CUSTODY_DIRECTORY="' in _UNINSTALL.read_text(encoding="utf-8") + + +def test_the_uninstall_notice_says_what_the_custody_directory_keeps(tmp_path: Path) -> None: + """The notice names both key files, says master.key keeps its own entry for the account + whatever happens to the directory's, and warns that a reinstall refuses the kept directory. + The control: with no custody directory, none of it is printed.""" + from tests.test_service_install_manifest import _FULL_FACTS, _notice + + flat = " ".join(_notice(tmp_path, _FULL_FACTS).split()) + for needed in ( + "master.key", + "handoff.key", + "master.key keeps its own entry for 'NT SERVICE\\MessageFoundry'", + "A reinstall refuses this directory", + ): + assert needed in flat, (needed, flat) + without = " ".join(_notice(tmp_path, {**_FULL_FACTS, "CustodyDir": ""}).split()) + assert "handoff.key" not in without and "Custody" not in without, without diff --git a/tests/test_store_custody_host.py b/tests/test_store_custody_host.py index 8644b2a312..c58656abfe 100644 --- a/tests/test_store_custody_host.py +++ b/tests/test_store_custody_host.py @@ -365,31 +365,27 @@ def test_a_host_blob_anywhere_the_host_provider_reads_refuses_every_other_key_pr assert foreign_custody_refusal(settings, environ=unusable) is not None -def test_another_provider_is_not_refused_for_a_file_beside_the_store_it_would_not_read( - tmp_path: Path, +@pytest.mark.parametrize("secrets_setting", ["absolute", "relative"]) +def test_a_file_beside_the_store_refuses_another_provider_until_it_is_moved_out( + tmp_path: Path, secrets_setting: str ) -> None: - """With MEFOR_SECRETS_DIRECTORY set, the host provider would not read beside the store, so a - file there does not refuse another provider, as before MEFOR_CUSTODY_DIRECTORY existed. The - refusal's own remedy, a new directory named by a variable, can then clear it. The left-behind - check, which stops a second key, still looks there.""" + """A host mint with neither variable writes beside the store, so a file there refuses another + provider whatever is set; a MEFOR_SECRETS_DIRECTORY that is not an absolute path counts as + unset. The refusal names the file, and moving it out, its way on, clears it.""" secrets = _own_custody_directory(tmp_path / "secrets") - (tmp_path / "master.key").write_bytes(b"not read") + beside = tmp_path / "master.key" + beside.write_bytes(b"not read") settings = _settings(tmp_path, key_provider="auto", encryption_key_file="k.bin") - for environ in ( - {"MEFOR_SECRETS_DIRECTORY": str(secrets)}, - {"MEFOR_SECRETS_DIRECTORY": str(secrets), "MEFOR_CUSTODY_DIRECTORY": str(secrets)}, - ): - assert foreign_custody_refusal(settings, environ=environ) is None, environ - custody_dir = _own_custody_directory(tmp_path / "custody") - with pytest.raises(HostCustodyRefused, match="move it into"): - load_host_custody( - _settings(tmp_path), - enforcing=True, - environ={ - "MEFOR_CUSTODY_DIRECTORY": str(custody_dir), - "MEFOR_SECRETS_DIRECTORY": str(secrets), - }, - ) + environ = { + "MEFOR_SECRETS_DIRECTORY": str(secrets) if secrets_setting == "absolute" else "secrets", + "MEFOR_CUSTODY_DIRECTORY": str(_own_custody_directory(tmp_path / "custody")), + } + refusal = foreign_custody_refusal(settings, environ=environ) + assert refusal is not None and str(beside) in refusal, refusal + assert "move it as an administrator out of that directory" in refusal, refusal + aside = _own_custody_directory(tmp_path / "aside") + beside.rename(aside / beside.name) + assert foreign_custody_refusal(settings, environ=environ) is None def test_the_way_on_names_the_custody_directory_of_its_own(tmp_path: Path) -> None: @@ -427,16 +423,27 @@ async def test_the_first_start_converts_into_a_directory_it_may_only_read_and_ad # The grant took: this account may add a file there, and holds nothing more through any # entry: SYSTEM's full control and this account's read and add-file are the whole list. assert restricted_file.can_add_a_file(custody_dir) is True + # Read by SID, not by a localized account name or icacls's console text. import subprocess + quoted = str(custody_dir).replace("'", "''") + read = ( + f"@((Get-Acl -LiteralPath '{quoted}').Access | ForEach-Object {{ [pscustomobject]@{{ " + "sid = $_.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value; " + 'rights = [int64]$_.FileSystemRights; inherit = "$($_.InheritanceFlags)"; ' + 'kind = "$($_.AccessControlType)" } }) | ConvertTo-Json -Compress -AsArray' + ) listed = subprocess.run( - ["icacls", str(custody_dir)], check=True, capture_output=True, text=True + ["pwsh", "-NoProfile", "-Command", read], check=True, capture_output=True, text=True ).stdout - entries = [line.strip() for line in listed.splitlines()[:-1] if line.strip()] - entries[0] = entries[0].removeprefix(str(custody_dir)).strip() - assert len(entries) == 2, listed - assert any(e.endswith(":(OI)(F)") and "SYSTEM" in e for e in entries), listed - assert any(e.endswith(":(RX,WD)") for e in entries), listed + entries = sorted( + (e["sid"], e["rights"], e["inherit"], e["kind"]) for e in json.loads(listed) + ) + me = _me().removeprefix("*") + # FullControl inherited by files, and ReadAndExecute | CreateFiles | Synchronize. + assert entries == sorted( + [("S-1-5-18", 0x1F01FF, "ObjectInherit", "Allow"), (me, 0x1200AB, "None", "Allow")] + ), listed env = {"MEFOR_CUSTODY_DIRECTORY": str(custody_dir), "MEFOR_SECRETS_DIRECTORY": str(secrets)} with pytest.MonkeyPatch.context() as patch: for name, value in env.items(): @@ -490,8 +497,13 @@ async def test_a_host_blob_refuses_every_other_key_provider(tmp_path: Path, name condition = low.index("if it holds this store's key") assert condition < low.index(keep), refusal assert ". " not in low[condition : low.index(_KEY_SETTINGS_OUT)], refusal - assert not _advises_changing(refusal, allowed=(_KEY_SETTINGS_OUT,)), refusal - assert custody_host.keep_the_key_step(settings, new_store=False) in refusal, refusal + # The one change it may advise beside the settings is the move that clears it, which keeps + # the file (Manager decision 2026-11-22, vault BACKLOG #3411): a new custody directory would + # not clear it, since this check reads the secrets and data directories whatever is set. + allowed = (_KEY_SETTINGS_OUT, custody_host._MOVE_OUT_STEP) + assert not _advises_changing(refusal, allowed=allowed), refusal + assert custody_host._MOVE_OUT_STEP in refusal, refusal + assert custody_host.keep_the_key_step(settings, new_store=False) not in refusal, refusal assert "mints this store's key" not in refusal, refusal # only the host provider mints with pytest.raises(HostCustodyRefused, match=name): await open_store(settings, create=True) @@ -2243,7 +2255,7 @@ def _held(self: Path, missing_ok: bool = False) -> None: (fallback, "run with the custody directory that holds the store's host blob"), ("which names the way on",), (fallback,), - (fallback, "set [store].key_provider = 'host'"), + ("If it holds no key this store needs, move it", "set [store].key_provider = 'host'"), (fallback, "leaves it in place"), ("Run the command again with that file in place",), (fallback, "This run minted it and nothing was written under it"), @@ -2258,7 +2270,7 @@ def _held(self: Path, missing_ok: bool = False) -> None: if _advises_changing( text, allowed=( - (_KEY_SETTINGS_OUT,) + (_KEY_SETTINGS_OUT, custody_host._MOVE_OUT_STEP) if text is foreign else (cli._REMOVE_THE_VOID_KEY,) if text is held From d04015b27099df59bff6f03cfe0cdce2099866a3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 18:19:12 -0600 Subject: [PATCH 14/28] Key custody: way-on texts leave every key file in place; installer re-run path; uninstall notice Vault BACKLOG #3411 slice B3c, design note 1, under the Manager's rulings of 2026-11-22, replacing the earlier move-out decision. - foreign_custody_refusal names each file with its directory, says it may be another store's only key and is left in place, and gives one platform-neutral way on (_LEAVE_KEY_FILES_STEP): run the store from a copy of its database in a directory holding neither file, or name new variable directories. keep_the_key_step is restored to it, and the PR 2804 fifth-hold guard's allowed list is back as it was. - resolve_key_provider records that refusal, so resolve_active_key and build_store_cipher keep its text. - The installer's two custody refusals after registration remove the directory only when this run made it and it holds nothing, then say to re-run the installer. The preflight is Get-CustodyDirProblem, which accepts a directory the service names and never says to remove one. - The uninstall notice names only the key files present, says each keeps its own entry for the account, and points at SERVICE.md's new "Reinstalling over a kept custody directory", which states the recipe once; the help cites #2595 slice C for the secrets directory. - The left-behind check stays limited to MEFOR_CUSTODY_DIRECTORY being set: reading beside the store with only MEFOR_SECRETS_DIRECTORY set refuses the PR 2804 fifth hold's recorded way on (item 4). That case is documented and tested, not built. - ADR amendment: "at least", and the access list stated once in SERVICE.md. Tests: a distinguishable relative-variable case and the both-variables left-behind case. --- docs/SERVICE.md | 11 +- ...-for-the-engine-s-secret-class-settings.md | 15 +-- messagefoundry/store/custody_host.py | 48 ++++--- messagefoundry/store/keyprovider.py | 10 +- scripts/service/install-service.ps1 | 122 +++++++++++------- scripts/service/uninstall-service.ps1 | 37 ++++-- tests/test_file_path_join_census.py | 5 +- tests/test_install_service_custody.py | 96 ++++++++++++-- tests/test_store_custody_host.py | 111 ++++++++++++---- 9 files changed, 324 insertions(+), 131 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index aa48171805..9d080234ec 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -291,6 +291,15 @@ accounts no entry. While the variable is set and neither file is there, a key fi directory or beside a SQLite store refuses a read and a mint, rather than being taken for no key at all, so a mint run without the variable does not lead to a second key. +**Reinstalling over a kept custody directory.** The install script refuses an existing custody +directory the service does not name, as after an uninstall, and it never removes one that holds +anything: `master.key` or `handoff.key` there may be the only copy of a store's key on this host, +so do not delete either. To go on, re-run the install script with `-CustodyDir` naming a new +folder. Then, with the service stopped, move each key file from the kept directory into the new +one as an administrator, on the same volume so it keeps its own access list, and start the +service. The same move applies to a key file left in a custody directory the service named before +a `-CustodyDir` change. + **Minting.** Set the variable in the elevated shell that runs `provision-admin --service-account`, to the same path, so the handoff lands where the service looks: @@ -1286,7 +1295,7 @@ list below says what it covers. | The `DataDir` tree — logs and message store | Your data | Delete it yourself once you are sure you are not reinstalling. `DataDir` is a PHI sink — dispose of it the way [PHI.md](PHI.md) describes | | The service's `nssm.exe`, in the installer's `-NssmDir` (`C:\Program Files\MessageFoundry\nssm` by default) | The copy the service ran; the inventory names the one it was registered with | Delete it yourself only when no other service installed with the same `-NssmDir` remains and you are not reinstalling | | An access-control entry for the run-as account on `DataDir` **and** on the config directory | The installer grants both so the service can read config and write logs | `-RemoveAccountAces`, or `icacls "" /remove:g "*"` | -| Under `[store].key_provider = 'host'`, the custody directory `MEFOR_CUSTODY_DIRECTORY` names, with `master.key` (and `handoff.key` before the first start), and the run-as account's read and add-file entry on it | The files hold the store's key, maybe its only copy on this host. `master.key` keeps its own entry for the account, which the directory's removal does not touch. A reinstall refuses the kept directory while the new service does not name it | Keep the files while the store is kept. `-RemoveAccountAces` removes the directory's entry. To reinstall, move the key files out as an administrator, on the same volume, remove the directory, re-run the installer, and move them back | +| Under `[store].key_provider = 'host'`, the custody directory `MEFOR_CUSTODY_DIRECTORY` names, with `master.key` (and `handoff.key` before the first start), and the run-as account's read and add-file entry on it | The files hold the store's key, maybe its only copy on this host. Each file carries its own access-control entry for the account, and `-RemoveAccountAces` takes the account's entry off the directory only, not off the files. A reinstall refuses the kept directory while the new service does not name it | Keep the directory and its files while the store is kept; never delete them. `-RemoveAccountAces` removes the directory's entry. To reinstall, see [Reinstalling over a kept custody directory](#the-custody-directory-under-the-host-key-provider) | | The `SeServiceLogonRight` ("Log on as a service") grant | Setting the service's run-as account does not grant it, so the installer does | `-RemoveLogonRight`, or secpol.msc under Local Policies, User Rights Assignment | | Inheritance turned off on `DataDir`, and (with `-LockConfigDir`) on the config directory plus its owner moved to Administrators | See below | `icacls "" /inheritance:e`, by hand | | Windows Error Reporting keys, when you installed with `-SuppressCrashDumps` — **two** surfaces, `ExcludedApplications` and `LocalDumps`, reported separately because Windows evaluates them independently | [Stated above](#suppress-windows-crash-dumps-of-the-engine-adr-0152-phase-0) — removing them switches PHI-carrying dumps back on | By hand, under that registry path | diff --git a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md index cf264c652a..5b686228b5 100644 --- a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md +++ b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md @@ -167,15 +167,12 @@ names ADR 0019 declared and nobody built. Also not moved: the store key's own re right included. While the variable is set and neither file is in that directory, a host file or handoff in this directory or beside a SQLite store refuses a read and a mint, so one made without the variable is not taken for no key; and the check that refuses another key provider - beside a host file or handoff looks in the custody directory, in this directory and beside a - SQLite store, whatever is set, and its way on is to move the file out rather than to name a new - directory. `install-service.ps1` makes the directory only when it reads that provider: `-CustodyDir`, - else the one the service names, else `-custody`, judged by slice C's rules with this - directory added to the paths it must not be, hold or sit inside, made restricted in one step, - and restricted to Administrators as owner, SYSTEM and Administrators with full control, and the - service account with read and add-file on the directory alone, which it reads back. It names - the directory to the service as `MEFOR_CUSTODY_DIRECTORY`. docs/SERVICE.md, *The custody - directory under the host key provider*, is the operator's text. + beside a host file or handoff looks in at least the custody directory, this directory and the + place beside a SQLite store, whatever is set; its way on leaves every file it finds in place. + `install-service.ps1` makes the custody directory only when it reads that provider, and names + it to the service as `MEFOR_CUSTODY_DIRECTORY`. docs/SERVICE.md, *The custody directory under + the host key provider*, states its location, its access list and the rest, and is the record + of them. - **2026-11-17, the Windows holder is read where the path resolves to (vault BACKLOG #5657).** This replaces parts of the 2026-11-13 amendment below. `_windows_surroundings_problem` still walks `full.parent`, except for a drive root such as `S:\`, whose own path it walks, so a diff --git a/messagefoundry/store/custody_host.py b/messagefoundry/store/custody_host.py index 13583448af..c9732217d8 100644 --- a/messagefoundry/store/custody_host.py +++ b/messagefoundry/store/custody_host.py @@ -286,32 +286,38 @@ def foreign_custody_refusal( the blob minted for it. A directory setting that is not an absolute path is passed over here, and the directories the other setting names are still looked in. - The way on names each file, and a step that clears the refusal whatever the variables say: - moving the file out of the directories this check reads. A new custody directory would not, - since the secrets directory and the data directory are read whatever names it.""" + The way on never changes a file it found (PR 2804 fifth hold; Manager ruling 2026-11-22): + :data:`_LEAVE_KEY_FILES_STEP`, then :func:`keep_the_key_step`.""" environ = os.environ if environ is None else environ found = _key_files_outside(settings, None, environ) if not found: return None - named = " and ".join(str(p) for p in found) + # One clause per file, so two files in two directories each name their own. + named = "; ".join(f"{p.name} in {p.parent}" for p in found) return ( - f"{named} is there, but [store].key_provider is " + f"host custody found ({named}), but [store].key_provider is " f"{settings.key_provider!r}. A store with a host blob takes its key from that blob only: " "if it holds this store's key, keep a copy of each key setting's value first, somewhere " "as protected as where it is now, since it may be the only copy of a store key, and then " "set [store].key_provider = 'host' and remove every other store key setting, with " "[store].cipher_provider = 'aesgcm', which that provider needs. The engine cannot tell " - f"whether the blob holds this store's key, so it leaves the file in place. {_MOVE_OUT_STEP}" + "whether the blob holds this store's key, so it leaves the file in place. " + f"{_LEAVE_KEY_FILES_STEP}. {keep_the_key_step(settings, new_store=False, environ=environ)}" ) -#: The step that clears :func:`foreign_custody_refusal` when the file holds no key this store -#: needs (Manager decision 2026-11-22 on vault BACKLOG #3411). A move, never a delete: the file -#: may be another store's only key. -_MOVE_OUT_STEP = ( - "If it holds no key this store needs, move it as an administrator out of that directory, to a " - "folder only administrators can read on the same volume so it keeps its own access list, and " - "start again; it may be another store's only key, so keep it" +#: The way on from :func:`foreign_custody_refusal` when a file it found is not this store's own, +#: stated once (Manager ruling 2026-11-22 on vault BACKLOG #3411). It changes no file it found: +#: each may be another store's only key. Platform-neutral. +_LEAVE_KEY_FILES_STEP = ( + "Each file named here may be another store's only key: leave it where it is. To go on, run " + "this store from places that hold neither master.key nor handoff.key. For a file beside the " + "store's database, with the engine stopped, copy the database file and any -wal and -shm file " + "beside it into a new directory that holds neither, and point the store at the copy by its " + "absolute path, with --db or [store].path, here and wherever the service names it. For a file " + "in the directory MEFOR_CUSTODY_DIRECTORY or MEFOR_SECRETS_DIRECTORY names, set that variable, " + "here and in the service's environment, to a new directory, and copy into it every file the " + "old one holds other than master.key and handoff.key" ) @@ -668,18 +674,24 @@ def _left_outside_the_custody_directory( """Why a read or a mint that found neither file in ``directory``, the custody directory ``MEFOR_CUSTODY_DIRECTORY`` names, must not go on as if no key was minted, or ``None``: a host file or a handoff sits in another directory :func:`_key_file_directories` names, where a mint - run without that variable writes it. A second key would not open a store the first one made.""" + run with other variables set wrote it. A second key would not open a store the first one made. + + Read only while ``MEFOR_CUSTODY_DIRECTORY`` is set. With only ``MEFOR_SECRETS_DIRECTORY`` set, + a file beside the store is not read here: :func:`keep_the_key_step`'s way on (PR 2804 fifth + hold, item 4) is a new secrets directory and a new SQLite path, which may sit beside the key + file it leaves in place, and reading there would refuse that way on.""" environ = os.environ if environ is None else environ if _directory_variable(environ) != CUSTODY_DIRECTORY_VARIABLE: - return None # without it the provider reads where it did before the variable existed + return None found = _key_files_outside(settings, directory, environ) if not found: return None + named = "; ".join(f"{p.name} in {p.parent}" for p in found) return ( f"no host blob or handoff is in the custody directory {directory}, which " - f"{CUSTODY_DIRECTORY_VARIABLE} names, but {' and '.join(str(p) for p in found)} is in a " - f"directory this provider reads only while {CUSTODY_DIRECTORY_VARIABLE} is unset. If it " - f"holds this store's key, move it into {directory} as an administrator, on the same " + f"{CUSTODY_DIRECTORY_VARIABLE} names, but host custody was found elsewhere " + f"({named}), where a mint run with other variables writes it. If one holds this store's " + f"key, move that file into {directory} with an account that may write there, on the same " "volume so it keeps its own access list, and try again; a key minted now would not open " "a store that key made" ) diff --git a/messagefoundry/store/keyprovider.py b/messagefoundry/store/keyprovider.py index 71324f7c53..ea52aeb563 100644 --- a/messagefoundry/store/keyprovider.py +++ b/messagefoundry/store/keyprovider.py @@ -336,10 +336,16 @@ def resolve_key_provider( return HostKeyProvider(settings, posture) # Every caller that resolves a key, not only a store open, refuses a host blob beside another # provider (vault BACKLOG #3411). - from messagefoundry.store.custody_host import HostCustodyRefused, foreign_custody_refusal + from messagefoundry.store.custody_host import ( + HostCustodyRefused, + _recorded_as, + foreign_custody_refusal, + ) if (refusal := foreign_custody_refusal(settings)) is not None: - raise HostCustodyRefused(refusal) + # Recorded as built by the engine, so a seam that replaces it (resolve_active_key and its + # siblings, BACKLOG #4882) keeps the files it names and the way on. + raise _recorded_as(HostCustodyRefused, refusal) builtin = _BUILTIN_PROVIDER_CLASSES.get(name) if builtin is not None: return builtin(settings) diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index 0be2fe83ac..f60c5def5a 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -1148,6 +1148,62 @@ function Get-CustodyGrantProblem { return "" } +function Get-CustodyDirProblem { + <# + Why $Path cannot be this install's custody directory, or "" when it can (vault BACKLOG #3411). + The secrets directory's rules, with $Holds and $NotWithin as the caller builds them. A + directory that already exists is accepted only when the service names it ($Named) and its + owner is one of $AcceptedOwners, Administrators or SYSTEM, as each install sets; any other + is refused, not adopted, as the secrets directory is, and the refusal never says to remove + it, since it may hold a store's only key. $AcceptedOwners is a parameter so the unelevated + tests can accept a folder they own. + #> + param([Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][string]$ServiceName, + [switch]$Named, [string[]]$Holds = @(), [string[]]$NotWithin = @(), + [string[]]$AcceptedOwners = @("S-1-5-32-544", "S-1-5-18")) + if (Test-Path -LiteralPath $Path -PathType Leaf) { return "it is a file" } + $problem = Get-LockPathProblem -Path $Path -Holds $Holds -NotWithin $NotWithin -OnlyFolders @() -AllowMissing + if (-not $problem) { $problem = Get-ReparsePointAncestor -Path $Path } + if ($problem) { return $problem } + # Another service's custody or secrets directory: the lockdown here would strip its grants. + $sharers = @(foreach ($name in @("MEFOR_CUSTODY_DIRECTORY", "MEFOR_SECRETS_DIRECTORY")) { + Get-OtherServiceNamingPath -ServiceName $ServiceName -Name $name -Path $Path }) + if ($sharers) { + return ("the service(s) $(@($sharers | Select-Object -Unique) -join ', ') name it, a folder " + + "inside it, a folder around it, or a path this installer cannot compare with it, as their " + + "custody or secrets directory, and the lockdown here could reach theirs. Pass -CustodyDir " + + "with a folder for this service") + } + if (-not (Test-Path -LiteralPath $Path)) { return "" } + if (-not $Named) { + return ("it already exists and the service does not name it. It may hold master.key or " + + "handoff.key, which may be the only copy of a store's key on this host, so do not " + + "delete it or anything in it; follow docs/SERVICE.md 'Reinstalling over a kept " + + "custody directory'") + } + $owner = (Get-Acl -LiteralPath $Path).GetOwner([Security.Principal.SecurityIdentifier]).Value + if ($AcceptedOwners -notcontains $owner) { + return ("the service names it, but its owner is now $owner, not the Administrators each " + + "install sets, so it may not be the folder the install made. Check who made it") + } + return "" +} + +function Remove-CustodyDirMadeHere { + <# + Remove the custody directory $Path when this run made it ($MadeHere) and it still holds + nothing, so a re-run, which refuses a directory the service does not name, can make it + again (vault BACKLOG #3411). A directory this run did not make, or one that holds anything, + is never touched. Returns what it did, for the refusal that follows. + #> + param([Parameter(Mandatory)][string]$Path, [switch]$MadeHere) + if (-not $MadeHere) { return "" } + $held = @(try { Get-ChildItem -LiteralPath $Path -Force -ErrorAction Stop } catch { "unread" }) + if ($held.Count -ne 0) { return "" } + try { Remove-Item -LiteralPath $Path -ErrorAction Stop } catch { return "" } + return " This run made '$Path' and it held nothing, so it was removed." +} + function Set-CustodyDirAcl { <# Restrict the custody directory (vault BACKLOG #3411, ADR 0214's 2026-11-22 amendment): @@ -1225,10 +1281,7 @@ function Set-CustodyDirAcl { if ($problems) { throw ("The custody directory '$Path' is not restricted as the host key provider needs: " + "$($problems -join '; '). The service's first start writes its store key file there. " + - "Check the directory's access list, then re-run the installer. When the service does " + - "not name the directory yet, as on a first install, remove the directory first, if it " + - "holds no master.key or handoff.key, since a rerun refuses a directory it finds and " + - "the service does not name.") + "Check the directory's access list.") } } @@ -3027,6 +3080,7 @@ if ($HostCustody) { # Judged here, before anything acts, by the secrets directory's rules, and made before the service # is registered; restricted (Set-CustodyDirAcl) once the account resolves. $CustodyDirNamed = $false +$CustodyDirMadeHere = $false if (-not $HostCustody) { if ($CustodyDir) { throw ("-CustodyDir is used only under [store].key_provider = 'host', which this install " + @@ -3064,43 +3118,10 @@ if (-not $HostCustody) { } Assert-NoNssmExpansion $CustodyDir # The secrets directory's rules, with that directory added to what it must not be, hold or sit in. - $custodyProblem = if (Test-Path -LiteralPath $CustodyDir -PathType Leaf) { "it is a file" } - else { - Get-LockPathProblem -Path $CustodyDir -Holds (@($SecretsHolds) + $SecretsDir) ` - -NotWithin (@($SecretsNotWithin) + $SecretsDir) -OnlyFolders @() -AllowMissing - } - if (-not $custodyProblem) { $custodyProblem = Get-ReparsePointAncestor -Path $CustodyDir } - if (-not $custodyProblem) { - # Another service's custody or secrets directory: the lockdown here would strip its grants. - $custodySharers = @(foreach ($named in @("MEFOR_CUSTODY_DIRECTORY", "MEFOR_SECRETS_DIRECTORY")) { - Get-OtherServiceNamingPath -ServiceName $ServiceName -Name $named -Path $CustodyDir }) - if ($custodySharers) { - $custodyProblem = ("the service(s) $(@($custodySharers | Select-Object -Unique) -join ', ') " + - "name it, a folder inside it, a folder around it, or a path this installer cannot " + - "compare with it, as their custody or secrets directory, and the lockdown here could " + - "reach theirs. Pass -CustodyDir with a folder for this service") - } - } - # Refused, not adopted, when it exists and the service does not name it, as the secrets - # directory is, for the reason given there. $CustodyDirNamed = [bool]$RegisteredCustodyDir -and ($RegisteredCustodyDir.TrimEnd('\') -eq $CustodyDir.TrimEnd('\')) - if (-not $custodyProblem -and (Test-Path -LiteralPath $CustodyDir)) { - if (-not $CustodyDirNamed) { - $custodyProblem = ("it already exists and the service does not name it. Check who made " + - "it. If it holds master.key or handoff.key, that may be the only copy of a store's key " + - "on this host: do not delete it. Move each such file, as an administrator, to a folder " + - "only administrators can read on the same volume, so it keeps its own access list. Then " + - "remove the directory, re-run the installer, which makes it restricted, and move the " + - "files back into it") - } else { - $owner = (Get-Acl -LiteralPath $CustodyDir).GetOwner([Security.Principal.SecurityIdentifier]).Value - if ($owner -ne "S-1-5-32-544" -and $owner -ne "S-1-5-18") { - $custodyProblem = ("the service names it, but its owner is now $owner, not the " + - "Administrators each install sets, so it may not be the folder the install made. " + - "Check who made it") - } - } - } + $custodyProblem = Get-CustodyDirProblem -Path $CustodyDir -ServiceName $ServiceName ` + -Named:$CustodyDirNamed -Holds (@($SecretsHolds) + $SecretsDir) ` + -NotWithin (@($SecretsNotWithin) + $SecretsDir) if ($custodyProblem) { throw ("-CustodyDir '$CustodyDir' cannot be the custody directory: $custodyProblem. Point it " + "at a folder of its own, such as the default '-custody'.") @@ -3163,6 +3184,7 @@ if ($HostCustody) { if (-not (Test-Path -LiteralPath $CustodyParent)) { New-AdminOnlyFolder -Path $CustodyParent } if (-not $CustodyDirNamed -or -not (Test-Path -LiteralPath $CustodyDir)) { New-RestrictedDirectory -Path $CustodyDir -What "the custody directory" + $CustodyDirMadeHere = $true $custodyHeld = @(Get-ChildItem -LiteralPath $CustodyDir -Force -ErrorAction Stop) if ($custodyHeld.Count -ne 0) { throw ("-CustodyDir '$CustodyDir' cannot be the custody directory: it holds " + @@ -3577,9 +3599,14 @@ try { # grant there is read and add-file, so its first start can write master.key. A directory left # otherwise is a refusal, and the service is disabled first, as above. if ($HostCustody) { + # Each refusal below removes the directory only when this run made it and it holds nothing + # (Remove-CustodyDirMadeHere), so the re-run it asks for can make it again; any other + # directory is left, and a re-run over a service that names it accepts it. try { Set-CustodyDirAcl -Path $CustodyDir -Account $ServiceAccount } catch { - throw "$($_.Exception.Message) $(Disable-RefusedService -ServiceName $ServiceName -Consequence 'its first start cannot write its store key file as the custody directory needs')" + $removed = Remove-CustodyDirMadeHere -Path $CustodyDir -MadeHere:$CustodyDirMadeHere + throw ("$($_.Exception.Message)$removed Re-run the installer. " + + "$(Disable-RefusedService -ServiceName $ServiceName -Consequence 'its first start cannot write its store key file as the custody directory needs')") } # A refusal, not a warning: without the variable the service reads the secrets directory, where # it cannot write its key file, and a mint made as SERVICE.md says lands where it does not look. @@ -3589,21 +3616,18 @@ if ($HostCustody) { $replacedCustodyDir = Set-ServiceEnvironmentValue -ServiceName $ServiceName -Name "MEFOR_CUSTODY_DIRECTORY" -Value $CustodyDir } catch { $custodyNamingError = $_.Exception.Message } if ($null -ne $custodyNamingError) { + $removed = Remove-CustodyDirMadeHere -Path $CustodyDir -MadeHere:$CustodyDirMadeHere throw ("Could not name the custody directory in the service's environment " + "($custodyNamingError), and without MEFOR_CUSTODY_DIRECTORY the service looks for its " + - "key file in the secrets directory, where it cannot write one. Add " + - "MEFOR_CUSTODY_DIRECTORY=$CustodyDir to the service's AppEnvironmentExtra by hand, keeping " + - "the entries already there, then re-enable the service; or remove the empty directory " + - "'$CustodyDir' and re-run the installer, since a rerun refuses a directory the service " + - "does not name. " + + "key file in the secrets directory, where it cannot write one.$removed " + + "Re-run the installer. " + "$(Disable-RefusedService -ServiceName $ServiceName -Consequence 'it would not find its custody directory')") } if ($replacedCustodyDir -and -not $CustodyDirNamed) { Write-Warning ("The service's MEFOR_CUSTODY_DIRECTORY named '$replacedCustodyDir' and now " + "names '$CustodyDir', as -CustodyDir asked. The engine reads no key file from the old " + - "directory: if master.key or handoff.key is there, move it into the new one as an " + - "administrator, on the same volume so it keeps its own access list. Then remove the " + - "service account's grant on the old directory.") + "directory. If master.key or handoff.key is there, do not delete it; follow " + + "docs/SERVICE.md 'Reinstalling over a kept custody directory'.") } Write-Host " Custody: '$CustodyDir', named to the service as MEFOR_CUSTODY_DIRECTORY (docs/SERVICE.md)." } diff --git a/scripts/service/uninstall-service.ps1 b/scripts/service/uninstall-service.ps1 index f34aa18726..c14692cc74 100644 --- a/scripts/service/uninstall-service.ps1 +++ b/scripts/service/uninstall-service.ps1 @@ -23,9 +23,10 @@ Two of them can be taken back on request, because both need elevation an operator may not have later: -RemoveLogonRight drops the "Log on as a service" right, and -RemoveAccountAces drops - the run-as account's entry from the data and config directories, and from the secrets and - custody directories the service names (vault BACKLOG #3411). On the custody directory that is - the directory's own entry: master.key there keeps its own list, which names the account. + the run-as account's entry from the data and config directories, from the secrets directory + the service names (vault BACKLOG #2595 slice C), and from the custody directory it names + (vault BACKLOG #3411). On the custody directory that is the directory's own entry: a key file + there keeps its own list, which names the account. The service SID type and the privilege list the installer sets are part of the registration, so they go with it. The script looks for the service's registry key after the removal, and the @@ -285,6 +286,8 @@ function Get-UninstallResidueNotice { # The custody directory read off MEFOR_CUSTODY_DIRECTORY (vault BACKLOG #3411). The installer # grants the run-as account read and add-file there, under the host key provider only. [string]$CustodyDir, + # The key files found in it, master.key or handoff.key, read before the notice. + [string[]]$CustodyFiles = @(), # Measured from the config dir's own ACL, not assumed from a switch this script never saw. [switch]$ConfigInheritanceStripped, # Path of the nssm.exe the registration starts, only when it is actually on disk. @@ -356,15 +359,16 @@ function Get-UninstallResidueNotice { if ($CustodyDir) { $lines += " Custody dir $CustodyDir" $lines += " The custody directory the service read under the host key" - $lines += " provider. master.key in it holds the store's key, and may be its" - $lines += " only copy on this host; handoff.key, there until the service's" - $lines += " first start, holds it too. This script leaves the directory and" - $lines += " its files. Keep them while the store is kept. master.key keeps" - $lines += " its own entry for '$ServiceAccount', whatever happens to the" - $lines += " directory's. A reinstall refuses this directory while the new" - $lines += " service does not name it: move the key files out as an" - $lines += " administrator, on the same volume, remove the directory, re-run" - $lines += " the installer, and move them back." + $lines += " provider. This script leaves it and everything in it." + $who = if ($ServiceAccount) { "'$ServiceAccount'" } else { "the account the service ran as" } + foreach ($file in @($CustodyFiles)) { + $lines += " $file holds the store's key, and may be its only copy on" + $lines += " this host: never delete it. It keeps its own entry for $who," + $lines += " which -RemoveAccountAces does not take off the file." + } + $lines += " A reinstall refuses this directory while the new service does" + $lines += " not name it: see docs/SERVICE.md 'Reinstalling over a kept" + $lines += " custody directory'." } if ($CachedNssm) { @@ -799,7 +803,8 @@ try { $custodyEntry = @($params.AppEnvironmentExtra | Where-Object { $_ -and ([string]$_).StartsWith("MEFOR_CUSTODY_DIRECTORY=", [StringComparison]::OrdinalIgnoreCase) }) | Select-Object -Last 1 - if ($custodyEntry) { $custodyDir = $custodyEntry.Substring("MEFOR_CUSTODY_DIRECTORY=".Length) } + # Trimmed, as the engine strips it before reading it. + if ($custodyEntry) { $custodyDir = $custodyEntry.Substring("MEFOR_CUSTODY_DIRECTORY=".Length).Trim() } } catch { $unreadable += ("the registered command line of '$ServiceName' ($($_.Exception.Message)) - so " + "the config directory and the data directory below could not be checked against it") @@ -972,6 +977,11 @@ $dataAceRemoved = $false $configAceRemoved = $false $secretsAceRemoved = $false $custodyAceRemoved = $false +# Which key files the custody directory holds, so the notice names only those (vault BACKLOG #3411). +$custodyFiles = @(if ($custodyDir) { + foreach ($name in @("master.key", "handoff.key")) { + if (Test-Path -LiteralPath (Join-Path $custodyDir $name)) { $name } + } }) if ($RemoveLogonRight) { if (-not $hasAccount) { @@ -1021,6 +1031,7 @@ Get-UninstallResidueNotice ` -ConfigDir $configDir ` -SecretsDir $secretsDir ` -CustodyDir $custodyDir ` + -CustodyFiles $custodyFiles ` -ConfigInheritanceStripped:$configProtected ` -CachedNssm $cachedNssm ` -WerImages $werImages ` diff --git a/tests/test_file_path_join_census.py b/tests/test_file_path_join_census.py index d8760ebf4f..996b53486f 100644 --- a/tests/test_file_path_join_census.py +++ b/tests/test_file_path_join_census.py @@ -1281,10 +1281,11 @@ def derived_script_sites() -> dict[str, int]: 1, OPERATOR, "A fixed name under the install directory." ), "scripts/service/uninstall-service.ps1": Site( - 7, + 8, OPERATOR, "Fixed names, and a folder named from a fresh GUID, under the Windows temp folder or a " - "parent the tests pass, and registry keys named after the service's images.", + "parent the tests pass, registry keys named after the service's images, and the two " + "fixed custody file names under the custody directory the registration names.", ), } diff --git a/tests/test_install_service_custody.py b/tests/test_install_service_custody.py index 6677cd29d1..0b0c270a81 100644 --- a/tests/test_install_service_custody.py +++ b/tests/test_install_service_custody.py @@ -12,6 +12,7 @@ from __future__ import annotations import json +import re import tomllib from pathlib import Path @@ -306,9 +307,8 @@ def test_the_installer_makes_and_names_the_custody_directory_under_the_host_prov facts = _preflight_facts(tmp_path) # Read by line: the call offsets count the file's own line endings, which read_text folds. text = _script_text() - check = _sole_call_on(facts, "Get-LockPathProblem", "-Path $CustodyDir") - assert "-AllowMissing" in check["text"] and "$SecretsDir" in check["text"], check["text"] - sharers = _sole_call_on(facts, "Get-OtherServiceNamingPath", "-Path $CustodyDir") + check = _sole_call_on(facts, "Get-CustodyDirProblem", "-Path $CustodyDir") + assert "$SecretsDir" in check["text"] and "-Named:$CustodyDirNamed" in check["text"], check creates = _sole_call_on(facts, "New-RestrictedDirectory", "-Path $CustodyDir") assert not [ c @@ -327,7 +327,7 @@ def test_the_installer_makes_and_names_the_custody_directory_under_the_host_prov if c["name"] == "Invoke-Nssm" and "install" in c["text"] ) host = _sole_call(facts, "Get-HostCustodyAccountProblem") - assert host["start"] < check["start"] < sharers["start"] < nssm + assert host["start"] < check["start"] < nssm assert creates["start"] < registered < secrets_lock["start"] < lock["start"] < named["start"] # Each act is inside an `if ($HostCustody)` block. lines = text.splitlines() @@ -342,6 +342,20 @@ def test_the_installer_makes_and_names_the_custody_directory_under_the_host_prov flat = " ".join(text.split()) refusal = flat.index('throw ("Could not name the custody directory') assert "Disable-RefusedService" in flat[refusal : refusal + 600], flat[refusal : refusal + 600] + # Both custody refusals after registration remove only a directory this run made, and ask for + # a re-run; neither tells anyone to add the variable by hand or to remove a directory. + removals = [ + c + for c in facts["commands"] + if c["name"] == "Remove-CustodyDirMadeHere" and c["start"] > registered + ] + assert len(removals) == 2, removals + assert all("-MadeHere:$CustodyDirMadeHere" in c["text"] for c in removals), removals + naming = flat[refusal : refusal + 800] + assert "Re-run the installer" in naming, naming + for gone in ("by hand", "re-enable the service", "remove the empty directory"): + assert gone not in naming, gone + assert "remove the empty directory" not in flat assert 'Write-Warning ("Could not name the custody directory' not in flat @@ -364,18 +378,78 @@ def test_the_uninstaller_names_the_custody_directory_and_removes_its_grant( def test_the_uninstall_notice_says_what_the_custody_directory_keeps(tmp_path: Path) -> None: - """The notice names both key files, says master.key keeps its own entry for the account - whatever happens to the directory's, and warns that a reinstall refuses the kept directory. - The control: with no custody directory, none of it is printed.""" + """The notice names each key file the directory holds, and only those, says each keeps its own + entry for the account, and warns that a reinstall refuses the kept directory. With no account + read it does not print an empty name. With no custody directory, none of it is printed.""" from tests.test_service_install_manifest import _FULL_FACTS, _notice - flat = " ".join(_notice(tmp_path, _FULL_FACTS).split()) + both = {**_FULL_FACTS, "CustodyFiles": ["master.key", "handoff.key"]} + flat = " ".join(_notice(tmp_path, both).split()) for needed in ( - "master.key", - "handoff.key", - "master.key keeps its own entry for 'NT SERVICE\\MessageFoundry'", + "master.key holds the store's key", + "handoff.key holds the store's key", + "It keeps its own entry for 'NT SERVICE\\MessageFoundry'", "A reinstall refuses this directory", + "Reinstalling over a kept custody directory", ): assert needed in flat, (needed, flat) + handoff_only = " ".join( + _notice(tmp_path, {**_FULL_FACTS, "CustodyFiles": ["handoff.key"]}).split() + ) + assert "handoff.key holds" in handoff_only and "master.key" not in handoff_only, handoff_only + nobody = " ".join( + _notice(tmp_path, {**both, "ServiceAccount": "", "ServiceAccountSid": ""}).split() + ) + assert "entry for ''" not in nobody and "the account the service ran as" in nobody, nobody without = " ".join(_notice(tmp_path, {**_FULL_FACTS, "CustodyDir": ""}).split()) assert "handoff.key" not in without and "Custody" not in without, without + + +@_windows_only +def test_the_custody_directory_check_accepts_a_named_one_and_never_says_remove( + tmp_path: Path, +) -> None: + """Get-CustodyDirProblem: a re-run over a service whose environment names the directory, with + an owner each install sets (here this account, which an unelevated test can own), accepts it; + the same directory the service does not name is refused without telling anyone to remove it. + Remove-CustodyDirMadeHere removes only a directory this run made that holds nothing.""" + assert _SCRIPT is not None + kept = tmp_path / "kept" + kept.mkdir() + made = tmp_path / "made" + made.mkdir() + full = tmp_path / "full" + full.mkdir() + (full / "master.key").write_bytes(b"k") + other = tmp_path / "other" + other.mkdir() + body = rf""" + $mySid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value + [pscustomobject]@{{ + named = [string](Get-CustodyDirProblem -Path {_psq(str(kept))} -ServiceName 'NoSuchSvc-w7' -Named -AcceptedOwners @($mySid)) + unnamed = [string](Get-CustodyDirProblem -Path {_psq(str(kept))} -ServiceName 'NoSuchSvc-w7' -AcceptedOwners @($mySid)) + owner = [string](Get-CustodyDirProblem -Path {_psq(str(kept))} -ServiceName 'NoSuchSvc-w7' -Named) + made = [string](Remove-CustodyDirMadeHere -Path {_psq(str(made))} -MadeHere) + full = [string](Remove-CustodyDirMadeHere -Path {_psq(str(full))} -MadeHere) + other = [string](Remove-CustodyDirMadeHere -Path {_psq(str(other))}) + }} | ConvertTo-Json -Compress +""" + names = [ + "Get-CustodyDirProblem", + "Remove-CustodyDirMadeHere", + "Get-LockPathProblem", + "Get-ReparsePointAncestor", + "Get-OtherServiceNamingPath", + "ConvertTo-NormalPath", + "ConvertTo-EngineStripped", + "Get-EnvironmentListValue", + "Test-EnvironmentEntryNames", + ] + got = json.loads(_ok(_extract(_SCRIPT, names, body), tmp_path).strip().splitlines()[-1]) + assert got["named"] == "", got + assert "does not name it" in got["unnamed"] and "do not delete" in got["unnamed"], got + assert not re.search(r"\bremov", got["unnamed"], re.IGNORECASE), got + assert "owner" in got["owner"], got # the control: this account is not an install's owner + assert not made.exists() and "was removed" in got["made"], got + assert (full / "master.key").exists() and got["full"] == "", got + assert other.exists() and got["other"] == "", got diff --git a/tests/test_store_custody_host.py b/tests/test_store_custody_host.py index c58656abfe..57dab8892b 100644 --- a/tests/test_store_custody_host.py +++ b/tests/test_store_custody_host.py @@ -308,30 +308,30 @@ def test_a_key_file_left_in_the_secrets_directory_is_not_taken_for_no_key(tmp_pa secrets = _own_custody_directory(tmp_path / "secrets") (secrets / "handoff.key").write_bytes(b"not read") environ = {"MEFOR_CUSTODY_DIRECTORY": str(custody_dir), "MEFOR_SECRETS_DIRECTORY": str(secrets)} - with pytest.raises(HostCustodyRefused, match="move it into") as refused: + with pytest.raises(HostCustodyRefused, match="move that file into") as refused: load_host_custody(_settings(tmp_path), enforcing=True, environ=environ) assert not isinstance(refused.value, HostCustodyMissing) - assert str(secrets / "handoff.key") in str(refused.value) + assert f"handoff.key in {secrets}" in str(refused.value) # The control: without the variable the secrets directory is the custody directory, and the # same file is read there (and refused as no handoff). with pytest.raises(HostCustodyRefused) as read: load_host_custody( _settings(tmp_path), enforcing=True, environ={"MEFOR_SECRETS_DIRECTORY": str(secrets)} ) - assert "move it into" not in str(read.value) + assert "move that file into" not in str(read.value) # With no secrets directory, beside a SQLite store, where a mint with neither variable writes. (secrets / "handoff.key").unlink() beside = tmp_path / "handoff.key" beside.write_bytes(b"not read") - with pytest.raises(HostCustodyRefused, match="move it into") as refused: + with pytest.raises(HostCustodyRefused, match="move that file into") as refused: load_host_custody( _settings(tmp_path), enforcing=True, environ={"MEFOR_CUSTODY_DIRECTORY": str(custody_dir)}, ) - assert str(beside) in str(refused.value) + assert f"{beside.name} in {beside.parent}" in str(refused.value) # A mint is stopped the same way, before anything is minted. - with pytest.raises(HostCustodyRefused, match="move it into"): + with pytest.raises(HostCustodyRefused, match="move that file into"): mint_target( _settings(tmp_path), service_account=None, @@ -365,27 +365,88 @@ def test_a_host_blob_anywhere_the_host_provider_reads_refuses_every_other_key_pr assert foreign_custody_refusal(settings, environ=unusable) is not None -@pytest.mark.parametrize("secrets_setting", ["absolute", "relative"]) -def test_a_file_beside_the_store_refuses_another_provider_until_it_is_moved_out( - tmp_path: Path, secrets_setting: str +def test_a_file_beside_the_store_refuses_another_provider_and_the_way_on_leaves_it( + tmp_path: Path, ) -> None: """A host mint with neither variable writes beside the store, so a file there refuses another - provider whatever is set; a MEFOR_SECRETS_DIRECTORY that is not an absolute path counts as - unset. The refusal names the file, and moving it out, its way on, clears it.""" + provider whatever is set. The refusal names the file, tells nobody to change it, and its way + on, a copy of the database in a directory that holds no key file, clears it with the file + still where it was.""" secrets = _own_custody_directory(tmp_path / "secrets") beside = tmp_path / "master.key" beside.write_bytes(b"not read") settings = _settings(tmp_path, key_provider="auto", encryption_key_file="k.bin") environ = { - "MEFOR_SECRETS_DIRECTORY": str(secrets) if secrets_setting == "absolute" else "secrets", + "MEFOR_SECRETS_DIRECTORY": str(secrets), "MEFOR_CUSTODY_DIRECTORY": str(_own_custody_directory(tmp_path / "custody")), } refusal = foreign_custody_refusal(settings, environ=environ) - assert refusal is not None and str(beside) in refusal, refusal - assert "move it as an administrator out of that directory" in refusal, refusal - aside = _own_custody_directory(tmp_path / "aside") - beside.rename(aside / beside.name) - assert foreign_custody_refusal(settings, environ=environ) is None + assert refusal is not None and f"master.key in {tmp_path}" in refusal, refusal + assert "leave it where it is" in refusal, refusal + assert not _advises_changing(refusal, allowed=(_KEY_SETTINGS_OUT,)), refusal + # Following it: the store's database copied into a new directory, and the store pointed there. + copied = _own_custody_directory(tmp_path / "copied") + moved_store = settings.model_copy(update={"path": str(copied / "store.db")}) + assert foreign_custody_refusal(moved_store, environ=environ) is None + assert beside.exists() + + +def test_the_other_provider_refusal_keeps_its_text_through_the_key_seams( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """build_store_cipher and resolve_active_key replace a refusal they did not see recorded with a + fixed text (BACKLOG #4882), so resolve_key_provider records this one: the file it names and + the way on reach the operator through them too.""" + from messagefoundry.store.base import build_store_cipher, resolve_active_key + + (tmp_path / "master.key").write_bytes(b"not read") + settings = _settings(tmp_path, key_provider="auto", encryption_key_file="k.bin") + for seam in (build_store_cipher, resolve_active_key): + with pytest.raises(KeyProviderError) as refused: + seam(settings) + text = str(refused.value) + assert f"master.key in {tmp_path}" in text, (seam.__name__, text) + assert "leave it where it is" in text, (seam.__name__, text) + + +def test_a_relative_secrets_variable_counts_as_unset_for_the_search( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A MEFOR_SECRETS_DIRECTORY that is not an absolute path names no directory to search, even + one that exists relative to the working directory and holds a key file. The control: the same + directory named absolutely is searched.""" + monkeypatch.chdir(tmp_path) + relative = _own_custody_directory(tmp_path / "rel") + (relative / "master.key").write_bytes(b"not read") + data = _own_custody_directory(tmp_path / "data") + settings = _settings(data, key_provider="auto", encryption_key_file="k.bin") + assert foreign_custody_refusal(settings, environ={"MEFOR_SECRETS_DIRECTORY": "rel"}) is None + named = foreign_custody_refusal(settings, environ={"MEFOR_SECRETS_DIRECTORY": str(relative)}) + assert named is not None and str(relative) in named, named + + +def test_the_left_behind_check_reads_beside_the_store_with_both_variables_set( + tmp_path: Path, +) -> None: + """Under the host provider with both variables set, the installer's environment, a key file + beside the store refuses a read and a mint rather than reading as no key. With only + MEFOR_SECRETS_DIRECTORY set it is not read there, so the PR 2804 fifth hold's way on, a new + secrets directory and a new SQLite path beside the old key, still goes ahead.""" + secrets = _own_custody_directory(tmp_path / "secrets") + custody_dir = _own_custody_directory(tmp_path / "custody") + beside = tmp_path / "handoff.key" + beside.write_bytes(b"not read") + both = {"MEFOR_CUSTODY_DIRECTORY": str(custody_dir), "MEFOR_SECRETS_DIRECTORY": str(secrets)} + with pytest.raises(HostCustodyRefused, match="move that file into") as refused: + load_host_custody(_settings(tmp_path), enforcing=True, environ=both) + assert not isinstance(refused.value, HostCustodyMissing) + assert f"handoff.key in {tmp_path}" in str(refused.value), refused.value + with pytest.raises(HostCustodyRefused, match="move that file into"): + mint_target(_settings(tmp_path), service_account=None, enforcing=True, environ=both) + with pytest.raises(HostCustodyMissing): + load_host_custody( + _settings(tmp_path), enforcing=True, environ={"MEFOR_SECRETS_DIRECTORY": str(secrets)} + ) def test_the_way_on_names_the_custody_directory_of_its_own(tmp_path: Path) -> None: @@ -497,13 +558,11 @@ async def test_a_host_blob_refuses_every_other_key_provider(tmp_path: Path, name condition = low.index("if it holds this store's key") assert condition < low.index(keep), refusal assert ". " not in low[condition : low.index(_KEY_SETTINGS_OUT)], refusal - # The one change it may advise beside the settings is the move that clears it, which keeps - # the file (Manager decision 2026-11-22, vault BACKLOG #3411): a new custody directory would - # not clear it, since this check reads the secrets and data directories whatever is set. - allowed = (_KEY_SETTINGS_OUT, custody_host._MOVE_OUT_STEP) - assert not _advises_changing(refusal, allowed=allowed), refusal - assert custody_host._MOVE_OUT_STEP in refusal, refusal - assert custody_host.keep_the_key_step(settings, new_store=False) not in refusal, refusal + assert not _advises_changing(refusal, allowed=(_KEY_SETTINGS_OUT,)), refusal + assert custody_host.keep_the_key_step(settings, new_store=False) in refusal, refusal + # The file is left in place, and the way on runs the store from somewhere else (Manager + # ruling 2026-11-22, vault BACKLOG #3411). + assert custody_host._LEAVE_KEY_FILES_STEP in refusal, refusal assert "mints this store's key" not in refusal, refusal # only the host provider mints with pytest.raises(HostCustodyRefused, match=name): await open_store(settings, create=True) @@ -2255,7 +2314,7 @@ def _held(self: Path, missing_ok: bool = False) -> None: (fallback, "run with the custody directory that holds the store's host blob"), ("which names the way on",), (fallback,), - ("If it holds no key this store needs, move it", "set [store].key_provider = 'host'"), + (fallback, "set [store].key_provider = 'host'", "leave it where it is"), (fallback, "leaves it in place"), ("Run the command again with that file in place",), (fallback, "This run minted it and nothing was written under it"), @@ -2270,7 +2329,7 @@ def _held(self: Path, missing_ok: bool = False) -> None: if _advises_changing( text, allowed=( - (_KEY_SETTINGS_OUT, custody_host._MOVE_OUT_STEP) + (_KEY_SETTINGS_OUT,) if text is foreign else (cli._REMOVE_THE_VOID_KEY,) if text is held From cfe8a3d9cda3ed6dd9b209bffc3553c374f0c5c1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 18:40:40 -0600 Subject: [PATCH 15/28] Key custody: review round-abff55c7b2 repairs (unsafe advice, a regression) Vault BACKLOG #3411 slice B3c, design note 1. - The left-behind refusal's move is offered only for a file that is this store's; otherwise it gives the leave-in-place way on. - The other-provider check passes over the store's own [store].encryption_key_file, which may be named master.key beside the database now that that directory is read whatever is set (a regression against main otherwise). - The installer's found-not-empty custody refusal no longer says to remove the directory; it points at SERVICE.md's reinstall recipe. - The uninstall notice says the account "still has an entry" on the custody directory, not which rights, since it does not read the list. --- messagefoundry/store/custody_host.py | 7 ++++++- scripts/service/install-service.ps1 | 4 +++- scripts/service/uninstall-service.ps1 | 2 +- tests/test_store_custody_host.py | 29 +++++++++++++++++++++++++++ 4 files changed, 39 insertions(+), 3 deletions(-) diff --git a/messagefoundry/store/custody_host.py b/messagefoundry/store/custody_host.py index c9732217d8..d191bb56c5 100644 --- a/messagefoundry/store/custody_host.py +++ b/messagefoundry/store/custody_host.py @@ -290,6 +290,11 @@ def foreign_custody_refusal( :data:`_LEAVE_KEY_FILES_STEP`, then :func:`keep_the_key_step`.""" environ = os.environ if environ is None else environ found = _key_files_outside(settings, None, environ) + if settings.encryption_key_file: + # The store's own key file, whatever it is named, is not a host blob: the directory beside + # the store is read whatever is set, and a key file named master.key may sit there. + own = Path(settings.encryption_key_file).resolve() + found = [p for p in found if p.resolve() != own] if not found: return None # One clause per file, so two files in two directories each name their own. @@ -693,7 +698,7 @@ def _left_outside_the_custody_directory( f"({named}), where a mint run with other variables writes it. If one holds this store's " f"key, move that file into {directory} with an account that may write there, on the same " "volume so it keeps its own access list, and try again; a key minted now would not open " - "a store that key made" + f"a store that key made. If none is this store's: {_LEAVE_KEY_FILES_STEP}" ) diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index f60c5def5a..32979e39a9 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -3189,7 +3189,9 @@ if ($HostCustody) { if ($custodyHeld.Count -ne 0) { throw ("-CustodyDir '$CustodyDir' cannot be the custody directory: it holds " + "$($custodyHeld.Count) item(s) the installer did not put there, such as " + - "'$($custodyHeld[0].Name)'. Remove the directory, check who wrote them, and re-run the installer.") + "'$($custodyHeld[0].Name)'. Check who wrote them. A master.key or handoff.key there " + + "may be a store's only key: do not delete it; follow docs/SERVICE.md 'Reinstalling " + + "over a kept custody directory'.") } } } diff --git a/scripts/service/uninstall-service.ps1 b/scripts/service/uninstall-service.ps1 index c14692cc74..6163731bf9 100644 --- a/scripts/service/uninstall-service.ps1 +++ b/scripts/service/uninstall-service.ps1 @@ -411,7 +411,7 @@ function Get-UninstallResidueNotice { if ($CustodyAceRemoved) { $lines += " Custody entry REMOVED - '$ServiceAccount' no longer has an entry on $CustodyDir." } else { - $lines += " Custody entry '$ServiceAccount' still has read and add-file on $CustodyDir." + $lines += " Custody entry '$ServiceAccount' still has an entry on $CustodyDir." $lines += " Remove it with:" $lines += " icacls `"$CustodyDir`" /remove:g `"$acePrincipal`"" } diff --git a/tests/test_store_custody_host.py b/tests/test_store_custody_host.py index 57dab8892b..09c876d487 100644 --- a/tests/test_store_custody_host.py +++ b/tests/test_store_custody_host.py @@ -409,6 +409,35 @@ def test_the_other_provider_refusal_keeps_its_text_through_the_key_seams( assert "leave it where it is" in text, (seam.__name__, text) +def test_the_stores_own_key_file_beside_it_is_not_taken_for_a_host_blob(tmp_path: Path) -> None: + """The beside-store directory is read whatever is set, so a store's own key file there named + master.key is passed over; the control is the same file with no key file setting.""" + secrets = _own_custody_directory(tmp_path / "secrets") + own = tmp_path / "master.key" + own.write_bytes(b"not read") + environ = {"MEFOR_SECRETS_DIRECTORY": str(secrets)} + settings = _settings(tmp_path, key_provider="auto", encryption_key_file=str(own)) + assert foreign_custody_refusal(settings, environ=environ) is None + other = _settings(tmp_path, key_provider="auto", encryption_key_file=str(tmp_path / "k.bin")) + assert foreign_custody_refusal(other, environ=environ) is not None + + +def test_the_left_behind_refusal_gives_a_way_on_that_leaves_another_stores_file( + tmp_path: Path, +) -> None: + """The move is offered only for a file that is this store's; otherwise the way on leaves it.""" + custody_dir = _own_custody_directory(tmp_path / "custody") + (tmp_path / "handoff.key").write_bytes(b"not read") + with pytest.raises(HostCustodyRefused) as refused: + load_host_custody( + _settings(tmp_path), + enforcing=True, + environ={"MEFOR_CUSTODY_DIRECTORY": str(custody_dir)}, + ) + text = str(refused.value) + assert "If none is this store's" in text and "leave it where it is" in text, text + + def test_a_relative_secrets_variable_counts_as_unset_for_the_search( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: From 04395c5be7bd72cc47f27e190df26f052a6dd540 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 19:07:59 -0600 Subject: [PATCH 16/28] Key custody: review round-e035104760 repairs (a regression, unsafe advice) Vault BACKLOG #3411 slice B3c, design note 1. - The uninstaller's custody key-file probe no longer stops the uninstall before its notice when the custody drive is gone: it joins without Join-Path, inside a try that names what it could not read. - The engine refuses a MEFOR_CUSTODY_DIRECTORY that is, holds or sits inside the secrets directory, before its access-list remedy could tell anyone to give the service add-file there. - The leave-in-place way on copies everything in the database's directory other than the two key files, not only the database. - New-RestrictedDirectory's squatter refusal no longer says to remove a custody directory; the custody preflight refusal no longer recommends the default path it may be refusing. --- messagefoundry/store/custody_host.py | 30 +++++++++++++++++++++++---- scripts/service/install-service.ps1 | 12 +++++++---- scripts/service/uninstall-service.ps1 | 15 ++++++++++---- tests/test_install_service_custody.py | 9 +++++++- tests/test_store_custody_host.py | 17 +++++++++++++++ 5 files changed, 70 insertions(+), 13 deletions(-) diff --git a/messagefoundry/store/custody_host.py b/messagefoundry/store/custody_host.py index d191bb56c5..7274975d03 100644 --- a/messagefoundry/store/custody_host.py +++ b/messagefoundry/store/custody_host.py @@ -188,8 +188,28 @@ def _own_directory_refusal(environ: Mapping[str, str]) -> str | None: link, and the folder that holds it is read by the holder rule. It reads known broad groups only, so an entry for one account, the service's or another's, is not refused. A directory ``MEFOR_SECRETS_DIRECTORY`` names is judged where the settings load reads it, and a SQLite - store's data directory is not judged here.""" + store's data directory is not judged here. + + Refused first, whether or not it exists: a custody directory that is, holds or sits inside + the directory ``MEFOR_SECRETS_DIRECTORY`` names, compared as written after normalizing. The + service may add files to its custody directory, and the secrets directory is + administrator-written (ADR 0214), so the two must stay apart.""" raw = environ.get(CUSTODY_DIRECTORY_VARIABLE, "").strip() + secrets = environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip() + if raw and secrets and os.path.isabs(raw) and os.path.isabs(secrets): + own, shared = (os.path.normcase(os.path.normpath(p)) for p in (raw, secrets)) + try: + overlap = os.path.commonpath([own, shared]) in (own, shared) + except ValueError: # different drives + overlap = False + if overlap: + return ( + f"the custody directory {CUSTODY_DIRECTORY_VARIABLE} names is, holds or sits inside " + f"the secrets directory {SECRETS_DIRECTORY_VARIABLE} names. The service may add " + "files to its custody directory, and must not be able to add one to the secrets " + f"directory, so do not give it that right there: set {CUSTODY_DIRECTORY_VARIABLE}, " + "here and in the service's environment, to a directory of its own outside it" + ) if not raw or not os.path.lexists(raw): # Nothing there: a read finds no file, and a mint refuses the missing directory itself. return None @@ -317,9 +337,11 @@ def foreign_custody_refusal( _LEAVE_KEY_FILES_STEP = ( "Each file named here may be another store's only key: leave it where it is. To go on, run " "this store from places that hold neither master.key nor handoff.key. For a file beside the " - "store's database, with the engine stopped, copy the database file and any -wal and -shm file " - "beside it into a new directory that holds neither, and point the store at the copy by its " - "absolute path, with --db or [store].path, here and wherever the service names it. For a file " + "store's database, with the engine stopped, copy everything in the database's directory other " + "than those two files, the database's -wal and -shm files and any other file or folder the " + "engine keeps there among them, into a new directory, and point the " + "store at the copied database by its absolute path, with --db or [store].path, here and " + "wherever the service names it. For a file " "in the directory MEFOR_CUSTODY_DIRECTORY or MEFOR_SECRETS_DIRECTORY names, set that variable, " "here and in the service's environment, to a new directory, and copy into it every file the " "old one holds other than master.key and handoff.key" diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index 32979e39a9..e5224eb4fd 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -979,9 +979,13 @@ function New-RestrictedDirectory { $acl = Get-Acl -LiteralPath $Path $owner = $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value if ($owner -ne $OwnerSid -or -not $acl.AreAccessRulesProtected) { + # The custody directory may hold a store's only key, so its refusal never says remove. + $remedy = if ($What -eq "the custody directory") { + "Check who made it. A master.key or handoff.key in it may be a store's only key: do not " + + "delete it; follow docs/SERVICE.md 'Reinstalling over a kept custody directory'." + } else { "Remove it, check who made it, and re-run the installer." } throw ("'$Path' was there before this install made it (its owner is $owner), so it is not " + - "the restricted folder the install asked for. Remove it, check who made it, and re-run " + - "the installer.") + "the restricted folder the install asked for. $remedy") } # Read again after the create, as Set-SecretsDirAcl does: a folder above may have become a # junction since the preflight judged the path. @@ -3123,8 +3127,8 @@ if (-not $HostCustody) { -Named:$CustodyDirNamed -Holds (@($SecretsHolds) + $SecretsDir) ` -NotWithin (@($SecretsNotWithin) + $SecretsDir) if ($custodyProblem) { - throw ("-CustodyDir '$CustodyDir' cannot be the custody directory: $custodyProblem. Point it " + - "at a folder of its own, such as the default '-custody'.") + throw ("'$CustodyDir' cannot be the custody directory: $custodyProblem. Pass -CustodyDir " + + "naming a new folder of this service's own, one that does not exist yet.") } } diff --git a/scripts/service/uninstall-service.ps1 b/scripts/service/uninstall-service.ps1 index 6163731bf9..211ad51cdd 100644 --- a/scripts/service/uninstall-service.ps1 +++ b/scripts/service/uninstall-service.ps1 @@ -978,10 +978,17 @@ $configAceRemoved = $false $secretsAceRemoved = $false $custodyAceRemoved = $false # Which key files the custody directory holds, so the notice names only those (vault BACKLOG #3411). -$custodyFiles = @(if ($custodyDir) { - foreach ($name in @("master.key", "handoff.key")) { - if (Test-Path -LiteralPath (Join-Path $custodyDir $name)) { $name } - } }) +# A read that fails, such as a drive that is gone, must not stop the uninstall before its notice. +$custodyFiles = @() +if ($custodyDir) { + try { + $custodyFiles = @(foreach ($name in @("master.key", "handoff.key")) { + if (Test-Path -LiteralPath ([IO.Path]::Combine($custodyDir, $name))) { $name } }) + } catch { + $unreadable += ("the key files in the custody directory '$custodyDir' ($($_.Exception.Message)) " + + "- check it for master.key and handoff.key, and do not delete either") + } +} if ($RemoveLogonRight) { if (-not $hasAccount) { diff --git a/tests/test_install_service_custody.py b/tests/test_install_service_custody.py index 0b0c270a81..1af7fc0741 100644 --- a/tests/test_install_service_custody.py +++ b/tests/test_install_service_custody.py @@ -374,7 +374,14 @@ def test_the_uninstaller_names_the_custody_directory_and_removes_its_grant( notice = _sole_call(facts, "Get-UninstallResidueNotice") assert "-CustodyDir $custodyDir" in notice["text"], notice["text"] assert "-CustodyAceRemoved:$custodyAceRemoved" in notice["text"], notice["text"] - assert 'StartsWith("MEFOR_CUSTODY_DIRECTORY="' in _UNINSTALL.read_text(encoding="utf-8") + uninstall = _UNINSTALL.read_text(encoding="utf-8") + assert 'StartsWith("MEFOR_CUSTODY_DIRECTORY="' in uninstall + # The key-file probe cannot stop the uninstall before its notice: Join-Path throws on a drive + # that is gone, so the probe joins without it, inside a try that names what it could not read. + probe = uninstall.index('foreach ($name in @("master.key", "handoff.key"))') + window = uninstall[uninstall.rindex("try {", 0, probe) : probe + 400] + assert "[IO.Path]::Combine($custodyDir, $name)" in window and "$unreadable +=" in window, window + assert "Join-Path $custodyDir" not in uninstall def test_the_uninstall_notice_says_what_the_custody_directory_keeps(tmp_path: Path) -> None: diff --git a/tests/test_store_custody_host.py b/tests/test_store_custody_host.py index 09c876d487..807b2fc5ae 100644 --- a/tests/test_store_custody_host.py +++ b/tests/test_store_custody_host.py @@ -409,6 +409,23 @@ def test_the_other_provider_refusal_keeps_its_text_through_the_key_seams( assert "leave it where it is" in text, (seam.__name__, text) +@pytest.mark.parametrize("where", ["same", "inside", "around"]) +def test_a_custody_directory_overlapping_the_secrets_directory_is_refused( + tmp_path: Path, where: str +) -> None: + """The custody directory must stay apart from the administrator-written secrets directory, so + one that is, sits inside or holds it is refused, and the remedy never tells anyone to give the + service add-file there. The control: two sibling directories pass this rule.""" + secrets = tmp_path / "secrets" + custody_dir = {"same": secrets, "inside": secrets / "custody", "around": tmp_path}[where] + environ = {"MEFOR_SECRETS_DIRECTORY": str(secrets), "MEFOR_CUSTODY_DIRECTORY": str(custody_dir)} + with pytest.raises(HostCustodyRefused, match="is, holds or sits inside") as refused: + load_host_custody(_settings(tmp_path), enforcing=True, environ=environ) + assert "add a file to it" not in str(refused.value), refused.value + siblings = {**environ, "MEFOR_CUSTODY_DIRECTORY": str(tmp_path / "custody")} + assert custody_host._own_directory_refusal(siblings) is None + + def test_the_stores_own_key_file_beside_it_is_not_taken_for_a_host_blob(tmp_path: Path) -> None: """The beside-store directory is read whatever is set, so a store's own key file there named master.key is passed over; the control is the same file with no key file setting.""" From 0cd9fa90189829dd0090d4325c4019af880e0140 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 20:27:50 -0600 Subject: [PATCH 17/28] Key custody: one SERVICE.md procedure for key-file refusals (review round-001caa04b0) Vault BACKLOG #3411 slice B3c, design note 1, under the Manager's design rule of 2026-11-22: a refusal names what it found, says to leave every key file and delete nothing, and points at one docs/SERVICE.md section. - _LEAVE_KEY_FILES_STEP no longer carries a copy procedure; it names docs/SERVICE.md 'When a refusal names master.key or handoff.key', which states the procedure once: stop the service, a new folder the installer makes restricted (-DataDir, -SecretsDir, -CustodyDir), never another store's database, and a move within one volume or a copy with owner and list across volumes, keeping the original until the start. - foreign_custody_refusal closes on that step, not keep_the_key_step, whose new secrets directory does not clear a file beside the store. - The left-behind refusal states no move of its own. - The custody and secrets overlap check compares resolved paths. - Variable names reach stderr as literals (CodeQL alert 315). - install-service.ps1 makes the custody directory just before naming it, disabling the service and removing a folder it made on a refusal; an empty unnamed one is not said to hold a key. Its comments say what the settings reader's answer decides. - uninstall-service.ps1 keeps the never-delete warning when the custody directory does not read as there. --- docs/SERVICE.md | 63 +++++++++-- messagefoundry/store/custody_host.py | 109 +++++++++++-------- scripts/service/install-service.ps1 | 89 +++++++++------ scripts/service/uninstall-service.ps1 | 19 +++- tests/test_install_service_custody.py | 55 ++++++++-- tests/test_store_custody_host.py | 149 ++++++++++++++++++++++---- 6 files changed, 366 insertions(+), 118 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index 9d080234ec..a151985f50 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -293,12 +293,8 @@ all, so a mint run without the variable does not lead to a second key. **Reinstalling over a kept custody directory.** The install script refuses an existing custody directory the service does not name, as after an uninstall, and it never removes one that holds -anything: `master.key` or `handoff.key` there may be the only copy of a store's key on this host, -so do not delete either. To go on, re-run the install script with `-CustodyDir` naming a new -folder. Then, with the service stopped, move each key file from the kept directory into the new -one as an administrator, on the same volume so it keeps its own access list, and start the -service. The same move applies to a key file left in a custody directory the service named before -a `-CustodyDir` change. +anything. [When a refusal names master.key or handoff.key](#when-a-refusal-names-masterkey-or-handoffkey) +says how to go on. **Minting.** Set the variable in the elevated shell that runs `provision-admin --service-account`, to the same path, so the handoff lands where the service looks: @@ -322,6 +318,59 @@ the service account and the operator can both open the store, in either order. T > new location. The startup CWD-mismatch WARNING names the resolved paths so any move is visible. Deployments > without `--project-root`, or with an absolute DB path, are unchanged. +#### When a refusal names master.key or handoff.key + +This is the one procedure for going on past a refusal that names `master.key` or `handoff.key`, the +host key provider's files ([The custody directory](#the-custody-directory-under-the-host-key-provider)). +The engine and the install and uninstall scripts point here when they find one where they cannot +tie it to this service's store, at least: a key file beside a store that another key provider +opens, a key file outside the custody directory the service names, and an existing custody +directory the service does not name, as after an uninstall. Neither the engine nor the scripts can +tell whose key a file holds, and either file may be the only copy of a store's key on this host. + +1. **Delete nothing, and leave every key file where it is**, in every directory the refusal names, + unless step 3 sends you to move one; then move it only as step 5 says. +2. **Stop the service** (`Stop-Service `) if it is installed, and work from an + elevated shell. +3. **If the file holds this store's key**, as when this store was set up under + `[store].key_provider = 'host'`: + - When the refusal says `[store].key_provider` is another provider, make the settings change + the refusal names. No file moves. + - When the file sits outside the custody directory the service names, move it into that + directory as step 5 says. + - When the install script refuses a kept custody directory, re-run it with `-CustodyDir` naming + a new folder that does not exist yet, which it creates restricted + ([The custody directory](#the-custody-directory-under-the-host-key-provider)). Then move each + key file from the kept directory into the new one as step 5 says. +4. **If the file is another store's, or you cannot tell**, this store needs places that hold + neither file. Let the install script make each one new and restricted, rather than making or + filling a folder by hand. Re-run it with the option for where the file is: + - beside the store's database: `-DataDir` naming a new folder that does not exist yet, and no + `-DbPath`, so the store is `\messagefoundry.db` in a directory the script creates and + restricts. A `-DbPath` outside `-DataDir` names a folder the script grants nothing on. + - in the directory `MEFOR_SECRETS_DIRECTORY` names: `-SecretsDir` naming a new folder that does + not exist yet. Then add this service's secret files to it as + [the secrets directory](#protect-the-store-encryption-key-at-rest-wp-11d) says. + - in the directory `MEFOR_CUSTODY_DIRECTORY` names: under the host provider, `-CustodyDir` + naming a new folder that does not exist yet. Under another provider the service reads no + custody directory of its own, so take the `MEFOR_CUSTODY_DIRECTORY` entry out of its NSSM + `AppEnvironmentExtra` list, keeping the other entries. + + A new data directory starts a new, empty store. Never copy another store's database, or any + key file, into it. To keep this store's own data, move its database file, and the `-wal` and + `-shm` files beside it when they are there, into the new data directory as step 5 says. +5. **Moving a file.** Within one volume, move it as an administrator + (`Move-Item -LiteralPath -Destination `): the file keeps its own owner and + access list, which the engine checks exactly on a key file. Across volumes a move is a copy, + and a plain copy takes the new directory's list in place of the file's own, so the engine + refuses a key file copied that way. Copy a key file with its owner and list instead + (`robocopy /COPY:DATSO /B`). Check that + `icacls ` prints the same entries for the copy as for the original, and that + `(Get-Acl -LiteralPath ).Owner` prints the same owner, and keep the original where it is + until the service has started and opened its store from the copy. Copy the database files + across volumes the same way, and keep their originals until then too. +6. **Start the service**, and read its log for a refusal ([Verify it's running](#verify-its-running)). + ## Update to a new build (restart vs reinstall) The service runs `\Scripts\python.exe -I -X disable-remote-debug -m messagefoundry @@ -1295,7 +1344,7 @@ list below says what it covers. | The `DataDir` tree — logs and message store | Your data | Delete it yourself once you are sure you are not reinstalling. `DataDir` is a PHI sink — dispose of it the way [PHI.md](PHI.md) describes | | The service's `nssm.exe`, in the installer's `-NssmDir` (`C:\Program Files\MessageFoundry\nssm` by default) | The copy the service ran; the inventory names the one it was registered with | Delete it yourself only when no other service installed with the same `-NssmDir` remains and you are not reinstalling | | An access-control entry for the run-as account on `DataDir` **and** on the config directory | The installer grants both so the service can read config and write logs | `-RemoveAccountAces`, or `icacls "" /remove:g "*"` | -| Under `[store].key_provider = 'host'`, the custody directory `MEFOR_CUSTODY_DIRECTORY` names, with `master.key` (and `handoff.key` before the first start), and the run-as account's read and add-file entry on it | The files hold the store's key, maybe its only copy on this host. Each file carries its own access-control entry for the account, and `-RemoveAccountAces` takes the account's entry off the directory only, not off the files. A reinstall refuses the kept directory while the new service does not name it | Keep the directory and its files while the store is kept; never delete them. `-RemoveAccountAces` removes the directory's entry. To reinstall, see [Reinstalling over a kept custody directory](#the-custody-directory-under-the-host-key-provider) | +| Under `[store].key_provider = 'host'`, the custody directory `MEFOR_CUSTODY_DIRECTORY` names, with `master.key` (and `handoff.key` before the first start), and the run-as account's read and add-file entry on it | The files hold the store's key, maybe its only copy on this host. Each file carries its own access-control entry for the account, and `-RemoveAccountAces` takes the account's entry off the directory only, not off the files. A reinstall refuses the kept directory while the new service does not name it | Keep the directory and its files while the store is kept; never delete them. `-RemoveAccountAces` removes the directory's entry. To reinstall, see [When a refusal names master.key or handoff.key](#when-a-refusal-names-masterkey-or-handoffkey) | | The `SeServiceLogonRight` ("Log on as a service") grant | Setting the service's run-as account does not grant it, so the installer does | `-RemoveLogonRight`, or secpol.msc under Local Policies, User Rights Assignment | | Inheritance turned off on `DataDir`, and (with `-LockConfigDir`) on the config directory plus its owner moved to Administrators | See below | `icacls "" /inheritance:e`, by hand | | Windows Error Reporting keys, when you installed with `-SuppressCrashDumps` — **two** surfaces, `ExcludedApplications` and `LocalDumps`, reported separately because Windows evaluates them independently | [Stated above](#suppress-windows-crash-dumps-of-the-engine-adr-0152-phase-0) — removing them switches PHI-carrying dumps back on | By hand, under that registry path | diff --git a/messagefoundry/store/custody_host.py b/messagefoundry/store/custody_host.py index 7274975d03..83f1cf8b26 100644 --- a/messagefoundry/store/custody_host.py +++ b/messagefoundry/store/custody_host.py @@ -164,7 +164,13 @@ def custody_directory( if variable is not None: path = Path(environ[variable].strip()) if not path.is_absolute(): - raise _recorded_as(HostCustodyRefused, f"{variable} must be an absolute path") + # Named as a literal: this text reaches stderr (keep_the_key_step says why). + name = ( + "MEFOR_CUSTODY_DIRECTORY" + if variable == CUSTODY_DIRECTORY_VARIABLE + else "MEFOR_SECRETS_DIRECTORY" + ) + raise _recorded_as(HostCustodyRefused, f"{name} must be an absolute path") return path if settings.backend is StoreBackend.SQLITE and settings.path != ":memory:": return Path(settings.path).resolve().parent @@ -191,25 +197,28 @@ def _own_directory_refusal(environ: Mapping[str, str]) -> str | None: store's data directory is not judged here. Refused first, whether or not it exists: a custody directory that is, holds or sits inside - the directory ``MEFOR_SECRETS_DIRECTORY`` names, compared as written after normalizing. The + the directory ``MEFOR_SECRETS_DIRECTORY`` names, compared where each resolves to + (:func:`_overlaps`), so a link or another spelling of the same place does not pass. The service may add files to its custody directory, and the secrets directory is administrator-written (ADR 0214), so the two must stay apart.""" raw = environ.get(CUSTODY_DIRECTORY_VARIABLE, "").strip() secrets = environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip() - if raw and secrets and os.path.isabs(raw) and os.path.isabs(secrets): - own, shared = (os.path.normcase(os.path.normpath(p)) for p in (raw, secrets)) - try: - overlap = os.path.commonpath([own, shared]) in (own, shared) - except ValueError: # different drives - overlap = False - if overlap: - return ( - f"the custody directory {CUSTODY_DIRECTORY_VARIABLE} names is, holds or sits inside " - f"the secrets directory {SECRETS_DIRECTORY_VARIABLE} names. The service may add " - "files to its custody directory, and must not be able to add one to the secrets " - f"directory, so do not give it that right there: set {CUSTODY_DIRECTORY_VARIABLE}, " - "here and in the service's environment, to a directory of its own outside it" - ) + if ( + raw + and secrets + and os.path.isabs(raw) + and os.path.isabs(secrets) + and _overlaps(raw, secrets) + ): + # The variables are named as literals: this text reaches stderr (keep_the_key_step says + # why). + return ( + "the custody directory MEFOR_CUSTODY_DIRECTORY names is, holds or sits inside the " + "secrets directory MEFOR_SECRETS_DIRECTORY names. The service may add files to its " + "custody directory, and must not be able to add one to the secrets directory, so do " + "not give it that right there: set MEFOR_CUSTODY_DIRECTORY, here and in the service's " + "environment, to a directory of its own outside it" + ) if not raw or not os.path.lexists(raw): # Nothing there: a read finds no file, and a mint refuses the missing directory itself. return None @@ -225,10 +234,20 @@ def _own_directory_refusal(environ: Mapping[str, str]) -> str | None: else "Make it owned by the account the engine runs as, mode 0700, in a folder only that " "account or root may write" ) - return ( - f"the custody directory {CUSTODY_DIRECTORY_VARIABLE} names is not restricted: {problem}. " - f"{remedy}" - ) + return f"the custody directory MEFOR_CUSTODY_DIRECTORY names is not restricted: {problem}. {remedy}" + + +def _overlaps(first: str, second: str) -> bool: + """Whether the directory ``first`` is, holds or sits inside ``second``, each compared where it + resolves to: links followed as far as the path exists (:func:`os.path.realpath`, which on + Windows also reads a short 8.3 name as the long one for the part that exists), then + case-folded where the platform folds case (:func:`os.path.normcase`). Two paths on different + drives do not overlap.""" + own, shared = (os.path.normcase(os.path.realpath(p)) for p in (first, second)) + try: + return os.path.commonpath([own, shared]) in (own, shared) + except ValueError: # different drives + return False def _custody_paths(directory: Path) -> tuple[Path, Path]: @@ -306,8 +325,8 @@ def foreign_custody_refusal( the blob minted for it. A directory setting that is not an absolute path is passed over here, and the directories the other setting names are still looked in. - The way on never changes a file it found (PR 2804 fifth hold; Manager ruling 2026-11-22): - :data:`_LEAVE_KEY_FILES_STEP`, then :func:`keep_the_key_step`.""" + The way on changes no file it found (PR 2804 fifth hold; Manager ruling 2026-11-22): after the + settings change for a blob that holds this store's key, :data:`_LEAVE_KEY_FILES_STEP`.""" environ = os.environ if environ is None else environ found = _key_files_outside(settings, None, environ) if settings.encryption_key_file: @@ -327,24 +346,22 @@ def foreign_custody_refusal( "set [store].key_provider = 'host' and remove every other store key setting, with " "[store].cipher_provider = 'aesgcm', which that provider needs. The engine cannot tell " "whether the blob holds this store's key, so it leaves the file in place. " - f"{_LEAVE_KEY_FILES_STEP}. {keep_the_key_step(settings, new_store=False, environ=environ)}" + f"{_LEAVE_KEY_FILES_STEP}" ) -#: The way on from :func:`foreign_custody_refusal` when a file it found is not this store's own, -#: stated once (Manager ruling 2026-11-22 on vault BACKLOG #3411). It changes no file it found: -#: each may be another store's only key. Platform-neutral. +#: The section of docs/SERVICE.md that holds the one procedure for going on past a refusal that +#: names a key file (Manager design rule 2026-11-22 on vault BACKLOG #3411). The engine's texts +#: name it and state no file procedure of their own; tests check the heading is there. +_SERVICE_PROCEDURE_TITLE = "When a refusal names master.key or handoff.key" + +#: The way on from a refusal that found a key file it cannot tie to this store +#: (:func:`foreign_custody_refusal`, :func:`_left_outside_the_custody_directory`). It changes no +#: file: each may be another store's only key. _LEAVE_KEY_FILES_STEP = ( - "Each file named here may be another store's only key: leave it where it is. To go on, run " - "this store from places that hold neither master.key nor handoff.key. For a file beside the " - "store's database, with the engine stopped, copy everything in the database's directory other " - "than those two files, the database's -wal and -shm files and any other file or folder the " - "engine keeps there among them, into a new directory, and point the " - "store at the copied database by its absolute path, with --db or [store].path, here and " - "wherever the service names it. For a file " - "in the directory MEFOR_CUSTODY_DIRECTORY or MEFOR_SECRETS_DIRECTORY names, set that variable, " - "here and in the service's environment, to a new directory, and copy into it every file the " - "old one holds other than master.key and handoff.key" + "Leave each key file named here where it is, and delete nothing: each may be the only copy of " + "a store's key on this host. To go on, follow docs/SERVICE.md, " + f"'{_SERVICE_PROCEDURE_TITLE}'" ) @@ -483,9 +500,9 @@ def custody_refusal_at_open(exc: BaseException) -> HostCustodyRefused: chain and then flushes the replaced class's log line (BACKLOG #4882).""" return _read_refusal( "the store's key custody could not be read or checked at the open: check " - f"[store].key_provider, the custody directory ({CUSTODY_DIRECTORY_VARIABLE}, else " - f"{SECRETS_DIRECTORY_VARIABLE}, else a SQLite store's data directory) and the host file " - "and handoff in it", + "[store].key_provider, the custody directory (MEFOR_CUSTODY_DIRECTORY, else " + "MEFOR_SECRETS_DIRECTORY, else a SQLite store's data directory) and the host file and " + "handoff in it", exc, ) @@ -714,13 +731,13 @@ def _left_outside_the_custody_directory( if not found: return None named = "; ".join(f"{p.name} in {p.parent}" for p in found) + # The variable is named as a literal: this text reaches stderr (keep_the_key_step says why). return ( f"no host blob or handoff is in the custody directory {directory}, which " - f"{CUSTODY_DIRECTORY_VARIABLE} names, but host custody was found elsewhere " - f"({named}), where a mint run with other variables writes it. If one holds this store's " - f"key, move that file into {directory} with an account that may write there, on the same " - "volume so it keeps its own access list, and try again; a key minted now would not open " - f"a store that key made. If none is this store's: {_LEAVE_KEY_FILES_STEP}" + "MEFOR_CUSTODY_DIRECTORY names, but host custody was found elsewhere " + f"({named}), where a mint run with other variables writes it. A key minted now would not " + "open a store that key made, so none is read or minted here. " + f"{_LEAVE_KEY_FILES_STEP}" ) @@ -750,8 +767,8 @@ def check_host_custody_settings( raise _recorded_as( HostCustodyRefused, "[store].key_provider = 'host' needs a directory for the host blob: set " - f"{CUSTODY_DIRECTORY_VARIABLE} or {SECRETS_DIRECTORY_VARIABLE}, since this store has " - "no data directory of its own", + "MEFOR_CUSTODY_DIRECTORY or MEFOR_SECRETS_DIRECTORY, since this store has no data " + "directory of its own", ) refusal = _own_directory_refusal(environ) if refusal is not None: diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index e5224eb4fd..efc76cb19d 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -981,8 +981,9 @@ function New-RestrictedDirectory { if ($owner -ne $OwnerSid -or -not $acl.AreAccessRulesProtected) { # The custody directory may hold a store's only key, so its refusal never says remove. $remedy = if ($What -eq "the custody directory") { - "Check who made it. A master.key or handoff.key in it may be a store's only key: do not " + - "delete it; follow docs/SERVICE.md 'Reinstalling over a kept custody directory'." + "Check who made it. Leave every key file in it where it is, and delete nothing: a " + + "master.key or handoff.key there may be the only copy of a store's key on this " + + "host. Then follow docs/SERVICE.md 'When a refusal names master.key or handoff.key'." } else { "Remove it, check who made it, and re-run the installer." } throw ("'$Path' was there before this install made it (its owner is $owner), so it is not " + "the restricted folder the install asked for. $remedy") @@ -1180,10 +1181,18 @@ function Get-CustodyDirProblem { } if (-not (Test-Path -LiteralPath $Path)) { return "" } if (-not $Named) { - return ("it already exists and the service does not name it. It may hold master.key or " + - "handoff.key, which may be the only copy of a store's key on this host, so do not " + - "delete it or anything in it; follow docs/SERVICE.md 'Reinstalling over a kept " + - "custody directory'") + # What it holds decides the text: an empty folder is not said to hold a key. A listing that + # fails reads as one $null item, never as empty. + $held = @(try { Get-ChildItem -LiteralPath $Path -Force -ErrorAction Stop } catch { $null }) + if ($held.Count -eq 0) { + return ("it already exists, holds nothing, and the service does not name it, so it is " + + "not a folder this install made. Check who made it, and follow docs/SERVICE.md 'When a refusal names master.key or handoff.key'") + } + $what = if ($null -eq $held[0]) { "could not be listed, so it may hold master.key or handoff.key" } + else { "holds $($held.Count) item(s), such as '$($held[0].Name)'" } + return ("it already exists, the service does not name it, and it $what. Leave every key " + + "file in it where it is, and delete nothing: master.key or handoff.key there may be " + + "the only copy of a store's key on this host. Follow docs/SERVICE.md 'When a refusal names master.key or handoff.key'") } $owner = (Get-Acl -LiteralPath $Path).GetOwner([Security.Principal.SecurityIdentifier]).Value if ($AcceptedOwners -notcontains $owner) { @@ -1344,9 +1353,10 @@ function Get-SettingsKeyProvider { do. Other forms can misread either way: at least a header it does not recognize (a tab, or a quoted key with a space or punctuation) leaves the lines after it credited to the table before it, and a triple quote in a comment or a one-line string, or a multi-line string - holding the other delimiter, can make it misread every line after it. What the installer does - with the answer is an early refusal: the engine applies its own key custody refusals at start - whatever this returns. + holding the other delimiter, can make it misread every line after it. The answer decides, at + least, whether the installer refuses a shared account for the host provider, makes a custody + directory and names it to the service, and accepts -CustodyDir. The engine applies its own key + custody refusals at start whatever this returns. #> param([Parameter(Mandatory)][string]$Path) $value = '(?:"(?[^"\\]*)"|''(?[^'']*)'')' @@ -3057,8 +3067,9 @@ if ($ServiceConfig -and -not (Test-Path -LiteralPath $ServiceConfig -PathType Le # --- key custody: [store].key_provider = 'host' (vault BACKLOG #3411, S3 slice B3c) -------------------- # On a rerun, a MEFOR_STORE_KEY_PROVIDER in the service's NSSM environment (AppEnvironmentExtra) # wins over the settings file, as an environment variable does at start. No other environment is -# read here, the machine's included. Refused before anything acts. Get-SettingsKeyProvider says -# what it reads, and why the engine's own refusal at start does not rest on it. +# read here, the machine's included. The answer decides the account refusal below, made before +# anything acts, and whether the custody directory is made and named and -CustodyDir accepted. +# Get-SettingsKeyProvider says what it reads, and that the engine's refusals do not rest on it. $RegisteredKeyProvider = Get-RegisteredEnvironmentValue -ServiceName $ServiceName -Name "MEFOR_STORE_KEY_PROVIDER" $HostCustody = if ($null -ne $RegisteredKeyProvider) { $RegisteredKeyProvider -ceq "host" } else { (Get-SettingsKeyProvider -Path $ServiceConfig) -ceq "host" } @@ -3081,8 +3092,8 @@ if ($HostCustody) { # handoff provision-admin leaves, so it must add a file where those two live. The secrets directory # is administrator-written (ADR 0214), so they get a directory of their own, named to the service as # MEFOR_CUSTODY_DIRECTORY, which the engine reads in place of MEFOR_SECRETS_DIRECTORY for them. -# Judged here, before anything acts, by the secrets directory's rules, and made before the service -# is registered; restricted (Set-CustodyDirAcl) once the account resolves. +# Judged here, before anything acts, by the secrets directory's rules; made, restricted +# (Set-CustodyDirAcl) and named once the account resolves, after the service is registered. $CustodyDirNamed = $false $CustodyDirMadeHere = $false if (-not $HostCustody) { @@ -3181,24 +3192,9 @@ if (-not $SecretsDirNamed -or -not (Test-Path -LiteralPath $SecretsDir)) { $heldProblem = Get-SecretsDirHeldProblem -Path $SecretsDir if ($heldProblem) { throw "-SecretsDir '$SecretsDir' cannot be the secrets directory: $heldProblem." } } -# The custody directory the same way (vault BACKLOG #3411): made restricted in one step, and then -# empty, since a key file in it that this install did not see made would be read as the store's. -if ($HostCustody) { - $CustodyParent = Split-Path -Parent $CustodyDir - if (-not (Test-Path -LiteralPath $CustodyParent)) { New-AdminOnlyFolder -Path $CustodyParent } - if (-not $CustodyDirNamed -or -not (Test-Path -LiteralPath $CustodyDir)) { - New-RestrictedDirectory -Path $CustodyDir -What "the custody directory" - $CustodyDirMadeHere = $true - $custodyHeld = @(Get-ChildItem -LiteralPath $CustodyDir -Force -ErrorAction Stop) - if ($custodyHeld.Count -ne 0) { - throw ("-CustodyDir '$CustodyDir' cannot be the custody directory: it holds " + - "$($custodyHeld.Count) item(s) the installer did not put there, such as " + - "'$($custodyHeld[0].Name)'. Check who wrote them. A master.key or handoff.key there " + - "may be a store's only key: do not delete it; follow docs/SERVICE.md 'Reinstalling " + - "over a kept custody directory'.") - } - } -} +# The custody directory is made LATER, just before it is restricted and named to the service (vault +# BACKLOG #3411): a refusal between its making and its naming would leave a folder the service does +# not name, which the next run refuses. # NB the data-dir + config-dir ACL lockdown is applied LATER, AFTER the service is registered and its # ObjectName (run-as account) is set - see "ACLs" below. The default run-as is now a per-service VIRTUAL # account (NT SERVICE\, #224), whose SID does NOT resolve for icacls until the service @@ -3608,6 +3604,32 @@ if ($HostCustody) { # Each refusal below removes the directory only when this run made it and it holds nothing # (Remove-CustodyDirMadeHere), so the re-run it asks for can make it again; any other # directory is left, and a re-run over a service that names it accepts it. + # + # Made here, restricted in one step as the secrets directory is, and then empty, since a key + # file in it that this install did not see made would be read as the store's. Made this late, + # just before it is named, so that a refusal earlier in the run leaves no folder behind. + try { + $CustodyParent = Split-Path -Parent $CustodyDir + if (-not (Test-Path -LiteralPath $CustodyParent)) { New-AdminOnlyFolder -Path $CustodyParent } + if (-not $CustodyDirNamed -or -not (Test-Path -LiteralPath $CustodyDir)) { + # Read before the call: CreateDirectory succeeds on a folder that is already there. + $CustodyDirMadeHere = -not (Test-Path -LiteralPath $CustodyDir) + New-RestrictedDirectory -Path $CustodyDir -What "the custody directory" + $custodyHeld = @(Get-ChildItem -LiteralPath $CustodyDir -Force -ErrorAction Stop) + if ($custodyHeld.Count -ne 0) { + throw ("-CustodyDir '$CustodyDir' cannot be the custody directory: it holds " + + "$($custodyHeld.Count) item(s) the installer did not put there, such as " + + "'$($custodyHeld[0].Name)'. Check who wrote them. Leave every key file in it " + + "where it is, and delete nothing: a master.key or handoff.key there may be the " + + "only copy of a store's key on this host. Then follow docs/SERVICE.md 'When a " + + "refusal names master.key or handoff.key'.") + } + } + } catch { + $removed = Remove-CustodyDirMadeHere -Path $CustodyDir -MadeHere:$CustodyDirMadeHere + throw ("$($_.Exception.Message)$removed " + + "$(Disable-RefusedService -ServiceName $ServiceName -Consequence 'it has no custody directory to write its store key file in')") + } try { Set-CustodyDirAcl -Path $CustodyDir -Account $ServiceAccount } catch { $removed = Remove-CustodyDirMadeHere -Path $CustodyDir -MadeHere:$CustodyDirMadeHere @@ -3632,8 +3654,9 @@ if ($HostCustody) { if ($replacedCustodyDir -and -not $CustodyDirNamed) { Write-Warning ("The service's MEFOR_CUSTODY_DIRECTORY named '$replacedCustodyDir' and now " + "names '$CustodyDir', as -CustodyDir asked. The engine reads no key file from the old " + - "directory. If master.key or handoff.key is there, do not delete it; follow " + - "docs/SERVICE.md 'Reinstalling over a kept custody directory'.") + "directory. Leave every key file there where it is, and delete nothing: a master.key " + + "or handoff.key there may be the only copy of a store's key on this host. Then follow " + + "docs/SERVICE.md 'When a refusal names master.key or handoff.key'.") } Write-Host " Custody: '$CustodyDir', named to the service as MEFOR_CUSTODY_DIRECTORY (docs/SERVICE.md)." } diff --git a/scripts/service/uninstall-service.ps1 b/scripts/service/uninstall-service.ps1 index 211ad51cdd..79988cc49a 100644 --- a/scripts/service/uninstall-service.ps1 +++ b/scripts/service/uninstall-service.ps1 @@ -288,6 +288,9 @@ function Get-UninstallResidueNotice { [string]$CustodyDir, # The key files found in it, master.key or handoff.key, read before the notice. [string[]]$CustodyFiles = @(), + # The directory could not be read as there, so $CustodyFiles may be missing a key file: at + # least a drive that is offline, which reads as absent without an error. + [switch]$CustodyUnconfirmed, # Measured from the config dir's own ACL, not assumed from a switch this script never saw. [switch]$ConfigInheritanceStripped, # Path of the nssm.exe the registration starts, only when it is actually on disk. @@ -366,9 +369,15 @@ function Get-UninstallResidueNotice { $lines += " this host: never delete it. It keeps its own entry for $who," $lines += " which -RemoveAccountAces does not take off the file." } + if ($CustodyUnconfirmed) { + # A drive that is offline reads as absent, so not finding a file proves nothing. + $lines += " This script could not confirm what it holds. It may still" + $lines += " hold master.key or handoff.key, the store's key and maybe" + $lines += " its only copy on this host: never delete either." + } $lines += " A reinstall refuses this directory while the new service does" - $lines += " not name it: see docs/SERVICE.md 'Reinstalling over a kept" - $lines += " custody directory'." + $lines += " not name it: see docs/SERVICE.md 'When a refusal names" + $lines += " master.key or handoff.key'." } if ($CachedNssm) { @@ -980,11 +989,16 @@ $custodyAceRemoved = $false # Which key files the custody directory holds, so the notice names only those (vault BACKLOG #3411). # A read that fails, such as a drive that is gone, must not stop the uninstall before its notice. $custodyFiles = @() +# Test-Path reads an offline drive, or a folder this account cannot see, as absent without an +# error, so the notice keeps its warning unless the directory itself is read as there. +$custodyUnconfirmed = $false if ($custodyDir) { try { + $custodyUnconfirmed = -not (Test-Path -LiteralPath $custodyDir -PathType Container) $custodyFiles = @(foreach ($name in @("master.key", "handoff.key")) { if (Test-Path -LiteralPath ([IO.Path]::Combine($custodyDir, $name))) { $name } }) } catch { + $custodyUnconfirmed = $true $unreadable += ("the key files in the custody directory '$custodyDir' ($($_.Exception.Message)) " + "- check it for master.key and handoff.key, and do not delete either") } @@ -1039,6 +1053,7 @@ Get-UninstallResidueNotice ` -SecretsDir $secretsDir ` -CustodyDir $custodyDir ` -CustodyFiles $custodyFiles ` + -CustodyUnconfirmed:$custodyUnconfirmed ` -ConfigInheritanceStripped:$configProtected ` -CachedNssm $cachedNssm ` -WerImages $werImages ` diff --git a/tests/test_install_service_custody.py b/tests/test_install_service_custody.py index 1af7fc0741..d0f3a75d02 100644 --- a/tests/test_install_service_custody.py +++ b/tests/test_install_service_custody.py @@ -301,8 +301,8 @@ def test_the_installer_makes_and_names_the_custody_directory_under_the_host_prov tmp_path: Path, ) -> None: """CALL-SITE guard: the custody directory is judged with the secrets directory's rules before - NSSM is resolved, made restricted before the service is registered, restricted after the - secrets directory once the account resolves, and named to the service. Each step sits under + NSSM is resolved, and made restricted, restricted for the account and named to the service + after the secrets directory, once the service is registered. Each step sits under the host provider's branch, and -CustodyDir is refused without it.""" facts = _preflight_facts(tmp_path) # Read by line: the call offsets count the file's own line endings, which read_text folds. @@ -328,7 +328,9 @@ def test_the_installer_makes_and_names_the_custody_directory_under_the_host_prov ) host = _sole_call(facts, "Get-HostCustodyAccountProblem") assert host["start"] < check["start"] < nssm - assert creates["start"] < registered < secrets_lock["start"] < lock["start"] < named["start"] + # Made just before it is restricted and named (review round-001caa04b0 item 5), so a refusal + # earlier in the run leaves no folder the service does not name for the next run to refuse. + assert registered < secrets_lock["start"] < creates["start"] < lock["start"] < named["start"] # Each act is inside an `if ($HostCustody)` block. lines = text.splitlines() for call in (creates, lock, named): @@ -342,14 +344,21 @@ def test_the_installer_makes_and_names_the_custody_directory_under_the_host_prov flat = " ".join(text.split()) refusal = flat.index('throw ("Could not name the custody directory') assert "Disable-RefusedService" in flat[refusal : refusal + 600], flat[refusal : refusal + 600] - # Both custody refusals after registration remove only a directory this run made, and ask for - # a re-run; neither tells anyone to add the variable by hand or to remove a directory. + # A refusal while it is made disables the service too, and "made here" is read before the + # create, which succeeds on a folder already there. + made = flat.index("$CustodyDirMadeHere = -not (Test-Path -LiteralPath $CustodyDir)") + create = flat.index('New-RestrictedDirectory -Path $CustodyDir -What "the custody directory"') + assert made < create, (made, create) + window = flat[create : flat.index("Set-CustodyDirAcl -Path $CustodyDir", create)] + assert "Disable-RefusedService" in window and "Remove-CustodyDirMadeHere" in window, window + # Each custody refusal after registration removes only a directory this run made; none + # tells anyone to add the variable by hand or to remove a directory. removals = [ c for c in facts["commands"] if c["name"] == "Remove-CustodyDirMadeHere" and c["start"] > registered ] - assert len(removals) == 2, removals + assert len(removals) == 3, removals assert all("-MadeHere:$CustodyDirMadeHere" in c["text"] for c in removals), removals naming = flat[refusal : refusal + 800] assert "Re-run the installer" in naming, naming @@ -382,6 +391,12 @@ def test_the_uninstaller_names_the_custody_directory_and_removes_its_grant( window = uninstall[uninstall.rindex("try {", 0, probe) : probe + 400] assert "[IO.Path]::Combine($custodyDir, $name)" in window and "$unreadable +=" in window, window assert "Join-Path $custodyDir" not in uninstall + # The warning stays unless the directory itself reads as there (review round-001caa04b0 item 6). + assert "-CustodyUnconfirmed:$custodyUnconfirmed" in notice["text"], notice["text"] + assert ( + "$custodyUnconfirmed = -not (Test-Path -LiteralPath $custodyDir -PathType Container)" + in uninstall + ) def test_the_uninstall_notice_says_what_the_custody_directory_keeps(tmp_path: Path) -> None: @@ -397,13 +412,23 @@ def test_the_uninstall_notice_says_what_the_custody_directory_keeps(tmp_path: Pa "handoff.key holds the store's key", "It keeps its own entry for 'NT SERVICE\\MessageFoundry'", "A reinstall refuses this directory", - "Reinstalling over a kept custody directory", + "When a refusal names master.key or handoff.key", ): assert needed in flat, (needed, flat) handoff_only = " ".join( _notice(tmp_path, {**_FULL_FACTS, "CustodyFiles": ["handoff.key"]}).split() ) - assert "handoff.key holds" in handoff_only and "master.key" not in handoff_only, handoff_only + assert "handoff.key holds" in handoff_only, handoff_only + assert "master.key holds" not in handoff_only, handoff_only + # Review round-001caa04b0 item 6: an offline drive reads as absent without an error, so a + # directory not read as there keeps the never-delete warning with no file named. The control: + # a directory read as there, holding neither file, carries no such warning. + warning = "It may still hold master.key or handoff.key" + unread = {**_FULL_FACTS, "CustodyFiles": [], "CustodyUnconfirmed": True} + unconfirmed = " ".join(_notice(tmp_path, unread).split()) + assert warning in unconfirmed and "never delete either" in unconfirmed, unconfirmed + read = " ".join(_notice(tmp_path, {**unread, "CustodyUnconfirmed": False}).split()) + assert warning not in read, read nobody = " ".join( _notice(tmp_path, {**both, "ServiceAccount": "", "ServiceAccountSid": ""}).split() ) @@ -419,10 +444,14 @@ def test_the_custody_directory_check_accepts_a_named_one_and_never_says_remove( """Get-CustodyDirProblem: a re-run over a service whose environment names the directory, with an owner each install sets (here this account, which an unelevated test can own), accepts it; the same directory the service does not name is refused without telling anyone to remove it. + An empty one is refused without being said to hold a key (review round-001caa04b0 item 5). Remove-CustodyDirMadeHere removes only a directory this run made that holds nothing.""" assert _SCRIPT is not None kept = tmp_path / "kept" kept.mkdir() + (kept / "master.key").write_bytes(b"k") + empty = tmp_path / "empty" + empty.mkdir() made = tmp_path / "made" made.mkdir() full = tmp_path / "full" @@ -435,6 +464,7 @@ def test_the_custody_directory_check_accepts_a_named_one_and_never_says_remove( [pscustomobject]@{{ named = [string](Get-CustodyDirProblem -Path {_psq(str(kept))} -ServiceName 'NoSuchSvc-w7' -Named -AcceptedOwners @($mySid)) unnamed = [string](Get-CustodyDirProblem -Path {_psq(str(kept))} -ServiceName 'NoSuchSvc-w7' -AcceptedOwners @($mySid)) + empty = [string](Get-CustodyDirProblem -Path {_psq(str(empty))} -ServiceName 'NoSuchSvc-w7' -AcceptedOwners @($mySid)) owner = [string](Get-CustodyDirProblem -Path {_psq(str(kept))} -ServiceName 'NoSuchSvc-w7' -Named) made = [string](Remove-CustodyDirMadeHere -Path {_psq(str(made))} -MadeHere) full = [string](Remove-CustodyDirMadeHere -Path {_psq(str(full))} -MadeHere) @@ -454,8 +484,13 @@ def test_the_custody_directory_check_accepts_a_named_one_and_never_says_remove( ] got = json.loads(_ok(_extract(_SCRIPT, names, body), tmp_path).strip().splitlines()[-1]) assert got["named"] == "", got - assert "does not name it" in got["unnamed"] and "do not delete" in got["unnamed"], got - assert not re.search(r"\bremov", got["unnamed"], re.IGNORECASE), got + assert "does not name it" in got["unnamed"] and "delete nothing" in got["unnamed"], got + assert "When a refusal names master.key or handoff.key" in got["unnamed"], got + assert "holds 1 item(s), such as 'master.key'" in got["unnamed"], got + assert "holds nothing" in got["empty"] and "may hold" not in got["empty"], got + assert "may be the only copy" not in got["empty"], got + for text in (got["unnamed"], got["empty"]): + assert not re.search(r"\bremov", text, re.IGNORECASE), text assert "owner" in got["owner"], got # the control: this account is not an install's owner assert not made.exists() and "was removed" in got["made"], got assert (full / "master.key").exists() and got["full"] == "", got diff --git a/tests/test_store_custody_host.py b/tests/test_store_custody_host.py index 807b2fc5ae..916a406493 100644 --- a/tests/test_store_custody_host.py +++ b/tests/test_store_custody_host.py @@ -308,7 +308,7 @@ def test_a_key_file_left_in_the_secrets_directory_is_not_taken_for_no_key(tmp_pa secrets = _own_custody_directory(tmp_path / "secrets") (secrets / "handoff.key").write_bytes(b"not read") environ = {"MEFOR_CUSTODY_DIRECTORY": str(custody_dir), "MEFOR_SECRETS_DIRECTORY": str(secrets)} - with pytest.raises(HostCustodyRefused, match="move that file into") as refused: + with pytest.raises(HostCustodyRefused, match="host custody was found elsewhere") as refused: load_host_custody(_settings(tmp_path), enforcing=True, environ=environ) assert not isinstance(refused.value, HostCustodyMissing) assert f"handoff.key in {secrets}" in str(refused.value) @@ -318,12 +318,12 @@ def test_a_key_file_left_in_the_secrets_directory_is_not_taken_for_no_key(tmp_pa load_host_custody( _settings(tmp_path), enforcing=True, environ={"MEFOR_SECRETS_DIRECTORY": str(secrets)} ) - assert "move that file into" not in str(read.value) + assert "host custody was found elsewhere" not in str(read.value) # With no secrets directory, beside a SQLite store, where a mint with neither variable writes. (secrets / "handoff.key").unlink() beside = tmp_path / "handoff.key" beside.write_bytes(b"not read") - with pytest.raises(HostCustodyRefused, match="move that file into") as refused: + with pytest.raises(HostCustodyRefused, match="host custody was found elsewhere") as refused: load_host_custody( _settings(tmp_path), enforcing=True, @@ -331,7 +331,7 @@ def test_a_key_file_left_in_the_secrets_directory_is_not_taken_for_no_key(tmp_pa ) assert f"{beside.name} in {beside.parent}" in str(refused.value) # A mint is stopped the same way, before anything is minted. - with pytest.raises(HostCustodyRefused, match="move that file into"): + with pytest.raises(HostCustodyRefused, match="host custody was found elsewhere"): mint_target( _settings(tmp_path), service_account=None, @@ -369,9 +369,9 @@ def test_a_file_beside_the_store_refuses_another_provider_and_the_way_on_leaves_ tmp_path: Path, ) -> None: """A host mint with neither variable writes beside the store, so a file there refuses another - provider whatever is set. The refusal names the file, tells nobody to change it, and its way - on, a copy of the database in a directory that holds no key file, clears it with the file - still where it was.""" + provider whatever is set. The refusal names the file and tells nobody to change it, and its + way on for a file that is not this store's, docs/SERVICE.md's new data directory, clears it + with the file still where it was.""" secrets = _own_custody_directory(tmp_path / "secrets") beside = tmp_path / "master.key" beside.write_bytes(b"not read") @@ -382,9 +382,9 @@ def test_a_file_beside_the_store_refuses_another_provider_and_the_way_on_leaves_ } refusal = foreign_custody_refusal(settings, environ=environ) assert refusal is not None and f"master.key in {tmp_path}" in refusal, refusal - assert "leave it where it is" in refusal, refusal + assert "where it is, and delete nothing" in refusal, refusal assert not _advises_changing(refusal, allowed=(_KEY_SETTINGS_OUT,)), refusal - # Following it: the store's database copied into a new directory, and the store pointed there. + # Following it: the store in a new data directory that holds neither file. copied = _own_custody_directory(tmp_path / "copied") moved_store = settings.model_copy(update={"path": str(copied / "store.db")}) assert foreign_custody_refusal(moved_store, environ=environ) is None @@ -406,7 +406,7 @@ def test_the_other_provider_refusal_keeps_its_text_through_the_key_seams( seam(settings) text = str(refused.value) assert f"master.key in {tmp_path}" in text, (seam.__name__, text) - assert "leave it where it is" in text, (seam.__name__, text) + assert "where it is, and delete nothing" in text, (seam.__name__, text) @pytest.mark.parametrize("where", ["same", "inside", "around"]) @@ -442,7 +442,7 @@ def test_the_stores_own_key_file_beside_it_is_not_taken_for_a_host_blob(tmp_path def test_the_left_behind_refusal_gives_a_way_on_that_leaves_another_stores_file( tmp_path: Path, ) -> None: - """The move is offered only for a file that is this store's; otherwise the way on leaves it.""" + """The refusal names the file and leaves it, and its way on is docs/SERVICE.md's procedure.""" custody_dir = _own_custody_directory(tmp_path / "custody") (tmp_path / "handoff.key").write_bytes(b"not read") with pytest.raises(HostCustodyRefused) as refused: @@ -452,7 +452,115 @@ def test_the_left_behind_refusal_gives_a_way_on_that_leaves_another_stores_file( environ={"MEFOR_CUSTODY_DIRECTORY": str(custody_dir)}, ) text = str(refused.value) - assert "If none is this store's" in text and "leave it where it is" in text, text + assert f"handoff.key in {tmp_path}" in text, text + assert custody_host._LEAVE_KEY_FILES_STEP in text, text + assert not _advises_changing(text), text + + +def _service_md_section(title: str) -> str: + """The text of docs/SERVICE.md's section headed ``title``, up to the next heading of its level + or above; fails when no such heading is there.""" + text = (Path(__file__).resolve().parents[1] / "docs" / "SERVICE.md").read_text(encoding="utf-8") + lines = text.splitlines() + heads = [i for i, line in enumerate(lines) if line.lstrip("#").strip() == title] + assert len(heads) == 1 and lines[heads[0]].startswith("#"), (title, heads) + level = len(lines[heads[0]]) - len(lines[heads[0]].lstrip("#")) + body = [] + for line in lines[heads[0] + 1 :]: + if line.startswith("#") and len(line) - len(line.lstrip("#")) <= level: + break + body.append(line) + return "\n".join(body) + + +def test_each_key_file_refusal_points_at_one_service_md_procedure_and_states_no_file_steps( + tmp_path: Path, +) -> None: + """Manager design rule 2026-11-22 (vault BACKLOG #3411): a refusal that found a key file it + cannot tie to this store names it, says to leave every key file and delete nothing, and points + at one docs/SERVICE.md procedure by its title, which is there. It carries no file procedure of + its own: no copy of a directory's contents, no move. The other-provider refusal's closing is + that procedure, not keep_the_key_step's new-secrets-directory step, which does not clear a + file beside the store (review round-001caa04b0 item 3).""" + title = custody_host._SERVICE_PROCEDURE_TITLE + assert f"'{title}'" in custody_host._LEAVE_KEY_FILES_STEP + (tmp_path / "master.key").write_bytes(b"not read") + settings = _settings(tmp_path, key_provider="auto", encryption_key_file="k.bin") + foreign = foreign_custody_refusal(settings, environ={}) + custody_dir = _own_custody_directory(tmp_path / "custody") + with pytest.raises(HostCustodyRefused) as refused: + load_host_custody( + _settings(tmp_path), + enforcing=True, + environ={"MEFOR_CUSTODY_DIRECTORY": str(custody_dir)}, + ) + assert foreign is not None + for text in (foreign, str(refused.value)): + flat = " ".join(text.split()) + assert f"master.key in {tmp_path}" in flat, flat + assert "Leave each key file named here where it is, and delete nothing" in flat, flat + assert f"docs/SERVICE.md, '{title}'" in flat, flat + for step in ("copy everything", "copy into it", "same volume", "move that file"): + assert step not in flat, (step, flat) + assert "To go on without it" not in foreign, foreign + assert custody_host.keep_the_key_step(settings, new_store=False) not in foreign, foreign + # The procedure states what clears each place: a new data directory for a file beside the + # store, and the move rule within one volume and across volumes. + section = " ".join(_service_md_section(title).split()) + for needed in ("-DataDir", "-SecretsDir", "-CustodyDir", "Delete nothing", "Across volumes"): + assert needed in section, (needed, section) + + +def test_the_custody_and_secrets_overlap_is_compared_where_each_resolves(tmp_path: Path) -> None: + """Review round-001caa04b0 item 4: a custody directory reached through a link into the secrets + directory, or spelled in another case where the platform folds case, is refused; the control is + a sibling reached the same way.""" + secrets = tmp_path / "secrets" + secrets.mkdir() + alias = tmp_path / "alias" + if sys.platform == "win32": + import _winapi + + _winapi.CreateJunction(str(secrets), str(alias)) + else: + alias.symlink_to(secrets, target_is_directory=True) + linked = {"MEFOR_SECRETS_DIRECTORY": str(secrets), "MEFOR_CUSTODY_DIRECTORY": str(alias / "c")} + refusal = custody_host._own_directory_refusal(linked) + assert refusal is not None and "is, holds or sits inside" in refusal, refusal + sibling = tmp_path / "sibling" + sibling.mkdir() + (tmp_path / "other").mkdir() + if sys.platform == "win32": + _winapi.CreateJunction(str(sibling), str(tmp_path / "salias")) + else: + (tmp_path / "salias").symlink_to(sibling, target_is_directory=True) + control = {**linked, "MEFOR_CUSTODY_DIRECTORY": str(tmp_path / "salias" / "c")} + assert custody_host._own_directory_refusal(control) is None + if os.path.normcase("A") == os.path.normcase("a"): + cased = {**linked, "MEFOR_CUSTODY_DIRECTORY": str(secrets).upper() + os.sep + "c"} + assert custody_host._own_directory_refusal(cased) is not None + + +def test_the_custody_texts_name_the_directory_variables_as_literals() -> None: + """Review round-001caa04b0 item 11: a variable name reaching stderr is written as a literal, + never through SECRETS_DIRECTORY_VARIABLE (CodeQL alert 315 reads that constant as a secret). + The literals are pinned to the constants the engine reads.""" + from messagefoundry.engine_secrets import ( + CUSTODY_DIRECTORY_VARIABLE, + SECRETS_DIRECTORY_VARIABLE, + ) + + source = Path(custody_host.__file__).read_text(encoding="utf-8") + for constant in ("SECRETS_DIRECTORY_VARIABLE", "CUSTODY_DIRECTORY_VARIABLE"): + assert "{" + constant + "}" not in source, constant + assert (SECRETS_DIRECTORY_VARIABLE, CUSTODY_DIRECTORY_VARIABLE) == ( + "MEFOR_SECRETS_DIRECTORY", + "MEFOR_CUSTODY_DIRECTORY", + ) + with pytest.raises(HostCustodyRefused, match="^MEFOR_CUSTODY_DIRECTORY must be an absolute"): + custody_host.custody_directory( + StoreSettings(), environ={"MEFOR_CUSTODY_DIRECTORY": "relative"} + ) def test_a_relative_secrets_variable_counts_as_unset_for_the_search( @@ -483,11 +591,11 @@ def test_the_left_behind_check_reads_beside_the_store_with_both_variables_set( beside = tmp_path / "handoff.key" beside.write_bytes(b"not read") both = {"MEFOR_CUSTODY_DIRECTORY": str(custody_dir), "MEFOR_SECRETS_DIRECTORY": str(secrets)} - with pytest.raises(HostCustodyRefused, match="move that file into") as refused: + with pytest.raises(HostCustodyRefused, match="host custody was found elsewhere") as refused: load_host_custody(_settings(tmp_path), enforcing=True, environ=both) assert not isinstance(refused.value, HostCustodyMissing) assert f"handoff.key in {tmp_path}" in str(refused.value), refused.value - with pytest.raises(HostCustodyRefused, match="move that file into"): + with pytest.raises(HostCustodyRefused, match="host custody was found elsewhere"): mint_target(_settings(tmp_path), service_account=None, enforcing=True, environ=both) with pytest.raises(HostCustodyMissing): load_host_custody( @@ -605,8 +713,8 @@ async def test_a_host_blob_refuses_every_other_key_provider(tmp_path: Path, name assert condition < low.index(keep), refusal assert ". " not in low[condition : low.index(_KEY_SETTINGS_OUT)], refusal assert not _advises_changing(refusal, allowed=(_KEY_SETTINGS_OUT,)), refusal - assert custody_host.keep_the_key_step(settings, new_store=False) in refusal, refusal - # The file is left in place, and the way on runs the store from somewhere else (Manager + assert custody_host.keep_the_key_step(settings, new_store=False) not in refusal, refusal + # The file is left in place, and the way on is docs/SERVICE.md's procedure (Manager # ruling 2026-11-22, vault BACKLOG #3411). assert custody_host._LEAVE_KEY_FILES_STEP in refusal, refusal assert "mints this store's key" not in refusal, refusal # only the host provider mints @@ -2065,9 +2173,10 @@ async def _never_started_pin_text(directory: Path) -> str: return str(refused.value) -#: Phrases the guard takes out of every text first: one reports what failed, and one forbids a -#: change (the kept-key warning's "Keep both, and do not delete either"). -_NOT_CHANGING_WHAT_EXISTS = ("could not be removed", "do not delete either") +#: Phrases the guard takes out of every text first: one reports what failed, and the others forbid +#: a change (the kept-key warning's "Keep both, and do not delete either", and the key-file +#: refusals' "and delete nothing"). +_NOT_CHANGING_WHAT_EXISTS = ("could not be removed", "do not delete either", "and delete nothing") #: foreign_custody_refusal's own remedy, which changes settings only. Allowed for that text alone. _KEY_SETTINGS_OUT = "remove every other store key setting" @@ -2360,7 +2469,7 @@ def _held(self: Path, missing_ok: bool = False) -> None: (fallback, "run with the custody directory that holds the store's host blob"), ("which names the way on",), (fallback,), - (fallback, "set [store].key_provider = 'host'", "leave it where it is"), + ("set [store].key_provider = 'host'", "where it is, and delete nothing", "docs/SERVICE.md"), (fallback, "leaves it in place"), ("Run the command again with that file in place",), (fallback, "This run minted it and nothing was written under it"), From 09b6d4c75f4136c70d8722c2e57c1614ffaa1ae1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 21:01:45 -0600 Subject: [PATCH 18/28] Key custody: review round-0c8608ba47 repairs (unsafe advice, a false claim) Vault BACKLOG #3411 slice B3c, design note 1. - The secrets-directory texts that say to delete or remove files (the -SecretsDir change warning, the existing-directory refusal, the squatter refusal and the uninstall notice) carve out master.key and handoff.key and point at the SERVICE.md procedure, which now sends operators there. - The procedure says what to do once the service has started from a cross-volume copy, how a store switching to the host provider gets its file where that provider reads it, and how to go on without the install scripts, as on Linux. - The leave-in-place step says to change a key file only as the procedure says, and the ADR amendment no longer says the way on changes no file. - The installer marks the custody directory as made by this run only after New-RestrictedDirectory's read-back, so a folder someone made in between is never removed as this run's. - SERVICE.md's custody sections follow the provisioning text they had split. --- docs/SERVICE.md | 55 +++++++++++++------ ...-for-the-engine-s-secret-class-settings.md | 3 +- messagefoundry/store/custody_host.py | 15 +++-- scripts/service/install-service.ps1 | 23 ++++++-- scripts/service/uninstall-service.ps1 | 5 +- tests/test_install_service_custody.py | 34 ++++++++++-- 6 files changed, 99 insertions(+), 36 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index a151985f50..4079d258d7 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -246,6 +246,21 @@ Administrator from an elevated shell on the host: messagefoundry provision-admin --username --email
--db C:\ProgramData\MessageFoundry\messagefoundry.db ``` +If the service started first, at the shipped posture it refuses to start. Once the earlier start +checks pass (the store key and `[alerts]` among them), that refusal names `provision-admin` in the +log; run the command, then restart the service. In the data directory the install script hardens, +the service account and the operator can both open the store, in either order. The rules are in +[SECURITY.md](SECURITY.md#provisioning-the-first-administrator-asvs-632). + +> **Migration note (ADR 0050, `--project-root`).** `serve`/`supervise --project-root R` now anchors the +> **whole** config bundle under `R` — the `--config` graph, `environments/.toml`, `messagefoundry.toml`, +> **and** a relative `[store].path` / `--db` (and each shard's `_.db`). Previously only +> `environments/` was anchored; a relative DB resolved against the process CWD. If you already run with +> `--project-root` **and** a relative DB path, the DB will now be found/created under `R` — pass an +> **absolute** `[store].path` / `--db` to keep it in place (absolute paths bypass the root), or accept the +> new location. The startup CWD-mismatch WARNING names the resolved paths so any move is visible. Deployments +> without `--project-root`, or with an absolute DB path, are unchanged. + Under `[store].key_provider = 'host'` (vault BACKLOG #3411) the service cannot run as SYSTEM, LOCAL SERVICE or NETWORK SERVICE: that provider refuses them as the engine account. When the install script reads that setting, from the settings file as its `Get-SettingsKeyProvider` @@ -303,21 +318,6 @@ to the same path, so the handoff lands where the service looks: $env:MEFOR_CUSTODY_DIRECTORY = 'C:\ProgramData\MessageFoundry-custody' ``` -If the service started first, at the shipped posture it refuses to start. Once the earlier start -checks pass (the store key and `[alerts]` among them), that refusal names `provision-admin` in the -log; run the command, then restart the service. In the data directory the install script hardens, -the service account and the operator can both open the store, in either order. The rules are in -[SECURITY.md](SECURITY.md#provisioning-the-first-administrator-asvs-632). - -> **Migration note (ADR 0050, `--project-root`).** `serve`/`supervise --project-root R` now anchors the -> **whole** config bundle under `R` — the `--config` graph, `environments/.toml`, `messagefoundry.toml`, -> **and** a relative `[store].path` / `--db` (and each shard's `_.db`). Previously only -> `environments/` was anchored; a relative DB resolved against the process CWD. If you already run with -> `--project-root` **and** a relative DB path, the DB will now be found/created under `R` — pass an -> **absolute** `[store].path` / `--db` to keep it in place (absolute paths bypass the root), or accept the -> new location. The startup CWD-mismatch WARNING names the resolved paths so any move is visible. Deployments -> without `--project-root`, or with an absolute DB path, are unchanged. - #### When a refusal names master.key or handoff.key This is the one procedure for going on past a refusal that names `master.key` or `handoff.key`, the @@ -329,13 +329,19 @@ directory the service does not name, as after an uninstall. Neither the engine n tell whose key a file holds, and either file may be the only copy of a store's key on this host. 1. **Delete nothing, and leave every key file where it is**, in every directory the refusal names, - unless step 3 sends you to move one; then move it only as step 5 says. + unless step 3 sends you to move one; then move it only as step 5 says, which also says when an + original may go. 2. **Stop the service** (`Stop-Service `) if it is installed, and work from an elevated shell. 3. **If the file holds this store's key**, as when this store was set up under `[store].key_provider = 'host'`: - When the refusal says `[store].key_provider` is another provider, make the settings change - the refusal names. No file moves. + the refusal names. That provider reads the file only from the custody directory + `MEFOR_CUSTODY_DIRECTORY` names, else the one `MEFOR_SECRETS_DIRECTORY` names, else beside a + SQLite store, and needs to add a file there. So, under the install script, re-run it once the + settings name that provider, which makes the custody directory and names it to the service + ([The custody directory](#the-custody-directory-under-the-host-key-provider)), and move the + file into it as step 5 says. - When the file sits outside the custody directory the service names, move it into that directory as step 5 says. - When the install script refuses a kept custody directory, re-run it with `-CustodyDir` naming @@ -368,9 +374,22 @@ tell whose key a file holds, and either file may be the only copy of a store's k `icacls ` prints the same entries for the copy as for the original, and that `(Get-Acl -LiteralPath ).Owner` prints the same owner, and keep the original where it is until the service has started and opened its store from the copy. Copy the database files - across volumes the same way, and keep their originals until then too. + across volumes the same way, and keep their originals until then too. Once it has, delete each + original as an administrator: a second copy of a key file is a second place the key can be + read from, a `handoff.key` on this machine by any account, and the database originals may + hold PHI, disposed of as [PHI.md](PHI.md) describes. 6. **Start the service**, and read its log for a refusal ([Verify it's running](#verify-its-running)). +**Without the install scripts**, as on Linux or in a container, the same steps hold with the +engine stopped in place of the service: leave every key file and delete nothing; for a file that +is this store's, make the settings change and put the file where the host provider reads it; for +one that is not, run the store from a new, empty data directory for a file beside it, or set the +variable that names the file's directory, `MEFOR_SECRETS_DIRECTORY` or `MEFOR_CUSTODY_DIRECTORY`, +to a new directory owned by the account the engine runs as, mode 0700, in a folder only that +account or root may write, and add the engine's other secret files to a new secrets directory. A move +within one file system keeps the file's owner and mode; across file systems, copy it keeping them +(`cp -p`, as root), and keep the original until the engine has opened its store from the copy. + ## Update to a new build (restart vs reinstall) The service runs `\Scripts\python.exe -I -X disable-remote-debug -m messagefoundry diff --git a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md index 5b686228b5..e7fee3dbe0 100644 --- a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md +++ b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md @@ -168,7 +168,8 @@ names ADR 0019 declared and nobody built. Also not moved: the store key's own re handoff in this directory or beside a SQLite store refuses a read and a mint, so one made without the variable is not taken for no key; and the check that refuses another key provider beside a host file or handoff looks in at least the custody directory, this directory and the - place beside a SQLite store, whatever is set; its way on leaves every file it finds in place. + place beside a SQLite store, whatever is set. Its refusal deletes no file it finds and moves + none, and points at the one procedure in docs/SERVICE.md that says when a key file may move. `install-service.ps1` makes the custody directory only when it reads that provider, and names it to the service as `MEFOR_CUSTODY_DIRECTORY`. docs/SERVICE.md, *The custody directory under the host key provider*, states its location, its access list and the rest, and is the record diff --git a/messagefoundry/store/custody_host.py b/messagefoundry/store/custody_host.py index 83f1cf8b26..6fe7bb4c5e 100644 --- a/messagefoundry/store/custody_host.py +++ b/messagefoundry/store/custody_host.py @@ -325,8 +325,9 @@ def foreign_custody_refusal( the blob minted for it. A directory setting that is not an absolute path is passed over here, and the directories the other setting names are still looked in. - The way on changes no file it found (PR 2804 fifth hold; Manager ruling 2026-11-22): after the - settings change for a blob that holds this store's key, :data:`_LEAVE_KEY_FILES_STEP`.""" + The way on deletes no file it found and moves none itself (PR 2804 fifth hold; Manager ruling + 2026-11-22): after the settings change for a blob that holds this store's key, + :data:`_LEAVE_KEY_FILES_STEP`.""" environ = os.environ if environ is None else environ found = _key_files_outside(settings, None, environ) if settings.encryption_key_file: @@ -356,12 +357,14 @@ def foreign_custody_refusal( _SERVICE_PROCEDURE_TITLE = "When a refusal names master.key or handoff.key" #: The way on from a refusal that found a key file it cannot tie to this store -#: (:func:`foreign_custody_refusal`, :func:`_left_outside_the_custody_directory`). It changes no -#: file: each may be another store's only key. +#: (:func:`foreign_custody_refusal`, :func:`_left_outside_the_custody_directory`). It deletes no +#: file and moves none itself, since each may be another store's only key: the procedure it names +#: says when a file may move, whether or not it is this store's, and covers a host without the +#: install scripts too. _LEAVE_KEY_FILES_STEP = ( "Leave each key file named here where it is, and delete nothing: each may be the only copy of " - "a store's key on this host. To go on, follow docs/SERVICE.md, " - f"'{_SERVICE_PROCEDURE_TITLE}'" + "a store's key on this host. To go on, whether or not it is this store's, follow " + f"docs/SERVICE.md, '{_SERVICE_PROCEDURE_TITLE}', and change a key file only as it says" ) diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index efc76cb19d..371cb1db4f 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -984,7 +984,11 @@ function New-RestrictedDirectory { "Check who made it. Leave every key file in it where it is, and delete nothing: a " + "master.key or handoff.key there may be the only copy of a store's key on this " + "host. Then follow docs/SERVICE.md 'When a refusal names master.key or handoff.key'." - } else { "Remove it, check who made it, and re-run the installer." } + } else { + "Remove it, check who made it, and re-run the installer. If it holds master.key or " + + "handoff.key, do not remove it or delete either file: follow docs/SERVICE.md 'When " + + "a refusal names master.key or handoff.key'." + } throw ("'$Path' was there before this install made it (its owner is $owner), so it is not " + "the restricted folder the install asked for. $remedy") } @@ -3021,7 +3025,10 @@ $SecretsDirNamed = [bool]$RegisteredSecretsDir -and ($RegisteredSecretsDir.TrimE if (-not $secretsProblem -and (Test-Path -LiteralPath $SecretsDir)) { if (-not $SecretsDirNamed) { $secretsProblem = ("it already exists and the service does not name it. Remove it, check who " + - "made it, and re-run the installer, which then makes it restricted") + "made it, and re-run the installer, which then makes it restricted. If it holds " + + "master.key or handoff.key, which may be the only copy of a store's key on this host, " + + "do not remove it or delete either file: pass -SecretsDir naming a new folder, and " + + "follow docs/SERVICE.md 'When a refusal names master.key or handoff.key'") } else { $owner = (Get-Acl -LiteralPath $SecretsDir).GetOwner([Security.Principal.SecurityIdentifier]).Value if ($owner -ne "S-1-5-32-544" -and $owner -ne "S-1-5-18") { @@ -3589,7 +3596,10 @@ try { Write-Warning ("The service's MEFOR_SECRETS_DIRECTORY named '$replacedSecretsDir' and now names " + "'$SecretsDir', as -SecretsDir asked. Copy each file from the old directory, never move " + "it: a moved file keeps its old access list, not the new directory's. Then delete the old " + - "files, and remove the service account's grant there.") + "files you copied, and remove the service account's grant there. Leave a master.key or " + + "handoff.key there where it is, and delete neither: either may be the only copy of a " + + "store's key on this host, and docs/SERVICE.md 'When a refusal names master.key or " + + "handoff.key' says how to go on.") } Write-Host " Secrets: '$SecretsDir', named to the service as MEFOR_SECRETS_DIRECTORY (docs/SERVICE.md)." } catch { @@ -3612,9 +3622,12 @@ if ($HostCustody) { $CustodyParent = Split-Path -Parent $CustodyDir if (-not (Test-Path -LiteralPath $CustodyParent)) { New-AdminOnlyFolder -Path $CustodyParent } if (-not $CustodyDirNamed -or -not (Test-Path -LiteralPath $CustodyDir)) { - # Read before the call: CreateDirectory succeeds on a folder that is already there. - $CustodyDirMadeHere = -not (Test-Path -LiteralPath $CustodyDir) + # Read before the call, since CreateDirectory succeeds on a folder that is already + # there, and set only once the call has read back the owner it asked for: a folder + # someone made in between fails that read-back, and is not this run's to remove. + $custodyExisted = Test-Path -LiteralPath $CustodyDir New-RestrictedDirectory -Path $CustodyDir -What "the custody directory" + $CustodyDirMadeHere = -not $custodyExisted $custodyHeld = @(Get-ChildItem -LiteralPath $CustodyDir -Force -ErrorAction Stop) if ($custodyHeld.Count -ne 0) { throw ("-CustodyDir '$CustodyDir' cannot be the custody directory: it holds " + diff --git a/scripts/service/uninstall-service.ps1 b/scripts/service/uninstall-service.ps1 index 79988cc49a..d63f4bc729 100644 --- a/scripts/service/uninstall-service.ps1 +++ b/scripts/service/uninstall-service.ps1 @@ -356,7 +356,10 @@ function Get-UninstallResidueNotice { $lines += " Secrets dir $SecretsDir" $lines += " The secrets directory the service read: any file in it holds" $lines += " a secret in plain text. This script leaves it and its files." - $lines += " Delete them once nothing needs them." + $lines += " Delete them once nothing needs them, except master.key and" + $lines += " handoff.key: either may be a store's only key on this host," + $lines += " so never delete either. See docs/SERVICE.md 'When a refusal" + $lines += " names master.key or handoff.key'." } if ($CustodyDir) { diff --git a/tests/test_install_service_custody.py b/tests/test_install_service_custody.py index d0f3a75d02..fe0c25a963 100644 --- a/tests/test_install_service_custody.py +++ b/tests/test_install_service_custody.py @@ -344,11 +344,13 @@ def test_the_installer_makes_and_names_the_custody_directory_under_the_host_prov flat = " ".join(text.split()) refusal = flat.index('throw ("Could not name the custody directory') assert "Disable-RefusedService" in flat[refusal : refusal + 600], flat[refusal : refusal + 600] - # A refusal while it is made disables the service too, and "made here" is read before the - # create, which succeeds on a folder already there. - made = flat.index("$CustodyDirMadeHere = -not (Test-Path -LiteralPath $CustodyDir)") + # A refusal while it is made disables the service too. Whether it was there is read before the + # create, which succeeds on a folder already there, and "made here" is set only after the + # create's read-back, so a folder someone made in between is never removed as this run's. + made = flat.index("$custodyExisted = Test-Path -LiteralPath $CustodyDir") create = flat.index('New-RestrictedDirectory -Path $CustodyDir -What "the custody directory"') - assert made < create, (made, create) + marked = flat.index("$CustodyDirMadeHere = -not $custodyExisted") + assert made < create < marked, (made, create, marked) window = flat[create : flat.index("Set-CustodyDirAcl -Path $CustodyDir", create)] assert "Disable-RefusedService" in window and "Remove-CustodyDirMadeHere" in window, window # Each custody refusal after registration removes only a directory this run made; none @@ -434,7 +436,7 @@ def test_the_uninstall_notice_says_what_the_custody_directory_keeps(tmp_path: Pa ) assert "entry for ''" not in nobody and "the account the service ran as" in nobody, nobody without = " ".join(_notice(tmp_path, {**_FULL_FACTS, "CustodyDir": ""}).split()) - assert "handoff.key" not in without and "Custody" not in without, without + assert "handoff.key holds" not in without and "Custody" not in without, without @_windows_only @@ -495,3 +497,25 @@ def test_the_custody_directory_check_accepts_a_named_one_and_never_says_remove( assert not made.exists() and "was removed" in got["made"], got assert (full / "master.key").exists() and got["full"] == "", got assert other.exists() and got["other"] == "", got + + +def test_the_secrets_directory_texts_never_send_a_key_file_to_be_deleted(tmp_path: Path) -> None: + """Review round-0c8608ba47 item 1: docs/SERVICE.md's key-file procedure sends an operator to a + new -SecretsDir, and the custody files may sit in the secrets directory, so each installer and + uninstaller text that says to delete or remove the secrets directory or its files carves out + master.key and handoff.key and points at that procedure.""" + from tests.test_service_install_manifest import _FULL_FACTS, _notice + + # The script's string pieces joined, so a sentence split over `" +` lines reads whole. + joined = re.sub(r'"\s*\+\s*"', "", " ".join(_script_text().split())) + title = "When a refusal names master.key or handoff.key" + for start in ( + "Then delete the old files you copied", + "it already exists and the service does not name it. Remove it, check who made it", + "Remove it, check who made it, and re-run the installer. If it holds master.key", + ): + window = joined[joined.index(start) : joined.index(start) + 500] + assert "handoff.key" in window and title in window, window + notice = " ".join(_notice(tmp_path, {**_FULL_FACTS, "CustodyDir": ""}).split()) + assert "except master.key and handoff.key" in notice, notice + assert "never delete either" in notice, notice From 3bb69a0e7033016aa96ff655b0ebcb2e5c02602a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 21:35:16 -0600 Subject: [PATCH 19/28] Key custody: review round-ba0f0fa1e7 repairs (unsafe advice, false control claims) Vault BACKLOG #3411 slice B3c, design note 1. - The -SecretsDir change warning carves out master.key and handoff.key before it says to copy and delete the old files. - The secrets directory's existing-directory, squatter and held-files refusals list the folder, and say no remove when it holds a key file or cannot be listed; they point at the SERVICE.md procedure instead. - engine_secrets no longer says the host provider checks a key file in the secrets directory while MEFOR_CUSTODY_DIRECTORY names another one. - The overlap check's docstring names the UNC spelling it does not catch. - SERVICE.md says the custody read-back accepts SYSTEM as the owner too. --- docs/SERVICE.md | 2 +- messagefoundry/engine_secrets.py | 9 +++-- messagefoundry/store/custody_host.py | 6 ++- scripts/service/install-service.ps1 | 55 ++++++++++++++++++--------- tests/test_install_service_custody.py | 35 +++++++++++++---- 5 files changed, 76 insertions(+), 31 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index 4079d258d7..a6af67e4f3 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -291,7 +291,7 @@ directory's rules, made restricted in one step, and then given this list: The script replaces any other grant the service account holds there, and removes every other account's allow entry and every deny entry, whoever it names. It then reads the list back, and -refuses, disabling the service, at least when it has another owner, still inherits, still has an +refuses, disabling the service, at least when its owner is neither Administrators nor SYSTEM, still inherits, still has an allow entry for another account or a deny entry on the directory, or gives the service account more or less than that grant. When the script does not read that provider, it refuses `-CustodyDir`. diff --git a/messagefoundry/engine_secrets.py b/messagefoundry/engine_secrets.py index 133054588b..a7e2ac5d3f 100644 --- a/messagefoundry/engine_secrets.py +++ b/messagefoundry/engine_secrets.py @@ -22,9 +22,12 @@ UTF-8, or one over :data:`MAX_FILE_BYTES`. * **The store key is not read from here as a setting.** A file named for the store key, or for its retired keys, is refused. The key custody host blob and its handoff (:data:`CUSTODY_FILE_NAMES`) - may sit here, and the listing passes over them: the ``host`` key provider reads them itself - (:mod:`messagefoundry.store.custody_host`, vault BACKLOG #3411), checking each as a key file. - :data:`CUSTODY_DIRECTORY_VARIABLE`, when set, names another directory for them. + may sit here, and the listing passes over them: with :data:`CUSTODY_DIRECTORY_VARIABLE` unset, + the ``host`` key provider reads them itself (:mod:`messagefoundry.store.custody_host`, vault + BACKLOG #3411), checking each as a key file. With it set, the provider reads them in the + directory that variable names instead, and a key file left here is not checked as one: its + name alone refuses another key provider, and a read or a mint while that directory holds + neither file. **What this slice does not do**, at least: refuse a secret found in the environment (slice B later made the NSSM reading in :mod:`messagefoundry.serviceenv` refuse one in the service's own diff --git a/messagefoundry/store/custody_host.py b/messagefoundry/store/custody_host.py index 6fe7bb4c5e..97906af8a1 100644 --- a/messagefoundry/store/custody_host.py +++ b/messagefoundry/store/custody_host.py @@ -198,7 +198,9 @@ def _own_directory_refusal(environ: Mapping[str, str]) -> str | None: Refused first, whether or not it exists: a custody directory that is, holds or sits inside the directory ``MEFOR_SECRETS_DIRECTORY`` names, compared where each resolves to - (:func:`_overlaps`), so a link or another spelling of the same place does not pass. The + (:func:`_overlaps`), so at least a link, or a spelling in another case where the platform + folds case, does not pass. A UNC spelling of a local path, such as ``\\\\localhost\\C$\\...``, + is not read as that path, so it is not caught. The service may add files to its custody directory, and the secrets directory is administrator-written (ADR 0214), so the two must stay apart.""" raw = environ.get(CUSTODY_DIRECTORY_VARIABLE, "").strip() @@ -242,7 +244,7 @@ def _overlaps(first: str, second: str) -> bool: resolves to: links followed as far as the path exists (:func:`os.path.realpath`, which on Windows also reads a short 8.3 name as the long one for the part that exists), then case-folded where the platform folds case (:func:`os.path.normcase`). Two paths on different - drives do not overlap.""" + drives do not overlap, and a UNC spelling of a local path reads as a different drive.""" own, shared = (os.path.normcase(os.path.realpath(p)) for p in (first, second)) try: return os.path.commonpath([own, shared]) in (own, shared) diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index 371cb1db4f..12932fed1f 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -979,16 +979,17 @@ function New-RestrictedDirectory { $acl = Get-Acl -LiteralPath $Path $owner = $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value if ($owner -ne $OwnerSid -or -not $acl.AreAccessRulesProtected) { - # The custody directory may hold a store's only key, so its refusal never says remove. - $remedy = if ($What -eq "the custody directory") { + # A custody directory, or any folder holding a key file or one that cannot be listed, may + # hold a store's only key, so its refusal never says remove (vault BACKLOG #3411). + $keyHeld = try { + [bool]@(Get-ChildItem -LiteralPath $Path -Force -ErrorAction Stop | + Where-Object { $_.Name -in @("master.key", "handoff.key") }).Count + } catch { $true } + $remedy = if ($What -eq "the custody directory" -or $keyHeld) { "Check who made it. Leave every key file in it where it is, and delete nothing: a " + "master.key or handoff.key there may be the only copy of a store's key on this " + "host. Then follow docs/SERVICE.md 'When a refusal names master.key or handoff.key'." - } else { - "Remove it, check who made it, and re-run the installer. If it holds master.key or " + - "handoff.key, do not remove it or delete either file: follow docs/SERVICE.md 'When " + - "a refusal names master.key or handoff.key'." - } + } else { "Remove it, check who made it, and re-run the installer." } throw ("'$Path' was there before this install made it (its owner is $owner), so it is not " + "the restricted folder the install asked for. $remedy") } @@ -1104,6 +1105,14 @@ function Get-SecretsDirHeldProblem { param([Parameter(Mandatory)][string]$Path) $held = @(Get-ChildItem -LiteralPath $Path -Force -ErrorAction Stop) if ($held.Count -eq 0) { return "" } + # A key file there may be a store's only key (vault BACKLOG #3411), so no remove is said then. + $keys = @($held | Where-Object { $_.Name -in @("master.key", "handoff.key") }) + if ($keys) { + return ("it holds $($held.Count) item(s) the installer did not put there, among them " + + "'$($keys[0].Name)', which may be the only copy of a store's key on this host. Leave " + + "every key file in it where it is, and delete nothing; check who wrote them, and follow " + + "docs/SERVICE.md 'When a refusal names master.key or handoff.key'") + } return ("it holds $($held.Count) item(s) the installer did not put there, such as " + "'$($held[0].Name)'. Remove the directory, check who wrote them, and re-run the installer; " + "after the install create or copy each file in, never move one: a moved file keeps its " + @@ -3024,11 +3033,21 @@ if (-not $secretsProblem) { $SecretsDirNamed = [bool]$RegisteredSecretsDir -and ($RegisteredSecretsDir.TrimEnd('\') -eq $SecretsDir.TrimEnd('\')) if (-not $secretsProblem -and (Test-Path -LiteralPath $SecretsDir)) { if (-not $SecretsDirNamed) { - $secretsProblem = ("it already exists and the service does not name it. Remove it, check who " + - "made it, and re-run the installer, which then makes it restricted. If it holds " + - "master.key or handoff.key, which may be the only copy of a store's key on this host, " + - "do not remove it or delete either file: pass -SecretsDir naming a new folder, and " + - "follow docs/SERVICE.md 'When a refusal names master.key or handoff.key'") + # A key file there, or a listing that fails, may be a store's only key (vault BACKLOG + # #3411), so no remove is said then. + $secretsKeyHeld = try { + [bool]@(Get-ChildItem -LiteralPath $SecretsDir -Force -ErrorAction Stop | + Where-Object { $_.Name -in @("master.key", "handoff.key") }).Count + } catch { $true } + $secretsProblem = if ($secretsKeyHeld) { + ("it already exists, the service does not name it, and it may hold master.key or " + + "handoff.key, which may be the only copy of a store's key on this host. Leave every " + + "key file in it where it is, and delete nothing: pass -SecretsDir naming a new " + + "folder, and follow docs/SERVICE.md 'When a refusal names master.key or handoff.key'") + } else { + ("it already exists and the service does not name it. Remove it, check who made it, " + + "and re-run the installer, which then makes it restricted") + } } else { $owner = (Get-Acl -LiteralPath $SecretsDir).GetOwner([Security.Principal.SecurityIdentifier]).Value if ($owner -ne "S-1-5-32-544" -and $owner -ne "S-1-5-18") { @@ -3594,12 +3613,12 @@ try { # A named directory is the same one in another spelling, never a replaced one: its files stay. if ($replacedSecretsDir -and -not $SecretsDirNamed) { Write-Warning ("The service's MEFOR_SECRETS_DIRECTORY named '$replacedSecretsDir' and now names " + - "'$SecretsDir', as -SecretsDir asked. Copy each file from the old directory, never move " + - "it: a moved file keeps its old access list, not the new directory's. Then delete the old " + - "files you copied, and remove the service account's grant there. Leave a master.key or " + - "handoff.key there where it is, and delete neither: either may be the only copy of a " + - "store's key on this host, and docs/SERVICE.md 'When a refusal names master.key or " + - "handoff.key' says how to go on.") + "'$SecretsDir', as -SecretsDir asked. Leave a master.key or handoff.key in the old " + + "directory where it is, and delete neither: either may be the only copy of a store's key " + + "on this host, and docs/SERVICE.md 'When a refusal names master.key or handoff.key' says " + + "how to go on. Copy each other file from the old directory, never move it: a moved file " + + "keeps its old access list, not the new directory's. Then delete the old files you " + + "copied, and remove the service account's grant there.") } Write-Host " Secrets: '$SecretsDir', named to the service as MEFOR_SECRETS_DIRECTORY (docs/SERVICE.md)." } catch { diff --git a/tests/test_install_service_custody.py b/tests/test_install_service_custody.py index fe0c25a963..ff0a594b32 100644 --- a/tests/test_install_service_custody.py +++ b/tests/test_install_service_custody.py @@ -509,13 +509,34 @@ def test_the_secrets_directory_texts_never_send_a_key_file_to_be_deleted(tmp_pat # The script's string pieces joined, so a sentence split over `" +` lines reads whole. joined = re.sub(r'"\s*\+\s*"', "", " ".join(_script_text().split())) title = "When a refusal names master.key or handoff.key" - for start in ( - "Then delete the old files you copied", - "it already exists and the service does not name it. Remove it, check who made it", - "Remove it, check who made it, and re-run the installer. If it holds master.key", - ): - window = joined[joined.index(start) : joined.index(start) + 500] - assert "handoff.key" in window and title in window, window + # The -SecretsDir change warning carves the key files out before it says to copy and delete. + keep = joined.index("Leave a master.key or handoff.key in the old directory where it is") + assert keep < joined.index("Then delete the old files you copied"), keep + assert title in joined[keep : keep + 400], joined[keep : keep + 400] + # The existing-directory refusal and the squatter refusal say remove only when no key file + # is listed there, and a listing that fails counts as one. + held = joined.index("$secretsProblem = if ($secretsKeyHeld) {") + assert title in joined[held : held + 500] and "} catch { $true }" in joined[held - 300 : held] + assert '$remedy = if ($What -eq "the custody directory" -or $keyHeld) {' in joined + assert "} catch { $true }" in joined[joined.index("$keyHeld = try {") :][:300] + # Get-SecretsDirHeldProblem says no remove over a key file; the control is another file. + assert _SCRIPT is not None + with_key = tmp_path / "with-key" + with_key.mkdir() + (with_key / "handoff.key").write_bytes(b"k") + other = tmp_path / "other-file" + other.mkdir() + (other / "MEFOR_X").write_bytes(b"v") + body = ( + " [pscustomobject]@{ key = [string](Get-SecretsDirHeldProblem -Path " + f"{_psq(str(with_key))}); other = [string](Get-SecretsDirHeldProblem -Path " + f"{_psq(str(other))}) }} | ConvertTo-Json -Compress\n" + ) + out = _ok(_extract(_SCRIPT, ["Get-SecretsDirHeldProblem"], body), tmp_path) + got = json.loads(out.strip().splitlines()[-1]) + assert "handoff.key" in got["key"] and title in got["key"], got + assert not re.search(r"\bremov", got["key"], re.IGNORECASE), got + assert "Remove the directory" in got["other"], got notice = " ".join(_notice(tmp_path, {**_FULL_FACTS, "CustodyDir": ""}).split()) assert "except master.key and handoff.key" in notice, notice assert "never delete either" in notice, notice From f9017f4a1fc4ee6c00696906e2f8020b627bb477 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Sun, 22 Nov 2026 22:10:02 -0600 Subject: [PATCH 20/28] Key custody: text only, the five lead items of review round-0255766107 Vault BACKLOG #3411 slice B3c, design note 1, under the Manager's decision of 2026-11-22. Text only: no behaviour changed, so no further review round runs on it. - SERVICE.md step 5: a second copy of a key file is read by whoever its access list names (SYSTEM, Administrators, the service); a handoff is machine-scope DPAPI, so anyone holding its bytes can unwrap it. - Step 4: a new -DataDir takes everything the engine keeps in the old one, at least the database with -wal and -shm, the log spool and the generated certificate, except the two key files. - No text says to delete a key file: an original a copy replaced is moved into an administrator-only folder and kept, as the uninstall notice's never-delete line says. - keep_the_key_step, _refuse_an_unusable_directory and check_host_custody_settings point at the SERVICE.md procedure in place of a secrets directory writable by the service. - ADR 0214's amendment, and the two comments that repeated it, say the installer's access list makes the secrets directory administrator-written and the engine does not enforce that. --- docs/SERVICE.md | 23 +++--- ...-for-the-engine-s-secret-class-settings.md | 7 +- messagefoundry/store/custody_host.py | 76 +++++++------------ scripts/service/install-service.ps1 | 5 +- tests/test_store_custody_host.py | 30 +++++--- 5 files changed, 69 insertions(+), 72 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index a6af67e4f3..3dabb98bd4 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -329,8 +329,8 @@ directory the service does not name, as after an uninstall. Neither the engine n tell whose key a file holds, and either file may be the only copy of a store's key on this host. 1. **Delete nothing, and leave every key file where it is**, in every directory the refusal names, - unless step 3 sends you to move one; then move it only as step 5 says, which also says when an - original may go. + unless step 3 sends you to move one; then move it only as step 5 says, which also says how to + keep an original that a copy replaced. 2. **Stop the service** (`Stop-Service `) if it is installed, and work from an elevated shell. 3. **If the file holds this store's key**, as when this store was set up under @@ -363,8 +363,10 @@ tell whose key a file holds, and either file may be the only copy of a store's k `AppEnvironmentExtra` list, keeping the other entries. A new data directory starts a new, empty store. Never copy another store's database, or any - key file, into it. To keep this store's own data, move its database file, and the `-wal` and - `-shm` files beside it when they are there, into the new data directory as step 5 says. + key file, into it. To keep this store's own data, move everything the engine keeps in the old + data directory into the new one as step 5 says, at least the database with its `-wal` and + `-shm` files, the log spool and the generated API certificate, except `master.key` and + `handoff.key`, which stay where they are or follow step 3. 5. **Moving a file.** Within one volume, move it as an administrator (`Move-Item -LiteralPath -Destination `): the file keeps its own owner and access list, which the engine checks exactly on a key file. Across volumes a move is a copy, @@ -374,10 +376,12 @@ tell whose key a file holds, and either file may be the only copy of a store's k `icacls ` prints the same entries for the copy as for the original, and that `(Get-Acl -LiteralPath ).Owner` prints the same owner, and keep the original where it is until the service has started and opened its store from the copy. Copy the database files - across volumes the same way, and keep their originals until then too. Once it has, delete each - original as an administrator: a second copy of a key file is a second place the key can be - read from, a `handoff.key` on this machine by any account, and the database originals may - hold PHI, disposed of as [PHI.md](PHI.md) describes. + across volumes the same way, and keep their originals until then too. Once it has, retire each + key file original rather than delete it: move it, within its volume, into a folder only + administrators can read, and keep it there. Never delete it. A second copy of a key file is + read by whoever its access list names, SYSTEM, Administrators and the service; a + `handoff.key` is machine-scope DPAPI, so anyone who already has its bytes can unwrap it. The + database originals may hold PHI; dispose of them as [PHI.md](PHI.md) describes. 6. **Start the service**, and read its log for a refusal ([Verify it's running](#verify-its-running)). **Without the install scripts**, as on Linux or in a container, the same steps hold with the @@ -388,7 +392,8 @@ variable that names the file's directory, `MEFOR_SECRETS_DIRECTORY` or `MEFOR_CU to a new directory owned by the account the engine runs as, mode 0700, in a folder only that account or root may write, and add the engine's other secret files to a new secrets directory. A move within one file system keeps the file's owner and mode; across file systems, copy it keeping them -(`cp -p`, as root), and keep the original until the engine has opened its store from the copy. +(`cp -p`, as root). Once the engine has opened its store from the copy, move the original, within +its file system, into a folder only root can read, and keep it there; never delete it. ## Update to a new build (restart vs reinstall) diff --git a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md index e7fee3dbe0..d78309ea25 100644 --- a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md +++ b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md @@ -156,9 +156,10 @@ names ADR 0019 declared and nobody built. Also not moved: the store key's own re - **2026-11-22, the host key provider's files get a custody directory of their own (vault BACKLOG #3411).** Under `[store].key_provider = 'host'` the service's first start writes its own key file, `master.key`, beside the `handoff.key` an administrator's `provision-admin - --service-account` left. Decision 5 and slice C keep this directory administrator-written, with - the service at read only, and a service right to add a file here would let it supply a - secret-class setting. So those two files move to a directory of their own when + --service-account` left. The installer's access list makes this directory administrator-written, + with the service at read only; the engine does not enforce that, since decision 4's check + passes a directory one named account may write. A service right to add a file here would let + it supply a secret-class setting. So those two files move to a directory of their own when `MEFOR_CUSTODY_DIRECTORY` names one, an absolute path, which wins over `MEFOR_SECRETS_DIRECTORY` for them; unset, they stay where they were, in this directory or beside a SQLite store. Before a read or a mint, the engine applies decision 4's check to the directory that variable names, diff --git a/messagefoundry/store/custody_host.py b/messagefoundry/store/custody_host.py index 97906af8a1..3272dc965c 100644 --- a/messagefoundry/store/custody_host.py +++ b/messagefoundry/store/custody_host.py @@ -201,8 +201,9 @@ def _own_directory_refusal(environ: Mapping[str, str]) -> str | None: (:func:`_overlaps`), so at least a link, or a spelling in another case where the platform folds case, does not pass. A UNC spelling of a local path, such as ``\\\\localhost\\C$\\...``, is not read as that path, so it is not caught. The - service may add files to its custody directory, and the secrets directory is - administrator-written (ADR 0214), so the two must stay apart.""" + service may add files to its custody directory, and the installer's access list makes the + secrets directory administrator-written (ADR 0214; the engine does not enforce that), so the + two must stay apart.""" raw = environ.get(CUSTODY_DIRECTORY_VARIABLE, "").strip() secrets = environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip() if ( @@ -771,9 +772,10 @@ def check_host_custody_settings( if directory is None: raise _recorded_as( HostCustodyRefused, - "[store].key_provider = 'host' needs a directory for the host blob: set " - "MEFOR_CUSTODY_DIRECTORY or MEFOR_SECRETS_DIRECTORY, since this store has no data " - "directory of its own", + "[store].key_provider = 'host' needs a directory for the host blob, since this store " + "has no data directory of its own: give it a custody directory of its own, named by " + "MEFOR_CUSTODY_DIRECTORY, as docs/SERVICE.md, " + f"'{_SERVICE_PROCEDURE_TITLE}', says", ) refusal = _own_directory_refusal(environ) if refusal is not None: @@ -933,34 +935,20 @@ def keep_the_key_step( or store they cannot tie to this store (PR 2804 fifth and sixth holds). It advises changing no existing file, key, blob or store: it asks for a new custody directory, and with ``new_store`` a new store location, which changes the settings that name them. Names no path and no key. - ``environ`` is read for which variable names the custody directory now.""" + ``environ`` is accepted from its callers; the text no longer depends on it.""" from messagefoundry.config.settings import SchemaManagement, StoreBackend server = settings.backend is not StoreBackend.SQLITE - own = _directory_variable(os.environ if environ is None else environ) == ( - CUSTODY_DIRECTORY_VARIABLE - ) # The variable is named here as a literal, not through SECRETS_DIRECTORY_VARIABLE: this text # can reach stderr, and CodeQL's name heuristic reads that constant as a secret (alert 315). + # It describes no folder to make: the secrets directory must never be made writable by the + # service, so the one procedure in docs/SERVICE.md says how to get a custody directory. text = ( - ( - # A directory of its own holds no other secret, so nothing is copied into it. - "To go on without it, give this store a custody directory of its own: a new directory, " - "restricted as docs/SERVICE.md says, which the engine checks at start, named by " - "MEFOR_CUSTODY_DIRECTORY here and in this store's own service environment, never in one " - "that another store's service also reads, since that store would then look for its key " - "there" - ) - if own - else ( - "To go on without it, give this store a custody directory of its own: a new directory, " - "restricted and writable by the service as a secrets directory must be, which the engine " - "checks at start, named by MEFOR_SECRETS_DIRECTORY here and in this store's own service " - "environment, never in one that another store's service also reads, since that store " - "would then look for its key there. Copy into it every secret file the current secrets " - f"directory holds other than {HOST_FILE_NAME} and {HANDOFF_FILE_NAME}, if one is set, " - "since the service reads its other secrets from there too" - ) + "To go on without it, give this store a custody directory of its own, named by " + "MEFOR_CUSTODY_DIRECTORY here and in this store's own service environment, never one that " + "another store's service also reads, since that store would then look for its key there: " + f"docs/SERVICE.md, '{_SERVICE_PROCEDURE_TITLE}', says how, and the engine checks that " + "directory at start" ) if new_store: text += ". Point [store] at a store location of its own: " + ( @@ -1110,30 +1098,24 @@ def _refuse_an_unusable_directory( writers = "this account" + ( "" if service_account is None else f' and the service account "{service_account}"' ) - own = named == CUSTODY_DIRECTORY_VARIABLE + # No folder to make is described here, and the secrets directory is never offered: it must not + # be made writable by the service. The one procedure in docs/SERVICE.md says how. secrets_directory = ( - "restricted as docs/SERVICE.md says for a custody directory, and writable by " - if own - else "restricted as a secrets directory must be and writable by " - ) + writers + f"a custody directory of its own, got as docs/SERVICE.md, '{_SERVICE_PROCEDURE_TITLE}', " + f"says, which {writers} can add a file to" + ) def move_on(to: str) -> str: # The variable is named as a literal: this text reaches stderr (keep_the_key_step says # why). - if own: - return ( - f"set MEFOR_CUSTODY_DIRECTORY, here and in the service's own environment, to {to}" - ) variable = ( - "set MEFOR_SECRETS_DIRECTORY, here and in the service's own environment, to " - f"{to}, and copy into it every other secret file the current secrets directory " - "holds, if one is set, since the service reads its other secrets from there too" + f"set MEFOR_CUSTODY_DIRECTORY, here and in the service's own environment, to {to}" ) if named: return variable return ( - f"point --db at a SQLite path in {to}, by its absolute path, here and wherever the " - "service passes --db, since the store key sits beside the store file, or " + "point --db at a SQLite path in a new data directory, by its absolute path, here and " + "wherever the service passes --db, since the store key sits beside the store file, or " f"{variable}" ) @@ -1141,14 +1123,14 @@ def move_on(to: str) -> str: if os.path.lexists(directory): raise HostCustodyRefused( f"the custody directory {directory} is not a directory this account can read, " - f"{none_shown}. To go on, {move_on('a directory ' + secrets_directory)}, and run " + f"{none_shown}. To go on, {move_on(secrets_directory)}, and run " "the command again" ) # A directory behind a parent this account cannot search reads as absent here too. raise HostCustodyRefused( f"the custody directory {directory} is missing, or a directory above it is one this " - f"account cannot search, {none_shown}. Create it, {secrets_directory}, or let this " - "account search the directories above it, and run the command again" + f"account cannot search, {none_shown}. To go on, {move_on(secrets_directory)}, or let " + "this account search the directories above it, and run the command again" ) can_add = can_add_a_file(directory) if can_add is None: @@ -1161,7 +1143,7 @@ def move_on(to: str) -> str: if can_add is False: raise HostCustodyRefused( f"this account cannot add a file to the custody directory {directory}, {none_shown}. " - f"Let this account add files there, or {move_on('a directory ' + secrets_directory)}, " + f"Let this account add files there, or {move_on(secrets_directory)}, " "and run the command again" ) try: @@ -1171,13 +1153,13 @@ def move_on(to: str) -> str: f"the file system of the custody directory {directory} could not be checked, since " f"this account could not open the directory ({exc.strerror or type(exc).__name__}), " f"{none_shown}. Let this account open it, or " - f"{move_on('a directory ' + secrets_directory)}, and run the command again" + f"{move_on(secrets_directory)}, and run the command again" ) from exc if volume is not None: raise HostCustodyRefused( f"the custody directory {directory} cannot hold a store key: {volume}. No store key " "was minted and no recovery key was shown. To go on, " - f"{move_on('a directory on a local file system, ' + secrets_directory)}, and run the " + f"{move_on(secrets_directory + ', on a local file system')}, and run the " "command again" ) diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index 12932fed1f..c020ed2f26 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -3115,8 +3115,9 @@ if ($HostCustody) { # --- the custody directory (vault BACKLOG #3411, ADR 0214's 2026-11-22 amendment) -------------------- # Under the host provider the service's first start writes its own key file, master.key, beside the -# handoff provision-admin leaves, so it must add a file where those two live. The secrets directory -# is administrator-written (ADR 0214), so they get a directory of their own, named to the service as +# handoff provision-admin leaves, so it must add a file where those two live. This script's access +# list makes the secrets directory administrator-written (ADR 0214; the engine does not enforce +# that), so they get a directory of their own, named to the service as # MEFOR_CUSTODY_DIRECTORY, which the engine reads in place of MEFOR_SECRETS_DIRECTORY for them. # Judged here, before anything acts, by the secrets directory's rules; made, restricted # (Set-CustodyDirAcl) and named once the account resolves, after the service is registered. diff --git a/tests/test_store_custody_host.py b/tests/test_store_custody_host.py index 916a406493..60742a441e 100644 --- a/tests/test_store_custody_host.py +++ b/tests/test_store_custody_host.py @@ -190,7 +190,7 @@ def test_the_custody_directory_is_the_secrets_directory_or_the_data_directory( assert custody_host.custody_directory(memory, environ={}) is None server = settings.model_copy(update={"backend": StoreBackend.POSTGRES}) assert custody_host.custody_directory(server, environ={}) is None - with pytest.raises(HostCustodyRefused, match="MEFOR_SECRETS_DIRECTORY"): + with pytest.raises(HostCustodyRefused, match="MEFOR_CUSTODY_DIRECTORY"): load_host_custody(server, enforcing=True, environ={}) @@ -509,6 +509,12 @@ def test_each_key_file_refusal_points_at_one_service_md_procedure_and_states_no_ section = " ".join(_service_md_section(title).split()) for needed in ("-DataDir", "-SecretsDir", "-CustodyDir", "Delete nothing", "Across volumes"): assert needed in section, (needed, section) + # Manager decision 2026-11-22: a new data directory takes everything the engine keeps there + # but the key files; a key file original a copy replaced is kept in an administrator-only + # folder, never deleted; and a second copy is read by whoever its access list names. + for needed in ("the log spool", "the generated API certificate", "Never delete it"): + assert needed in section, (needed, section) + assert "delete each original" not in section and "by any account" not in section, section def test_the_custody_and_secrets_overlap_is_compared_where_each_resolves(tmp_path: Path) -> None: @@ -610,7 +616,7 @@ def test_the_way_on_names_the_custody_directory_of_its_own(tmp_path: Path) -> No # No other secret lives there, so none is to be copied, and the secrets directory is not named. assert "Copy into it" not in step and "MEFOR_SECRETS_DIRECTORY" not in step, step secrets = custody_host.keep_the_key_step(_settings(tmp_path), new_store=False, environ={}) - assert "named by MEFOR_SECRETS_DIRECTORY here" in secrets, secrets + assert "named by MEFOR_CUSTODY_DIRECTORY here" in secrets, secrets @windows_only @@ -2085,7 +2091,9 @@ async def _open(settings: StoreSettings, **kwargs: object) -> Store: assert "run with the custody directory that holds the store's host blob" in flat, err # A server backend: the other secret files are carried over, and the external schema is # provisioned first. - assert "new, empty" not in flat and "Copy into it every secret file" in flat, err + assert ( + "new, empty" not in flat and "When a refusal names master.key or handoff.key" in flat + ), err assert "a new database, whose schema a DDL-capable login provisions first" in flat, err assert driver_text not in err assert list(secrets.iterdir()) == [] # no host blob, no handoff @@ -2194,10 +2202,10 @@ def _advises_changing(text: str, *, allowed: tuple[str, ...] = ()) -> bool: def test_the_keep_the_key_step_names_the_variable_the_engine_reads(tmp_path: Path) -> None: # The step writes the variable's name as a literal (CodeQL alert 315), so pin it to the # constant the engine reads. - from messagefoundry.engine_secrets import SECRETS_DIRECTORY_VARIABLE + from messagefoundry.engine_secrets import CUSTODY_DIRECTORY_VARIABLE step = custody_host.keep_the_key_step(_settings(tmp_path), new_store=True) - assert f"named by {SECRETS_DIRECTORY_VARIABLE} here" in step + assert f"named by {CUSTODY_DIRECTORY_VARIABLE} here" in step @pytest.mark.parametrize("backend", [StoreBackend.SQLITE, StoreBackend.POSTGRES]) @@ -2213,7 +2221,7 @@ def test_the_fallback_step_fits_the_backend_and_the_command( settings, new_store=True, service_account="NT SERVICE\\MessageFoundry" ) assert "empty directory" not in step and "new, empty" not in step - assert "Copy into it every secret file" in step, step + assert "When a refusal names master.key or handoff.key" in step, step # Quoted, since a service account name can hold a space. command = ( "run `messagefoundry provision-admin` again to mint this store's key in the new custody " @@ -2221,9 +2229,9 @@ def test_the_fallback_step_fits_the_backend_and_the_command( '\\MessageFoundry" among them' ) assert command in step, step - assert "restricted and writable by the service as a secrets directory must be" in step, step + assert "writable by the service" not in step, step assert "The new store starts empty" in step, step - assert "other than master.key and handoff.key" in step, step + assert "MEFOR_SECRETS_DIRECTORY" not in step, step assert "recovery key shown when an existing key file was minted goes with that file" in step schema = "whose schema a DDL-capable login provisions first" assert (schema in step) is (backend is StoreBackend.POSTGRES), step @@ -2608,7 +2616,7 @@ async def _b() -> None: assert code == 2 err = capsys.readouterr().err assert not _advises_changing(err) and "leaves it and the store in place" in err, err - assert "named by MEFOR_SECRETS_DIRECTORY here" in " ".join(err.split()), err + assert "named by MEFOR_CUSTODY_DIRECTORY here" in " ".join(err.split()), err assert kept.exists() # B's pre-check was refused before its first write, so nothing was bound under A's key. import sqlite3 @@ -2644,7 +2652,7 @@ async def _unstarted() -> None: _mint(settings) kept = tmp_path / custody_host.HOST_FILE_NAME assert _run_provision_admin(tmp_path, monkeypatch, store_path) == 2 - assert "named by MEFOR_SECRETS_DIRECTORY here" in " ".join(capsys.readouterr().err.split()) + assert "named by MEFOR_CUSTODY_DIRECTORY here" in " ".join(capsys.readouterr().err.split()) left = {path: path.read_bytes() for path in (kept, store_path)} secrets = tmp_path / "new-secrets" secrets.mkdir() @@ -2764,7 +2772,7 @@ def _held(self: Path, missing_ok: bool = False) -> None: assert _advises_changing(cli._REMOVE_THE_VOID_KEY) and _advises_changing(warning), warning assert not _advises_changing(warning, allowed=(cli._REMOVE_THE_VOID_KEY,)), warning assert "cannot tell whose key" not in warning, warning - assert "Copy into it every secret file" in " ".join(warning.split()), warning + assert "When a refusal names master.key or handoff.key" in " ".join(warning.split()), warning @pytest.mark.parametrize("service_account", [None, "NT SERVICE\\MessageFoundry"]) From 555144575f040d5ebfc31387cf448def0ba83ca3 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 09:57:21 -0600 Subject: [PATCH 21/28] Key custody: PR 3168 hold items 1-10, a way on that reaches a mint Vault BACKLOG #3411 slice B3c. Behaviour changes (f9017f4a1fc's "no behaviour changed" did not hold, hold item 1): - keep_the_key_step reads environ again. With MEFOR_CUSTODY_DIRECTORY set, a key file in the secrets directory or beside a SQLite store refuses a mint, so where the kept key sits in the secrets directory the step also asks for a new secrets directory, and where it sits beside the store, for a new store location; a new SQLite path goes in a directory of its own. Tested by following the refusal's text to a mint, from both places (item 9; red before the fix). - _refuse_an_unusable_directory: the --db alternative keeps "on a local file system", and a missing custody or data directory may be created (items 12 and 13, fixed alongside). Text: SERVICE.md steps 1, 4, 5 (items 2, 4-8); ADR 0214, the installer comment and the overlap docstring say the installer adds a read grant and takes no wider one away (item 3); the two "must never be made writable" comments restated (item 10); the left-behind docstring (item 11, alongside). --- docs/SERVICE.md | 47 ++++++-- ...-for-the-engine-s-secret-class-settings.md | 9 +- messagefoundry/store/custody_host.py | 79 ++++++++---- scripts/service/install-service.ps1 | 8 +- tests/test_store_custody_host.py | 113 ++++++++++++++---- 5 files changed, 195 insertions(+), 61 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index 9a2a563c70..8264de2d05 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -344,8 +344,9 @@ directory the service does not name, as after an uninstall. Neither the engine n tell whose key a file holds, and either file may be the only copy of a store's key on this host. 1. **Delete nothing, and leave every key file where it is**, in every directory the refusal names, - unless step 3 sends you to move one; then move it only as step 5 says, which also says how to - keep an original that a copy replaced. + except as step 5 says once a copy has replaced an original, and unless step 3 sends you to move + one; then move it only as step 5 says, which also says what to + do with an original that a copy replaced. 2. **Stop the service** (`Stop-Service `) if it is installed, and work from an elevated shell. 3. **If the file holds this store's key**, as when this store was set up under @@ -378,10 +379,16 @@ tell whose key a file holds, and either file may be the only copy of a store's k `AppEnvironmentExtra` list, keeping the other entries. A new data directory starts a new, empty store. Never copy another store's database, or any - key file, into it. To keep this store's own data, move everything the engine keeps in the old - data directory into the new one as step 5 says, at least the database with its `-wal` and - `-shm` files, the log spool and the generated API certificate, except `master.key` and - `handoff.key`, which stay where they are or follow step 3. + key file, into it. To keep this store's own data, move into the new one, as step 5 says, only + files you know are this store's or this service's, and leave everything else where it is, at + least any other database with its `-wal` and `-shm` files, since an old data directory may be + shared. Those files are at least this store's database, the file the service's `--db` names, + with that file's own `-wal` and `-shm` files; and, only where no other store's database sits + in the same directory, the `log-spool` folder and the generated API certificate pair, + `api-generated-cert.pem` with `api-generated-key.pem`. Move that pair together or not at all: + the engine mints a new pair when it finds either one missing, and a client that pins the old + certificate then refuses the new one. Leave `master.key` and `handoff.key` where they are: in + this step they may be another store's. 5. **Moving a file.** Within one volume, move it as an administrator (`Move-Item -LiteralPath -Destination `): the file keeps its own owner and access list, which the engine checks exactly on a key file. Across volumes a move is a copy, @@ -391,12 +398,28 @@ tell whose key a file holds, and either file may be the only copy of a store's k `icacls ` prints the same entries for the copy as for the original, and that `(Get-Acl -LiteralPath ).Owner` prints the same owner, and keep the original where it is until the service has started and opened its store from the copy. Copy the database files - across volumes the same way, and keep their originals until then too. Once it has, retire each - key file original rather than delete it: move it, within its volume, into a folder only - administrators can read, and keep it there. Never delete it. A second copy of a key file is - read by whoever its access list names, SYSTEM, Administrators and the service; a - `handoff.key` is machine-scope DPAPI, so anyone who already has its bytes can unwrap it. The - database originals may hold PHI; dispose of them as [PHI.md](PHI.md) describes. + across volumes the same way, and keep their originals until then too. Copy the generated API + certificate pair the same way, both files. Once the service has opened its store from the + copies: + - **A `master.key` original:** keep it as a second copy of the store's key, but take the + service's access to it away first. Moving a file into another folder does not do that: the + file keeps its own owner and access list, and an account that list names can still open it + by its path. Set the original's owner and list, then check both + (`icacls /setowner *S-1-5-32-544`, then + `icacls /inheritance:r /grant:r *S-1-5-32-544:F *S-1-5-18:F /remove:g ""`, + then `icacls `, which must print entries for Administrators and SYSTEM only, removing + any other with `/remove:g`). Then move it, within its volume, into a folder only + administrators can read, and keep it there. It is still read by at least SYSTEM, + Administrators, and any account holding a privilege that reads past an access list, such as + SeBackupPrivilege, which the `robocopy /B` above uses. + - **A `handoff.key` original:** delete it once the service has started from the copy. A + handoff is meant to last only from install to the service's first start, which converts it + into `master.key` and deletes the copy it read. It is machine-scope DPAPI: on this host, any + process that can read the file can unwrap the store key from it, though it does not unwrap + on another host. + - **An `api-generated-key.pem` original:** delete it with its `api-generated-cert.pem`. It is + the private key of a certificate the service still presents. + - **The database originals** may hold PHI; dispose of them as [PHI.md](PHI.md) describes. 6. **Start the service**, and read its log for a refusal ([Verify it's running](#verify-its-running)). **Without the install scripts**, as on Linux or in a container, the same steps hold with the diff --git a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md index d78309ea25..27bb23f42d 100644 --- a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md +++ b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md @@ -156,10 +156,11 @@ names ADR 0019 declared and nobody built. Also not moved: the store key's own re - **2026-11-22, the host key provider's files get a custody directory of their own (vault BACKLOG #3411).** Under `[store].key_provider = 'host'` the service's first start writes its own key file, `master.key`, beside the `handoff.key` an administrator's `provision-admin - --service-account` left. The installer's access list makes this directory administrator-written, - with the service at read only; the engine does not enforce that, since decision 4's check - passes a directory one named account may write. A service right to add a file here would let - it supply a secret-class setting. So those two files move to a directory of their own when + --service-account` left. The installer adds the service's read grant on this directory and + takes no wider grant away, so a write grant the service already holds, such as one the Vault + Agent sink route gives it, survives a rerun; the engine does not refuse one either, since + decision 4's check passes a directory one named account may write. A service right to add a + file here would let it supply a secret-class setting. So those two files move to a directory of their own when `MEFOR_CUSTODY_DIRECTORY` names one, an absolute path, which wins over `MEFOR_SECRETS_DIRECTORY` for them; unset, they stay where they were, in this directory or beside a SQLite store. Before a read or a mint, the engine applies decision 4's check to the directory that variable names, diff --git a/messagefoundry/store/custody_host.py b/messagefoundry/store/custody_host.py index 3272dc965c..c01cbfb628 100644 --- a/messagefoundry/store/custody_host.py +++ b/messagefoundry/store/custody_host.py @@ -201,9 +201,11 @@ def _own_directory_refusal(environ: Mapping[str, str]) -> str | None: (:func:`_overlaps`), so at least a link, or a spelling in another case where the platform folds case, does not pass. A UNC spelling of a local path, such as ``\\\\localhost\\C$\\...``, is not read as that path, so it is not caught. The - service may add files to its custody directory, and the installer's access list makes the - secrets directory administrator-written (ADR 0214; the engine does not enforce that), so the - two must stay apart.""" + service may add files to its custody directory, and a service that may add a file to the + secrets directory may supply a secret-class setting (ADR 0214's 2026-11-22 amendment), so the + two must stay apart. The installer adds the service's read grant on the secrets directory and + takes no wider grant away, and the engine refuses none, so neither leaves the service at read + only there.""" raw = environ.get(CUSTODY_DIRECTORY_VARIABLE, "").strip() secrets = environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip() if ( @@ -727,9 +729,11 @@ def _left_outside_the_custody_directory( run with other variables set wrote it. A second key would not open a store the first one made. Read only while ``MEFOR_CUSTODY_DIRECTORY`` is set. With only ``MEFOR_SECRETS_DIRECTORY`` set, - a file beside the store is not read here: :func:`keep_the_key_step`'s way on (PR 2804 fifth - hold, item 4) is a new secrets directory and a new SQLite path, which may sit beside the key - file it leaves in place, and reading there would refuse that way on.""" + a file beside the store is not read here, as the PR 2804 fifth hold's way on (item 4), a new + secrets directory and a new SQLite path beside the key file it left in place, needed. + :func:`keep_the_key_step`'s way on now sets ``MEFOR_CUSTODY_DIRECTORY``, so it names a new + secrets directory and a new SQLite path in a directory of its own wherever the key file it + leaves in place sits in either (PR 3168 hold, item 1).""" environ = os.environ if environ is None else environ if _directory_variable(environ) != CUSTODY_DIRECTORY_VARIABLE: return None @@ -935,14 +939,26 @@ def keep_the_key_step( or store they cannot tie to this store (PR 2804 fifth and sixth holds). It advises changing no existing file, key, blob or store: it asks for a new custody directory, and with ``new_store`` a new store location, which changes the settings that name them. Names no path and no key. - ``environ`` is accepted from its callers; the text no longer depends on it.""" + + ``environ`` says where the key file it leaves in place sits, so the step reaches a mint (PR + 3168 hold, item 1): once ``MEFOR_CUSTODY_DIRECTORY`` is set, + :func:`_left_outside_the_custody_directory` refuses a mint while a key file sits in the + directory ``MEFOR_SECRETS_DIRECTORY`` names or beside a SQLite store. So where the custody + directory in use is the secrets directory, the step also asks for a new secrets directory, + and where it is a SQLite store's data directory, for a new store location, whatever + ``new_store`` says; a new SQLite path always goes in a directory of its own.""" from messagefoundry.config.settings import SchemaManagement, StoreBackend server = settings.backend is not StoreBackend.SQLITE - # The variable is named here as a literal, not through SECRETS_DIRECTORY_VARIABLE: this text + variable = _directory_variable(os.environ if environ is None else environ) + if variable is None and not server: + # The key file sits beside the store, and stays there. + new_store = True + # The variables are named here as literals, not through SECRETS_DIRECTORY_VARIABLE: this text # can reach stderr, and CodeQL's name heuristic reads that constant as a secret (alert 315). - # It describes no folder to make: the secrets directory must never be made writable by the - # service, so the one procedure in docs/SERVICE.md says how to get a custody directory. + # It describes no folder to make and offers no secrets directory as the custody directory: a + # service that may add a file there may supply a secret-class setting (ADR 0214's 2026-11-22 + # amendment), so the one procedure in docs/SERVICE.md says how to get a custody directory. text = ( "To go on without it, give this store a custody directory of its own, named by " "MEFOR_CUSTODY_DIRECTORY here and in this store's own service environment, never one that " @@ -950,9 +966,22 @@ def keep_the_key_step( f"docs/SERVICE.md, '{_SERVICE_PROCEDURE_TITLE}', says how, and the engine checks that " "directory at start" ) + if variable == SECRETS_DIRECTORY_VARIABLE: + text += ( + ". Give it a new secrets directory, named by MEFOR_SECRETS_DIRECTORY in both places, " + f"holding this service's other secret files but no {HOST_FILE_NAME} and no " + f"{HANDOFF_FILE_NAME}, as that procedure says: while either file is in the secrets " + "directory MEFOR_SECRETS_DIRECTORY names, the engine mints no key in a custody " + "directory" + ) if new_store: text += ". Point [store] at a store location of its own: " + ( - "a new database" if server else "a new SQLite path" + "a new database" + if server + else ( + f"a new SQLite path in a directory of its own, with no {HOST_FILE_NAME} and no " + f"{HANDOFF_FILE_NAME} in it" + ) ) if server and settings.resolved_schema_management() is SchemaManagement.EXTERNAL: text += ( @@ -1098,14 +1127,15 @@ def _refuse_an_unusable_directory( writers = "this account" + ( "" if service_account is None else f' and the service account "{service_account}"' ) - # No folder to make is described here, and the secrets directory is never offered: it must not - # be made writable by the service. The one procedure in docs/SERVICE.md says how. + # The secrets directory is not offered as the custody directory: a service that may add a file + # there may supply a secret-class setting (ADR 0214's 2026-11-22 amendment). The one procedure + # in docs/SERVICE.md says how to get a custody directory. secrets_directory = ( f"a custody directory of its own, got as docs/SERVICE.md, '{_SERVICE_PROCEDURE_TITLE}', " f"says, which {writers} can add a file to" ) - def move_on(to: str) -> str: + def move_on(to: str, *, local: bool = False) -> str: # The variable is named as a literal: this text reaches stderr (keep_the_key_step says # why). variable = ( @@ -1113,9 +1143,10 @@ def move_on(to: str) -> str: ) if named: return variable + where = "a new data directory" + (" on a local file system" if local else "") return ( - "point --db at a SQLite path in a new data directory, by its absolute path, here and " - "wherever the service passes --db, since the store key sits beside the store file, or " + f"point --db at a SQLite path in {where}, by its absolute path, here and wherever the " + "service passes --db, since the store key sits beside the store file, or " f"{variable}" ) @@ -1126,11 +1157,19 @@ def move_on(to: str) -> str: f"{none_shown}. To go on, {move_on(secrets_directory)}, and run " "the command again" ) - # A directory behind a parent this account cannot search reads as absent here too. + # A directory behind a parent this account cannot search reads as absent here too. A + # missing secrets directory is not to be made one the service may add a file to. + create = { + CUSTODY_DIRECTORY_VARIABLE: ( + f"create it as docs/SERVICE.md, '{_SERVICE_PROCEDURE_TITLE}', says, so that " + f"{writers} can add a file to it, or " + ), + None: f"create it, a directory {writers} can add a file to, or ", + }.get(named, "") raise HostCustodyRefused( f"the custody directory {directory} is missing, or a directory above it is one this " - f"account cannot search, {none_shown}. To go on, {move_on(secrets_directory)}, or let " - "this account search the directories above it, and run the command again" + f"account cannot search, {none_shown}. To go on, {create}{move_on(secrets_directory)}, " + "or let this account search the directories above it, and run the command again" ) can_add = can_add_a_file(directory) if can_add is None: @@ -1159,7 +1198,7 @@ def move_on(to: str) -> str: raise HostCustodyRefused( f"the custody directory {directory} cannot hold a store key: {volume}. No store key " "was minted and no recovery key was shown. To go on, " - f"{move_on(secrets_directory + ', on a local file system')}, and run the " + f"{move_on(secrets_directory + ', on a local file system', local=True)}, and run the " "command again" ) diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index 126fa064d5..1805d58712 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -3157,9 +3157,11 @@ if ($HostCustody) { # --- the custody directory (vault BACKLOG #3411, ADR 0214's 2026-11-22 amendment) -------------------- # Under the host provider the service's first start writes its own key file, master.key, beside the -# handoff provision-admin leaves, so it must add a file where those two live. This script's access -# list makes the secrets directory administrator-written (ADR 0214; the engine does not enforce -# that), so they get a directory of their own, named to the service as +# handoff provision-admin leaves, so it must add a file where those two live. A service that may add +# a file to the secrets directory may supply a secret-class setting (ADR 0214's amendment), and +# Set-SecretsDirAcl adds the service's read grant there without taking away a wider grant it +# already holds, nor does the engine refuse one, so the key files do not rest on the service +# lacking that right. They get a directory of their own, named to the service as # MEFOR_CUSTODY_DIRECTORY, which the engine reads in place of MEFOR_SECRETS_DIRECTORY for them. # Judged here, before anything acts, by the secrets directory's rules; made, restricted # (Set-CustodyDirAcl) and named once the account resolves, after the service is registered. diff --git a/tests/test_store_custody_host.py b/tests/test_store_custody_host.py index 60742a441e..dbda5116cb 100644 --- a/tests/test_store_custody_host.py +++ b/tests/test_store_custody_host.py @@ -509,12 +509,33 @@ def test_each_key_file_refusal_points_at_one_service_md_procedure_and_states_no_ section = " ".join(_service_md_section(title).split()) for needed in ("-DataDir", "-SecretsDir", "-CustodyDir", "Delete nothing", "Across volumes"): assert needed in section, (needed, section) - # Manager decision 2026-11-22: a new data directory takes everything the engine keeps there - # but the key files; a key file original a copy replaced is kept in an administrator-only - # folder, never deleted; and a second copy is read by whoever its access list names. - for needed in ("the log spool", "the generated API certificate", "Never delete it"): + # PR 3168 hold, items 2 and 4 to 8: a new data directory takes only this store's own files, + # the certificate pair together; a kept master.key original has its list set, not only moved; + # a handoff original goes once the service has started; machine-scope DPAPI unwraps on this + # host only; and its readers are an "at least" list. + for needed in ( + "only files you know are this store's or this service's", + "any other database with its `-wal` and `-shm` files", + "`api-generated-cert.pem` with `api-generated-key.pem`. Move that pair together", + "Moving a file into another folder does not do that", + "/remove:g", + "/setowner", + "A `handoff.key` original:** delete it once the service has started from the copy", + "though it does not unwrap on another host", + "It is still read by at least SYSTEM", + "SeBackupPrivilege", + "in this step they may be another store's", + ): assert needed in section, (needed, section) - assert "delete each original" not in section and "by any account" not in section, section + for gone in ( + "Never delete it", + "anyone who already has its bytes", + "move everything the engine keeps", + "or follow step 3", + "delete each original", + "by any account", + ): + assert gone not in section, (gone, section) def test_the_custody_and_secrets_overlap_is_compared_where_each_resolves(tmp_path: Path) -> None: @@ -619,6 +640,30 @@ def test_the_way_on_names_the_custody_directory_of_its_own(tmp_path: Path) -> No assert "named by MEFOR_CUSTODY_DIRECTORY here" in secrets, secrets +@pytest.mark.parametrize("backend", [StoreBackend.SQLITE, StoreBackend.POSTGRES]) +@pytest.mark.parametrize("named", ["custody", "secrets", "neither"]) +def test_the_way_on_moves_off_every_directory_the_left_behind_check_reads( + tmp_path: Path, backend: StoreBackend, named: str +) -> None: + """PR 3168 hold, items 1 and 9: once MEFOR_CUSTODY_DIRECTORY is set, a key file in the secrets + directory or beside a SQLite store refuses a mint, so the step names a new one of each that + holds the key file it leaves in place, even where its caller keeps the store location.""" + settings = _settings(tmp_path).model_copy(update={"backend": backend}) + environ = { + "custody": {"MEFOR_CUSTODY_DIRECTORY": str(tmp_path / "custody")}, + "secrets": {"MEFOR_SECRETS_DIRECTORY": str(tmp_path / "secrets")}, + "neither": {}, + }[named] + step = custody_host.keep_the_key_step(settings, new_store=False, environ=environ) + assert "named by MEFOR_CUSTODY_DIRECTORY here" in step, step + assert ("a new secrets directory, named by MEFOR_SECRETS_DIRECTORY" in step) is ( + named == "secrets" + ), step + beside = named == "neither" and backend is StoreBackend.SQLITE + assert ("a new SQLite path in a directory of its own" in step) is beside, step + assert ("Point [store]" in step) is beside, step + + @windows_only async def test_the_first_start_converts_into_a_directory_it_may_only_read_and_add_a_file_to( tmp_path: Path, @@ -2237,11 +2282,13 @@ def test_the_fallback_step_fits_the_backend_and_the_command( assert (schema in step) is (backend is StoreBackend.POSTGRES), step assert ("a new database" in step) is (backend is StoreBackend.POSTGRES), step monkeypatch.setattr(sys, "platform", "win32") - windows = custody_host.keep_the_key_step(settings, new_store=False) + # A custody directory of its own is in use, so the store location may stay. + own = {"MEFOR_CUSTODY_DIRECTORY": str(tmp_path / "custody")} + windows = custody_host.keep_the_key_step(settings, new_store=False, environ=own) assert "add --service-account with that account" in windows, windows assert "Point [store]" not in windows, windows auto = custody_host.keep_the_key_step( - settings.model_copy(update={"key_provider": "auto"}), new_store=False + settings.model_copy(update={"key_provider": "auto"}), new_store=False, environ=own ) assert "provision-admin" not in auto and "run the command again" in auto, auto # No key is minted there, so no new key or recovery key is spoken of. @@ -2264,8 +2311,9 @@ def test_the_fallback_re_run_never_points_back_at_the_old_store( # [store].server/database, here and for the service. With the store kept, the re-run keeps # every argument, --db and --service-config among them. settings = _settings(tmp_path).model_copy(update={"backend": backend}) + own = {"MEFOR_CUSTODY_DIRECTORY": str(tmp_path / "custody")} step = custody_host.keep_the_key_step( - settings, new_store=new_store, service_account=service_account + settings, new_store=new_store, service_account=service_account, environ=own ) assert "same arguments" not in step, step command = ( @@ -2631,35 +2679,56 @@ async def _a_still_opens() -> None: @host_file_platforms +@pytest.mark.parametrize("kept_in", ["beside the store", "the secrets directory"]) def test_the_way_on_a_never_started_refusal_names_lets_the_mint_go_ahead( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + kept_in: str, ) -> None: - # PR 2804 fifth hold, item 4: follow the refusal's one way on, a new, empty custody directory - # and a new store location, and the re-run mints this store's key there through mint_target - # and provisions it. The key file and the store left in place are untouched. + # PR 2804 fifth hold, item 4, and PR 3168's hold, items 1 and 9: follow the refusal's way on as + # it reads, wherever the key file it leaves in place sits, and the re-run mints this store's + # key in the new custody directory MEFOR_CUSTODY_DIRECTORY names, through mint_target, and + # provisions it. With that variable set, a key file in the secrets directory or beside the + # store refuses a mint (_left_outside_the_custody_directory), so the way on must name new ones + # too. The key file and the store left in place are untouched. import asyncio from messagefoundry import __main__ as cli from messagefoundry.__main__ import main - settings = _settings(tmp_path) + store_dir = tmp_path / "old" + store_dir.mkdir() + settings = _settings(store_dir) store_path = Path(settings.path) async def _unstarted() -> None: await (await _keyless_store(store_path)).close() asyncio.run(_unstarted()) + if kept_in == "beside the store": + kept_dir = store_dir + else: + kept_dir = _own_custody_directory(tmp_path / "secrets") + monkeypatch.setenv("MEFOR_SECRETS_DIRECTORY", str(kept_dir)) _mint(settings) - kept = tmp_path / custody_host.HOST_FILE_NAME + kept = kept_dir / custody_host.HOST_FILE_NAME + assert kept.exists() assert _run_provision_admin(tmp_path, monkeypatch, store_path) == 2 - assert "named by MEFOR_CUSTODY_DIRECTORY here" in " ".join(capsys.readouterr().err.split()) + err = " ".join(capsys.readouterr().err.split()) + assert "named by MEFOR_CUSTODY_DIRECTORY here" in err, err + assert "a new SQLite path in a directory of its own" in err, err + new_secrets = "a new secrets directory, named by MEFOR_SECRETS_DIRECTORY" + assert (new_secrets in err) is (kept_in == "the secrets directory"), err left = {path: path.read_bytes() for path in (kept, store_path)} - secrets = tmp_path / "new-secrets" - secrets.mkdir() - if sys.platform != "win32": - secrets.chmod(0o700) - monkeypatch.setenv("MEFOR_SECRETS_DIRECTORY", str(secrets)) - new_store = tmp_path / "new-store.db" + custody = _own_custody_directory(tmp_path / "custody") + monkeypatch.setenv("MEFOR_CUSTODY_DIRECTORY", str(custody)) + if kept_in == "the secrets directory": + monkeypatch.setenv( + "MEFOR_SECRETS_DIRECTORY", str(_own_custody_directory(tmp_path / "new-secrets")) + ) + (tmp_path / "new").mkdir() + new_store = tmp_path / "new" / "store.db" minted: list[Path] = [] real_target = custody_host.mint_target @@ -2675,7 +2744,7 @@ def _target(store: StoreSettings, **kwargs: Any) -> Path: monkeypatch.setattr(cli, "_RecoveryKeyConsole", lambda: _Console("", "wrong")) argv = ["provision-admin", "--username", "site-admin", "--email", "ops@example.invalid"] assert main([*argv, "--db", str(new_store)]) == 0, capsys.readouterr().err - assert minted and set(minted) == {secrets / custody_host.HOST_FILE_NAME}, minted + assert minted and set(minted) == {custody / custody_host.HOST_FILE_NAME}, minted assert minted[0].exists() assert new_store.exists() assert {path: path.read_bytes() for path in left} == left From 711cb880c789b39ec3c4494bf0342dbcacafcb50 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 10:28:12 -0600 Subject: [PATCH 22/28] Key custody: review round-ddf319bc80 repairs to the PR 3168 hold fixes Vault BACKLOG #3411 slice B3c. - keep_the_key_step reads where the kept key file sits, the custody directory in use, not which variable is set: a variable naming the store's own directory now moves the store too, and provision-admin's missing-key refusal (no key file left) passes key_file_left=False and gets no new-secrets-directory ask. A new SQLite path is the default path in a new -DataDir under install-service.ps1, as SERVICE.md step 4 says. Followed to a mint through mint_target from beside the store. - _refuse_an_unusable_directory: the secrets directory is not offered for writing on the add-file refusal; only a missing custody directory is offered for making by hand, with the access list SERVICE.md gives; move_on takes the local-volume fact once. Each text is tested. - The installer's grant keeps a grant the service account itself holds, not every wider grant (ADR 0214, installer comment, docstring). - SERVICE.md: a kept master.key original's owner and list are recorded before they change; the no-scripts paragraph matches step 5. --- docs/SERVICE.md | 9 +- ...-for-the-engine-s-secret-class-settings.md | 4 +- messagefoundry/__main__.py | 5 +- messagefoundry/store/custody_host.py | 97 ++++++++++++------- scripts/service/install-service.ps1 | 4 +- tests/test_store_custody_host.py | 88 ++++++++++++++++- 6 files changed, 161 insertions(+), 46 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index 8264de2d05..c8ebcc6fde 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -402,7 +402,10 @@ tell whose key a file holds, and either file may be the only copy of a store's k certificate pair the same way, both files. Once the service has opened its store from the copies: - **A `master.key` original:** keep it as a second copy of the store's key, but take the - service's access to it away first. Moving a file into another folder does not do that: the + service's access to it away first. Record its owner and list before you change them + (`(Get-Acl -LiteralPath ).Sddl`), and keep that record with it: the engine reads it as + a key file again only once that owner and list are back, and only as the account it was + written for. Moving a file into another folder does not do that: the file keeps its own owner and access list, and an account that list names can still open it by its path. Set the original's owner and list, then check both (`icacls /setowner *S-1-5-32-544`, then @@ -431,7 +434,9 @@ to a new directory owned by the account the engine runs as, mode 0700, in a fold account or root may write, and add the engine's other secret files to a new secrets directory. A move within one file system keeps the file's owner and mode; across file systems, copy it keeping them (`cp -p`, as root). Once the engine has opened its store from the copy, move the original, within -its file system, into a folder only root can read, and keep it there; never delete it. +its file system, into a folder only root can read, and keep it there; never delete it. On +Windows, set a kept original's owner and list as step 5 says rather than only moving it, and +delete a `handoff.key` original once the service has started from the copy, as step 5 says. ## Update to a new build (restart vs reinstall) diff --git a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md index 27bb23f42d..5ce2a17127 100644 --- a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md +++ b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md @@ -157,8 +157,8 @@ names ADR 0019 declared and nobody built. Also not moved: the store key's own re BACKLOG #3411).** Under `[store].key_provider = 'host'` the service's first start writes its own key file, `master.key`, beside the `handoff.key` an administrator's `provision-admin --service-account` left. The installer adds the service's read grant on this directory and - takes no wider grant away, so a write grant the service already holds, such as one the Vault - Agent sink route gives it, survives a rerun; the engine does not refuse one either, since + keeps a grant the service account itself already holds there, so a write grant given to that + account, such as one the Vault Agent sink route gives it, survives a rerun; the engine does not refuse one either, since decision 4's check passes a directory one named account may write. A service right to add a file here would let it supply a secret-class setting. So those two files move to a directory of their own when `MEFOR_CUSTODY_DIRECTORY` names one, an absolute path, which wins over `MEFOR_SECRETS_DIRECTORY` diff --git a/messagefoundry/__main__.py b/messagefoundry/__main__.py index 1fcd2af165..bedc3b75bd 100644 --- a/messagefoundry/__main__.py +++ b/messagefoundry/__main__.py @@ -10592,7 +10592,10 @@ async def server_store_found() -> Literal["none", "empty", "held"]: # On a server the probe refused only a store with a genesis record or with data. held = "exists" if settings.store.backend is StoreBackend.SQLITE else "holds data" step = keep_the_key_step( - settings.store, new_store=True, service_account=args.service_account + settings.store, + new_store=True, + service_account=args.service_account, + key_file_left=False, ) raise HostCustodyRefused( f"the store already {held}, and {missing}. A new key cannot open a store " diff --git a/messagefoundry/store/custody_host.py b/messagefoundry/store/custody_host.py index c01cbfb628..d353206a7c 100644 --- a/messagefoundry/store/custody_host.py +++ b/messagefoundry/store/custody_host.py @@ -204,8 +204,8 @@ def _own_directory_refusal(environ: Mapping[str, str]) -> str | None: service may add files to its custody directory, and a service that may add a file to the secrets directory may supply a secret-class setting (ADR 0214's 2026-11-22 amendment), so the two must stay apart. The installer adds the service's read grant on the secrets directory and - takes no wider grant away, and the engine refuses none, so neither leaves the service at read - only there.""" + keeps a wider grant the service account itself already holds there, and the engine refuses + none, so neither leaves the service at read only there.""" raw = environ.get(CUSTODY_DIRECTORY_VARIABLE, "").strip() secrets = environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip() if ( @@ -255,6 +255,12 @@ def _overlaps(first: str, second: str) -> bool: return False +def _same_directory(first: str, second: str) -> bool: + """Whether ``first`` and ``second`` name one directory, each compared where it resolves to, as + :func:`_overlaps` compares them.""" + return os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)) + + def _custody_paths(directory: Path) -> tuple[Path, Path]: return directory / HOST_FILE_NAME, directory / HANDOFF_FILE_NAME @@ -934,31 +940,47 @@ def keep_the_key_step( new_store: bool, service_account: str | None = None, environ: Mapping[str, str] | None = None, + key_file_left: bool = True, ) -> str: """A fallback way on, after a caller's own remedy, at least for the paths that meet a key file or store they cannot tie to this store (PR 2804 fifth and sixth holds). It advises changing no existing file, key, blob or store: it asks for a new custody directory, and with ``new_store`` a new store location, which changes the settings that name them. Names no path and no key. - ``environ`` says where the key file it leaves in place sits, so the step reaches a mint (PR - 3168 hold, item 1): once ``MEFOR_CUSTODY_DIRECTORY`` is set, - :func:`_left_outside_the_custody_directory` refuses a mint while a key file sits in the - directory ``MEFOR_SECRETS_DIRECTORY`` names or beside a SQLite store. So where the custody - directory in use is the secrets directory, the step also asks for a new secrets directory, - and where it is a SQLite store's data directory, for a new store location, whatever - ``new_store`` says; a new SQLite path always goes in a directory of its own.""" + ``key_file_left`` says a key file is left in place in the custody directory these settings and + ``environ`` name, as at least every caller but provision-admin's missing-key refusal has. The + step then reaches a mint from where it sits (PR 3168 hold, item 1): once + ``MEFOR_CUSTODY_DIRECTORY`` is set, :func:`_left_outside_the_custody_directory` refuses a mint + while a key file sits in the directory ``MEFOR_SECRETS_DIRECTORY`` names or in a SQLite + store's data directory. So where that custody directory is the secrets directory, the step + also asks for a new secrets directory, and where it is the store's data directory, for a new + store location, whatever ``new_store`` says. A new SQLite path always goes in a directory with + neither key file in it.""" from messagefoundry.config.settings import SchemaManagement, StoreBackend server = settings.backend is not StoreBackend.SQLITE - variable = _directory_variable(os.environ if environ is None else environ) - if variable is None and not server: + environ = os.environ if environ is None else environ + kept: Path | None = None + if key_file_left: + try: + kept = custody_directory(settings, environ=environ) + except HostCustodyRefused: + kept = None + secrets = environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip() + in_secrets = kept is not None and os.path.isabs(secrets) and _same_directory(str(kept), secrets) + data_directory = custody_directory(settings, environ={}) + if ( + kept is not None + and data_directory is not None + and _same_directory(str(kept), str(data_directory)) + ): # The key file sits beside the store, and stays there. new_store = True # The variables are named here as literals, not through SECRETS_DIRECTORY_VARIABLE: this text # can reach stderr, and CodeQL's name heuristic reads that constant as a secret (alert 315). - # It describes no folder to make and offers no secrets directory as the custody directory: a - # service that may add a file there may supply a secret-class setting (ADR 0214's 2026-11-22 - # amendment), so the one procedure in docs/SERVICE.md says how to get a custody directory. + # It offers no secrets directory as the custody directory: a service that may add a file there + # may supply a secret-class setting (ADR 0214's 2026-11-22 amendment), so the one procedure in + # docs/SERVICE.md says how to get a custody directory. text = ( "To go on without it, give this store a custody directory of its own, named by " "MEFOR_CUSTODY_DIRECTORY here and in this store's own service environment, never one that " @@ -966,7 +988,7 @@ def keep_the_key_step( f"docs/SERVICE.md, '{_SERVICE_PROCEDURE_TITLE}', says how, and the engine checks that " "directory at start" ) - if variable == SECRETS_DIRECTORY_VARIABLE: + if in_secrets: text += ( ". Give it a new secrets directory, named by MEFOR_SECRETS_DIRECTORY in both places, " f"holding this service's other secret files but no {HOST_FILE_NAME} and no " @@ -979,8 +1001,9 @@ def keep_the_key_step( "a new database" if server else ( - f"a new SQLite path in a directory of its own, with no {HOST_FILE_NAME} and no " - f"{HANDOFF_FILE_NAME} in it" + f"a new SQLite path in a directory with no {HOST_FILE_NAME} and no " + f"{HANDOFF_FILE_NAME} in it (with install-service.ps1, the default path in a new " + "-DataDir, which it creates and restricts, as that procedure says)" ) ) if server and settings.resolved_schema_management() is SchemaManagement.EXTERNAL: @@ -1035,7 +1058,7 @@ def keep_the_key_step( else: text += ". Then run the command again" if new_store: - text += ". The new store starts empty: nothing in the one left in place is carried over" + text += ". The new store starts empty: nothing in a store left in place is carried over" if host: text += ( ". The recovery key shown when an existing key file was minted goes with that file, " @@ -1135,15 +1158,17 @@ def _refuse_an_unusable_directory( f"says, which {writers} can add a file to" ) - def move_on(to: str, *, local: bool = False) -> str: + def move_on(*, local: bool = False) -> str: # The variable is named as a literal: this text reaches stderr (keep_the_key_step says # why). + on = ", on a local file system" if local else "" variable = ( - f"set MEFOR_CUSTODY_DIRECTORY, here and in the service's own environment, to {to}" + "set MEFOR_CUSTODY_DIRECTORY, here and in the service's own environment, to " + f"{secrets_directory}{on}" ) if named: return variable - where = "a new data directory" + (" on a local file system" if local else "") + where = "a new data directory" + on return ( f"point --db at a SQLite path in {where}, by its absolute path, here and wherever the " "service passes --db, since the store key sits beside the store file, or " @@ -1154,21 +1179,22 @@ def move_on(to: str, *, local: bool = False) -> str: if os.path.lexists(directory): raise HostCustodyRefused( f"the custody directory {directory} is not a directory this account can read, " - f"{none_shown}. To go on, {move_on(secrets_directory)}, and run " + f"{none_shown}. To go on, {move_on()}, and run " "the command again" ) # A directory behind a parent this account cannot search reads as absent here too. A # missing secrets directory is not to be made one the service may add a file to. - create = { - CUSTODY_DIRECTORY_VARIABLE: ( - f"create it as docs/SERVICE.md, '{_SERVICE_PROCEDURE_TITLE}', says, so that " - f"{writers} can add a file to it, or " - ), - None: f"create it, a directory {writers} can add a file to, or ", - }.get(named, "") + # A missing data directory is the install script's to make and restrict (docs/SERVICE.md's + # procedure, step 4), so only a custody directory is offered for making by hand. + create = ( + "create it with the access list docs/SERVICE.md, 'The custody directory under the " + f"host key provider', gives, so that {writers} can add a file to it, or " + if named == CUSTODY_DIRECTORY_VARIABLE + else "" + ) raise HostCustodyRefused( f"the custody directory {directory} is missing, or a directory above it is one this " - f"account cannot search, {none_shown}. To go on, {create}{move_on(secrets_directory)}, " + f"account cannot search, {none_shown}. To go on, {create}{move_on()}, " "or let this account search the directories above it, and run the command again" ) can_add = can_add_a_file(directory) @@ -1180,10 +1206,13 @@ def move_on(to: str, *, local: bool = False) -> str: directory, ) if can_add is False: + # Not offered for the secrets directory, for the reason secrets_directory gives. + let_add = ( + "" if named == SECRETS_DIRECTORY_VARIABLE else "Let this account add files there, or " + ) raise HostCustodyRefused( f"this account cannot add a file to the custody directory {directory}, {none_shown}. " - f"Let this account add files there, or {move_on(secrets_directory)}, " - "and run the command again" + f"{let_add}{move_on()}, and run the command again" ) try: volume = key_directory_volume_problem(directory) @@ -1192,13 +1221,13 @@ def move_on(to: str, *, local: bool = False) -> str: f"the file system of the custody directory {directory} could not be checked, since " f"this account could not open the directory ({exc.strerror or type(exc).__name__}), " f"{none_shown}. Let this account open it, or " - f"{move_on(secrets_directory)}, and run the command again" + f"{move_on()}, and run the command again" ) from exc if volume is not None: raise HostCustodyRefused( f"the custody directory {directory} cannot hold a store key: {volume}. No store key " "was minted and no recovery key was shown. To go on, " - f"{move_on(secrets_directory + ', on a local file system', local=True)}, and run the " + f"{move_on(local=True)}, and run the " "command again" ) diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index 1805d58712..ae6746717d 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -3159,8 +3159,8 @@ if ($HostCustody) { # Under the host provider the service's first start writes its own key file, master.key, beside the # handoff provision-admin leaves, so it must add a file where those two live. A service that may add # a file to the secrets directory may supply a secret-class setting (ADR 0214's amendment), and -# Set-SecretsDirAcl adds the service's read grant there without taking away a wider grant it -# already holds, nor does the engine refuse one, so the key files do not rest on the service +# Set-SecretsDirAcl adds the service's read grant there and keeps a wider grant the service account +# itself already holds, nor does the engine refuse one, so the key files do not rest on the service # lacking that right. They get a directory of their own, named to the service as # MEFOR_CUSTODY_DIRECTORY, which the engine reads in place of MEFOR_SECRETS_DIRECTORY for them. # Judged here, before anything acts, by the secrets directory's rules; made, restricted diff --git a/tests/test_store_custody_host.py b/tests/test_store_custody_host.py index dbda5116cb..06db43ab29 100644 --- a/tests/test_store_custody_host.py +++ b/tests/test_store_custody_host.py @@ -641,27 +641,105 @@ def test_the_way_on_names_the_custody_directory_of_its_own(tmp_path: Path) -> No @pytest.mark.parametrize("backend", [StoreBackend.SQLITE, StoreBackend.POSTGRES]) -@pytest.mark.parametrize("named", ["custody", "secrets", "neither"]) +@pytest.mark.parametrize( + "named", ["custody", "secrets", "neither", "custody is the data directory"] +) def test_the_way_on_moves_off_every_directory_the_left_behind_check_reads( tmp_path: Path, backend: StoreBackend, named: str ) -> None: """PR 3168 hold, items 1 and 9: once MEFOR_CUSTODY_DIRECTORY is set, a key file in the secrets directory or beside a SQLite store refuses a mint, so the step names a new one of each that - holds the key file it leaves in place, even where its caller keeps the store location.""" + holds the key file it leaves in place, even where its caller keeps the store location; where + the variable names the store's own directory, that is beside the store too.""" settings = _settings(tmp_path).model_copy(update={"backend": backend}) environ = { "custody": {"MEFOR_CUSTODY_DIRECTORY": str(tmp_path / "custody")}, "secrets": {"MEFOR_SECRETS_DIRECTORY": str(tmp_path / "secrets")}, "neither": {}, + "custody is the data directory": {"MEFOR_CUSTODY_DIRECTORY": str(tmp_path)}, }[named] step = custody_host.keep_the_key_step(settings, new_store=False, environ=environ) assert "named by MEFOR_CUSTODY_DIRECTORY here" in step, step assert ("a new secrets directory, named by MEFOR_SECRETS_DIRECTORY" in step) is ( named == "secrets" ), step - beside = named == "neither" and backend is StoreBackend.SQLITE - assert ("a new SQLite path in a directory of its own" in step) is beside, step + beside = named in ("neither", "custody is the data directory") and ( + backend is StoreBackend.SQLITE + ) + assert ("a new SQLite path in a directory with no master.key" in step) is beside, step assert ("Point [store]" in step) is beside, step + # PR 3168 review round-ddf319bc80: with no key file left in place, as provision-admin's + # missing-key refusal has, nothing but a new custody directory and the caller's own ask. + none_left = custody_host.keep_the_key_step( + settings, new_store=False, environ=environ, key_file_left=False + ) + assert "MEFOR_SECRETS_DIRECTORY" not in none_left and "Point [store]" not in none_left + + +@host_file_platforms +@pytest.mark.parametrize("named", ["neither", "custody is the data directory"]) +def test_the_way_on_from_a_key_file_beside_the_store_reaches_a_mint( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, named: str +) -> None: + """PR 3168 review round-ddf319bc80: mint_target's refusal of a key file beside the store keeps + the store location by its caller, so the step moves it; following the step's text reaches a + mint, through mint_target, with the key file left in place.""" + store_dir = tmp_path / "old" + store_dir.mkdir() + if named == "neither": + environ: dict[str, str] = {} + else: + environ = {"MEFOR_CUSTODY_DIRECTORY": str(_own_custody_directory(store_dir / "c"))} + store_dir = Path(environ["MEFOR_CUSTODY_DIRECTORY"]) + settings = _settings(store_dir) + kept = store_dir / custody_host.HOST_FILE_NAME + kept.write_bytes(b"not read") + with pytest.raises(FileExistsError) as refused: + mint_target(settings, service_account=None, enforcing=True, environ=environ) + text = " ".join(str(refused.value).split()) + assert "named by MEFOR_CUSTODY_DIRECTORY here" in text, text + assert "a new SQLite path in a directory with no master.key" in text, text + followed = {"MEFOR_CUSTODY_DIRECTORY": str(_own_custody_directory(tmp_path / "custody"))} + (tmp_path / "new").mkdir() + moved = settings.model_copy(update={"path": str(tmp_path / "new" / "store.db")}) + target = mint_target(moved, service_account=None, enforcing=True, environ=followed) + assert target == tmp_path / "custody" / custody_host.HOST_FILE_NAME + assert kept.read_bytes() == b"not read" + + +@pytest.mark.skipif(sys.platform not in ("linux", "win32"), reason="mints on Linux and Windows") +@pytest.mark.parametrize("named", ["MEFOR_CUSTODY_DIRECTORY", "MEFOR_SECRETS_DIRECTORY", None]) +def test_the_unusable_directory_refusals_name_their_own_way_on( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, named: str | None +) -> None: + """PR 3168 hold items 12 and 13: a missing custody directory may be created with its access + list, and nothing else is offered for making by hand; the --db alternative keeps "on a local + file system" where the volume is refused; the secrets directory is not offered for writing.""" + from messagefoundry import restricted_file + + missing = tmp_path / "missing" + with pytest.raises(HostCustodyRefused) as refused: + custody_host._refuse_an_unusable_directory(missing, service_account=None, named=named) + text = " ".join(str(refused.value).split()) + created = "create it with the access list docs/SERVICE.md, 'The custody directory under" + assert (created in text) is (named == "MEFOR_CUSTODY_DIRECTORY"), text + assert "create it," not in text, text + monkeypatch.setattr(restricted_file, "can_add_a_file", lambda _d: True) + monkeypatch.setattr( + restricted_file, "key_directory_volume_problem", lambda _d: "a network share" + ) + with pytest.raises(HostCustodyRefused) as volume: + custody_host._refuse_an_unusable_directory(tmp_path, service_account=None, named=named) + text = " ".join(str(volume.value).split()) + assert "can add a file to, on a local file system" in text, text + assert ("in a new data directory, on a local file system" in text) is (named is None), text + monkeypatch.setattr(restricted_file, "can_add_a_file", lambda _d: False) + with pytest.raises(HostCustodyRefused) as no_add: + custody_host._refuse_an_unusable_directory(tmp_path, service_account=None, named=named) + text = str(no_add.value) + assert ("Let this account add files there" in text) is (named != "MEFOR_SECRETS_DIRECTORY"), ( + text + ) @windows_only @@ -2717,7 +2795,7 @@ async def _unstarted() -> None: assert _run_provision_admin(tmp_path, monkeypatch, store_path) == 2 err = " ".join(capsys.readouterr().err.split()) assert "named by MEFOR_CUSTODY_DIRECTORY here" in err, err - assert "a new SQLite path in a directory of its own" in err, err + assert "a new SQLite path in a directory with no master.key" in err, err new_secrets = "a new secrets directory, named by MEFOR_SECRETS_DIRECTORY" assert (new_secrets in err) is (kept_in == "the secrets directory"), err left = {path: path.read_bytes() for path in (kept, store_path)} From eab1e461be148b01b42516ab34bfc97c0df51f45 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 11:10:16 -0600 Subject: [PATCH 23/28] Key custody: review round-1d986c2c9d repairs to the PR 3168 hold fixes Vault BACKLOG #3411 slice B3c. - SERVICE.md: the merge of main kept the host-provider paragraph twice; main's copy, which said a service under this provider does not start, goes. The custody directory section no longer says the secrets directory leaves the service at read only. The certificate pair moves together, and leaving it behind mints a new pair too. - keep_the_key_step moves off every directory the left-behind check reads that holds a key file, not only the custody directory in use; followed to a mint from a key in the secrets directory and an older one beside the store. - _refuse_an_unusable_directory offers no directory for making by hand, since the installer refuses a custody directory it did not make (hold item 13 stays open for a row); the secrets-directory add-file refusal reads as a sentence; a resolved-path helper; own_custody renamed. --- docs/SERVICE.md | 25 +++-------- messagefoundry/store/custody_host.py | 64 ++++++++++++++-------------- tests/test_store_custody_host.py | 38 ++++++++++++++--- 3 files changed, 71 insertions(+), 56 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index c8ebcc6fde..6c70613e69 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -246,21 +246,6 @@ Administrator from an elevated shell on the host: messagefoundry provision-admin --username --email
--db C:\ProgramData\MessageFoundry\messagefoundry.db ``` -Under `[store].key_provider = 'host'` (vault BACKLOG #3411) the service cannot run as SYSTEM, -LOCAL SERVICE or NETWORK SERVICE: that provider refuses them as the engine account. When the -install script reads that setting, from the settings file as its `Get-SettingsKeyProvider` -describes, or from `MEFOR_STORE_KEY_PROVIDER` in the service's own -environment, it refuses such an account before it changes anything: `-AllowLocalSystem` with no -`-ServiceAccount`, and at least the usual spellings of those accounts as `-ServiceAccount`. Under -`[security].enforcement = 'enforce'` the provider also refuses an account that is not local to -this host, such as a domain user or a gMSA, and the script does not check for that. - -The steps above do not yet cover that provider. It refuses a store key set beside it, so step 1's -key makes `provision-admin` refuse; and it mints the store key, which `--service-account` mints for -the service's account rather than yours. The script grants that account read only on the secrets -directory, where the service's first start must write its own key file, so a service the script -installs under this provider does not start yet (vault BACKLOG #3411). - If the service started first, at the shipped posture it refuses to start. Once the earlier start checks pass (the store key and `[alerts]` among them), that refusal names `provision-admin` in the log; run the command, then restart the service. In the data directory the install script hardens, @@ -293,8 +278,10 @@ the service's account rather than yours (vault BACKLOG #3411). The host key provider keeps two files, `handoff.key`, which `provision-admin --service-account` writes, and `master.key`, which the service's first start writes from it and then reads at every -start. The service must be able to add a file where they live, and the secrets directory gives it -read only, since administrators write that directory (ADR 0214). So when the install script reads +start. The service must be able to add a file where they live, and a service that may add a file +to the secrets directory may supply a secret-class setting (ADR 0214's 2026-11-22 amendment); the +install script's own grant there is read, though it keeps a wider grant the service account +already holds. So when the install script reads `[store].key_provider = 'host'` it also makes a **custody directory** of its own for those two files, `-CustodyDir`, else the one the service already names, else `-custody`, and names it to the service as `MEFOR_CUSTODY_DIRECTORY`. It is judged before anything acts by the secrets @@ -385,8 +372,8 @@ tell whose key a file holds, and either file may be the only copy of a store's k shared. Those files are at least this store's database, the file the service's `--db` names, with that file's own `-wal` and `-shm` files; and, only where no other store's database sits in the same directory, the `log-spool` folder and the generated API certificate pair, - `api-generated-cert.pem` with `api-generated-key.pem`. Move that pair together or not at all: - the engine mints a new pair when it finds either one missing, and a client that pins the old + `api-generated-cert.pem` with `api-generated-key.pem`. Move the pair together: where the new + directory lacks either file, the engine mints a new pair there, and a client that pins the old certificate then refuses the new one. Leave `master.key` and `handoff.key` where they are: in this step they may be another store's. 5. **Moving a file.** Within one volume, move it as an administrator diff --git a/messagefoundry/store/custody_host.py b/messagefoundry/store/custody_host.py index d353206a7c..707889e8a0 100644 --- a/messagefoundry/store/custody_host.py +++ b/messagefoundry/store/custody_host.py @@ -248,17 +248,22 @@ def _overlaps(first: str, second: str) -> bool: Windows also reads a short 8.3 name as the long one for the part that exists), then case-folded where the platform folds case (:func:`os.path.normcase`). Two paths on different drives do not overlap, and a UNC spelling of a local path reads as a different drive.""" - own, shared = (os.path.normcase(os.path.realpath(p)) for p in (first, second)) + own, shared = (_resolved(p) for p in (first, second)) try: return os.path.commonpath([own, shared]) in (own, shared) except ValueError: # different drives return False +def _resolved(path: str) -> str: + """Where ``path`` resolves to, case-folded where the platform folds case (:func:`_overlaps`).""" + return os.path.normcase(os.path.realpath(path)) + + def _same_directory(first: str, second: str) -> bool: """Whether ``first`` and ``second`` name one directory, each compared where it resolves to, as :func:`_overlaps` compares them.""" - return os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)) + return _resolved(first) == _resolved(second) def _custody_paths(directory: Path) -> tuple[Path, Path]: @@ -949,32 +954,34 @@ def keep_the_key_step( ``key_file_left`` says a key file is left in place in the custody directory these settings and ``environ`` name, as at least every caller but provision-admin's missing-key refusal has. The - step then reaches a mint from where it sits (PR 3168 hold, item 1): once - ``MEFOR_CUSTODY_DIRECTORY`` is set, :func:`_left_outside_the_custody_directory` refuses a mint - while a key file sits in the directory ``MEFOR_SECRETS_DIRECTORY`` names or in a SQLite - store's data directory. So where that custody directory is the secrets directory, the step - also asks for a new secrets directory, and where it is the store's data directory, for a new - store location, whatever ``new_store`` says. A new SQLite path always goes in a directory with - neither key file in it.""" + step reaches a mint from there (PR 3168 hold, item 1): once ``MEFOR_CUSTODY_DIRECTORY`` is set, + :func:`_left_outside_the_custody_directory` refuses a mint while a key file sits in the + directory ``MEFOR_SECRETS_DIRECTORY`` names or in a SQLite store's data directory. So where + that custody directory, or any directory :func:`_key_file_directories` names that holds a key + file, is the secrets directory, the step also asks for a new secrets directory, and where it is + the store's data directory, for a new store location, whatever ``new_store`` says. A new SQLite + path always goes in a directory with neither key file in it.""" from messagefoundry.config.settings import SchemaManagement, StoreBackend server = settings.backend is not StoreBackend.SQLITE environ = os.environ if environ is None else environ - kept: Path | None = None + # Every directory the left-behind check reads that holds a key file, the custody directory in + # use among them when a key file is left there. + held = {p.parent for p in _key_files_outside(settings, None, environ)} if key_file_left: try: kept = custody_directory(settings, environ=environ) except HostCustodyRefused: kept = None + if kept is not None: + held.add(kept) secrets = environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip() - in_secrets = kept is not None and os.path.isabs(secrets) and _same_directory(str(kept), secrets) + in_secrets = os.path.isabs(secrets) and any(_same_directory(str(d), secrets) for d in held) data_directory = custody_directory(settings, environ={}) - if ( - kept is not None - and data_directory is not None - and _same_directory(str(kept), str(data_directory)) + if data_directory is not None and any( + _same_directory(str(d), str(data_directory)) for d in held ): - # The key file sits beside the store, and stays there. + # A key file sits beside the store, and stays there. new_store = True # The variables are named here as literals, not through SECRETS_DIRECTORY_VARIABLE: this text # can reach stderr, and CodeQL's name heuristic reads that constant as a secret (alert 315). @@ -1153,7 +1160,7 @@ def _refuse_an_unusable_directory( # The secrets directory is not offered as the custody directory: a service that may add a file # there may supply a secret-class setting (ADR 0214's 2026-11-22 amendment). The one procedure # in docs/SERVICE.md says how to get a custody directory. - secrets_directory = ( + own_custody = ( f"a custody directory of its own, got as docs/SERVICE.md, '{_SERVICE_PROCEDURE_TITLE}', " f"says, which {writers} can add a file to" ) @@ -1164,7 +1171,7 @@ def move_on(*, local: bool = False) -> str: on = ", on a local file system" if local else "" variable = ( "set MEFOR_CUSTODY_DIRECTORY, here and in the service's own environment, to " - f"{secrets_directory}{on}" + f"{own_custody}{on}" ) if named: return variable @@ -1182,19 +1189,12 @@ def move_on(*, local: bool = False) -> str: f"{none_shown}. To go on, {move_on()}, and run " "the command again" ) - # A directory behind a parent this account cannot search reads as absent here too. A - # missing secrets directory is not to be made one the service may add a file to. - # A missing data directory is the install script's to make and restrict (docs/SERVICE.md's - # procedure, step 4), so only a custody directory is offered for making by hand. - create = ( - "create it with the access list docs/SERVICE.md, 'The custody directory under the " - f"host key provider', gives, so that {writers} can add a file to it, or " - if named == CUSTODY_DIRECTORY_VARIABLE - else "" - ) + # A directory behind a parent this account cannot search reads as absent here too. None + # is offered for making by hand: the install script makes and restricts each one + # (docs/SERVICE.md's procedure, step 4), and it refuses a custody directory it did not make. raise HostCustodyRefused( f"the custody directory {directory} is missing, or a directory above it is one this " - f"account cannot search, {none_shown}. To go on, {create}{move_on()}, " + f"account cannot search, {none_shown}. To go on, {move_on()}, " "or let this account search the directories above it, and run the command again" ) can_add = can_add_a_file(directory) @@ -1206,9 +1206,11 @@ def move_on(*, local: bool = False) -> str: directory, ) if can_add is False: - # Not offered for the secrets directory, for the reason secrets_directory gives. + # Not offered for the secrets directory, for the reason own_custody gives. let_add = ( - "" if named == SECRETS_DIRECTORY_VARIABLE else "Let this account add files there, or " + "To go on, " + if named == SECRETS_DIRECTORY_VARIABLE + else "Let this account add files there, or " ) raise HostCustodyRefused( f"this account cannot add a file to the custody directory {directory}, {none_shown}. " diff --git a/tests/test_store_custody_host.py b/tests/test_store_custody_host.py index 06db43ab29..424f1f50b2 100644 --- a/tests/test_store_custody_host.py +++ b/tests/test_store_custody_host.py @@ -413,7 +413,7 @@ def test_the_other_provider_refusal_keeps_its_text_through_the_key_seams( def test_a_custody_directory_overlapping_the_secrets_directory_is_refused( tmp_path: Path, where: str ) -> None: - """The custody directory must stay apart from the administrator-written secrets directory, so + """The custody directory must stay apart from the secrets directory (ADR 0214's amendment), so one that is, sits inside or holds it is refused, and the remedy never tells anyone to give the service add-file there. The control: two sibling directories pass this rule.""" secrets = tmp_path / "secrets" @@ -516,7 +516,7 @@ def test_each_key_file_refusal_points_at_one_service_md_procedure_and_states_no_ for needed in ( "only files you know are this store's or this service's", "any other database with its `-wal` and `-shm` files", - "`api-generated-cert.pem` with `api-generated-key.pem`. Move that pair together", + "`api-generated-cert.pem` with `api-generated-key.pem`. Move the pair together", "Moving a file into another folder does not do that", "/remove:g", "/setowner", @@ -679,7 +679,7 @@ def test_the_way_on_moves_off_every_directory_the_left_behind_check_reads( @host_file_platforms @pytest.mark.parametrize("named", ["neither", "custody is the data directory"]) def test_the_way_on_from_a_key_file_beside_the_store_reaches_a_mint( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, named: str + tmp_path: Path, named: str ) -> None: """PR 3168 review round-ddf319bc80: mint_target's refusal of a key file beside the store keeps the store location by its caller, so the step moves it; following the step's text reaches a @@ -721,9 +721,8 @@ def test_the_unusable_directory_refusals_name_their_own_way_on( with pytest.raises(HostCustodyRefused) as refused: custody_host._refuse_an_unusable_directory(missing, service_account=None, named=named) text = " ".join(str(refused.value).split()) - created = "create it with the access list docs/SERVICE.md, 'The custody directory under" - assert (created in text) is (named == "MEFOR_CUSTODY_DIRECTORY"), text - assert "create it," not in text, text + # None is offered for making by hand: the install script makes and restricts each one. + assert "create it" not in text.lower(), text monkeypatch.setattr(restricted_file, "can_add_a_file", lambda _d: True) monkeypatch.setattr( restricted_file, "key_directory_volume_problem", lambda _d: "a network share" @@ -740,6 +739,33 @@ def test_the_unusable_directory_refusals_name_their_own_way_on( assert ("Let this account add files there" in text) is (named != "MEFOR_SECRETS_DIRECTORY"), ( text ) + assert ". To go on, set MEFOR_CUSTODY_DIRECTORY" in text or named != "MEFOR_SECRETS_DIRECTORY" + + +@host_file_platforms +def test_the_way_on_moves_off_every_directory_holding_a_key_file(tmp_path: Path) -> None: + """PR 3168 review round-1d986c2c9d: a key file in the secrets directory and an older one beside + the store. The step names a new one of each, and following it reaches a mint.""" + store_dir = tmp_path / "old" + store_dir.mkdir() + secrets = _own_custody_directory(tmp_path / "secrets") + environ = {"MEFOR_SECRETS_DIRECTORY": str(secrets)} + settings = _settings(store_dir) + for kept in (secrets / custody_host.HOST_FILE_NAME, store_dir / custody_host.HOST_FILE_NAME): + kept.write_bytes(b"not read") + with pytest.raises(FileExistsError) as refused: + mint_target(settings, service_account=None, enforcing=True, environ=environ) + text = " ".join(str(refused.value).split()) + assert "a new secrets directory, named by MEFOR_SECRETS_DIRECTORY" in text, text + assert "a new SQLite path in a directory with no master.key" in text, text + followed = { + "MEFOR_CUSTODY_DIRECTORY": str(_own_custody_directory(tmp_path / "custody")), + "MEFOR_SECRETS_DIRECTORY": str(_own_custody_directory(tmp_path / "new-secrets")), + } + (tmp_path / "new").mkdir() + moved = settings.model_copy(update={"path": str(tmp_path / "new" / "store.db")}) + target = mint_target(moved, service_account=None, enforcing=True, environ=followed) + assert target == tmp_path / "custody" / custody_host.HOST_FILE_NAME @windows_only From cba611904dfebfab5632796f9ab5036e0ff6835c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 11:39:39 -0600 Subject: [PATCH 24/28] Key custody: text only, review round-0da6ce5df9 findings U2, U3, U4, U9 Vault BACKLOG #3411 slice B3c, under the Manager's instruction. Text only: comments, docs and one refusal message; no behaviour changed. - U3: SERVICE.md 'The custody directory under the host key provider' states once which secrets-directory grants survive a rerun (only an explicit grant to the service account; /inheritance:r drops inherited ones). ADR 0214, the installer comment and the overlap docstring point there. - U2: the comment says what Get-CustodyDirProblem refuses. - U4: the overlap refusal names the Vault Agent sink route as a right that may stay, with the key files kept out of it. - U9: the no-scripts paragraph no longer says never delete beside the handoff deletion; the certificate pair originals bullet is rewritten; step 4's -DbPath wording matches the engine's refusal. --- docs/SERVICE.md | 36 ++++++++++++------- ...-for-the-engine-s-secret-class-settings.md | 8 ++--- messagefoundry/store/custody_host.py | 19 ++++++---- scripts/service/install-service.ps1 | 8 ++--- 4 files changed, 43 insertions(+), 28 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index 6c70613e69..0fe35f5e90 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -279,9 +279,14 @@ the service's account rather than yours (vault BACKLOG #3411). The host key provider keeps two files, `handoff.key`, which `provision-admin --service-account` writes, and `master.key`, which the service's first start writes from it and then reads at every start. The service must be able to add a file where they live, and a service that may add a file -to the secrets directory may supply a secret-class setting (ADR 0214's 2026-11-22 amendment); the -install script's own grant there is read, though it keeps a wider grant the service account -already holds. So when the install script reads +to the secrets directory may supply a secret-class setting (ADR 0214's 2026-11-22 amendment). The +install script's own grant to the service there is read, and the engine refuses no grant to one +account, so the service is not thereby left at read only there: a rerun keeps an explicit grant to +the service account itself, such as the write the Vault Agent sink route +([CONFIGURATION.md](CONFIGURATION.md#the-secrets-directory-mefor_secrets_directory)) gives it. +Only an explicit grant survives: the script turns inheritance off (`/inheritance:r`), which drops +every inherited entry, and removes every other account's entry, a group's included. So when the +install script reads `[store].key_provider = 'host'` it also makes a **custody directory** of its own for those two files, `-CustodyDir`, else the one the service already names, else `-custody`, and names it to the service as `MEFOR_CUSTODY_DIRECTORY`. It is judged before anything acts by the secrets @@ -354,9 +359,11 @@ tell whose key a file holds, and either file may be the only copy of a store's k 4. **If the file is another store's, or you cannot tell**, this store needs places that hold neither file. Let the install script make each one new and restricted, rather than making or filling a folder by hand. Re-run it with the option for where the file is: - - beside the store's database: `-DataDir` naming a new folder that does not exist yet, and no - `-DbPath`, so the store is `\messagefoundry.db` in a directory the script creates and - restricts. A `-DbPath` outside `-DataDir` names a folder the script grants nothing on. + - beside the store's database: `-DataDir` naming a new folder that does not exist yet, so the + store is `\messagefoundry.db` in a directory the script creates and restricts. Pass + no `-DbPath`, or a `-DbPath` naming that same path, as the engine's refusal asks; keep both on + every later reinstall. A `-DbPath` outside `-DataDir` names a folder the script grants nothing + on. - in the directory `MEFOR_SECRETS_DIRECTORY` names: `-SecretsDir` naming a new folder that does not exist yet. Then add this service's secret files to it as [the secrets directory](#protect-the-store-encryption-key-at-rest-wp-11d) says. @@ -407,23 +414,26 @@ tell whose key a file holds, and either file may be the only copy of a store's k into `master.key` and deletes the copy it read. It is machine-scope DPAPI: on this host, any process that can read the file can unwrap the store key from it, though it does not unwrap on another host. - - **An `api-generated-key.pem` original:** delete it with its `api-generated-cert.pem`. It is - the private key of a certificate the service still presents. + - **The `api-generated-cert.pem` and `api-generated-key.pem` originals:** delete both once the + service presents the copied pair. The key original is a second copy of the private key the + service presents, readable by whoever its own access list names. - **The database originals** may hold PHI; dispose of them as [PHI.md](PHI.md) describes. 6. **Start the service**, and read its log for a refusal ([Verify it's running](#verify-its-running)). **Without the install scripts**, as on Linux or in a container, the same steps hold with the -engine stopped in place of the service: leave every key file and delete nothing; for a file that +engine stopped in place of the service: leave every key file, and delete none except as the end +of this paragraph says; for a file that is this store's, make the settings change and put the file where the host provider reads it; for one that is not, run the store from a new, empty data directory for a file beside it, or set the variable that names the file's directory, `MEFOR_SECRETS_DIRECTORY` or `MEFOR_CUSTODY_DIRECTORY`, to a new directory owned by the account the engine runs as, mode 0700, in a folder only that account or root may write, and add the engine's other secret files to a new secrets directory. A move within one file system keeps the file's owner and mode; across file systems, copy it keeping them -(`cp -p`, as root). Once the engine has opened its store from the copy, move the original, within -its file system, into a folder only root can read, and keep it there; never delete it. On -Windows, set a kept original's owner and list as step 5 says rather than only moving it, and -delete a `handoff.key` original once the service has started from the copy, as step 5 says. +(`cp -p`, as root). Once the engine has opened its store from the copy, move a `master.key` +original, within its file system, into a folder only root can read, and keep it there. On +Windows, set a kept `master.key` original's owner and list as step 5 says rather than only moving +it, and delete a `handoff.key` original once the service has started from the copy, as step 5 +says; keep every other key file original. ## Update to a new build (restart vs reinstall) diff --git a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md index 5ce2a17127..7c39380763 100644 --- a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md +++ b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md @@ -156,10 +156,10 @@ names ADR 0019 declared and nobody built. Also not moved: the store key's own re - **2026-11-22, the host key provider's files get a custody directory of their own (vault BACKLOG #3411).** Under `[store].key_provider = 'host'` the service's first start writes its own key file, `master.key`, beside the `handoff.key` an administrator's `provision-admin - --service-account` left. The installer adds the service's read grant on this directory and - keeps a grant the service account itself already holds there, so a write grant given to that - account, such as one the Vault Agent sink route gives it, survives a rerun; the engine does not refuse one either, since - decision 4's check passes a directory one named account may write. A service right to add a + --service-account` left. Neither the installer nor the engine leaves the service at read only + on this directory ([SERVICE.md, The custody directory under the host key + provider](../SERVICE.md#the-custody-directory-under-the-host-key-provider) says which grants + survive a rerun); decision 4's check passes a directory one named account may write. A service right to add a file here would let it supply a secret-class setting. So those two files move to a directory of their own when `MEFOR_CUSTODY_DIRECTORY` names one, an absolute path, which wins over `MEFOR_SECRETS_DIRECTORY` for them; unset, they stay where they were, in this directory or beside a SQLite store. Before diff --git a/messagefoundry/store/custody_host.py b/messagefoundry/store/custody_host.py index 707889e8a0..b6230a76d6 100644 --- a/messagefoundry/store/custody_host.py +++ b/messagefoundry/store/custody_host.py @@ -203,9 +203,9 @@ def _own_directory_refusal(environ: Mapping[str, str]) -> str | None: is not read as that path, so it is not caught. The service may add files to its custody directory, and a service that may add a file to the secrets directory may supply a secret-class setting (ADR 0214's 2026-11-22 amendment), so the - two must stay apart. The installer adds the service's read grant on the secrets directory and - keeps a wider grant the service account itself already holds there, and the engine refuses - none, so neither leaves the service at read only there.""" + two must stay apart. Neither the installer nor the engine leaves the service at read only on + the secrets directory: docs/SERVICE.md, 'The custody directory under the host key provider', + says which grants survive.""" raw = environ.get(CUSTODY_DIRECTORY_VARIABLE, "").strip() secrets = environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip() if ( @@ -220,9 +220,12 @@ def _own_directory_refusal(environ: Mapping[str, str]) -> str | None: return ( "the custody directory MEFOR_CUSTODY_DIRECTORY names is, holds or sits inside the " "secrets directory MEFOR_SECRETS_DIRECTORY names. The service may add files to its " - "custody directory, and must not be able to add one to the secrets directory, so do " - "not give it that right there: set MEFOR_CUSTODY_DIRECTORY, here and in the service's " - "environment, to a directory of its own outside it" + "custody directory, and a service that may add a file to the secrets directory may " + "supply a secret-class setting, so the two are kept apart. A right to add a file there " + "that a documented route gives the service, at least the Vault Agent sink route " + "docs/CONFIGURATION.md describes, may stay, but the key files go elsewhere: set " + "MEFOR_CUSTODY_DIRECTORY, here and in the service's environment, to a directory of its " + "own outside it" ) if not raw or not os.path.lexists(raw): # Nothing there: a read finds no file, and a mint refuses the missing directory itself. @@ -1191,7 +1194,9 @@ def move_on(*, local: bool = False) -> str: ) # A directory behind a parent this account cannot search reads as absent here too. None # is offered for making by hand: the install script makes and restricts each one - # (docs/SERVICE.md's procedure, step 4), and it refuses a custody directory it did not make. + # (docs/SERVICE.md's procedure, step 4). Its Get-CustodyDirProblem refuses an existing + # custody directory the service does not name, and one it names whose owner is neither + # Administrators nor SYSTEM; one made by hand in an elevated shell can pass that. raise HostCustodyRefused( f"the custody directory {directory} is missing, or a directory above it is one this " f"account cannot search, {none_shown}. To go on, {move_on()}, " diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index ae6746717d..0def6e3584 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -3158,10 +3158,10 @@ if ($HostCustody) { # --- the custody directory (vault BACKLOG #3411, ADR 0214's 2026-11-22 amendment) -------------------- # Under the host provider the service's first start writes its own key file, master.key, beside the # handoff provision-admin leaves, so it must add a file where those two live. A service that may add -# a file to the secrets directory may supply a secret-class setting (ADR 0214's amendment), and -# Set-SecretsDirAcl adds the service's read grant there and keeps a wider grant the service account -# itself already holds, nor does the engine refuse one, so the key files do not rest on the service -# lacking that right. They get a directory of their own, named to the service as +# a file to the secrets directory may supply a secret-class setting (ADR 0214's amendment), and the +# service is not left at read only there (docs/SERVICE.md 'The custody directory under the host key +# provider' says which grants survive), so the key files do not rest on the service lacking that +# right. They get a directory of their own, named to the service as # MEFOR_CUSTODY_DIRECTORY, which the engine reads in place of MEFOR_SECRETS_DIRECTORY for them. # Judged here, before anything acts, by the secrets directory's rules; made, restricted # (Set-CustodyDirAcl) and named once the account resolves, after the service is registered. From d11efef8f8f1418e036c5c401c5768afc8546c7a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 15:23:32 -0600 Subject: [PATCH 25/28] Key custody: text only, the Lander's hold at comment 7111305444 1. install-service.ps1: the custody-naming refusal and its comment no longer say the service cannot write a key file in the secrets directory; they say it would mint where it does not look. 2. ADR 0214, custody_host.py and install-service.ps1 (and SERVICE.md's custody-directory section): neither the installer nor the engine guarantees the service read only on the secrets directory. 3. SERVICE.md: Set-SecretsDirAcl removes every other account's Allow entry (icacls /remove:g). 4. SERVICE.md, without the install scripts: take the engine account's access to a kept master.key original away (chown to root, or a root-owned 0700 directory), recording owner and mode first. 5. SERVICE.md step 5: a handoff does not unwrap on another host without this host's machine DPAPI keys, which a system-state backup, disk image or cloned VM carries. 6. SERVICE.md step 5: "at least" on the generated key's readers. 7. SERVICE.md step 4: under the host provider, leave this store's database where it is; moving it is scoped to another provider. 8. SERVICE.md: the closing paragraph deletes the generated API pair's originals as step 5 does, and keeps the other master.key and handoff.key originals. No behaviour changed apart from one refusal message's wording. BACKLOG #3411 --- docs/SERVICE.md | 29 ++++++++++++------- ...-for-the-engine-s-secret-class-settings.md | 2 +- messagefoundry/store/custody_host.py | 2 +- scripts/service/install-service.ps1 | 8 ++--- 4 files changed, 24 insertions(+), 17 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index 0fe35f5e90..f2b32ddc7c 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -281,11 +281,11 @@ writes, and `master.key`, which the service's first start writes from it and the start. The service must be able to add a file where they live, and a service that may add a file to the secrets directory may supply a secret-class setting (ADR 0214's 2026-11-22 amendment). The install script's own grant to the service there is read, and the engine refuses no grant to one -account, so the service is not thereby left at read only there: a rerun keeps an explicit grant to +account, so nothing guarantees the service read only there: a rerun keeps an explicit grant to the service account itself, such as the write the Vault Agent sink route ([CONFIGURATION.md](CONFIGURATION.md#the-secrets-directory-mefor_secrets_directory)) gives it. Only an explicit grant survives: the script turns inheritance off (`/inheritance:r`), which drops -every inherited entry, and removes every other account's entry, a group's included. So when the +every inherited entry, and removes every other account's Allow entry, a group's included. So when the install script reads `[store].key_provider = 'host'` it also makes a **custody directory** of its own for those two files, `-CustodyDir`, else the one the service already names, else `-custody`, and names @@ -373,8 +373,10 @@ tell whose key a file holds, and either file may be the only copy of a store's k `AppEnvironmentExtra` list, keeping the other entries. A new data directory starts a new, empty store. Never copy another store's database, or any - key file, into it. To keep this store's own data, move into the new one, as step 5 says, only - files you know are this store's or this service's, and leave everything else where it is, at + key file, into it. Under the host provider, leave this store's database with its `-wal` and + `-shm` files where they are: the service mints a new store key for the new store, and that key + cannot open them. Under another provider, to keep this store's own data, move into the new + one, as step 5 says, only files you know are this store's or this service's, and leave everything else where it is, at least any other database with its `-wal` and `-shm` files, since an old data directory may be shared. Those files are at least this store's database, the file the service's `--db` names, with that file's own `-wal` and `-shm` files; and, only where no other store's database sits @@ -413,10 +415,11 @@ tell whose key a file holds, and either file may be the only copy of a store's k handoff is meant to last only from install to the service's first start, which converts it into `master.key` and deletes the copy it read. It is machine-scope DPAPI: on this host, any process that can read the file can unwrap the store key from it, though it does not unwrap - on another host. + on another host without this host's machine DPAPI keys, which at least a system-state backup, + a disk image or a cloned virtual machine of this host carries. - **The `api-generated-cert.pem` and `api-generated-key.pem` originals:** delete both once the service presents the copied pair. The key original is a second copy of the private key the - service presents, readable by whoever its own access list names. + service presents, readable by at least whoever its own access list names. - **The database originals** may hold PHI; dispose of them as [PHI.md](PHI.md) describes. 6. **Start the service**, and read its log for a refusal ([Verify it's running](#verify-its-running)). @@ -429,11 +432,15 @@ variable that names the file's directory, `MEFOR_SECRETS_DIRECTORY` or `MEFOR_CU to a new directory owned by the account the engine runs as, mode 0700, in a folder only that account or root may write, and add the engine's other secret files to a new secrets directory. A move within one file system keeps the file's owner and mode; across file systems, copy it keeping them -(`cp -p`, as root). Once the engine has opened its store from the copy, move a `master.key` -original, within its file system, into a folder only root can read, and keep it there. On -Windows, set a kept `master.key` original's owner and list as step 5 says rather than only moving -it, and delete a `handoff.key` original once the service has started from the copy, as step 5 -says; keep every other key file original. +(`cp -p`, as root). Once the engine has opened its store from the copy, take the engine +account's access to a `master.key` original away, since the file stays owned by that account +with mode 0600 wherever it moves. Record its owner and mode first (`stat -c '%U:%G %a' `), then either make root its owner (`chown root:root `, +keeping mode 0600), or move it, within its file system, into a directory root owns with mode +0700; keep it there. On Windows, set a kept `master.key` original's owner and list as step 5 +says rather than only moving it, and delete a `handoff.key` original once the service has +started from the copy, as step 5 says. Delete the `api-generated-cert.pem` and +`api-generated-key.pem` originals once the engine presents the copied pair, as step 5 says. +Keep every other `master.key` or `handoff.key` original. ## Update to a new build (restart vs reinstall) diff --git a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md index 7c39380763..20c9719312 100644 --- a/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md +++ b/docs/adr/0214-a-secrets-directory-and-one-accessor-for-the-engine-s-secret-class-settings.md @@ -156,7 +156,7 @@ names ADR 0019 declared and nobody built. Also not moved: the store key's own re - **2026-11-22, the host key provider's files get a custody directory of their own (vault BACKLOG #3411).** Under `[store].key_provider = 'host'` the service's first start writes its own key file, `master.key`, beside the `handoff.key` an administrator's `provision-admin - --service-account` left. Neither the installer nor the engine leaves the service at read only + --service-account` left. Neither the installer nor the engine guarantees the service read only on this directory ([SERVICE.md, The custody directory under the host key provider](../SERVICE.md#the-custody-directory-under-the-host-key-provider) says which grants survive a rerun); decision 4's check passes a directory one named account may write. A service right to add a diff --git a/messagefoundry/store/custody_host.py b/messagefoundry/store/custody_host.py index b6230a76d6..0c160c2e07 100644 --- a/messagefoundry/store/custody_host.py +++ b/messagefoundry/store/custody_host.py @@ -203,7 +203,7 @@ def _own_directory_refusal(environ: Mapping[str, str]) -> str | None: is not read as that path, so it is not caught. The service may add files to its custody directory, and a service that may add a file to the secrets directory may supply a secret-class setting (ADR 0214's 2026-11-22 amendment), so the - two must stay apart. Neither the installer nor the engine leaves the service at read only on + two must stay apart. Neither the installer nor the engine guarantees the service read only on the secrets directory: docs/SERVICE.md, 'The custody directory under the host key provider', says which grants survive.""" raw = environ.get(CUSTODY_DIRECTORY_VARIABLE, "").strip() diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index 0def6e3584..44a7b8da40 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -3159,7 +3159,7 @@ if ($HostCustody) { # Under the host provider the service's first start writes its own key file, master.key, beside the # handoff provision-admin leaves, so it must add a file where those two live. A service that may add # a file to the secrets directory may supply a secret-class setting (ADR 0214's amendment), and the -# service is not left at read only there (docs/SERVICE.md 'The custody directory under the host key +# neither the installer nor the engine guarantees the service read only there (docs/SERVICE.md 'The custody directory under the host key # provider' says which grants survive), so the key files do not rest on the service lacking that # right. They get a directory of their own, named to the service as # MEFOR_CUSTODY_DIRECTORY, which the engine reads in place of MEFOR_SECRETS_DIRECTORY for them. @@ -3713,8 +3713,8 @@ if ($HostCustody) { throw ("$($_.Exception.Message)$removed Re-run the installer. " + "$(Disable-RefusedService -ServiceName $ServiceName -Consequence 'its first start cannot write its store key file as the custody directory needs')") } - # A refusal, not a warning: without the variable the service reads the secrets directory, where - # it cannot write its key file, and a mint made as SERVICE.md says lands where it does not look. + # A refusal, not a warning: without the variable the service reads the secrets directory for its + # key file, so a mint made as SERVICE.md says lands where the service does not look. $custodyNamingError = $null $replacedCustodyDir = $null try { @@ -3724,7 +3724,7 @@ if ($HostCustody) { $removed = Remove-CustodyDirMadeHere -Path $CustodyDir -MadeHere:$CustodyDirMadeHere throw ("Could not name the custody directory in the service's environment " + "($custodyNamingError), and without MEFOR_CUSTODY_DIRECTORY the service looks for its " + - "key file in the secrets directory, where it cannot write one.$removed " + + "key file in the secrets directory and would mint where it does not look.$removed " + "Re-run the installer. " + "$(Disable-RefusedService -ServiceName $ServiceName -Consequence 'it would not find its custody directory')") } From b49710ba4c3f0f9a85dc4c8a8dce58208d61eca2 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 15:40:17 -0600 Subject: [PATCH 26/28] Key custody: text only, review round-0d8df5163a findings - install-service.ps1: the custody-naming refusal no longer says the service mints; a key provision-admin mints lands where the service does not look, and on a rerun the service may still name an older custody directory. Stray "the" removed from the custody comment. - Set-SecretsDirAcl's docstring and comment say Allow entries are removed (icacls /remove:g), so an explicit Deny entry stays; SERVICE.md says which entries survive the same way. - SERVICE.md step 4: the move-only-this-store's-files guidance applies under every provider again; under the host provider the database stays out of the move on both routes, because provision-admin refuses to mint for a SQLite store that exists, and the -CustodyDir route needs a new data directory and provision-admin again. - SERVICE.md step 5: the DPAPI caveat names a disk image or cloned VM only; the generated key's readers are the accounts its list grants read plus privilege holders. - SERVICE.md, without the install scripts: chown the master.key original to root and move it into a root-owned 0700 directory, both; the empty "keep every other original" sentence is gone. - test_store_custody_host.py: the comment matches the DPAPI caveat. No behaviour changed apart from one refusal message's wording. BACKLOG #3411 --- docs/SERVICE.md | 43 +++++++++++++++++------------ scripts/service/install-service.ps1 | 17 +++++++----- tests/test_store_custody_host.py | 4 +-- 3 files changed, 38 insertions(+), 26 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index f2b32ddc7c..3bfcc0f051 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -284,9 +284,10 @@ install script's own grant to the service there is read, and the engine refuses account, so nothing guarantees the service read only there: a rerun keeps an explicit grant to the service account itself, such as the write the Vault Agent sink route ([CONFIGURATION.md](CONFIGURATION.md#the-secrets-directory-mefor_secrets_directory)) gives it. -Only an explicit grant survives: the script turns inheritance off (`/inheritance:r`), which drops -every inherited entry, and removes every other account's Allow entry, a group's included. So when the -install script reads +Of the entries the script does not set itself, only an explicit grant to the service account +and an explicit Deny entry survive: the script turns inheritance off (`/inheritance:r`), which +drops every inherited entry, and removes every other account's Allow entry, a group's included. +So when the install script reads `[store].key_provider = 'host'` it also makes a **custody directory** of its own for those two files, `-CustodyDir`, else the one the service already names, else `-custody`, and names it to the service as `MEFOR_CUSTODY_DIRECTORY`. It is judged before anything acts by the secrets @@ -373,10 +374,8 @@ tell whose key a file holds, and either file may be the only copy of a store's k `AppEnvironmentExtra` list, keeping the other entries. A new data directory starts a new, empty store. Never copy another store's database, or any - key file, into it. Under the host provider, leave this store's database with its `-wal` and - `-shm` files where they are: the service mints a new store key for the new store, and that key - cannot open them. Under another provider, to keep this store's own data, move into the new - one, as step 5 says, only files you know are this store's or this service's, and leave everything else where it is, at + key file, into it. To keep this store's own data, move into the new one, as step 5 says, only + files you know are this store's or this service's, and leave everything else where it is, at least any other database with its `-wal` and `-shm` files, since an old data directory may be shared. Those files are at least this store's database, the file the service's `--db` names, with that file's own `-wal` and `-shm` files; and, only where no other store's database sits @@ -385,6 +384,13 @@ tell whose key a file holds, and either file may be the only copy of a store's k directory lacks either file, the engine mints a new pair there, and a client that pins the old certificate then refuses the new one. Leave `master.key` and `handoff.key` where they are: in this step they may be another store's. + + Under the host provider, leave this store's database, with its `-wal` and `-shm` files, out of + that move, on the `-CustodyDir` route as well as the `-DataDir` one. The new store needs a key + that `messagefoundry provision-admin --service-account` mints for it, and `provision-admin` + refuses to mint for a SQLite store that already exists, because a new key cannot open it. So + under that provider the `-CustodyDir` route needs a new data directory too, and then + `provision-admin` run again for the new store before step 6. 5. **Moving a file.** Within one volume, move it as an administrator (`Move-Item -LiteralPath -Destination `): the file keeps its own owner and access list, which the engine checks exactly on a key file. Across volumes a move is a copy, @@ -415,11 +421,12 @@ tell whose key a file holds, and either file may be the only copy of a store's k handoff is meant to last only from install to the service's first start, which converts it into `master.key` and deletes the copy it read. It is machine-scope DPAPI: on this host, any process that can read the file can unwrap the store key from it, though it does not unwrap - on another host without this host's machine DPAPI keys, which at least a system-state backup, - a disk image or a cloned virtual machine of this host carries. + on another host without this host's machine DPAPI keys, which at least a disk image or a + cloned virtual machine of this host carries. - **The `api-generated-cert.pem` and `api-generated-key.pem` originals:** delete both once the service presents the copied pair. The key original is a second copy of the private key the - service presents, readable by at least whoever its own access list names. + service presents, readable by at least the accounts its own access list grants read and any + account holding a privilege that reads past an access list, such as SeBackupPrivilege. - **The database originals** may hold PHI; dispose of them as [PHI.md](PHI.md) describes. 6. **Start the service**, and read its log for a refusal ([Verify it's running](#verify-its-running)). @@ -434,13 +441,15 @@ account or root may write, and add the engine's other secret files to a new secr within one file system keeps the file's owner and mode; across file systems, copy it keeping them (`cp -p`, as root). Once the engine has opened its store from the copy, take the engine account's access to a `master.key` original away, since the file stays owned by that account -with mode 0600 wherever it moves. Record its owner and mode first (`stat -c '%U:%G %a' `), then either make root its owner (`chown root:root `, -keeping mode 0600), or move it, within its file system, into a directory root owns with mode -0700; keep it there. On Windows, set a kept `master.key` original's owner and list as step 5 -says rather than only moving it, and delete a `handoff.key` original once the service has -started from the copy, as step 5 says. Delete the `api-generated-cert.pem` and -`api-generated-key.pem` originals once the engine presents the copied pair, as step 5 says. -Keep every other `master.key` or `handoff.key` original. +with mode 0600 wherever it moves. Record its owner and mode first +(`stat -c '%U:%G %a' `) and keep that record with it, so they can be restored if the engine +ever has to read it again. Then make root its owner (`chown root:root `, keeping mode 0600), +and move it, within its file system, into a directory root owns with mode 0700, so the engine +account can neither read it nor rename or delete it; keep it there. On Windows, set a kept +`master.key` original's owner and list as step 5 says rather than only moving it, and delete a +`handoff.key` original once the service has started from the copy, as step 5 says. Delete the +`api-generated-cert.pem` and `api-generated-key.pem` originals once the engine presents the copied +pair, as step 5 says. ## Update to a new build (restart vs reinstall) diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index 44a7b8da40..cb23ef0c66 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -1012,7 +1012,8 @@ function Set-SecretsDirAcl { THE ACCOUNT'S GRANT IS ADDED, NEVER REPLACED. An existing directory may give a dedicated engine account more than read, for the Vault Agent sink route docs/CONFIGURATION.md describes, and a rerun must not take that away. Inheritance comes off, so a grant the directory inherited goes. - Every entry for another account is removed: none is offered one, and anyone may have made the + Every Allow entry for another account is removed (icacls /remove:g removes grants only, so an + explicit Deny entry stays): none is offered one, and anyone may have made the folder first under ProgramData. THROWS WHEN THE RESULT IS NOT RESTRICTED. Each step runs whatever the one before it did, so one @@ -1053,7 +1054,7 @@ function Set-SecretsDirAcl { $broad = Get-WellKnownBroadSids & icacls $Path /remove:g @broad | Out-Null # No other account is offered a grant here (docs/CONFIGURATION.md), and a folder made under - # ProgramData may have been made by any local user first. So every other entry is removed. + # ProgramData may have been made by any local user first. So every other Allow entry is removed. foreach ($holder in @(Get-BroadAclResidue -Path $Path -Account $Account)) { $spelled = if ($holder -match '^S-1-') { "*$holder" } else { $holder } & icacls $Path /remove:g $spelled | Out-Null @@ -3158,7 +3159,7 @@ if ($HostCustody) { # --- the custody directory (vault BACKLOG #3411, ADR 0214's 2026-11-22 amendment) -------------------- # Under the host provider the service's first start writes its own key file, master.key, beside the # handoff provision-admin leaves, so it must add a file where those two live. A service that may add -# a file to the secrets directory may supply a secret-class setting (ADR 0214's amendment), and the +# a file to the secrets directory may supply a secret-class setting (ADR 0214's amendment), and # neither the installer nor the engine guarantees the service read only there (docs/SERVICE.md 'The custody directory under the host key # provider' says which grants survive), so the key files do not rest on the service lacking that # right. They get a directory of their own, named to the service as @@ -3713,8 +3714,9 @@ if ($HostCustody) { throw ("$($_.Exception.Message)$removed Re-run the installer. " + "$(Disable-RefusedService -ServiceName $ServiceName -Consequence 'its first start cannot write its store key file as the custody directory needs')") } - # A refusal, not a warning: without the variable the service reads the secrets directory for its - # key file, so a mint made as SERVICE.md says lands where the service does not look. + # A refusal, not a warning: unless the variable names this directory, the service reads its key + # file elsewhere (the secrets directory, or a custody directory an earlier install named), so a + # key provision-admin mints here as SERVICE.md says lands where the service does not look. $custodyNamingError = $null $replacedCustodyDir = $null try { @@ -3723,8 +3725,9 @@ if ($HostCustody) { if ($null -ne $custodyNamingError) { $removed = Remove-CustodyDirMadeHere -Path $CustodyDir -MadeHere:$CustodyDirMadeHere throw ("Could not name the custody directory in the service's environment " + - "($custodyNamingError), and without MEFOR_CUSTODY_DIRECTORY the service looks for its " + - "key file in the secrets directory and would mint where it does not look.$removed " + + "($custodyNamingError). Unless MEFOR_CUSTODY_DIRECTORY names it, the service looks for its " + + "key file elsewhere, in the secrets directory or a custody directory an earlier install " + + "named, so a key provision-admin mints here lands where the service does not look.$removed " + "Re-run the installer. " + "$(Disable-RefusedService -ServiceName $ServiceName -Consequence 'it would not find its custody directory')") } diff --git a/tests/test_store_custody_host.py b/tests/test_store_custody_host.py index 424f1f50b2..3753d117d2 100644 --- a/tests/test_store_custody_host.py +++ b/tests/test_store_custody_host.py @@ -511,8 +511,8 @@ def test_each_key_file_refusal_points_at_one_service_md_procedure_and_states_no_ assert needed in section, (needed, section) # PR 3168 hold, items 2 and 4 to 8: a new data directory takes only this store's own files, # the certificate pair together; a kept master.key original has its list set, not only moved; - # a handoff original goes once the service has started; machine-scope DPAPI unwraps on this - # host only; and its readers are an "at least" list. + # a handoff original goes once the service has started; machine-scope DPAPI does not unwrap on + # another host without this host's machine keys; and its readers are an "at least" list. for needed in ( "only files you know are this store's or this service's", "any other database with its `-wal` and `-shm` files", From d811625a3128eef6070f7b0ed88d3176b08259b0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Mon, 23 Nov 2026 16:02:57 -0600 Subject: [PATCH 27/28] Key custody: text only, review round-693a596586 findings - SERVICE.md custody section: what survives the secrets-directory lockdown is an "at least" list, adding SYSTEM or Administrators entries with other inheritance flags (icacls /grant:r). - install-service.ps1: Get-OtherServiceNamingPath's docstring says Allow entries, as the rest of the file now does; the custody-naming refusal and comment list where the service looks as "at least", now including beside the store. - SERVICE.md step 4: under the host provider every route needs a new store (a new data directory for SQLite, a new database for a server store), then provision-admin with the arguments its refusal names, at least an absolute --db and MEFOR_CUSTODY_DIRECTORY. - SERVICE.md, Linux: record the owner with numeric ids (%u:%g). - Tests: the installer test comment matches the refusal; the SERVICE.md doc-pin test pins the host-provider database rule, the new-store remedy and the Linux chown step. Left for filing: Set-SecretsDirAcl's read-back does not refuse a Deny entry that outranks the service account's read (a code change). No behaviour changed apart from one refusal message's wording. BACKLOG #3411 --- docs/SERVICE.md | 40 +++++++++++++++------------ scripts/service/install-service.ps1 | 15 +++++----- tests/test_install_service_custody.py | 2 +- tests/test_store_custody_host.py | 5 ++++ 4 files changed, 36 insertions(+), 26 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index 3bfcc0f051..1f4ffcc66a 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -284,8 +284,9 @@ install script's own grant to the service there is read, and the engine refuses account, so nothing guarantees the service read only there: a rerun keeps an explicit grant to the service account itself, such as the write the Vault Agent sink route ([CONFIGURATION.md](CONFIGURATION.md#the-secrets-directory-mefor_secrets_directory)) gives it. -Of the entries the script does not set itself, only an explicit grant to the service account -and an explicit Deny entry survive: the script turns inheritance off (`/inheritance:r`), which +Of the entries the script does not set itself, at least an explicit grant to the service +account, an explicit Deny entry, and an explicit SYSTEM or Administrators entry with other +inheritance flags survive: the script turns inheritance off (`/inheritance:r`), which drops every inherited entry, and removes every other account's Allow entry, a group's included. So when the install script reads `[store].key_provider = 'host'` it also makes a **custody directory** of its own for those two @@ -386,11 +387,14 @@ tell whose key a file holds, and either file may be the only copy of a store's k this step they may be another store's. Under the host provider, leave this store's database, with its `-wal` and `-shm` files, out of - that move, on the `-CustodyDir` route as well as the `-DataDir` one. The new store needs a key - that `messagefoundry provision-admin --service-account` mints for it, and `provision-admin` - refuses to mint for a SQLite store that already exists, because a new key cannot open it. So - under that provider the `-CustodyDir` route needs a new data directory too, and then - `provision-admin` run again for the new store before step 6. + that move, whichever route above you take. The new store needs a key that + `messagefoundry provision-admin --service-account` mints for it, and `provision-admin` refuses + to mint for a SQLite store that exists or a server database that holds data, because a new key + cannot open it. So under that provider every route above needs a new store too: a new data + directory for a SQLite store, a new database for a server store. Then run `provision-admin` + again for the new store before step 6, with the arguments the engine's refusal names, at least + `--db` naming the new SQLite path by its absolute path, and `MEFOR_CUSTODY_DIRECTORY` set in + that shell to the custody directory the service names. 5. **Moving a file.** Within one volume, move it as an administrator (`Move-Item -LiteralPath -Destination `): the file keeps its own owner and access list, which the engine checks exactly on a key file. Across volumes a move is a copy, @@ -439,17 +443,17 @@ variable that names the file's directory, `MEFOR_SECRETS_DIRECTORY` or `MEFOR_CU to a new directory owned by the account the engine runs as, mode 0700, in a folder only that account or root may write, and add the engine's other secret files to a new secrets directory. A move within one file system keeps the file's owner and mode; across file systems, copy it keeping them -(`cp -p`, as root). Once the engine has opened its store from the copy, take the engine -account's access to a `master.key` original away, since the file stays owned by that account -with mode 0600 wherever it moves. Record its owner and mode first -(`stat -c '%U:%G %a' `) and keep that record with it, so they can be restored if the engine -ever has to read it again. Then make root its owner (`chown root:root `, keeping mode 0600), -and move it, within its file system, into a directory root owns with mode 0700, so the engine -account can neither read it nor rename or delete it; keep it there. On Windows, set a kept -`master.key` original's owner and list as step 5 says rather than only moving it, and delete a -`handoff.key` original once the service has started from the copy, as step 5 says. Delete the -`api-generated-cert.pem` and `api-generated-key.pem` originals once the engine presents the copied -pair, as step 5 says. +(`cp -p`, as root). Once the engine has opened its store from the copy, take the engine account's +access to a `master.key` original away, since the file stays owned by that account with mode 0600 +wherever it moves. Record its owner and mode first (`stat -c '%u:%g %a' `, numeric ids, since +the engine's account may have no passwd entry) and keep that record with it, so they can be +restored if the engine ever has to read it again. Then make root its owner (`chown root:root +`, keeping mode 0600), and move it, within its file system, into a directory root owns with +mode 0700, so the engine account can neither read it nor rename or delete it; keep it there. On +Windows, set a kept `master.key` original's owner and list as step 5 says rather than only moving +it, and delete a `handoff.key` original once the service has started from the copy, as step 5 says. +Delete the `api-generated-cert.pem` and `api-generated-key.pem` originals once the engine presents +the copied pair, as step 5 says. ## Update to a new build (restart vs reinstall) diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index cb23ef0c66..5322e5c88f 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -909,9 +909,9 @@ function Get-OtherServiceNamingPath { protected Windows services deny administrators that read, and none of them is an NSSM service. A SECOND SERVICE ON THE SAME -DataDir GETS THE SAME DEFAULT secrets directory, and - Set-SecretsDirAcl removes every account's entry but its own service's. So adopting the - directory would strip the first service's read, and sharing it would let each service read - the other's secrets. The installer refuses instead. + Set-SecretsDirAcl removes every Allow entry but its own service's and the two admin ones. So + adopting the directory would strip the first service's read, and sharing it would let each + service read the other's secrets. The installer refuses instead. #> param([Parameter(Mandatory)][string]$ServiceName, [Parameter(Mandatory)][string]$Name, [Parameter(Mandatory)][string]$Path, @@ -3715,8 +3715,8 @@ if ($HostCustody) { "$(Disable-RefusedService -ServiceName $ServiceName -Consequence 'its first start cannot write its store key file as the custody directory needs')") } # A refusal, not a warning: unless the variable names this directory, the service reads its key - # file elsewhere (the secrets directory, or a custody directory an earlier install named), so a - # key provision-admin mints here as SERVICE.md says lands where the service does not look. + # file elsewhere (at least the secrets directory, a custody directory an earlier install named, + # or beside the store), so a key provision-admin mints here lands where the service does not look. $custodyNamingError = $null $replacedCustodyDir = $null try { @@ -3726,8 +3726,9 @@ if ($HostCustody) { $removed = Remove-CustodyDirMadeHere -Path $CustodyDir -MadeHere:$CustodyDirMadeHere throw ("Could not name the custody directory in the service's environment " + "($custodyNamingError). Unless MEFOR_CUSTODY_DIRECTORY names it, the service looks for its " + - "key file elsewhere, in the secrets directory or a custody directory an earlier install " + - "named, so a key provision-admin mints here lands where the service does not look.$removed " + + "key file elsewhere, at least in the secrets directory, a custody directory an earlier " + + "install named, or beside the store, so a key provision-admin mints here lands where " + + "the service does not look.$removed " + "Re-run the installer. " + "$(Disable-RefusedService -ServiceName $ServiceName -Consequence 'it would not find its custody directory')") } diff --git a/tests/test_install_service_custody.py b/tests/test_install_service_custody.py index 650cee5602..266d963691 100644 --- a/tests/test_install_service_custody.py +++ b/tests/test_install_service_custody.py @@ -379,7 +379,7 @@ def test_the_installer_makes_and_names_the_custody_directory_under_the_host_prov assert head < at < end, call["text"] assert "-CustodyDir is used only under [store].key_provider = 'host'" in text # A custody variable the installer could not write refuses and disables the service, as a - # lockdown failure does: without it the service reads the secrets directory for its key file. + # lockdown failure does: without it the service reads its key file elsewhere. flat = " ".join(text.split()) refusal = flat.index('throw ("Could not name the custody directory') assert "Disable-RefusedService" in flat[refusal : refusal + 600], flat[refusal : refusal + 600] diff --git a/tests/test_store_custody_host.py b/tests/test_store_custody_host.py index 3753d117d2..5aee500e6b 100644 --- a/tests/test_store_custody_host.py +++ b/tests/test_store_custody_host.py @@ -525,6 +525,11 @@ def test_each_key_file_refusal_points_at_one_service_md_procedure_and_states_no_ "It is still read by at least SYSTEM", "SeBackupPrivilege", "in this step they may be another store's", + # PR 3168 hold at comment 7111305444, items 4, 7 and 8. + "leave this store's database, with its `-wal` and `-shm` files, out of that move", + "a new data directory for a SQLite store, a new database for a server store", + "`chown root:root `", + "into a directory root owns with mode 0700", ): assert needed in section, (needed, section) for gone in ( From 530e998e5657904386ad40913a69d88c68756a85 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 11:56:17 -0600 Subject: [PATCH 28/28] Secrets-directory lockdown: name the conditional Allow entry that survives /remove:g Answers the Lander hold at comment 7116430423 on d811625a312. SERVICE.md and the Set-SecretsDirAcl and Get-OtherServiceNamingPath docstrings said the install script removes every other account's Allow entry. A conditional (callback) Allow entry survives icacls /remove:g, and the read-back then refuses the install. The text now says "at least every plain Allow entry" and names that case. SERVICE.md also says the read-back does not check a surviving Deny entry. Text only; no behaviour changed. Proposed PR title: Key custody B3c: a custody directory of its own --- docs/SERVICE.md | 5 ++++- scripts/service/install-service.ps1 | 13 ++++++++----- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index 1f4ffcc66a..bcba376b9f 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -287,7 +287,10 @@ the service account itself, such as the write the Vault Agent sink route Of the entries the script does not set itself, at least an explicit grant to the service account, an explicit Deny entry, and an explicit SYSTEM or Administrators entry with other inheritance flags survive: the script turns inheritance off (`/inheritance:r`), which -drops every inherited entry, and removes every other account's Allow entry, a group's included. +drops every inherited entry, and removes at least every other account's plain Allow entry, a +group's included. A conditional (callback) Allow entry survives that removal, and the read-back +then refuses the install. The read-back does not check a surviving Deny entry, so one that names +the service account, or a group it belongs to, can leave the service unable to read its secrets. So when the install script reads `[store].key_provider = 'host'` it also makes a **custody directory** of its own for those two files, `-CustodyDir`, else the one the service already names, else `-custody`, and names diff --git a/scripts/service/install-service.ps1 b/scripts/service/install-service.ps1 index 5322e5c88f..2e985a8576 100644 --- a/scripts/service/install-service.ps1 +++ b/scripts/service/install-service.ps1 @@ -909,7 +909,8 @@ function Get-OtherServiceNamingPath { protected Windows services deny administrators that read, and none of them is an NSSM service. A SECOND SERVICE ON THE SAME -DataDir GETS THE SAME DEFAULT secrets directory, and - Set-SecretsDirAcl removes every Allow entry but its own service's and the two admin ones. So + Set-SecretsDirAcl removes at least every plain Allow entry but its own service's and the two + admin ones (a conditional Allow entry survives, and its read-back then refuses). So adopting the directory would strip the first service's read, and sharing it would let each service read the other's secrets. The installer refuses instead. #> @@ -1012,9 +1013,10 @@ function Set-SecretsDirAcl { THE ACCOUNT'S GRANT IS ADDED, NEVER REPLACED. An existing directory may give a dedicated engine account more than read, for the Vault Agent sink route docs/CONFIGURATION.md describes, and a rerun must not take that away. Inheritance comes off, so a grant the directory inherited goes. - Every Allow entry for another account is removed (icacls /remove:g removes grants only, so an - explicit Deny entry stays): none is offered one, and anyone may have made the - folder first under ProgramData. + At least every plain Allow entry for another account is removed (icacls /remove:g removes + grants only, so an explicit Deny entry stays, and a conditional (callback) Allow entry + survives it too, which the read-back below then refuses): none is offered one, and anyone may + have made the folder first under ProgramData. THROWS WHEN THE RESULT IS NOT RESTRICTED. Each step runs whatever the one before it did, so one failure does not leave a broad entry standing; then the owner and the list are read back, and @@ -1054,7 +1056,8 @@ function Set-SecretsDirAcl { $broad = Get-WellKnownBroadSids & icacls $Path /remove:g @broad | Out-Null # No other account is offered a grant here (docs/CONFIGURATION.md), and a folder made under - # ProgramData may have been made by any local user first. So every other Allow entry is removed. + # ProgramData may have been made by any local user first. So every other plain Allow entry is + # removed; a conditional (callback) Allow entry survives /remove:g, and the read-back refuses it. foreach ($holder in @(Get-BroadAclResidue -Path $Path -Account $Account)) { $spelled = if ($holder -match '^S-1-') { "*$holder" } else { $holder } & icacls $Path /remove:g $spelled | Out-Null