# enstate: state next to the store, a design draft Draft 4, 2026-11-29. What is built of it, [README.md](../README.md) says. Section 12 lists what is open. The name, enstate, may change. An older model of state objects is in [state-object.md](state-object.md); section 9 says how it fits in. [migrations.md](migrations.md) walks through the migration model with three made-up cases. ## 1. The problem A NixOS host is built from two kinds of data. - **Generations**: the system, in the store. They move forward and roll back, get copied to builders and caches, and are readable by everyone on the host. - **State**: keys, passwords, tokens, and also public data about other hosts (their keys, addresses). It has one current value. It moves forward only, on its own schedule (a rotation, a new peer), and each piece has its own audience. NixOS has no facility for the second kind, so it ends up in one of three wrong places: in the store (readable, copied around, and rolled back with the generation: sops-nix and agenix fix the first and not the last), in files nobody declared (`/var/src/secrets`, where a missing file shows up as a failed unit), or evaluated into the system (the host database: a new peer means deploying every host). ## 2. Goals 1. Change state without deploying: rotate a key, add a peer, update known hosts, authorized keys, host names, and have the running system pick it up. 2. A system declares what state it can consume. State that doesn't fit is refused, with the reason, before anything changes. 3. An operator can hand over a part of the state, see what it would do before it is done, and say for each piece whether it must go in or may be left out. 4. State never rolls back when the generation does. Between two generations that expect different state there is a migration. 5. Secrets are never in the store, never on a builder, never evaluated. 6. Independent of hrm and of NixOS: a program and file formats of its own. NixOS integrates it with a module; another system could, too. Scope: the system's state first. Users' state (a user's keys, tokens) and early state (the initrd's ssh host key, a disk's key) come later, by the same mechanism where possible; nothing here may prevent them. Not goals: storing or generating secrets at the source (password-store and the like stay), and configuration management (no code in what gets handed over, see 5.7). ## 3. Words One word per concept, and no word used for two things, so that renaming stays a search and replace. All of them are working names. | word | meaning | |---|---| | **state** | all of it, as opposed to generations; never one piece | | **channel** | one of "the other databases": state with its own provider, order and cadence | | **slot** | a named place in a channel that a generation offers; it holds one entry | | **entry** | what a slot holds: one file, of the slot's type | | **record** | one part of an entry whose type is keyed, under its key | | **type** | what an entry is, as a media type: its shape and encoding | | **snapshot** | the whole content of one channel on one host at one moment | | **submission** | what gets handed to the host: a set of items for one channel, complete or partial | | **manifest** | the part of a submission that lists its items | | **item** | one piece of a submission: an entry or a record to set or remove, and whether it is required | | **group** | items of a submission that go in together or not at all | | **plan** | what a submission would do: which items go in, which don't and why, how the views change, what reacts | | **order** | what makes one snapshot the successor of another (a channel's choice) | | **schema** | what one generation accepts: its channels, slots, types, validators, views, reactions | | **view** | a file made from one or more slots, at a stable path, for services and tools to read | | **invocation** | what the receptor tells a validator, renderer, converter or step: what it is given, and what it is to produce | | **objection** | a complaint about one address, by a validator, converter or step | | **validator** | the program that checks one or more slots' entries | | **renderer** | the program that makes a view | | **converter** | the program that turns an entry of one type into an entry of another | | **step** | a program that makes slots of one schema from slots of another, where no converter can | | **reaction** | what the system does when a view changes: reload or restart units | | **receptor** | the program on the host that plans, accepts or refuses submissions, and migrates | | **provider** | whatever makes submissions and delivers them | | **source** | where a provider takes one item from: a file, a command, an environment variable | | **source list** | the file that names, for one submission, each item's source, and whether it is required | | **migration** | how state accepted under one schema serves another | | **policy** | what to do with a slot that can't be filled | Gone since draft 3: **format** and type **versions** (a type is a media type, 5.1), and the file and structured slots (every slot holds a file). ## 4. The parts | part | where it lives | |---|---| | schema | in the generation (store); it is code, like the system | | validators, renderers, converters, steps | in the generation, or in a generation the stored snapshot was accepted under (section 6) | | submission | made outside, handed to the host | | snapshot | on the host, kept by the receptor | | receptor | on the host, set up by activation; a small program run on demand, like an activation script, not a service; language secondary, Rust a candidate | | provider | outside the host (a deploy tool, an operator, `enstate --pack`), or an agent on it (a sync) | A host would start with two channels: its own secrets (from the deploying host), and the fleet's public data (from a registry). ## 5. How it works ### 5.1 Slots, entries and types A slot holds one entry, and an entry is a file: a private key, a certificate, a ready-made configuration file, or the fleet's hosts as one JSON document. Channels and slots have names from the portable filename character set of POSIX (POSIX.1-2017, 3.281), not starting with a hyphen, `[0-9A-Za-z._][0-9A-Za-z._-]*`, except `.` and `..`, so that a name is always a file name. A slot has a type, and a type is a media type, with parameters where needed: application/x-openssh-private-key; algorithm=ed25519 application/x-pem-file application/octet-stream application/x-enstate-hosts+json A media type names both the shape of an entry and its encoding: the hosts type above is a shape of its own (a host's name, its addresses, its keys), encoded as JSON (the `+json` suffix). Parameters narrow it: an OpenSSH private key in general, or an ed25519 one. The receptor compares types in a normal form (case, order of parameters). The type names here are working names; which media type trees enstate uses (`x-`, `prs.`, `vnd.`) is open (section 12). A change of shape is a new type, not a version of the old one: hosts with one address and hosts with several are two types, and a converter (5.2) turns one into the other. That two types mean the same thing, encoded differently, is a matter of converters between them, not of a field. Where one service wants a key in its own encoding (continuum's ed25519 key, from the same key as ssh's), the slot keeps one type, and a view renders the other. **Records.** Where a type's definition says that its top level is an object keyed by record, the keys are records, and they get addresses of their own. To start with, that is the `+json` types whose top level is an object. The structure is in the entry, not in the slot: a slot has no kind besides its type. **Addresses.** `CHANNEL/SLOT` for an entry, `CHANNEL/SLOT/KEY` for a record. **Validators** come from two places, by the same protocol: - a type's own: is this an ed25519 key in the OpenSSH encoding, are these hosts well formed, do no two hosts have one address. Written once, for the type, and used wherever the type is. - the schema's, across slots: this public key belongs to this private key, this certificate is for this key. Declared in the generation, with the slots they see. A validator sees whole entries, not one record at a time, so it can check what holds between records, and its objections name addresses. ### 5.2 Programs Validators, renderers, converters and steps are programs from generations, and they all follow one protocol. The receptor calls `PROGRAM IN OUT`. Standard input is `/dev/null`, the environment is empty, `IN` is read-only, and `OUT` is the only place it may write. `IN` holds: IN/invocation.json IN/channels/secrets/retiolum.key IN/channels/fleet/hosts Below `channels/`, a path is an address: each slot the program is given is a file at `channels/CHANNEL/SLOT`, its entry exactly as stored. A slot the program is given but which is unfilled is listed in the invocation and has no file. Next to `channels/` there is room for what may come later (the content in place before a submission, or its history). The invocation: ```json { "protocol": 1, "program": "renderer", "view": "ssh-known-hosts", "slots": { "fleet/hosts": { "type": "application/x-enstate-hosts+json" }, "secrets/retiolum.key": { "type": "application/x-openssh-private-key; algorithm=ed25519" } }, "produces": {} } ``` `produces` says what the receptor expects in `OUT`: | program | is given | writes to `OUT` | |---|---|---| | validator | the slots it checks, as they would be after the submission | nothing | | renderer | the slots its view is made from | the view's files: regular files and directories only | | converter | one slot, of one type | `OUT/channels/CHANNEL/SLOT`, of the type in `produces` | | step | the slots of one schema it names | the slots of the other schema in `produces`, the same way | **Objections** are JSON lines on standard output, each naming an address among those the program was given: {"address": "fleet/hosts/ne", "message": "address 10.243.0.1 is taken by xu"} An objection to `CHANNEL/SLOT` is to the entry as a whole. A converter or step that can't carry something over objects to it, the same way; that is how migrations refuse with an address (section 6). A renderer doesn't object; what it can't render, it fails on. **Exit status**: 0 means the program ran, whether or not it objected. Anything else means it failed: the plan refuses, names the program, shows what it wrote to standard error, and blames no item. Standard error is the program's log in either case. The receptor sets the modes of what it installs; a program has no say. `IN` and `OUT` are below `/run` (memory), readable by root only. A renderer for a public view is given secret slots only if the schema says so. Later the receptor runs programs in a sandbox, without network and without anything writable but `OUT`; the protocol needs no change for it. ### 5.3 Views and renderers Services don't read slots, they read views: files at stable paths. An entry can be its own view. For anything else, the generation declares a view with a renderer. What a renderer does depends on the data and on who reads it: host records become known hosts for ssh, a zone file for a resolver, host files for tincr. (Host names go to a resolver, not into `/etc/hosts`: that file is the generation's in NixOS, and enstate doesn't touch what a generation owns. How names get resolved can change.) So enstate doesn't define renderers, only the protocol they follow (5.2), and that a renderer reads nothing but `IN`, reaches no network, and gives the same output for the same input. The receptor compares what was written with what is in place, installs it atomically, and runs the reactions of the views that changed. Because a renderer only writes into the directory it is given, the receptor can run it without installing anything. That is what makes plans (5.5) possible without each renderer having a dry-run mode of its own. A sketch of the NixOS side, names not final: ```nix enstate.channels.secrets.slots."retiolum.key" = { type = "application/x-openssh-private-key; algorithm=ed25519"; secret = true; credentialFor = [ "tincr-retiolum" ]; # LoadCredential= follows reaction.restart = [ "tincr-retiolum" ]; }; enstate.channels.secrets.slots."retiolum.pub" = { type = "application/x-openssh-public-key; algorithm=ed25519"; }; enstate.validators.retiolum-key-pair = { # across slots slots = [ "secrets/retiolum.key" "secrets/retiolum.pub" ]; program = ./check-key-pair; }; enstate.channels.fleet.slots.hosts = { type = "application/x-enstate-hosts+json"; # records under host names }; enstate.views.ssh-known-hosts = { from = [ "fleet/hosts" ]; renderer = ./render-known-hosts; }; ``` From the declarations the module generates the schema (a file in the system), the units' credentials, and the receptor's setup. Static configuration points at the views' stable paths (`GlobalKnownHostsFile /run/…/ssh-known-hosts`); what is behind them changes. ### 5.4 Submissions A provider hands the receptor a submission for one channel. It is a directory in the layout of 5.2, with a manifest in place of an invocation: manifest.json channels/secrets/retiolum.key channels/fleet/hosts ```json { "submission": 1, "channel": "fleet", "complete": false, "base": "4f0c…", "items": [ { "address": "fleet/hosts/ne", "op": "set", "group": "ne" }, { "address": "fleet/users/tv", "op": "set", "required": false }, { "address": "fleet/hosts/wu", "op": "remove" } ], "groups": { "ne": { "required": true } } } ``` An item that sets an entry has its file at `channels/CHANNEL/SLOT`. An item that sets records has them in that file, too, as an object with just the records it sets. How the submission gets to the host is not the receptor's business: over ssh from a deploy tool or an operator, or fetched by an agent. `base` is for the order (5.9). Items and groups are required unless they say otherwise, and an item in a group is as required as its group. A submission is **complete** or **partial**: - complete: it is the channel's new content; what it doesn't mention goes. For a provider that owns a channel, like a deploy tool with a host's secrets. - partial: it sets or removes the items it names and leaves the rest. For an operator who adds a host and a key, or rotates one key. **Removing** (proposed): an item may remove an entry or a record instead of setting it. A removal that leaves a required slot unfilled is refused by the plan's check that every required slot is filled (5.5, point 3), like anything else that leaves one unfilled. Each item says whether it is **required** or **optional**: - required: if this item can't go in, the whole submission is refused. - optional: if this item can't go in, it is left out, with a warning, and the rest goes on. Items that belong together can be put in a **group**: the items of a group go in together or not at all, and the group is required or optional as a whole. Grouping is the submission's choice. Items outside a group stand alone, so a submission can let an item in without its companion (a key for a host whose record was left out), if that is what the operator wants. Example: an operator submits a new host record and a new authorized key, both required. The validator objects to the host record (its address is taken), so the submission is refused, with that message. The key still has to change, so the operator submits the key alone; or submits both again with the host record marked optional, and gets the key in and a warning for the record. Had the two been an optional group, neither would have gone in, with one warning. ### 5.5 Plan, then apply The receptor works in two stages, and the first can be run alone, as a dry run. **Plan.** Without changing anything, the receptor: 1. checks that the channel exists in the running generation's schema, and the order (5.9); 2. applies the items to a copy of the current snapshot; 3. checks that every slot the schema requires is filled (an optional removal that would leave one unfilled is taken out); 4. runs the validators on the result, which are given filled slots. Optional items that an objection names are taken out, with their groups, and the checks run again; an objection to a required item, or to something already in place, refuses the submission; 5. runs the renderers into a scratch directory, and compares. The plan says, for each item, whether it goes in, and if not, why; for each view, how it would change (a diff for public views; for secret ones, and files that aren't text, only which files differ, as diffutils says it for binary files); and which reactions would run. **Apply.** The same, and then: the new snapshot becomes current, the views are installed atomically, and each reaction runs once (reload or restart per unit, deduplicated). A submission that is refused changes nothing. ### 5.6 Forcing Not in the first version. Later, a forced submission would go in although it doesn't fit, and policies (section 7) would say what happens to what it leaves unfilled. ### 5.7 No code in submissions A submission is data. Programs, migrations and reactions all come from generations, never from a submission. So whoever can deliver state can change values, but can't run anything on the host, and a submission can be inspected, and planned, before it is applied. (Sources, section 10, run commands, but on the provider's side, before there is a submission.) ### 5.8 Where things are on the host - The current snapshot of each channel is kept on disk, so it survives a reboot, together with the schema it was accepted under (section 6 needs it). Secrets there are root's, as `/var/src/secrets` is today; later they can be encrypted to the host's key. - At boot and on each apply, the receptor materializes the views under `/run` (memory): secret ones readable by root only and handed to services as systemd credentials; public ones readable by everyone. ### 5.9 Order Each channel chooses what makes a snapshot the successor of another. An identifier alone (a UUID) doesn't order; an identifier with what it follows does. Proposed, for the first version: - a **chain**: each snapshot has an id (a UUID), and a submission may name in `base` the snapshot it builds on. If it does, it goes in only if that is the current one, so two providers can't overwrite each other unnoticed. A submission that names none applies to whatever is current. `enstate --status` tells a provider the current id. Later, for a provider that can't ask the host what is current, like a registry many hosts fetch from: a **counter** or a **timestamp** per channel. ## 6. Migrations Generations differ in what they accept: a slot gets added, renamed, removed, split, or its type changes. The state on the host was accepted under one schema and has to serve another whenever the generation changes (switch, rollback, boot) and no fresh submission is at hand. Between two schemas there is a migration, ideally in both directions; that can't be demanded, so there are fallbacks. Generations don't form a line: any one may follow any other. So a migration can't be a numbered script per release. Instead it is put together from parts, most of them implicit, so that having migrations is simple: 1. **Same name, same type**: carries over. Most slots, most of the time; nothing to declare. 2. **Renames**: a slot says `renamedFrom`. 3. **Converters**: from one type to another, in both directions where possible (5.2). They belong to the types, not to a host's configuration, so they're written once. A converter objects to what it can't carry over, by address. 4. **Derived slots**: a slot that can be computed from another (a public key from its private key, as in the state objects) gets filled on the host. 5. **Steps**: a program from the generation, for what the above can't say (splitting one slot in two). The escape hatch. 6. **Fallback**: what no slot wants is kept and reported (it may be wanted again after a rollback); a slot that can't be filled falls to the policy (section 7). Two rules make this work in both directions, and [migrations.md](migrations.md) shows them at work: - **The receptor keeps the schema the snapshot was accepted under.** A rename or a step declared by a newer schema can then be undone for an older generation that has never heard of it: the way back comes from the newer schema, which the state still carries. - **A generation change never rewrites the snapshot.** The receptor computes what the new generation sees from what is stored, and stores that only when the next submission is applied under the new generation. So switching to an older generation and back loses nothing, and a conversion that drops something happens only when an operator hands something over under the older generation, and the plan says what would be dropped. Migrations are code from generations that ran or are about to run on this host, and they run on the host, so secrets don't leave it. The receptor keeps what it needs of the stored schema alive in the store. A fresh submission made for the new schema beats a migration, and the provider knows what to make: the schema is a file in the system it deploys. The order for a change that needs both: first submit what the new generation wants (the old one keeps and ignores it), then switch. With that, most switches need no migration, and migrations are for the times nobody is there: rollbacks and boots. ## 7. Policy One policy to start with: **refuse**. A submission that leaves a required slot unfilled is refused; a switch to a generation whose required slots the state can't fill, even by migrating, is refused before switching, with the reason. At boot nobody can refuse. For now, a slot that can't be filled then has no views, and what needs them fails to start. More policies (stop what can't work, keep the last value that fit), and forcing, come when they turn out to be needed. ## 8. Trust (all of it, eventually) Three stages, each usable on its own: 1. **As today.** The host's ssh host key is the first key. It gets to the host as it does now (rsync over ssh), the authorized keys that allow this are part of the generation, and root on the host hands submissions to the receptor. Transport is trusted because it is ssh. 2. **Signed submissions.** The schema names the keys a channel accepts signatures from. Then the fleet channel can be fetched from somewhere untrusted, like a federation, by an agent without privileges. 3. **Encrypted items.** Secrets encrypted to the host's key, for transport and at rest. The host key itself stays the exception that stage 1 provides, until that evolves. ## 9. How the state objects fit in [state-object.md](state-object.md) describes objects (a key pair, its public half, a certificate), where they may exist (SOURCE, TARGET, REGISTRY, ACTIVE) and the pipelines that move them. That is the provider's side, and this design is the last part of it: - SOURCE and the pipelines (generate, derive the public key, publish it) happen outside the host, in the tool that makes submissions; sources (section 10) are where it reads SOURCE. - TARGET is the receptor's snapshot; ACTIVE is the views. - REGISTRY is where the fleet channel's submissions come from: every host's public halves, composed per host. So one private key appears twice: in its own host's secrets channel, and, as its derived public half, in everyone's fleet channel. A rotation is one pipeline run that produces both. The dependencies there (derived-from) are the derived slots of section 6. Types here and object types there should be one list. ## 10. Providers and sources enstate brings a provider of its own, `enstate --pack`, so that making a submission needs no deploy tool. It reads a source list and writes a submission. Deploy tools may call it, or make submissions themselves; krops' populate and enstate's sources are separate, so each can be used without the other and both can evolve on their own (and learn from each other). A source list names a channel, whether the submission is complete, and, for each item, its source, whether it is required, and its group: ```json { "channel": "secrets", "complete": true, "items": { "retiolum.key": { "source": "cmd:secrets ${env:HOST} show retiolum.ed25519_key.priv" }, "retiolum.pub": { "source": { "command": ["secrets", "${env:HOST}", "show", "retiolum.ed25519_key.pub"] } }, "tls.pem": { "source": { "file": "/etc/ssl/some.pem" }, "required": false } } } ``` Source lists are JSON, or TOML, which maps onto the same data; the extension says which. Sources and their interpolation are those of continuum's `config` crate (continuum's `docs/configuration.md`, on importing values; https://cgit.krebsco.de/continuum), which enstate uses rather than a syntax of its own: - `env:`, `file:`, `cmd:`, and the forms `{ "env": … }`, `{ "file": … }`, `{ "command": "…" }` (a shell command) and `{ "command": [ … ] }` (a program and its arguments, without a shell); - placeholders `${env:…}`, `${file:…}`, `${cmd:…}` in text, which nest: a name, a path, a shell command and each argument may hold them; - a placeholder's value stays data where it goes, never code: into an argument it is exactly one argument; into a shell command it is passed as a positional parameter, and refused where the shell would read it as code (in single quotes, backquotes, arithmetic, after a backslash); - `pack` takes an entry byte-exact, as `+raw` does (no trailing line break removed, UTF-8 or not), since an entry is a file, without the source list having to say so; record items are JSON, as `+json`. Given the schema of the system it deploys (a file in that system), `pack` checks the source list against it before it runs any source: channels, slots, required slots without a source. On the host, a submission goes to the receptor as a directory: ```sh enstate --pack secrets.json --out sub/ rsync -a sub/ root@xu:/var/lib/enstate/incoming/secrets/ ssh root@xu enstate --plan /var/lib/enstate/incoming/secrets ssh root@xu enstate --apply /var/lib/enstate/incoming/secrets ``` (Paths and option names are working names.) enstate's own command line and configuration files use the same crate, so they take JSON or TOML, imported values, and `--print-config` as continuum does. ## 11. Cases to cover, and hrm as a test | case | channel | view, and how the host uses it | reaction | |---|---|---|---| | rotate a service's key | secrets | the key, as a systemd credential | restart or reload the service | | ssh known hosts | fleet | rendered from host records; `GlobalKnownHostsFile` | none, read at each use | | authorized keys | fleet | rendered from user records; `AuthorizedKeysFile` | none | | host names | fleet | a zone file for a local resolver; `/etc/hosts` stays the generation's | reload the resolver | | retiolum peers | fleet | tincr's host files, rendered from host records | reload tincr | | passwords (`shadow-overrides`) | secrets | read at activation today | needs a reaction of its own | What it would replace in hrm: - `/var/src/secrets`, delivered by krops' populate: becomes the secrets channel, with a source list reading the same password-store (`secrets HOST show …`). The `secrets*` rule in `krops.nix`, `inputs.secrets`, and `` in modules go away. - `modules/systemd-credentials.nix` (a path unit and checksum per service): the receptor does this once for all. - The host database evaluated from kartei (retiolum's host files, wiregrill's peers, known hosts): becomes the fleet channel, with the continuum document as its registry. ## 12. Open questions 1. **Types**: where a type is defined (its media type, validator, converters, whether it is keyed): in enstate, as a library of common types, in generations, or both; and which media type tree enstate's own types use (`x-`, `prs.`, `vnd.`). The shape of records stays the type's validator's business for now; JSON Schema could come later. 2. **Order**: the chain is proposed (5.9); counters or timestamps for registries are open. 3. **Removing** (5.4) is proposed, not settled. 4. **What programs see**: only the content as it would be. The content in place before a submission, or history (whole or in part), is postponed; there is room for it next to `channels/` (5.2). 5. **At boot** with a slot that can't be filled: is "no views, consumers fail" good enough until there are more policies? 6. **Names** (section 3). ## 13. A first version Small enough to try on one host, large enough to replace something real: - one channel; slots of type `application/octet-stream` and one or two with validators; one keyed `+json` slot, a validator and a renderer; one validator across two slots (a key pair); - submissions complete and partial, items required and optional, groups, the chain as order; - programs by the protocol of 5.2; - the receptor as a command: `--plan`, `--apply`, `--migrate` (on a generation change), `--materialize` (at boot), `--status`; - `enstate --pack` with source lists in JSON and TOML; - migrations: same name carries over, `renamedFrom`, kept and reported; the two rules of section 6; policy: refuse; - a NixOS module: slot, validator and view options, schema file, credentials, reactions, the check before switching; - tested in a NixOS VM test: apply, refuse (missing slot, wrong base, a validator's objection), an optional item left out with a warning, a plan that changes nothing, rotate without switching, switch and roll back across a rename with state in place. Then: more views, the fleet channel and a registry, signing, converters, steps, forcing and policies, encryption.