diff --git a/docs/SERVICE.md b/docs/SERVICE.md index 0652952f8e..bcba376b9f 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` | @@ -245,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, @@ -275,6 +261,203 @@ 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. +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 (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 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 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, 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 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 +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 allow entry and every deny entry, whoever it names. It then reads the list back, and +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`. + +**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, 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 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. + +**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. [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: + +```powershell +$env:MEFOR_CUSTODY_DIRECTORY = 'C:\ProgramData\MessageFoundry-custody' +``` + +#### 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, + 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 + `[store].key_provider = 'host'`: + - When the refusal says `[store].key_provider` is another provider, make the settings change + 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 + 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, 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. + - 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 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 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. + + Under the host provider, leave this store's database, with its `-wal` and `-shm` files, out of + 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, + 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. 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. 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 + `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 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 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)). + +**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 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, 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) The service runs `\Scripts\python.exe -I -X disable-remote-debug -m messagefoundry @@ -724,7 +907,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 @@ -1283,6 +1466,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 [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/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..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 @@ -153,6 +153,29 @@ 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. 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 + 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; 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 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 at least the custody directory, this directory and the + 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 + 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/__main__.py b/messagefoundry/__main__.py index c70142cc07..729bc14df6 100644 --- a/messagefoundry/__main__.py +++ b/messagefoundry/__main__.py @@ -10592,13 +10592,17 @@ 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 " "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 @@ -10926,13 +10930,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..a7e2ac5d3f 100644 --- a/messagefoundry/engine_secrets.py +++ b/messagefoundry/engine_secrets.py @@ -22,8 +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. + 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 @@ -50,6 +54,7 @@ from typing import Final __all__ = [ + "CUSTODY_DIRECTORY_VARIABLE", "CUSTODY_FILE_NAMES", "DIRECTORY_SETTING_NAMES", "KEY_CLASS_NAMES", @@ -103,6 +108,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..0c160c2e07 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``. @@ -21,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 :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 @@ -57,6 +59,7 @@ record_key_custody, ) from messagefoundry.engine_secrets import ( + CUSTODY_DIRECTORY_VARIABLE, CUSTODY_FILE_NAMES, KEY_CLASS_NAMES, SECRETS_DIRECTORY_VARIABLE, @@ -150,29 +153,156 @@ 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" + # 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 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. 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. + + 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 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 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 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() + secrets = environ.get(SECRETS_DIRECTORY_VARIABLE, "").strip() + 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 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. + return None + from messagefoundry.restricted_file import broad_access_problem + + 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 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, and a UNC spelling of a local path reads as a different drive.""" + 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 _resolved(first) == _resolved(second) + + 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]: + """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)) + 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 = [] @@ -209,31 +339,54 @@ 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 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. + + 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 - 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 = _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. + named = "; ".join(f"{p.name} in {p.parent}" for p in found) return ( - f"{' and '.join(found)} is in {directory}, 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 " - "whether the blob holds this store's key, so it " - f"leaves the file in place. {keep_the_key_step(settings, new_store=False)}" + "whether the blob holds this store's key, so it leaves the file in place. " + f"{_LEAVE_KEY_FILES_STEP}" ) +#: 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 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, 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" +) + + # --- the account ---------------------------------------------------------------------------------- @@ -369,8 +522,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", + "[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, ) @@ -580,6 +734,37 @@ 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 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 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, 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 + found = _key_files_outside(settings, directory, environ) + 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 " + "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}" + ) + + def _missing(host: Path, handoff: Path) -> HostCustodyMissing: """Neither ``host`` nor ``handoff`` is there.""" return _recorded_as( @@ -593,7 +778,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 @@ -604,9 +790,14 @@ 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 " - f"{SECRETS_DIRECTORY_VARIABLE}, 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: + raise _recorded_as(HostCustodyRefused, refusal) return _custody_paths(directory) @@ -675,6 +866,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_outside_the_custody_directory(settings, host.parent, environ) + if stray is not None: + raise _recorded_as(HostCustodyRefused, stray) raise _missing(host, handoff) try: try: @@ -749,29 +943,78 @@ 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, + 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.""" + new store location, which changes the settings that name them. Names no path and no key. + + ``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 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 - # The variable is named here as a literal, not through SECRETS_DIRECTORY_VARIABLE: this text + environ = os.environ if environ is None else environ + # 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 = os.path.isabs(secrets) and any(_same_directory(str(d), secrets) for d in held) + data_directory = custody_directory(settings, environ={}) + if data_directory is not None and any( + _same_directory(str(d), str(data_directory)) for d in held + ): + # 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). + # 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: 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 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 " + 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 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: text += ( @@ -825,7 +1068,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, " @@ -856,8 +1099,14 @@ 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 + ) ) + # 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). @@ -886,21 +1135,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,20 +1160,27 @@ 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 + # 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. + 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" + ) - def move_on(to: str) -> 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 = ( - "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" + "set MEFOR_CUSTODY_DIRECTORY, here and in the service's own environment, to " + f"{own_custody}{on}" ) if named: return variable + where = "a new data directory" + on return ( - f"point --db at a SQLite path in {to}, by its absolute path, here and wherever the " + 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}" ) @@ -933,14 +1189,18 @@ 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()}, 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. None + # is offered for making by hand: the install script makes and restricts each one + # (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}. 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()}, " + "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: @@ -951,10 +1211,15 @@ def move_on(to: str) -> str: directory, ) if can_add is False: + # Not offered for the secrets directory, for the reason own_custody gives. + let_add = ( + "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}. " - f"Let this account add files there, or {move_on('a directory ' + secrets_directory)}, " - "and run the command again" + f"{let_add}{move_on()}, and run the command again" ) try: volume = key_directory_volume_problem(directory) @@ -963,13 +1228,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()}, 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(local=True)}, and run the " "command again" ) 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 4efa183f6c..2e985a8576 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 - @@ -903,9 +909,10 @@ 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 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. #> param([Parameter(Mandatory)][string]$ServiceName, [Parameter(Mandatory)][string]$Name, [Parameter(Mandatory)][string]$Path, @@ -951,7 +958,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) @@ -972,14 +980,24 @@ function New-RestrictedDirectory { $acl = Get-Acl -LiteralPath $Path $owner = $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value if ($owner -ne $OwnerSid -or -not $acl.AreAccessRulesProtected) { + # 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." } 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. $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 { @@ -995,8 +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 entry for another account is removed: 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 @@ -1036,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 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 @@ -1088,12 +1109,212 @@ 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 " + "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. At least a right + beyond those, an allow entry that files or folders inside inherit, a missing read or add-file, + 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 + 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)) { + $sid = try { $rule.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value } + catch { "$($rule.IdentityReference)" } + if ($rule.AccessControlType -ne [Security.AccessControl.AccessControlType]::Allow) { + # 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))" + } + $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 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) { + # 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) { + 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): + 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)" + } + # 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 + } + # /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) { + $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.") + } +} + function Get-MergedEnvironmentList { <# $Existing, an NSSM environment list of NAME=value entries, with every entry for $Name replaced @@ -1154,8 +1375,9 @@ function Get-SettingsKeyProvider { Other forms can misread: at least a value or a quoted key with an escape, and a triple-quoted value, are not read, and at least an inline table that spans lines (through a multi-line string or array value, or as TOML 1.1 allows) and a file that is not valid TOML can misread - 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. + either way. 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 = '(?:"(?[^"\\]*)"|''(?[^'']*)'')' @@ -2835,13 +3057,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 @@ -2853,8 +3079,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") + # 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") { @@ -2900,8 +3139,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" } @@ -2919,6 +3159,65 @@ 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 +# 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. +# 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) { + 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. + $CustodyDirNamed = [bool]$RegisteredCustodyDir -and ($RegisteredCustodyDir.TrimEnd('\') -eq $CustodyDir.TrimEnd('\')) + $custodyProblem = Get-CustodyDirProblem -Path $CustodyDir -ServiceName $ServiceName ` + -Named:$CustodyDirNamed -Holds (@($SecretsHolds) + $SecretsDir) ` + -NotWithin (@($SecretsNotWithin) + $SecretsDir) + if ($custodyProblem) { + 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.") + } +} + # 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 @@ -2968,6 +3267,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 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 @@ -3360,9 +3662,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, and remove the service account's grant there.") + "'$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 { @@ -3370,6 +3675,75 @@ 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) { + # 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, 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 " + + "$($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 + 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: unless the variable names this directory, the service reads its key + # 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 { + $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). Unless MEFOR_CUSTODY_DIRECTORY names it, the service looks for its " + + "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')") + } + 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. 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)." +} # 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/scripts/service/uninstall-service.ps1 b/scripts/service/uninstall-service.ps1 index e31c468d22..d63f4bc729 100644 --- a/scripts/service/uninstall-service.ps1 +++ b/scripts/service/uninstall-service.ps1 @@ -23,7 +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. + 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 @@ -54,7 +57,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 ) @@ -279,6 +283,14 @@ 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, + # 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. @@ -297,6 +309,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). @@ -343,7 +356,31 @@ 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) { + $lines += " Custody dir $CustodyDir" + $lines += " The custody directory the service read under the host key" + $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." + } + 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 'When a refusal names" + $lines += " master.key or handoff.key'." } if ($CachedNssm) { @@ -382,6 +419,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 an entry 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 +791,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 +811,12 @@ 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 + # 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") @@ -934,6 +988,24 @@ $script:LogonRightUnproven = $false $dataAceRemoved = $false $configAceRemoved = $false $secretsAceRemoved = $false +$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") + } +} if ($RemoveLogonRight) { if (-not $hasAccount) { @@ -969,6 +1041,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 +1054,9 @@ Get-UninstallResidueNotice ` -ServiceAccountSid $accountSid ` -ConfigDir $configDir ` -SecretsDir $secretsDir ` + -CustodyDir $custodyDir ` + -CustodyFiles $custodyFiles ` + -CustodyUnconfirmed:$custodyUnconfirmed ` -ConfigInheritanceStripped:$configProtected ` -CachedNssm $cachedNssm ` -WerImages $werImages ` @@ -988,6 +1066,7 @@ Get-UninstallResidueNotice ` -DataAceRemoved:$dataAceRemoved ` -ConfigAceRemoved:$configAceRemoved ` -SecretsAceRemoved:$secretsAceRemoved ` + -CustodyAceRemoved:$custodyAceRemoved ` -RegistrationPending:$registrationPending ` -Unreadable $unreadable | ForEach-Object { Write-Host $_ } diff --git a/tests/test_file_path_join_census.py b/tests/test_file_path_join_census.py index b153550f74..165afbbdf0 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 @@ -1286,7 +1286,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 " @@ -1294,7 +1294,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.", @@ -1310,10 +1311,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 0f96d38504..266d963691 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 sys import tomllib from pathlib import Path @@ -24,8 +25,11 @@ _ok, _preflight_facts, _psq, + _run, _script_text, _sole_call, + _sole_call_on, + _windows_only, ) _SCRIPT = svc.install_script_path() @@ -195,3 +199,383 @@ 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 + ("(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 and deny.""" + assert _SCRIPT is not None + dirs = [] + for i, (spelled, _) in enumerate(_GRANTS): + d = tmp_path / f"g{i}" + d.mkdir() + 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 "{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: + got = json.loads(_ok(_extract(_SCRIPT, ["Get-CustodyGrantProblem"], body), tmp_path)) + finally: + restore = "\n".join( + " $s = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value\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 + ) + _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, and + 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.""" + 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 + & 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)} + 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 + denies = @($acl.Access | Where-Object {{ "$($_.AccessControlType)" -eq 'Deny' }}).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"] + 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"] + 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, 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. + text = _script_text() + 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 + 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") + 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"] < nssm + # 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): + 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 + # A custody variable the installer could not write refuses and disables the service, as a + # 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] + # 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"') + 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 + # 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) == 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 + 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 + + +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"] + 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 + # 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: + """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 + + both = {**_FULL_FACTS, "CustodyFiles": ["master.key", "handoff.key"]} + flat = " ".join(_notice(tmp_path, both).split()) + for needed in ( + "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", + "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, 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() + ) + 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 holds" 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. + 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" + 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)) + 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) + 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 "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 + 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" + # 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 diff --git a/tests/test_service_install_manifest.py b/tests/test_service_install_manifest.py index e88cf50ceb..90cc05ac34 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", @@ -1231,6 +1232,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. @@ -2743,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"], @@ -2757,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", @@ -2914,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, ( @@ -3744,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"] @@ -4018,8 +4033,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 +4049,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 +4060,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"] diff --git a/tests/test_store_custody_host.py b/tests/test_store_custody_host.py index e08c093482..5aee500e6b 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": @@ -189,10 +190,649 @@ 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={}) +# --- 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 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 + + +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: + # 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) + + +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="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) + # 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 "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="host custody was found elsewhere") as refused: + load_host_custody( + _settings(tmp_path), + enforcing=True, + environ={"MEFOR_CUSTODY_DIRECTORY": str(custody_dir)}, + ) + 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="host custody was found elsewhere"): + 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"]) +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_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. 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") + settings = _settings(tmp_path, key_provider="auto", encryption_key_file="k.bin") + environ = { + "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 f"master.key in {tmp_path}" 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 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 + 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 "where it is, and delete nothing" 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 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" + 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.""" + 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 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: + load_host_custody( + _settings(tmp_path), + enforcing=True, + environ={"MEFOR_CUSTODY_DIRECTORY": str(custody_dir)}, + ) + text = str(refused.value) + 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) + # 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 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", + "`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", + "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", + # 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 ( + "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: + """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( + 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="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="host custody was found elsewhere"): + 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: + 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_CUSTODY_DIRECTORY here" in secrets, secrets + + +@pytest.mark.parametrize("backend", [StoreBackend.SQLITE, StoreBackend.POSTGRES]) +@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; 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 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, 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()) + # 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" + ) + 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 + ) + 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 +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) + # 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, 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( + ["pwsh", "-NoProfile", "-Command", read], check=True, capture_output=True, text=True + ).stdout + 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(): + 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"), [ @@ -233,7 +873,10 @@ 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 + 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 with pytest.raises(HostCustodyRefused, match=name): await open_store(settings, create=True) @@ -1602,7 +2245,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 @@ -1690,9 +2335,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" @@ -1710,10 +2356,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]) @@ -1729,7 +2375,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 " @@ -1737,19 +2383,21 @@ 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 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. @@ -1772,8 +2420,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 = ( @@ -1985,7 +2634,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'"), + ("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"), @@ -2124,7 +2773,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 @@ -2139,35 +2788,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_SECRETS_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 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)} - 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 @@ -2183,7 +2853,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 @@ -2280,7 +2950,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"])