From e1644b9d0f72e9bad824e75e3b294968b06a454e Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 30 Nov 2026 13:13:44 +0000 Subject: nix: the package, a NixOS module, its VM test The module makes the schema from options (/etc/enstate/schema.json), every slot its own view unless it says otherwise, and names the views' paths (read-only `path` options) for the services that read them. It configures none of them: a service whose LoadCredential= reads a view is ordered after the unit that puts the views in place, by itself. That unit runs --migrate at boot and when the schema changes; the check before a switch is --migrate --dry-run against the new schema. The test: a consumer with a LoadCredential= of its own; apply from a source list, rotate, switch across a rename and back, a switch refused, a reboot. --- nix/module.nix | 340 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ nix/package.nix | 37 ++++++ nix/test.nix | 119 ++++++++++++++++++++ 3 files changed, 496 insertions(+) create mode 100644 nix/module.nix create mode 100644 nix/package.nix create mode 100644 nix/test.nix (limited to 'nix') diff --git a/nix/module.nix b/nix/module.nix new file mode 100644 index 0000000..f81bea9 --- /dev/null +++ b/nix/module.nix @@ -0,0 +1,340 @@ +# enstate on NixOS (docs/design.md, 5.3): the schema from options, the receptor run at +# boot and after each switch, and the check before a switch. +# +# enstate.enable = true; +# enstate.channels.secrets.slots."retiolum.key" = { +# type = "application/x-openssh-private-key; algorithm=ed25519"; +# secret = true; +# reactions.restart = [ "tincr-retiolum.service" ]; # unless it restarts itself +# }; +# enstate.channels.fleet.slots.hosts.type = "application/x-enstate-hosts+json"; +# enstate.views.ssh-known-hosts = { +# from = [ "fleet/hosts" ]; +# renderer = ./render-known-hosts; +# }; +# +# systemd.services.tincr-retiolum.serviceConfig.LoadCredential = +# "retiolum.key:${config.enstate.channels.secrets.slots."retiolum.key".path}"; +# +# Every slot is its own view, `CHANNEL.SLOT`, unless it says `view = false`; its file +# is the slot's `path`, `/run/enstate/views/CHANNEL.SLOT/SLOT`. Services read views +# as they like; one whose `LoadCredential=` reads a view is ordered after the unit that +# puts the views in place, by itself. +{ + config, + lib, + pkgs, + ... +}: + +let + inherit (lib) mkOption types; + cfg = config.enstate; + + reactions = { + restart = mkOption { + type = types.listOf types.str; + default = [ ]; + description = "Units to restart when the view changes (`foo.service`)."; + }; + reload = mkOption { + type = types.listOf types.str; + default = [ ]; + description = "Units to reload (or restart, if they can't reload) when the view changes."; + }; + }; + + slot = + channel: + types.submodule ( + { name, config, ... }: + { + options = { + type = mkOption { + type = types.str; + description = "What the slot holds, as a media type."; + example = "application/x-openssh-private-key; algorithm=ed25519"; + }; + required = mkOption { + type = types.bool; + default = true; + description = "Whether a submission, or a switch, that leaves the slot unfilled is refused."; + }; + secret = mkOption { + type = types.bool; + default = false; + description = "Whether the slot's views are readable by root only."; + }; + renamedFrom = mkOption { + type = types.nullOr types.str; + default = null; + description = "The slot's name in an earlier generation, so its entry carries over, both ways."; + }; + view = mkOption { + type = types.bool; + default = true; + description = "Whether the slot is its own view, `CHANNEL.SLOT`."; + }; + path = mkOption { + type = types.nullOr types.str; + readOnly = true; + default = if config.view then "${cfg.runDir}/views/${channel}.${name}/${name}" else null; + defaultText = lib.literalExpression ''"''${config.enstate.runDir}/views/CHANNEL.SLOT/SLOT"''; + description = "Where the slot's own view puts its entry, if it has one, for services to read."; + }; + inherit reactions; + }; + } + ); + + # The views of slots that are their own. + slotViews = lib.concatMapAttrs ( + channel: channelCfg: + lib.concatMapAttrs ( + name: slotCfg: + lib.optionalAttrs slotCfg.view { + "${channel}.${name}" = { + from = [ "${channel}/${name}" ]; + inherit (slotCfg) reactions; + }; + } + ) channelCfg.slots + ) cfg.channels; + + nonNull = lib.filterAttrs (_: value: value != null); + + schema = { + schema = 1; + types = lib.mapAttrs ( + _: typeCfg: nonNull { validator = lib.mapNullable toString typeCfg.validator; } + ) cfg.types; + channels = lib.mapAttrs (_: channelCfg: { + slots = lib.mapAttrs ( + _: slotCfg: + nonNull { + inherit (slotCfg) + type + required + secret + renamedFrom + ; + } + ) channelCfg.slots; + }) cfg.channels; + validators = lib.mapAttrs (_: validatorCfg: { + inherit (validatorCfg) slots; + program = toString validatorCfg.program; + }) cfg.validators; + views = + slotViews + // lib.mapAttrs ( + _: viewCfg: + nonNull { + inherit (viewCfg) from secret; + renderer = lib.mapNullable toString viewCfg.renderer; + reactions = { inherit (viewCfg.reactions) restart reload; }; + } + ) cfg.views; + }; + + schemaFile = pkgs.writers.writeJSON "enstate-schema.json" schema; + + settings = pkgs.writers.writeJSON "enstate-config.json" { + state-dir = cfg.stateDir; + run-dir = cfg.runDir; + }; + + enstate = lib.getExe cfg.package; + + + # Whether a `LoadCredential=` (`ID:PATH`) reads a view. + readsView = + credential: + let + parts = lib.splitString ":" credential; + in + lib.length parts > 1 + && lib.hasPrefix "${cfg.runDir}/views/" (lib.concatStringsSep ":" (lib.tail parts)); +in +{ + options.enstate = { + enable = lib.mkEnableOption "enstate, state next to the Nix store"; + + package = mkOption { + type = types.package; + default = pkgs.callPackage ./package.nix { }; + defaultText = lib.literalExpression "pkgs.callPackage ./package.nix { }"; + description = "enstate, the program."; + }; + + stateDir = mkOption { + type = types.str; + default = "/var/lib/enstate"; + description = "Where the snapshots are kept."; + }; + + runDir = mkOption { + type = types.str; + default = "/run/enstate"; + description = "Where the views are put."; + }; + + types = mkOption { + type = types.attrsOf ( + types.submodule { + options.validator = mkOption { + type = types.nullOr types.path; + default = null; + description = "The type's validator (docs/design.md, 5.2)."; + }; + } + ); + default = { }; + description = "Types, by media type, and their validators."; + }; + + channels = mkOption { + type = types.attrsOf ( + types.submodule ( + { name, ... }: + { + options.slots = mkOption { + type = types.attrsOf (slot name); + default = { }; + description = "The channel's slots."; + }; + } + ) + ); + default = { }; + description = "Channels, and the slots this generation offers in them."; + }; + + validators = mkOption { + type = types.attrsOf ( + types.submodule { + options = { + slots = mkOption { + type = types.listOf types.str; + description = "The slots it is given (`CHANNEL/SLOT`)."; + }; + program = mkOption { + type = types.path; + description = "The validator (docs/design.md, 5.2)."; + }; + }; + } + ); + default = { }; + description = "Validators across slots."; + }; + + views = mkOption { + type = types.attrsOf ( + types.submodule ( + { name, ... }: + { + options = { + from = mkOption { + type = types.listOf types.str; + description = "The slots it is made from (`CHANNEL/SLOT`)."; + }; + renderer = mkOption { + type = types.nullOr types.path; + default = null; + description = "The renderer (docs/design.md, 5.2); none for a view of one entry."; + }; + secret = mkOption { + type = types.nullOr types.bool; + default = null; + description = "Whether it is readable by root only; by default, if a slot it is made from is secret."; + }; + path = mkOption { + type = types.str; + readOnly = true; + default = "${cfg.runDir}/views/${name}"; + defaultText = lib.literalExpression ''"''${config.enstate.runDir}/views/NAME"''; + description = "The directory the view's files are in, for services to read."; + }; + inherit reactions; + }; + } + ) + ); + default = { }; + description = "Views made by renderers."; + }; + + checkBeforeSwitch = mkOption { + type = types.bool; + default = true; + description = '' + Whether a switch to a generation whose required slots the state can't fill, + even by migrating, is refused before switching. Not checked when the running + system has no enstate, nor for `boot` and `dry-activate`. + ''; + }; + }; + + # A service whose `LoadCredential=` reads a view is ordered after the unit that puts + # the views in place, and wants it: without saying so itself. + options.systemd.services = mkOption { + type = types.attrsOf ( + types.submodule ( + { config, ... }: + let + credentials = lib.concatMap (option: lib.toList (config.serviceConfig.${option} or [ ])) [ + "LoadCredential" + "LoadCredentialEncrypted" + ]; + in + { + config = lib.mkIf (cfg.enable && lib.any readsView credentials) { + after = [ "enstate.service" ]; + wants = [ "enstate.service" ]; + }; + } + ) + ); + }; + + config = lib.mkIf cfg.enable { + assertions = [ + { + assertion = lib.intersectLists (lib.attrNames slotViews) (lib.attrNames cfg.views) == [ ]; + message = "enstate.views: ${toString (lib.intersectLists (lib.attrNames slotViews) (lib.attrNames cfg.views))} is also a slot's own view"; + } + ]; + + environment.systemPackages = [ cfg.package ]; + environment.etc."enstate/schema.json".source = schemaFile; + environment.etc."enstate/config.json".source = settings; + + # At boot and after a switch that changes the schema: the views of this + # generation, from the snapshots, and the reactions of those that changed. + systemd.services.enstate = { + description = "enstate: the views of this generation"; + wantedBy = [ "multi-user.target" ]; + after = [ "local-fs.target" ]; + restartTriggers = [ schemaFile ]; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + ExecStart = "${enstate} --migrate"; + }; + }; + + system.preSwitchChecks = lib.mkIf cfg.checkBeforeSwitch { + enstate = '' + case "''${2-}" in + boot|dry-activate) exit 0 ;; + esac + if [ ! -e /etc/enstate/schema.json ]; then + echo "enstate: the running system has none, not checking" + exit 0 + fi + ${enstate} --migrate --dry-run --schema "$1/etc/enstate/schema.json" + ''; + }; + }; +} diff --git a/nix/package.nix b/nix/package.nix new file mode 100644 index 0000000..a919061 --- /dev/null +++ b/nix/package.nix @@ -0,0 +1,37 @@ +# enstate, the program (README.md). +{ + lib, + runCommand, + rustPlatform, + util-linux, +}: + +rustPlatform.buildRustPackage { + pname = "enstate"; + version = "0.0.1"; + + # Only what the build reads, each part on its own, never the whole checkout: a + # filter over the checkout can't tell its files apart below a symbolic link (Nix + # gives it the resolved paths), and lib.fileset refuses one. + src = runCommand "enstate-source" { } '' + mkdir $out + cp ${../Cargo.toml} $out/Cargo.toml + cp ${../Cargo.lock} $out/Cargo.lock + cp -r ${../src} $out/src + cp -r ${../tests} $out/tests + ''; + + # The tests' fake systemctl looks at the store's lock with flock. + nativeCheckInputs = [ util-linux ]; + + cargoLock = { + lockFile = ../Cargo.lock; + outputHashes."config-0.1.0" = "sha256-qtUSpjOQsC9NFwgDXqDIqzvzU1zZqoD90se/ccWSKNs="; + }; + + meta = { + description = "State next to the Nix store: plan, apply, and make submissions"; + mainProgram = "enstate"; + platforms = lib.platforms.linux; + }; +} diff --git a/nix/test.nix b/nix/test.nix new file mode 100644 index 0000000..f2739eb --- /dev/null +++ b/nix/test.nix @@ -0,0 +1,119 @@ +# The NixOS module on a VM (docs/design.md, section 13): a key that a service reads by +# LoadCredential= of its own; applied from a source list, rotated without switching; a +# switch across a rename and back, with the rotated key; a switch refused before +# switching; a reboot. +{ pkgs }: + +pkgs.testers.runNixOSTest { + name = "enstate"; + + nodes.machine = + { config, lib, ... }: + let + key = { + type = "application/octet-stream"; + secret = true; + reactions.restart = [ "consumer.service" ]; + }; + # The consumer gets its credential as hrm's services do, by LoadCredential= of + # its own; the ordering after enstate.service follows from that. + # (Given with a priority, so a specialisation's wins over the base's.) + credential = priority: config: name: { + environment.CRED = lib.mkOverride priority name; + serviceConfig.LoadCredential = lib.mkOverride priority "${name}:${config.enstate.channels.secrets.slots.${name}.path}"; + }; + in + { + imports = [ ./module.nix ]; + + enstate.enable = true; + enstate.channels.secrets.slots."tinc.key" = key; + + # Writes down which credential it got, and what is in it. + systemd.services.consumer = lib.mkMerge [ + { + wantedBy = [ "multi-user.target" ]; + script = '' + echo "$CRED $(cat "$CREDENTIALS_DIRECTORY/$CRED")" > /run/consumer-seen + exec sleep infinity + ''; + } + (credential 100 config "tinc.key") + ]; + + specialisation.renamed.configuration = + { config, ... }: + { + enstate.channels.secrets.slots = lib.mkForce { + "retiolum.key" = key // { + renamedFrom = "tinc.key"; + }; + }; + systemd.services.consumer = credential 50 config "retiolum.key"; + }; + + specialisation.retyped.configuration = { + enstate.channels.secrets.slots = lib.mkForce { + "tinc.key" = key // { + type = "text/plain"; + }; + }; + }; + }; + + testScript = '' + def submit(name, key): + machine.succeed( + f"mkdir -p /root/{name}", + f"printf '{key}' > /root/{name}/key", + f"""echo '{{"channel": "secrets", "complete": true, """ + f""""items": {{"tinc.key": {{"source": {{"file": "key"}}}}}}}}' """ + f"> /root/{name}/sources.json", + f"enstate --pack /root/{name}/sources.json --out /root/{name}/submission", + f"enstate --plan /root/{name}/submission", + f"enstate --apply /root/{name}/submission", + ) + + def seen(expected): + machine.wait_until_succeeds(f"grep -qx '{expected}' /run/consumer-seen") + + machine.wait_for_unit("multi-user.target") + + with subtest("the consumer reads a view by LoadCredential=, and is ordered after enstate"): + machine.succeed("systemctl show -p After consumer.service | grep -q enstate.service") + machine.succeed("systemctl show -p Wants consumer.service | grep -q enstate.service") + + with subtest("without state, the required slot is missing, and its consumer fails"): + machine.succeed("enstate --status | grep -q 'missing tinc.key'") + machine.fail("systemctl is-active consumer.service") + + with subtest("applied: the key is the consumer's credential, and it started"): + submit("first", "K") + machine.wait_for_unit("consumer.service") + seen("tinc.key K") + machine.succeed("test $(stat -c %a /run/enstate/views/secrets.tinc.key/tinc.key) = 600") + + with subtest("rotated without switching: the consumer is restarted"): + submit("second", "L") + seen("tinc.key L") + + with subtest("a switch across a rename: the key carries over"): + machine.succeed("/run/current-system/specialisation/renamed/bin/switch-to-configuration test") + seen("retiolum.key L") + machine.fail("test -e /run/enstate/views/secrets.tinc.key") + + with subtest("and back: the old name, the same key"): + machine.succeed("/run/booted-system/bin/switch-to-configuration test") + seen("tinc.key L") + + with subtest("a switch to a type the state can't fill is refused before switching"): + machine.fail("/run/booted-system/specialisation/retyped/bin/switch-to-configuration test") + machine.succeed("enstate --status | grep -q 'filled tinc.key'") + + with subtest("after a reboot, the views are there again"): + machine.shutdown() + machine.start() + machine.wait_for_unit("consumer.service") + seen("tinc.key L") + ''; +} -- cgit v1.3.1