git.delta.rocks / jrsonnet / refs/commits / d8f3e18873ec

difftreelog

refactor move parts to secret generator derivation

rquyvuskYaroslav Bolyukin2025-11-05parent: #488d19a.patch.diff
in: trunk

5 files changed

modifiedcmds/fleet/src/cmds/secrets/mod.rsdiffbeforeafterboth
--- a/cmds/fleet/src/cmds/secrets/mod.rs
+++ b/cmds/fleet/src/cmds/secrets/mod.rs
@@ -158,7 +158,7 @@
 	expectations: &Expectations,
 ) -> Result<FleetSharedSecret> {
 	let reason = secret_needs_regeneration(&secret.secret, &secret.owners, expectations);
-	let value = definition.inner();
+	let value = definition.definition_value();
 
 	let (should_reencrypt, reason) = match reason {
 		Some(RegenerationReason::OwnersAdded(_)) => {
@@ -401,7 +401,13 @@
 	// let owners: Vec<String> = nix_go_json!(secret.expectedOwners);
 	Ok(FleetSharedSecret {
 		managed: Some(true),
-		secret: generate(config, display_name, secret.inner(), expectations).await?,
+		secret: generate(
+			config,
+			display_name,
+			secret.definition_value(),
+			expectations,
+		)
+		.await?,
 		owners: expectations.owners.clone(),
 	})
 }
@@ -711,7 +717,9 @@
 				}
 
 				let definition = config.shared_secret_definition(&name)?;
-				let expectations = definition.expectations()?;
+				let expectations = definition
+					.expectations()
+					.with_context(|| format!("expectations for shared {name:?}"))?;
 
 				let updated = maybe_regenerate_shared_secret(
 					&name,
@@ -744,7 +752,9 @@
 							info!("skipping unmanaged secret: {missing}");
 							continue;
 						}
-						let expectations = definition.expectations()?;
+						let expectations = definition
+							.expectations()
+							.with_context(|| format!("expectations for shared {missing:?}"))?;
 						info!("generating secret: {missing}");
 						let shared = generate_shared(config, missing, definition, &expectations)
 							.in_current_span()
@@ -768,13 +778,18 @@
 							.into_iter()
 							.collect::<HashSet<_>>();
 						for missing_secret in expected_set.difference(&stored_set) {
+							let secret = host.secret_definition(missing_secret)?;
+							if secret.is_shared()? {
+								continue;
+							}
 							info!("generating missing secret: {missing_secret}");
-							let definition = host.secret_definition(missing_secret)?;
-							let expectations = definition.expectations()?;
+							let expectations = secret.expectations().with_context(|| {
+								format!("expectations for {missing_secret:?} of {:?}", host.name)
+							})?;
 							let generated = match generate(
 								config,
 								missing_secret,
-								definition.inner(),
+								secret.definition_value()?,
 								&expectations,
 							)
 							.in_current_span()
@@ -796,16 +811,19 @@
 							)
 						}
 						for known_secret in stored_set.intersection(&expected_set) {
+							let secret = host.secret_definition(known_secret)?;
+							if secret.is_shared()? {
+								continue;
+							}
 							info!("updating secret: {known_secret}");
 							let data = config.host_secret(&host.name, known_secret)?;
-							let definition = host.secret_definition(known_secret)?;
-							let expectations = definition.expectations()?;
+							let expectations = secret.expectations()?;
 							if let Some(regen_reason) = data.needs_regeneration(&expectations) {
 								info!("needs regeneration: {regen_reason}");
 								let generated = match generate(
 									config,
 									known_secret,
-									definition.inner(),
+									secret.definition_value()?,
 									&expectations,
 								)
 								.in_current_span()
@@ -828,6 +846,10 @@
 							}
 						}
 						for removed_secret in stored_set.difference(&expected_set) {
+							let definition = host.secret_definition(removed_secret)?;
+							if definition.is_shared()? {
+								continue;
+							}
 							info!("removing secret: {removed_secret}");
 							config.remove_secret(&host.name, removed_secret);
 						}
modifiedcrates/fleet-base/src/secret.rsdiffbeforeafterboth
--- a/crates/fleet-base/src/secret.rs
+++ b/crates/fleet-base/src/secret.rs
@@ -17,20 +17,37 @@
 pub struct HostSecretDefinition(pub(crate) String, pub(crate) Value);
 impl HostSecretDefinition {
 	pub fn is_managed(&self) -> Result<bool> {
-		let value = &self.1;
-		Ok(!nix_go!(value.generator).is_null())
+		let def = self.definition_value()?;
+		Ok(!nix_go!(def.generator).is_null())
 	}
+	pub fn is_shared(&self) -> Result<bool> {
+		let def = self.definition_value()?;
+		Ok(nix_go_json!(def.shared))
+	}
 	pub fn expectations(&self) -> Result<Expectations> {
-		let value = &self.1;
+		let def = self.definition_value()?;
+		let parts = nix_go!(def.parts);
+
+		let mut public_parts = BTreeSet::new();
+		let mut private_parts = BTreeSet::new();
+		for part in parts.list_fields()? {
+			if nix_go_json!(parts[&part].encrypted) {
+				private_parts.insert(part.clone());
+			} else {
+				public_parts.insert(part.clone());
+			}
+		}
+
 		Ok(Expectations {
 			owners: BTreeSet::from([self.0.clone()]),
-			generation_data: nix_go_json!(value.expectedGenerationData),
-			public_parts: nix_go_json!(value.expectedPublicParts),
-			private_parts: nix_go_json!(value.expectedPrivateParts),
+			generation_data: nix_go_json!(def.expectedGenerationData),
+			public_parts,
+			private_parts,
 		})
 	}
-	pub fn inner(&self) -> Value {
-		self.1.clone()
+	pub fn definition_value(&self) -> Result<Value> {
+		let value = &self.1;
+		Ok(nix_go!(value.definition))
 	}
 }
 
@@ -49,7 +66,7 @@
 			private_parts: nix_go_json!(value.expectedPrivateParts),
 		})
 	}
-	pub fn inner(&self) -> Value {
+	pub fn definition_value(&self) -> Value {
 		self.0.clone()
 	}
 }
modifiedlib/default.nixdiffbeforeafterboth
--- a/lib/default.nix
+++ b/lib/default.nix
@@ -57,215 +57,191 @@
 
   inherit (modules) mkFleetDefault mkFleetGeneratorDefault;
 
-  secrets =
-    let
-      describedGenerator =
-        generator: {parts ? {}}:
-        {parts = {};}
-        // {
-          __functionArgs = functionArgs generator;
-          __functor = _: generator;
-        };
-    in
-    {
-      inherit describedGenerator;
+  secrets = {
 
-      /**
-        Generate a random secret password, 32 ascii characters by default
+    /**
+      Generate a random secret password, 32 ascii characters by default
 
-        Options:
-          size: generated password length in ascii characters (bytes).
-          noSymbols: by default, character set includes various special characters ($ , ! + * : ~), and might
-                     not be accepted in some contexts, this option switches charset to just [A-Za-z0-9].
+      Options:
+        size: generated password length in ascii characters (bytes).
+        noSymbols: by default, character set includes various special characters ($ , ! + * : ~), and might
+                   not be accepted in some contexts, this option switches charset to just [A-Za-z0-9].
 
-        Output:
-          Resulting secret has only part: secret, which contains encrypted password.
-      */
-      mkPassword =
+      Output:
+        Resulting secret has only part: secret, which contains encrypted password.
+    */
+    mkPassword =
+      {
+        size ? 32,
+      }:
+      (
         {
-          size ? 32,
+          coreutils,
+          mkSecretGenerator,
         }:
-        describedGenerator
-          (
-            {
-              coreutils,
-              mkSecretGenerator,
-            }:
-            mkSecretGenerator {
-              script = ''
-                mkdir $out
-                gh generate password -o $out/secret --size ${toString size}
-              '';
-            }
-          )
-          {
-            parts.secret.encrypted = true;
-          };
+        mkSecretGenerator {
+          script = ''
+            mkdir $out
+            gh generate password -o $out/secret --size ${toString size}
+          '';
+          parts.secret.encrypted = true;
+        }
+      );
 
-      /**
-        Generate a random ed25519 keypair
+    /**
+      Generate a random ed25519 keypair
 
-        Options:
-          noEmbedPublic: By default, secret key also embeds public key in itself ("extended" format, 64 bytes)
-                         When noEmbedPublis is enabled - only the private scalar is included.
-          encoding: Encoring of public and secret parts, can be "raw" (default), "base64" or "hex".
+      Options:
+        noEmbedPublic: By default, secret key also embeds public key in itself ("extended" format, 64 bytes)
+                       When noEmbedPublis is enabled - only the private scalar is included.
+        encoding: Encoring of public and secret parts, can be "raw" (default), "base64" or "hex".
 
-        Output:
-          Resulting secret has two parts: public and secret, where the secret part is encrypted.
+      Output:
+        Resulting secret has two parts: public and secret, where the secret part is encrypted.
+
+      This secret format is used by e.g Garage S3 server
+    */
+    mkEd25519 =
+      {
+        noEmbedPublic ? false,
+        encoding ? null,
+      }:
+      (
+        { mkSecretGenerator }:
+        mkSecretGenerator {
+          script = ''
+            mkdir $out
+            gh generate ed25519 -p $out/public -s $out/secret \
+              ${optionalString noEmbedPublic "--no-embed-public"} \
+              ${optionalString (encoding != null) "--encoding=${encoding}"}
+          '';
+          parts.secret.encrypted = true;
+          parts.public.encrypted = false;
+        }
+      );
 
-        This secret format is used by e.g Garage S3 server
-      */
-      mkEd25519 =
-        {
-          noEmbedPublic ? false,
-          encoding ? null,
-        }:
-        describedGenerator
-          (
-            { mkSecretGenerator }:
-            mkSecretGenerator {
-              script = ''
-                mkdir $out
-                gh generate ed25519 -p $out/public -s $out/secret \
-                  ${optionalString noEmbedPublic "--no-embed-public"} \
-                  ${optionalString (encoding != null) "--encoding=${encoding}"}
-              '';
-            }
-          )
-          {
-            parts.secret.encrypted = true;
-            parts.public.encrypted = false;
-          };
+    /**
+      Generate a random x25519 keypair
 
-      /**
-        Generate a random x25519 keypair
+      Options:
+        encoding: Encoring of public and secret parts, can be "raw" (default), "base64" or "hex".
 
-        Options:
-          encoding: Encoring of public and secret parts, can be "raw" (default), "base64" or "hex".
+      Output:
+        Resulting secret has two parts: public and secret, where the secret part is encrypted.
 
-        Output:
-          Resulting secret has two parts: public and secret, where the secret part is encrypted.
+      This secret format is used by e.g Wireguard VPN for peers (base64-encoded)
+    */
+    mkX25519 =
+      {
+        encoding ? null,
+      }:
+      (
+        { mkSecretGenerator }:
+        mkSecretGenerator {
+          script = ''
+            mkdir $out
+            gh generate x25519 -p $out/public -s $out/secret \
+              ${optionalString (encoding != null) "--encoding=${encoding}"}
+          '';
 
-        This secret format is used by e.g Wireguard VPN for peers (base64-encoded)
-      */
-      mkX25519 =
-        {
-          encoding ? null,
-        }:
-        describedGenerator
-          (
-            { mkSecretGenerator }:
-            mkSecretGenerator {
-              script = ''
-                mkdir $out
-                gh generate x25519 -p $out/public -s $out/secret \
-                  ${optionalString (encoding != null) "--encoding=${encoding}"}
-              '';
-            }
-          )
-          {
-            parts.secret.encrypted = true;
-            parts.public.encrypted = false;
-          };
+          parts.secret.encrypted = true;
+          parts.public.encrypted = false;
+        }
+      );
 
-      /**
-        Generate a random RSA keypair
+    /**
+      Generate a random RSA keypair
 
-        Options:
-          size: RSA key size, 4096 by default
+      Options:
+        size: RSA key size, 4096 by default
 
-        Output:
-          Resulting secret has two parts: public and secret, where the secret part is encrypted.
-          Both parts are PEM encoded.
-      */
-      mkRsa =
+      Output:
+        Resulting secret has two parts: public and secret, where the secret part is encrypted.
+        Both parts are PEM encoded.
+    */
+    mkRsa =
+      {
+        size ? 4096,
+      }:
+      (
         {
-          size ? 4096,
+          openssl,
+          mkSecretGenerator,
         }:
-        describedGenerator
-          (
-            {
-              openssl,
-              mkSecretGenerator,
-            }:
-            mkSecretGenerator {
-              script = ''
-                mkdir $out
+        mkSecretGenerator {
+          script = ''
+            mkdir $out
+
+            ${openssl}/bin/openssl genrsa -out rsa_private.key ${toString size}
+            ${openssl}/bin/openssl rsa -in rsa_private.key -pubout -out rsa_public.key
 
-                ${openssl}/bin/openssl genrsa -out rsa_private.key ${toString size}
-                ${openssl}/bin/openssl rsa -in rsa_private.key -pubout -out rsa_public.key
+            cat rsa_private.key | gh private -o $out/secret
+            cat rsa_public.key | gh public -o $out/public
+          '';
 
-                cat rsa_private.key | gh private -o $out/secret
-                cat rsa_public.key | gh public -o $out/public
-              '';
-            }
-          )
-          {
-            parts.secret.encrypted = true;
-            parts.public.encrypted = false;
-          };
+          parts.secret.encrypted = true;
+          parts.public.encrypted = false;
+        }
+      );
 
-      /**
-        Generate a random byte sequence
+    /**
+      Generate a random byte sequence
 
-        Options:
-          size: generated password length in bytes, 32 by default.
-          encoding: how the generated bytes should be encoded, "raw" (default), "hex" or "base64"
-          noNuls: prevent output byte sequence from containing internal \0, useful for some C applications
-                  that can't handle their strings properly.
+      Options:
+        size: generated password length in bytes, 32 by default.
+        encoding: how the generated bytes should be encoded, "raw" (default), "hex" or "base64"
+        noNuls: prevent output byte sequence from containing internal \0, useful for some C applications
+                that can't handle their strings properly.
 
-        Output:
-          Resulting secret has only part: secret, which contains encrypted bytes.
+      Output:
+        Resulting secret has only part: secret, which contains encrypted bytes.
 
-        Might be used for e.g. Wireguard VPN PSK keys (base64-encoded)
-      */
-      mkBytes =
-        {
-          count ? 32,
-          encoding,
-          noNuls ? false,
-        }:
-        describedGenerator
-          (
-            { mkSecretGenerator }:
-            mkSecretGenerator {
-              script = ''
-                mkdir $out
-                gh generate bytes --count=${toString count} --encoding=${encoding} -o $out/secret \
-                  ${optionalString noNuls "--no-nuls"}
-              '';
-            }
-          )
-          {
-            parts.secret.encrypted = true;
-          };
-      /**
-        Shorthand for `mkBytes`, which defaults to "hex" encoding
-      */
-      mkHexBytes =
-        {
-          count ? 32,
-        }:
-        mkBytes {
-          inherit count;
-          encoding = "hex";
-        };
-      /**
-        Shorthand for `mkBytes`, which defaults to "base64" encoding
-      */
-      mkBase64Bytes =
-        {
-          count ? 32,
-        }:
-        mkBytes {
-          inherit count;
-          encoding = "base64";
-        };
+      Might be used for e.g. Wireguard VPN PSK keys (base64-encoded)
+    */
+    mkBytes =
+      {
+        count ? 32,
+        encoding,
+        noNuls ? false,
+      }:
+      (
+        { mkSecretGenerator }:
+        mkSecretGenerator {
+          script = ''
+            mkdir $out
+            gh generate bytes --count=${toString count} --encoding=${encoding} -o $out/secret \
+              ${optionalString noNuls "--no-nuls"}
+          '';
+          parts.secret.encrypted = true;
+        }
+      );
+    /**
+      Shorthand for `mkBytes`, which defaults to "hex" encoding
+    */
+    mkHexBytes =
+      {
+        count ? 32,
+      }:
+      mkBytes {
+        inherit count;
+        encoding = "hex";
+      };
+    /**
+      Shorthand for `mkBytes`, which defaults to "base64" encoding
+    */
+    mkBase64Bytes =
+      {
+        count ? 32,
+      }:
+      mkBytes {
+        inherit count;
+        encoding = "base64";
+      };
 
-      # Wireguard
-      # mkWireguard = {}: mkX25519 {encoding = "base64";};
-      # mkWireguardPsk = {}: mkBase64Bytes {count = 32;};
-    };
+    # Wireguard
+    # mkWireguard = {}: mkX25519 {encoding = "base64";};
+    # mkWireguardPsk = {}: mkBase64Bytes {count = 32;};
+  };
 
   inherit (secrets)
     mkPassword
modifiedmodules/nixos/secrets.nixdiffbeforeafterboth
before · modules/nixos/secrets.nix
1{2  lib,3  fleetLib,4  config,5  pkgs,6  ...7}:8let9  inherit (builtins)10    hashString11    elemAt12    length13    toJSON14    filter15    ;16  inherit (lib.stringsWithDeps) stringAfter;17  inherit (lib.options) mkOption literalExpression;18  inherit (lib.lists) optional;19  inherit (lib.attrsets) mapAttrs mapAttrsToList;20  inherit (lib.modules) mkIf mkMerge;21  inherit (lib.types)22    submodule23    str24    attrsOf25    nullOr26    unspecified27    lazyAttrsOf28    uniq29    functionTo30    package31    listOf32    bool33    ;34  inherit (fleetLib.strings) decodeRawSecret;3536  sysConfig = config;37  secretPartDataType = submodule {38    options = {39      raw = mkOption {40        type = str;41        internal = true;42        description = "Encoded & Encrypted secret part data, passed from fleet.nix";43      };44    };45  };46  secretDataType = submodule {47    freeformType = lazyAttrsOf secretPartDataType;48    options = {49      shared = mkOption {50        description = "Is this secret owned by this machine, or propagated from shared secrets";51        default = false;52      };53    };54  };55  secretPartType =56    secretName:57    submodule (58      { config, ... }:59      let60        partName = config._module.args.name;61      in62      {63        options = {64          encrypted = mkOption {65            type = bool;66            description = "Is this secret part supposed to be encrypted?";67          };6869          hash = mkOption {70            type = str;71            description = "Hash of secret in encoded format";72          };73          path = mkOption {74            type = str;75            description = "Path to secret part, incorporating data hash (thus it will be updated on secret change)";76          };77          stablePath = mkOption {78            type = str;79            description = "Path to secret part, stable path (users are expected to watch for file changes/re-read secret on demand)";80          };81          data = mkOption {82            type = str;83            description = "Secret public data (only available for plaintext)";84          };85        };86        config =87          let88            raw = sysConfig.data.secrets.${secretName}.${partName}.raw;89          in90          {91            hash = hashString "sha1" raw;92            data = decodeRawSecret raw;93            path = "/run/secrets/${secretName}/${config.hash}-${partName}";94            stablePath = "/run/secrets/${secretName}/${partName}";95          };96      }97    );98  secretType = submodule (99    {100      config,101      ...102    }:103    let104      secretName = config._module.args.name;105    in106    {107      options = {108        parts = mkOption {109          type = lazyAttrsOf (secretPartType secretName);110          description = "Definition of secret parts";111          default = {};112        };113        generator = mkOption {114          type = uniq (nullOr (functionTo package));115          description = "Derivation to evaluate for secret generation";116          default = null;117        };118        mode = mkOption {119          type = str;120          description = "Secret mode";121          default = "0440";122        };123        owner = mkOption {124          type = str;125          description = "Owner of the secret";126          default = "root";127        };128        group = mkOption {129          type = str;130          description = "Group of the secret";131          default = sysConfig.users.users.${config.owner}.group;132          defaultText = literalExpression "config.users.users.$${owner}.group";133        };134        expectedGenerationData = mkOption {135          type = unspecified;136          description = "Data that gets embedded into secret part";137          default = null;138        };139      };140      config.parts = mkMerge [141        (mkIf (config.generator != null && config.generator ? parts) config.generator.parts)142        (mapAttrs (_: _: {}) (removeAttrs (sysConfig.data.secrets.${secretName} or {}) ["shared" "managed"]))143      ];144    }145  );146  processPart = secretName: partName: part: {147    inherit (part) path stablePath;148    raw = config.data.secrets.${secretName}.${partName}.raw;149  };150  processSecret =151    secretName: secret:152    {153      inherit (secret.definition) group mode owner;154      parts = (mapAttrs (processPart secretName) (155        secret.definition.parts156      ));157    };158  secretsData = (mapAttrs (processSecret) config.secrets);159  secretsFile = pkgs.writeTextFile {160    name = "secrets.json";161    text = toJSON secretsData;162  };163  useSysusers =164    (config.systemd ? sysusers && config.systemd.sysusers.enable)165    || (config ? userborn && config.userborn.enable);166in167{168  options = {169    data.secrets = mkOption {170      type = attrsOf secretDataType;171      default = { };172      description = "Host-local secret data";173    };174    secrets = mkOption {175      type = attrsOf secretType;176      default = { };177      apply = v: (mapAttrs (_: secret: secret.parts // {definition = secret;}) v);178      description = "Host-local secrets";179    };180    system.secretsData = mkOption {181      type = unspecified;182      default = { };183      description = "secrets.json contents";184    };185  };186  config = {187    system = { inherit secretsData; };188    environment.systemPackages = [ pkgs.fleet-install-secrets ];189190    systemd.services.fleet-install-secrets = mkIf useSysusers {191      wantedBy = [ "sysinit.target" ];192      after = [ "systemd-sysusers.service" ];193      restartTriggers = [194        secretsFile195      ];196      aliases = [197        "sops-install-secrets"198        "agenix-install-secrets"199      ];200201      unitConfig.DefaultDependencies = false;202203      serviceConfig = {204        Type = "oneshot";205        RemainAfterExit = true;206        ExecStart = "${pkgs.fleet-install-secrets}/bin/fleet-install-secrets install ${secretsFile}";207      };208    };209    system.activationScripts.decryptSecrets = mkIf (!useSysusers) (210      stringAfter211        (212          [213            # secrets are owned by user/group, thus we need to refer to those214            "users"215            "groups"216            "specialfs"217          ]218          # nixos-impermanence compatibility: secrets are encrypted by host-key,219          # but with impermanence we expect that the host-key is installed by220          # persist-file activation script.221          ++ (optional (config.system.activationScripts ? "persist-files") "persist-files")222        )223        ''224          1>&2 echo "setting up secrets"225          ${pkgs.fleet-install-secrets}/bin/fleet-install-secrets install ${secretsFile}226        ''227    );228  };229}
modifiedmodules/secrets.nixdiffbeforeafterboth
--- a/modules/secrets.nix
+++ b/modules/secrets.nix
@@ -124,6 +124,7 @@
                 # If set - script will be run on remote machine, otherwise it will be run with fleet project in CWD
                 # (Some secrets-encryption-in-git/managed PKI solution is expected)
                 impureOn ? null,
+                parts,
               }:
               (prev.writeShellScript "impureGenerator.sh" ''
                 #!/bin/sh
@@ -151,12 +152,12 @@
               '').overrideAttrs
                 (old: {
                   passthru = {
-                    inherit impureOn;
+                    inherit impureOn parts;
                     generatorKind = "impure";
                   };
                 });
             # Pure generators are disabled for now
-            mkSecretGenerator = { script }: mkImpureSecretGenerator { inherit script; };
+            mkSecretGenerator = { script, parts }: mkImpureSecretGenerator { inherit script parts; };
 
             # TODO: Implement consistent naming
             # Pure secret generator is supposed to be run entirely by nix, using `__impure` derivation type...