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

difftreelog

feat expected secret parts

tylvsszvYaroslav Bolyukin2025-10-26parent: #7120038.patch.diff
in: trunk

16 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1055,6 +1055,7 @@
  "shlex",
  "tabled",
  "tempfile",
+ "thiserror 2.0.17",
  "time",
  "tokio",
  "tokio-util",
@@ -1087,6 +1088,7 @@
  "serde_json",
  "tabled",
  "tempfile",
+ "thiserror 2.0.17",
  "time",
  "tokio",
  "tokio-util",
modifiedcmds/fleet/Cargo.tomldiffbeforeafterboth
--- a/cmds/fleet/Cargo.toml
+++ b/cmds/fleet/Cargo.toml
@@ -47,6 +47,7 @@
 nom = "8.0.0"
 opentelemetry = "0.30.0"
 opentelemetry_sdk = "0.30.0"
+thiserror.workspace = true
 tracing-indicatif = { version = "0.3", optional = true }
 tracing-opentelemetry = "0.31.0"
 
modifiedcmds/fleet/src/cmds/secrets/mod.rsdiffbeforeafterboth
--- a/cmds/fleet/src/cmds/secrets/mod.rs
+++ b/cmds/fleet/src/cmds/secrets/mod.rs
@@ -2,17 +2,18 @@
 	collections::{BTreeMap, BTreeSet, HashSet},
 	io::{self, Read, Write, stdin, stdout},
 	path::PathBuf,
-	slice,
 };
 
-use age::Recipient;
 use anyhow::{Context, Result, anyhow, bail, ensure};
 use chrono::{DateTime, Utc};
 use clap::Parser;
 use fleet_base::{
-	fleetdata::{FleetSecret, FleetSecretPart, FleetSharedSecret, encrypt_secret_data},
+	fleetdata::{
+		FleetHostSecret, FleetSecretData, FleetSecretPart, FleetSharedSecret, encrypt_secret_data,
+	},
 	host::Config,
 	opts::FleetOpts,
+	secret::{Expectations, RegenerationReason, SharedSecretDefinition, secret_needs_regeneration},
 };
 use fleet_shared::SecretData;
 use nix_eval::{NixType, Value, nix_go, nix_go_json};
@@ -144,76 +145,55 @@
 		#[clap(short = 'p', long, default_value = "secret")]
 		part: String,
 	},
-}
-
-fn secret_needs_regeneration(
-	secret: &FleetSecret,
-	expected_generation_data: &serde_json::Value,
-) -> bool {
-	let data_is_expected = secret.generation_data == *expected_generation_data;
-	// TODO: Leeway?
-	let expired = secret
-		.expires_at
-		.map(|expiration| expiration < Utc::now())
-		.unwrap_or(false);
-	expired || !data_is_expected
 }
 
 #[allow(clippy::too_many_arguments)]
-#[tracing::instrument(skip(config, secret, field, prefer_identities))]
+#[tracing::instrument(skip(config, secret, definition, prefer_identities))]
 async fn maybe_regenerate_shared_secret(
 	secret_name: &str,
 	config: &Config,
 	mut secret: FleetSharedSecret,
-	field: Value,
-	expected_owners: &[String],
-	expected_generation_data: serde_json::Value,
+	definition: SharedSecretDefinition,
 	prefer_identities: &[String],
+	expectations: &Expectations,
 ) -> Result<FleetSharedSecret> {
-	let original_set = secret.owners.clone();
+	let reason = secret_needs_regeneration(&secret.secret, &secret.owners, expectations);
+	let value = definition.inner();
 
-	let set = original_set.iter().collect::<BTreeSet<_>>();
-	let expected_set = expected_owners.iter().collect::<BTreeSet<_>>();
-
-	let regeneration_required =
-		secret_needs_regeneration(&secret.secret, &expected_generation_data);
-
-	if set == expected_set && !regeneration_required {
-		info!("no need to update owner list, it is already correct");
-		return Ok(secret);
-	}
-
-	let should_regenerate = if regeneration_required {
-		info!("secret has its generation data changed, regeneration is required");
-		true
-	} else if set.difference(&expected_set).next().is_some() {
-		// TODO: Remove this warning for revokable secrets.
-		warn!(
-			"host was removed from secret owners, but until this host rebuild, the secret will still be stored on it."
-		);
-		nix_go_json!(field.regenerateOnOwnerRemoved)
-	} else if expected_set.difference(&set).next().is_some() {
-		nix_go_json!(field.regenerateOnOwnerAdded)
-	} else {
-		false
+	let (should_reencrypt, reason) = match reason {
+		Some(RegenerationReason::OwnersAdded(_)) => {
+			// Secret always needs to be reencrypted for new owners to be able to read it
+			(
+				true,
+				if nix_go_json!(value.regenerateOnOwnerAdded) {
+					reason
+				} else {
+					None
+				},
+			)
+		}
+		Some(RegenerationReason::OwnersRemoved(_)) => {
+			// No need to reencrypt, we can just leave stanzas in place.
+			if nix_go_json!(value.regenerateOnOwnerRemoved) {
+				(true, reason)
+			} else {
+				(false, None)
+			}
+		}
+		Some(_) => (true, reason),
+		None => (false, None),
 	};
 
-	if should_regenerate {
-		info!("secret needs to be regenerated");
-		let generated = generate_shared(
-			config,
-			secret_name,
-			field,
-			expected_owners.to_vec(),
-			expected_generation_data,
-		)
-		.await?;
+	if let Some(reason) = reason {
+		info!("secret needs to be regenerated: {reason}");
+		let generated = generate_shared(config, secret_name, definition, expectations).await?;
 		Ok(generated)
-	} else {
+	} else if should_reencrypt {
+		info!("secret needs to be reencrypted");
 		let identity_holder = if !prefer_identities.is_empty() {
 			prefer_identities
 				.iter()
-				.find(|i| original_set.iter().any(|s| s == *i))
+				.find(|i| secret.owners.iter().any(|s| s == *i))
 		} else {
 			secret.owners.first()
 		};
@@ -228,12 +208,16 @@
 			}
 			let host = config.host(identity_holder).await?;
 			let encrypted = host
-				.reencrypt(part.raw.clone(), expected_owners.to_vec())
+				.reencrypt(
+					part.raw.clone(),
+					expectations.owners.iter().cloned().collect(),
+				)
 				.await?;
 			part.raw = encrypted;
 		}
-
-		secret.owners = expected_owners.to_vec();
+		secret.owners = expectations.owners.clone();
+		Ok(secret)
+	} else {
 		Ok(secret)
 	}
 }
@@ -250,8 +234,8 @@
 	_display_name: &str,
 	_secret: Value,
 	_default_generator: Value,
-	_owners: &[String],
-) -> Result<FleetSecret> {
+	_expectations: &Expectations,
+) -> Result<FleetSecretData> {
 	bail!("pure generators are broken for now")
 }
 async fn generate_impure(
@@ -259,9 +243,8 @@
 	_display_name: &str,
 	secret: Value,
 	default_generator: Value,
-	expected_owners: &[String],
-	expected_generation_data: serde_json::Value,
-) -> Result<FleetSecret> {
+	expectations: &Expectations,
+) -> Result<FleetSecretData> {
 	let generator = nix_go!(secret.generator);
 	let on: Option<String> = nix_go_json!(default_generator.impureOn);
 
@@ -276,12 +259,11 @@
 	let mk_secret_generators = nix_go!(on_pkgs.mkSecretGenerators);
 
 	let mut recipients = Vec::new();
-	for owner in expected_owners {
+	for owner in &expectations.owners {
 		let key = config.key(owner).await?;
 		recipients.push(key);
 	}
 	let generators = nix_go!(mk_secret_generators(Obj { recipients }));
-	// FIXME: Apparently, // operator is slow in nix
 	let pkgs_and_generators = on_pkgs.attrs_update(generators)?;
 
 	let call_package = nix_go!(nixpkgs.lib.callPackageWith(pkgs_and_generators));
@@ -331,20 +313,26 @@
 	let created_at = host.read_file_value(format!("{out}/created_at")).await?;
 	let expires_at = host.read_file_value(format!("{out}/expires_at")).await.ok();
 
-	Ok(FleetSecret {
+	let new_data = FleetSecretData {
 		created_at,
 		expires_at,
 		parts,
-		generation_data: expected_generation_data,
-	})
+		generation_data: expectations.generation_data.clone(),
+	};
+
+	if let Some(reason) = secret_needs_regeneration(&new_data, &expectations.owners, expectations) {
+		bail!("newly generated secret needs to be regenerated: {reason}")
+	}
+
+	Ok(new_data)
 }
+
 async fn generate(
 	config: &Config,
 	display_name: &str,
 	secret: Value,
-	expected_owners: &[String],
-	expected_generation_data: serde_json::Value,
-) -> Result<FleetSecret> {
+	expectations: &Expectations,
+) -> Result<FleetSecretData> {
 	let generator = nix_go!(secret.generator);
 	// Can't properly check on nix module system level
 	{
@@ -388,8 +376,7 @@
 				display_name,
 				secret,
 				default_generator,
-				expected_owners,
-				expected_generation_data,
+				expectations,
 			)
 			.await
 		}
@@ -399,7 +386,7 @@
 				display_name,
 				secret,
 				default_generator,
-				expected_owners,
+				expectations,
 			)
 			.await
 		}
@@ -408,21 +395,14 @@
 async fn generate_shared(
 	config: &Config,
 	display_name: &str,
-	secret: Value,
-	expected_owners: Vec<String>,
-	expected_generation_data: serde_json::Value,
+	secret: SharedSecretDefinition,
+	expectations: &Expectations,
 ) -> Result<FleetSharedSecret> {
 	// let owners: Vec<String> = nix_go_json!(secret.expectedOwners);
 	Ok(FleetSharedSecret {
-		secret: generate(
-			config,
-			display_name,
-			secret,
-			&expected_owners,
-			expected_generation_data,
-		)
-		.await?,
-		owners: expected_owners,
+		managed: Some(true),
+		secret: generate(config, display_name, secret.inner(), expectations).await?,
+		owners: expectations.owners.clone(),
 	})
 }
 
@@ -457,11 +437,11 @@
 }
 
 fn parse_machines(
-	initial: Vec<String>,
+	initial: BTreeSet<String>,
 	machines: Option<Vec<String>>,
 	mut add_machines: Vec<String>,
 	mut remove_machines: Vec<String>,
-) -> Result<Vec<String>> {
+) -> Result<BTreeSet<String>> {
 	if machines.is_none() && add_machines.is_empty() && remove_machines.is_empty() {
 		bail!("no operation");
 	}
@@ -470,7 +450,6 @@
 	let mut target_machines = initial;
 	info!("Currently encrypted for {initial_machines:?}");
 
-	// ensure!(machines.is_some() || !add_machines.is_empty() || )
 	if let Some(machines) = machines {
 		ensure!(
 			add_machines.is_empty() && remove_machines.is_empty(),
@@ -487,20 +466,13 @@
 	}
 
 	for machine in &remove_machines {
-		let mut removed = false;
-		while let Some(pos) = target_machines.iter().position(|m| m == machine) {
-			target_machines.swap_remove(pos);
-			removed = true;
-		}
-		if !removed {
+		if !target_machines.remove(machine) {
 			warn!("secret is not enabled for {machine}");
 		}
 	}
 	for machine in &add_machines {
-		if target_machines.iter().any(|m| m == machine) {
+		if !target_machines.insert(machine.to_owned()) {
 			warn!("secret is already added to {machine}");
-		} else {
-			target_machines.push(machine.to_owned());
 		}
 	}
 	if !remove_machines.is_empty() {
@@ -527,7 +499,7 @@
 				}
 			}
 			Secret::AddShared {
-				mut machines,
+				machines,
 				name,
 				force,
 				public,
@@ -537,25 +509,32 @@
 				re_add,
 				part: part_name,
 			} => {
+				let mut machines: BTreeSet<String> = machines.into_iter().collect();
 				// TODO: Forbid updating secrets with set expectedOwners (= not user-managed).
 
-				let exists = config.has_shared(&name);
-				if exists && !force && !re_add {
-					bail!("secret already defined");
-				}
-				if re_add {
-					// Fixme: use clap to limit this usage
-					ensure!(!force, "--force and --readd are not compatible");
-					ensure!(exists, "secret doesn't exists");
-					ensure!(
-						machines.is_empty(),
-						"you can't use machines argument for --readd"
-					);
-					let shared = config.shared_secret(&name)?;
-					machines = shared.owners;
-				}
+				if let Some(old_shared) = config.shared_secret(&name)? {
+					if !force && !re_add {
+						bail!("secret already defined");
+					};
+					if old_shared.managed.unwrap_or(false) {
+						bail!("secret is marked as managed, should not be updated manually");
+					};
+					if re_add {
+						// Fixme: use clap to limit this usage
+						ensure!(!force, "--force and --readd are not compatible");
+						ensure!(
+							machines.is_empty(),
+							"you can't use machines argument for --readd"
+						);
+						machines = old_shared.owners;
+					}
+				} else if re_add {
+					bail!("secret doesn't exists");
+				};
 
-				let recipients = config.recipients(machines.clone()).await?;
+				let recipients = config
+					.recipients(machines.iter().cloned().collect())
+					.await?;
 
 				let mut parts = BTreeMap::new();
 
@@ -563,9 +542,8 @@
 				io::stdin().read_to_end(&mut input)?;
 
 				if !input.is_empty() {
-					let encrypted =
-						encrypt_secret_data(recipients.iter().map(|r| r as &dyn Recipient), input)
-							.ok_or_else(|| anyhow!("no recipients provided"))?;
+					let encrypted = encrypt_secret_data(recipients.iter(), input)
+						.ok_or_else(|| anyhow!("no recipients provided"))?;
 					parts.insert(part_name, FleetSecretPart { raw: encrypted });
 				}
 
@@ -576,8 +554,9 @@
 				config.replace_shared(
 					name,
 					FleetSharedSecret {
+						managed: Some(false),
 						owners: machines,
-						secret: FleetSecret {
+						secret: FleetSecretData {
 							created_at: Utc::now(),
 							expires_at,
 							parts,
@@ -607,34 +586,47 @@
 						.host_secret(&machine, &name)
 						.context("failed to read existing secret for --merge")?
 				} else {
-					FleetSecret {
-						created_at: Utc::now(),
-						expires_at: None,
-						parts: BTreeMap::new(),
-						generation_data: serde_json::Value::Null,
+					FleetHostSecret {
+						managed: Some(false),
+						secret: FleetSecretData {
+							created_at: Utc::now(),
+							expires_at: None,
+							parts: BTreeMap::new(),
+							generation_data: serde_json::Value::Null,
+						},
 					}
 				};
+				if out.managed.unwrap_or(false) {
+					bail!("secret is managed by fleet and should not be updated manually");
+				}
+				out.managed = Some(false);
 
 				if let Some(secret) = parse_secret().await? {
 					let recipient = config.recipient(&machine).await?;
-					let encrypted = encrypt_secret_data([&recipient as &dyn Recipient], secret)
-						.expect("recipient provided");
+					let encrypted =
+						encrypt_secret_data([&recipient], secret).expect("recipient provided");
 					if out
+						.secret
 						.parts
 						.insert(part_name.clone(), FleetSecretPart { raw: encrypted })
 						.is_some() && !replace
 					{
-						bail!("part {part_name:?} is already defined");
+						bail!(
+							"part {part_name:?} is already defined, use --replace if you wish to replace it"
+						);
 					}
 				}
 
 				if let Some(public) = parse_public(public, public_file).await? {
 					if out
+						.secret
 						.parts
 						.insert(public_name.clone(), FleetSecretPart { raw: public })
 						.is_some() && !replace
 					{
-						bail!("part {public_name:?} is already defined");
+						bail!(
+							"part {public_name:?} is already defined, use --replace if you wish to replace it"
+						);
 					}
 				};
 
@@ -647,7 +639,7 @@
 				part: part_name,
 			} => {
 				let secret = config.host_secret(&machine, &name)?;
-				let Some(secret) = secret.parts.get(&part_name) else {
+				let Some(secret) = secret.secret.parts.get(&part_name) else {
 					bail!("no part {part_name} in secret {name}");
 				};
 				let data = if secret.raw.encrypted {
@@ -664,7 +656,9 @@
 				part: part_name,
 				prefer_identities,
 			} => {
-				let secret = config.shared_secret(&name)?;
+				let Some(secret) = config.shared_secret(&name)? else {
+					bail!("secret doesn't exists");
+				};
 				let Some(part) = secret.secret.parts.get(&part_name) else {
 					bail!("no part {part_name} in secret {name}");
 				};
@@ -695,7 +689,9 @@
 			} => {
 				// TODO: Forbid updating secrets with set expectedOwners (= not user-managed).
 
-				let secret = config.shared_secret(&name)?;
+				let Some(secret) = config.shared_secret(&name)? else {
+					bail!("secret doesn't exists");
+				};
 				if secret.secret.parts.values().all(|v| !v.raw.encrypted) {
 					bail!("no secret");
 				}
@@ -714,20 +710,16 @@
 					return Ok(());
 				}
 
-				let config_field = &config.config_field;
-				let name_clone = name.clone();
-				let field = nix_go!(config_field.sharedSecrets[name_clone]);
-				let expected_generation_data = nix_go_json!(field.expectedGenerationData);
+				let definition = config.shared_secret_definition(&name)?;
+				let expectations = definition.expectations()?;
 
 				let updated = maybe_regenerate_shared_secret(
 					&name,
 					config,
 					secret,
-					field,
-					&target_machines,
-					expected_generation_data,
+					definition,
 					&prefer_identities,
-					// None,
+					&expectations,
 				)
 				.await?;
 				config.replace_shared(name, updated);
@@ -737,36 +729,26 @@
 				skip_hosts,
 			} => {
 				info!("checking for secrets to regenerate");
+				let expected_shared_set = config
+					.list_configured_shared()
+					.await?
+					.into_iter()
+					.collect::<HashSet<_>>();
 				let stored_shared_set = config.list_shared().into_iter().collect::<HashSet<_>>();
 				{
 					// Generate missing shared
 					let _span = info_span!("shared").entered();
-					let expected_shared_set = config
-						.list_configured_shared()
-						.await?
-						.into_iter()
-						.collect::<HashSet<_>>();
 					for missing in expected_shared_set.difference(&stored_shared_set) {
-						let config_field = &config.config_field;
-						let secret = nix_go!(config_field.sharedSecrets[{ missing }]);
-						let expected_generation_data: serde_json::Value =
-							nix_go_json!(secret.expectedGenerationData);
-						let expected_owners: Option<Vec<String>> =
-							nix_go_json!(secret.expectedOwners);
-						let Some(expected_owners) = expected_owners else {
-							// Can't generate this missing secret, as it has no defined owners.
+						let definition = config.shared_secret_definition(missing)?;
+						if !definition.is_managed()? {
+							info!("skipping unmanaged secret: {missing}");
 							continue;
-						};
+						}
+						let expectations = definition.expectations()?;
 						info!("generating secret: {missing}");
-						let shared = generate_shared(
-							config,
-							missing,
-							secret,
-							expected_owners,
-							expected_generation_data,
-						)
-						.in_current_span()
-						.await?;
+						let shared = generate_shared(config, missing, definition, &expectations)
+							.in_current_span()
+							.await?;
 						config.replace_shared(missing.to_string(), shared)
 					}
 				}
@@ -778,26 +760,22 @@
 
 						let _span = info_span!("host", host = host.name).entered();
 						let expected_set = host
-							.list_configured_secrets()
-							.in_current_span()
-							.await?
+							.list_defined_secrets()?
 							.into_iter()
 							.collect::<HashSet<_>>();
 						let stored_set = config
 							.list_secrets(&host.name)
 							.into_iter()
 							.collect::<HashSet<_>>();
-						for missing in expected_set.difference(&stored_set) {
-							info!("generating secret: {missing}");
-							let secret = host.secret_field(missing).in_current_span().await?;
-							let expected_generation_data =
-								nix_go_json!(secret.expectedGenerationData);
+						for missing_secret in expected_set.difference(&stored_set) {
+							info!("generating missing secret: {missing_secret}");
+							let definition = host.secret_definition(missing_secret)?;
+							let expectations = definition.expectations()?;
 							let generated = match generate(
 								config,
-								missing,
-								secret,
-								slice::from_ref(&host.name),
-								expected_generation_data,
+								missing_secret,
+								definition.inner(),
+								&expectations,
 							)
 							.in_current_span()
 							.await
@@ -808,21 +786,27 @@
 									continue;
 								}
 							};
-							config.insert_secret(&host.name, missing.to_string(), generated)
+							config.insert_secret(
+								&host.name,
+								missing_secret.to_string(),
+								FleetHostSecret {
+									managed: Some(true),
+									secret: generated,
+								},
+							)
 						}
-						for name in stored_set {
-							info!("updating secret: {name}");
-							let data = config.host_secret(&host.name, &name)?;
-							let secret = host.secret_field(&name).in_current_span().await?;
-							let expected_generation_data =
-								nix_go_json!(secret.expectedGenerationData);
-							if secret_needs_regeneration(&data, &expected_generation_data) {
+						for known_secret in stored_set.intersection(&expected_set) {
+							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()?;
+							if let Some(regen_reason) = data.needs_regeneration(&expectations) {
+								info!("needs regeneration: {regen_reason}");
 								let generated = match generate(
 									config,
-									&name,
-									secret,
-									slice::from_ref(&host.name),
-									expected_generation_data,
+									known_secret,
+									definition.inner(),
+									&expectations,
 								)
 								.in_current_span()
 								.await
@@ -833,43 +817,44 @@
 										continue;
 									}
 								};
-								config.insert_secret(&host.name, name.to_string(), generated)
+								config.insert_secret(
+									&host.name,
+									known_secret.to_string(),
+									FleetHostSecret {
+										managed: Some(true),
+										secret: generated,
+									},
+								)
 							}
 						}
+						for removed_secret in stored_set.difference(&expected_set) {
+							info!("removing secret: {removed_secret}");
+							config.remove_secret(&host.name, removed_secret);
+						}
 					}
 				}
-				let mut to_remove = Vec::new();
-				for name in &stored_shared_set {
-					info!("updating secret: {name}");
-					let data = config.shared_secret(name)?;
-					let config_field = &config.config_field;
-					let expected_owners: Option<Vec<String>> =
-						nix_go_json!(config_field.sharedSecrets[{ name }].expectedOwners);
-					let Some(expected_owners) = expected_owners else {
-						warn!("secret was removed from fleet config: {name}, removing from data");
-						to_remove.push(name.to_string());
-						continue;
-					};
+				for known_secret in stored_shared_set.intersection(&expected_shared_set) {
+					info!("updating shared secret: {known_secret}");
+					let data = config.shared_secret(known_secret)?.expect("exists");
 
-					let secret = nix_go!(config_field.sharedSecrets[{ name }]);
-					let expected_generation_data = nix_go_json!(secret.expectedGenerationData);
+					let definition = config.shared_secret_definition(known_secret)?;
+					let expectations = definition.expectations()?;
 					config.replace_shared(
-						name.to_owned(),
+						known_secret.to_owned(),
 						maybe_regenerate_shared_secret(
-							name,
+							known_secret,
 							config,
 							data,
-							secret,
-							&expected_owners,
-							expected_generation_data,
+							definition,
 							&prefer_identities,
-							// None,
+							&expectations,
 						)
 						.await?,
 					);
 				}
-				for k in to_remove {
-					config.remove_shared(&k);
+				for removed_secret in stored_shared_set.difference(&expected_shared_set) {
+					info!("removing shared secret: {removed_secret}");
+					config.remove_shared(removed_secret);
 				}
 			}
 			Secret::List {} => {
@@ -885,13 +870,14 @@
 				let mut table = vec![];
 				for name in configured.iter().cloned() {
 					let config = config.clone();
-					let expected_owners = config.shared_secret_expected_owners(&name).await?;
-					let data = config.shared_secret(&name)?;
+					let data = config.shared_secret(&name)?.expect("exists");
+					let definition = config.shared_secret_definition(&name)?;
+					let expectations = definition.expectations()?;
 					let owners = data
 						.owners
 						.iter()
 						.map(|o| {
-							if expected_owners.contains(o) {
+							if expectations.owners.contains(o) {
 								o.green().to_string()
 							} else {
 								o.red().to_string()
@@ -912,7 +898,7 @@
 				add,
 			} => {
 				let secret = config.host_secret(&machine, &name)?;
-				if let Some(data) = secret.parts.get(&part) {
+				if let Some(data) = secret.secret.parts.get(&part) {
 					let host = config.host(&machine).await?;
 					let secret = host.decrypt(data.raw.clone()).await?;
 					String::from_utf8(secret).context("secret is not utf8")?
modifiedcmds/fleet/src/main.rsdiffbeforeafterboth
--- a/cmds/fleet/src/main.rs
+++ b/cmds/fleet/src/main.rs
@@ -27,7 +27,7 @@
 use tracing::{Instrument, error, info, info_span};
 #[cfg(feature = "indicatif")]
 use tracing_indicatif::IndicatifLayer;
-use tracing_subscriber::{EnvFilter, fmt::format::Format, prelude::*};
+use tracing_subscriber::{EnvFilter, prelude::*};
 
 #[derive(Parser)]
 struct Prefetch {}
modifiedcrates/fleet-base/Cargo.tomldiffbeforeafterboth
--- a/crates/fleet-base/Cargo.toml
+++ b/crates/fleet-base/Cargo.toml
@@ -24,6 +24,7 @@
 serde_json = "1.0.140"
 tabled = "0.20.0"
 tempfile.workspace = true
+thiserror.workspace = true
 time = { version = "0.3.41", features = ["parsing"] }
 tokio.workspace = true
 tokio-util = "0.7.15"
modifiedcrates/fleet-base/src/fleetdata.rsdiffbeforeafterboth
--- a/crates/fleet-base/src/fleetdata.rs
+++ b/crates/fleet-base/src/fleetdata.rs
@@ -1,5 +1,5 @@
 use std::{
-	collections::BTreeMap,
+	collections::{BTreeMap, BTreeSet},
 	io::{self, Cursor},
 };
 
@@ -13,6 +13,8 @@
 use serde::{Deserialize, Serialize, de::Error};
 use serde_json::Value;
 
+use crate::secret::{Expectations, RegenerationReason, secret_needs_regeneration};
+
 #[derive(Serialize, Deserialize, Default)]
 #[serde(rename_all = "camelCase")]
 pub struct HostData {
@@ -75,30 +77,21 @@
 	pub shared_secrets: BTreeMap<String, FleetSharedSecret>,
 	#[serde(default)]
 	#[serde(skip_serializing_if = "BTreeMap::is_empty")]
-	pub host_secrets: BTreeMap<String, BTreeMap<String, FleetSecret>>,
+	pub host_secrets: BTreeMap<String, BTreeMap<String, FleetHostSecret>>,
 
 	// extra_name => anything
 	#[serde(default)]
 	#[serde(skip_serializing_if = "BTreeMap::is_empty")]
 	pub extra: BTreeMap<String, Value>,
-}
-
-#[derive(Serialize, Deserialize, Clone)]
-#[serde(rename_all = "camelCase")]
-#[must_use]
-pub struct FleetSharedSecret {
-	pub owners: Vec<String>,
-	#[serde(flatten)]
-	pub secret: FleetSecret,
 }
 
 /// Returns None if recipients.is_empty()
-pub fn encrypt_secret_data<'a>(
-	recipients: impl IntoIterator<Item = &'a dyn Recipient>,
+pub fn encrypt_secret_data<'r>(
+	recipients: impl IntoIterator<Item = &'r Box<dyn Recipient>>,
 	data: Vec<u8>,
 ) -> Option<SecretData> {
 	let mut encrypted = vec![];
-	let mut encryptor = age::Encryptor::with_recipients(recipients.into_iter())
+	let mut encryptor = age::Encryptor::with_recipients(recipients.into_iter().map(|v| &**v))
 		.ok()?
 		.wrap_output(&mut encrypted)
 		.expect("in memory write");
@@ -118,7 +111,7 @@
 #[derive(Serialize, Deserialize, Clone)]
 #[serde(rename_all = "camelCase")]
 #[must_use]
-pub struct FleetSecret {
+pub struct FleetSecretData {
 	#[serde(default = "Utc::now")]
 	pub created_at: DateTime<Utc>,
 	#[serde(default)]
@@ -132,3 +125,31 @@
 	#[serde(skip_serializing_if = "Value::is_null")]
 	pub generation_data: Value,
 }
+
+#[derive(Serialize, Deserialize, Clone)]
+#[serde(rename_all = "camelCase")]
+#[must_use]
+pub struct FleetHostSecret {
+	#[serde(default)]
+	#[serde(skip_serializing_if = "Option::is_none")]
+	pub managed: Option<bool>,
+	#[serde(flatten)]
+	pub secret: FleetSecretData,
+}
+impl FleetHostSecret {
+	pub fn needs_regeneration(&self, expectations: &Expectations) -> Option<RegenerationReason> {
+		secret_needs_regeneration(&self.secret, &expectations.owners, expectations)
+	}
+}
+
+#[derive(Serialize, Deserialize, Clone)]
+#[serde(rename_all = "camelCase")]
+#[must_use]
+pub struct FleetSharedSecret {
+	#[serde(default)]
+	#[serde(skip_serializing_if = "Option::is_none")]
+	pub managed: Option<bool>,
+	pub owners: BTreeSet<String>,
+	#[serde(flatten)]
+	pub secret: FleetSecretData,
+}
modifiedcrates/fleet-base/src/host.rsdiffbeforeafterboth
--- a/crates/fleet-base/src/host.rs
+++ b/crates/fleet-base/src/host.rs
@@ -22,7 +22,8 @@
 
 use crate::{
 	command::MyCommand,
-	fleetdata::{FleetData, FleetSecret, FleetSharedSecret},
+	fleetdata::{FleetData, FleetHostSecret, FleetSharedSecret},
+	secret::{HostSecretDefinition, SharedSecretDefinition},
 };
 
 pub struct FleetConfigInternals {
@@ -234,7 +235,7 @@
 		let is_fleet_managed = match self.file_exists("/etc/FLEET_HOST").await {
 			Ok(v) => v,
 			Err(e) => {
-				bail!("failed to query remote system kind: {}", e);
+				bail!("failed to query remote system kind: {e}");
 			}
 		};
 		if !is_fleet_managed {
@@ -501,7 +502,7 @@
 
 		Ok(nixos_config)
 	}
-	pub async fn nixos_unchecked_config(&self) -> Result<Value> {
+	pub fn nixos_unchecked_config(&self) -> Result<Value> {
 		if let Some(v) = self.nixos_unchecked_config.get() {
 			return Ok(v.clone());
 		}
@@ -515,23 +516,17 @@
 		Ok(nixos_config)
 	}
 
-	pub async fn list_configured_secrets(&self) -> Result<Vec<String>> {
-		let nixos = self.nixos_unchecked_config().await?;
+	pub fn list_defined_secrets(&self) -> Result<Vec<String>> {
+		let nixos = self.nixos_unchecked_config()?;
 		let secrets = nix_go!(nixos.secrets);
-		let mut out = Vec::new();
-		for name in secrets.list_fields()? {
-			let secret = secrets.get_field(&name).context("getting secret")?;
-			let is_shared: bool = nix_go_json!(secret.shared);
-			if is_shared {
-				continue;
-			}
-			out.push(name);
-		}
-		Ok(out)
+		secrets.list_fields()
 	}
-	pub async fn secret_field(&self, name: &str) -> Result<Value> {
-		let nixos = self.nixos_unchecked_config().await?;
-		Ok(nix_go!(nixos.secrets[{ name }]))
+	pub fn secret_definition(&self, name: &str) -> Result<HostSecretDefinition> {
+		let nixos = self.nixos_unchecked_config()?;
+		Ok(HostSecretDefinition(
+			self.name.clone(),
+			nix_go!(nixos.secrets[{ name }]),
+		))
 	}
 
 	/// Packages for this host, resolved with nixpkgs overlays
@@ -648,10 +643,19 @@
 
 	pub fn list_secrets(&self, host: &str) -> Vec<String> {
 		let data = self.data();
-		let Some(secrets) = data.host_secrets.get(host) else {
-			return Vec::new();
-		};
-		secrets.keys().cloned().collect()
+		let mut out = data
+			.host_secrets
+			.get(host)
+			.map(|s| s.keys().cloned().collect::<Vec<String>>())
+			.unwrap_or_default();
+
+		for (name, shared) in data.shared_secrets.iter() {
+			if shared.owners.contains(host) {
+				out.push(name.clone());
+			}
+		}
+
+		out
 	}
 
 	pub fn has_secret(&self, host: &str, secret: &str) -> bool {
@@ -661,34 +665,44 @@
 		};
 		host_secrets.contains_key(secret)
 	}
-	pub fn insert_secret(&self, host: &str, secret: String, value: FleetSecret) {
+	pub fn insert_secret(&self, host: &str, secret: String, value: FleetHostSecret) {
 		let mut data = self.data_mut();
 		let host_secrets = data.host_secrets.entry(host.to_owned()).or_default();
 		host_secrets.insert(secret, value);
 	}
+	pub fn remove_secret(&self, host: &str, secret: &str) {
+		let mut data = self.data_mut();
+		let host_secrets = data.host_secrets.entry(host.to_owned()).or_default();
+		host_secrets.remove(secret);
+	}
 
-	pub fn host_secret(&self, host: &str, secret: &str) -> Result<FleetSecret> {
+	pub fn host_secret(&self, host: &str, secret: &str) -> Result<FleetHostSecret> {
 		let data = self.data();
-		let Some(host_secrets) = data.host_secrets.get(host) else {
-			bail!("no secrets for machine {host}");
+		if let Some(host_secrets) = data.host_secrets.get(host) {
+			if let Some(secret) = host_secrets.get(secret) {
+				return Ok(secret.clone());
+			}
 		};
-		let Some(secret) = host_secrets.get(secret) else {
+		let Some(shared) = data.shared_secrets.get(secret) else {
 			bail!("machine {host} has no secret {secret}");
 		};
-		Ok(secret.clone())
+		if !shared.owners.contains(host) {
+			bail!("shared secret {secret} is not owned by {host}");
+		};
+		Ok(FleetHostSecret {
+			managed: shared.managed,
+			secret: shared.secret.clone(),
+		})
 	}
-	pub fn shared_secret(&self, secret: &str) -> Result<FleetSharedSecret> {
+	pub fn shared_secret(&self, secret: &str) -> Result<Option<FleetSharedSecret>> {
 		let data = self.data();
-		let Some(secret) = data.shared_secrets.get(secret) else {
-			bail!("no shared secret {secret}");
-		};
-		Ok(secret.clone())
+		Ok(data.shared_secrets.get(secret).cloned())
 	}
-	pub async fn shared_secret_expected_owners(&self, secret: &str) -> Result<Vec<String>> {
+	pub fn shared_secret_definition(&self, secret: &str) -> Result<SharedSecretDefinition> {
 		let config_field = &self.config_field;
-		Ok(nix_go_json!(
-			config_field.sharedSecrets[{ secret }].expectedOwners
-		))
+		Ok(SharedSecretDefinition(nix_go!(
+			config_field.sharedSecrets[{ secret }]
+		)))
 	}
 
 	// TODO: Should this be something modifiable from other processes?
modifiedcrates/fleet-base/src/keys.rsdiffbeforeafterboth
--- a/crates/fleet-base/src/keys.rs
+++ b/crates/fleet-base/src/keys.rs
@@ -39,12 +39,14 @@
 		}
 	}
 	/// Insecure, requires root
-	pub async fn recipient(&self, host: &str) -> anyhow::Result<impl Recipient + use<>> {
+	pub async fn recipient(&self, host: &str) -> anyhow::Result<Box<dyn Recipient>> {
 		let key = self.key(host).await?;
-		age::ssh::Recipient::from_str(&key).map_err(|e| anyhow!("parse recipient error: {:?}", e))
+		age::ssh::Recipient::from_str(&key)
+			.map_err(|e| anyhow!("parse recipient error: {e:?}"))
+			.map(|v| Box::new(v) as Box<dyn Recipient>)
 	}
 
-	pub async fn recipients(&self, hosts: Vec<String>) -> Result<Vec<impl Recipient + use<>>> {
+	pub async fn recipients(&self, hosts: Vec<String>) -> Result<Vec<Box<dyn Recipient>>> {
 		let hosts = self.expand_owner_set(hosts).await?;
 		futures::stream::iter(hosts.iter())
 			.then(|m| self.recipient(m.as_ref()))
modifiedcrates/fleet-base/src/lib.rsdiffbeforeafterboth
--- a/crates/fleet-base/src/lib.rs
+++ b/crates/fleet-base/src/lib.rs
@@ -4,3 +4,4 @@
 pub mod host;
 mod keys;
 pub mod opts;
+pub mod secret;
addedcrates/fleet-base/src/secret.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/fleet-base/src/secret.rs
@@ -0,0 +1,136 @@
+use std::collections::BTreeSet;
+
+use anyhow::Result;
+use chrono::{DateTime, Utc};
+use nix_eval::{Value, nix_go, nix_go_json};
+
+use crate::fleetdata::FleetSecretData;
+
+#[derive(Debug)]
+pub struct Expectations {
+	pub owners: BTreeSet<String>,
+	pub generation_data: serde_json::Value,
+	pub public_parts: BTreeSet<String>,
+	pub private_parts: BTreeSet<String>,
+}
+
+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())
+	}
+	pub fn expectations(&self) -> Result<Expectations> {
+		let value = &self.1;
+		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),
+		})
+	}
+	pub fn inner(&self) -> Value {
+		self.1.clone()
+	}
+}
+
+pub struct SharedSecretDefinition(pub(crate) Value);
+impl SharedSecretDefinition {
+	pub fn is_managed(&self) -> Result<bool> {
+		let value = &self.0;
+		Ok(!nix_go!(value.generator).is_null())
+	}
+	pub fn expectations(&self) -> Result<Expectations> {
+		let value = &self.0;
+		Ok(Expectations {
+			owners: nix_go_json!(value.expectedOwners),
+			generation_data: nix_go_json!(value.expectedGenerationData),
+			public_parts: nix_go_json!(value.expectedPublicParts),
+			private_parts: nix_go_json!(value.expectedPrivateParts),
+		})
+	}
+	pub fn inner(&self) -> Value {
+		self.0.clone()
+	}
+}
+
+#[derive(thiserror::Error, Debug)]
+pub enum RegenerationReason {
+	#[error("owners added: {0:?}")]
+	OwnersAdded(BTreeSet<String>),
+	#[error("owners added: {0:?}")]
+	OwnersRemoved(BTreeSet<String>),
+	#[error("unexpected generation data, expected: {expected:?}, found: {found:?}")]
+	GenerationData {
+		expected: serde_json::Value,
+		found: serde_json::Value,
+	},
+	#[error("unexpected part list, expected: {expected:?}, found: {found:?}")]
+	PartList {
+		expected: BTreeSet<String>,
+		found: BTreeSet<String>,
+	},
+	#[error("part {0} is expected to be encrypted")]
+	ExpectedPrivate(String),
+	#[error("part {0} is not expected to be encrypted")]
+	ExpectedPublic(String),
+	#[error("secret is expired at {0}")]
+	Expired(DateTime<Utc>),
+}
+
+pub fn secret_needs_regeneration(
+	secret: &FleetSecretData,
+	owners: &BTreeSet<String>,
+	expectations: &Expectations,
+) -> Option<RegenerationReason> {
+	if !owners.is_empty() {
+		let added: BTreeSet<String> = expectations.owners.difference(owners).cloned().collect();
+		if !added.is_empty() {
+			return Some(RegenerationReason::OwnersAdded(added));
+		}
+
+		let removed: BTreeSet<String> = owners.difference(&expectations.owners).cloned().collect();
+		if !removed.is_empty() {
+			return Some(RegenerationReason::OwnersRemoved(removed));
+		}
+	}
+
+	if secret.generation_data != expectations.generation_data {
+		return Some(RegenerationReason::GenerationData {
+			expected: expectations.generation_data.clone(),
+			found: secret.generation_data.clone(),
+		});
+	}
+
+	if !expectations.public_parts.is_empty() || !expectations.private_parts.is_empty() {
+		let expected: BTreeSet<String> = expectations
+			.public_parts
+			.union(&expectations.private_parts)
+			.cloned()
+			.collect();
+		let found: BTreeSet<String> = secret.parts.keys().cloned().collect();
+
+		if found != expected {
+			return Some(RegenerationReason::PartList { expected, found });
+		}
+
+		for (name, value) in secret.parts.iter() {
+			if value.raw.encrypted {
+				if !expectations.private_parts.contains(name) {
+					return Some(RegenerationReason::ExpectedPrivate(name.clone()));
+				}
+			} else if !expectations.public_parts.contains(name) {
+				return Some(RegenerationReason::ExpectedPublic(name.clone()));
+			}
+		}
+	}
+
+	if let Some(expiration) = secret.expires_at {
+		// TODO: Leeway?
+		if expiration < Utc::now() {
+			return Some(RegenerationReason::Expired(expiration));
+		}
+	}
+
+	None
+}
modifiedcrates/nix-eval/src/lib.rsdiffbeforeafterboth
after · crates/nix-eval/src/lib.rs
1use std::borrow::Cow;2use std::cell::RefCell;3use std::ffi::{CStr, CString, c_char, c_int, c_uint, c_void};4use std::ptr::null_mut;5use std::sync::LazyLock;6use std::{collections::HashMap, path::PathBuf};7use std::{fmt, slice};89use anyhow::{Context, anyhow, bail};10use serde::Serialize;11use serde::de::DeserializeOwned;1213pub use anyhow::Result;14use tracing::instrument;1516use self::logging::nix_logging_cxx;17use self::nix_cxx::set_fetcher_setting;18use self::nix_raw::{19	BindingsBuilder as c_bindings_builder, EvalState as c_eval_state, GC_SUCCESS,20	GC_allow_register_threads, GC_get_stack_base, GC_register_my_thread, GC_stack_base,21	GC_thread_is_registered, GC_unregister_my_thread, ListBuilder as c_list_builder,22	Store as c_store, StorePath as c_store_path, alloc_value, bindings_builder_free,23	bindings_builder_insert, c_context, c_context_create, c_context_free, clear_err, err_code,24	err_info_msg, err_msg, eval_state_build, eval_state_builder_load, eval_state_builder_new,25	eval_state_builder_set_eval_setting, expr_eval_from_string, fetchers_settings,26	fetchers_settings_free, fetchers_settings_new, flake_lock, flake_lock_flags,27	flake_lock_flags_free, flake_lock_flags_new, flake_reference,28	flake_reference_and_fragment_from_string, flake_reference_parse_flags,29	flake_reference_parse_flags_free, flake_reference_parse_flags_new,30	flake_reference_parse_flags_set_base_directory, flake_settings, flake_settings_free,31	flake_settings_new, gc_now as gc_now_raw, get_attr_byname, get_attr_name_byidx, get_attrs_size,32	get_list_byidx, get_list_size, get_string, get_type, has_attr_byname, init_bool, init_int,33	init_string, libexpr_init, libstore_init, libutil_init, list_builder_free, list_builder_insert,34	locked_flake, locked_flake_free, locked_flake_get_output_attrs, make_attrs,35	make_bindings_builder, make_list, make_list_builder, realised_string, realised_string_free,36	realised_string_get_buffer_size, realised_string_get_buffer_start,37	realised_string_get_store_path, realised_string_get_store_path_count, set_err_msg, setting_set,38	state_free, store_open, store_parse_path, store_path_free, store_path_name, string_realise,39	value, value_call, value_decref, value_incref,40};4142// Contains macros helpers43pub mod logging;44#[doc(hidden)]45pub mod macros;46pub mod util;4748#[allow(49	non_upper_case_globals,50	non_camel_case_types,51	non_snake_case,52	dead_code53)]54mod nix_raw {55	include!(concat!(env!("OUT_DIR"), "/bindings.rs"));56}57#[cxx::bridge]58pub mod nix_cxx {59	unsafe extern "C++" {60		type nix_fetchers_settings;61		include!("nix-eval/src/lib.hh");6263		unsafe fn set_fetcher_setting(64			settings: *mut nix_fetchers_settings,65			setting: *const c_char,66			value: *const c_char,67		);68	}69}7071#[derive(Debug, PartialEq, Eq)]72pub enum NixType {73	Thunk,74	Int,75	Float,76	Bool,77	String,78	Path,79	Null,80	Attrs,81	List,82	Function,83	External,84}85impl NixType {86	fn from_int(c: c_uint) -> Self {87		match c {88			0 => Self::Thunk,89			1 => Self::Int,90			2 => Self::Float,91			3 => Self::Bool,92			4 => Self::String,93			5 => Self::Path,94			6 => Self::Null,95			7 => Self::Attrs,96			8 => Self::List,97			9 => Self::Function,98			10 => Self::External,99			_ => unreachable!("unknown nix type: {c}"),100		}101	}102}103104enum FunctorKind {105	Function,106	Functor,107}108109#[derive(Debug)]110#[repr(i32)]111pub enum NixErrorKind {112	Unknown = 1,113	Overflow = 2,114	Key = 3,115	Generic = 4,116}117impl NixErrorKind {118	fn from_int(v: c_int) -> Option<Self> {119		Some(match v {120			0 => return None,121			-1 => Self::Unknown,122			-2 => Self::Overflow,123			-3 => Self::Key,124			-4 => Self::Generic,125			_ => {126				debug_assert!(false, "unexpected nix error kind: {v}");127				Self::Unknown128			}129		})130	}131}132133pub fn gc_now() {134	unsafe { gc_now_raw() };135}136137pub fn gc_register_my_thread() {138	assert_eq!(unsafe { GC_thread_is_registered() }, 0);139140	let mut sb = GC_stack_base {141		mem_base: null_mut(),142	};143	let r = unsafe { GC_get_stack_base(&mut sb) };144	if r as u32 != GC_SUCCESS {145		panic!("failed to get thread stack base");146	}147	unsafe { GC_register_my_thread(&sb) };148}149pub fn gc_unregister_my_thread() {150	assert_eq!(unsafe { GC_thread_is_registered() }, 1);151152	unsafe { GC_unregister_my_thread() };153}154155pub struct ThreadRegisterGuard {}156impl ThreadRegisterGuard {157	#[allow(clippy::new_without_default)]158	pub fn new() -> Self {159		gc_register_my_thread();160		Self {}161	}162}163impl Drop for ThreadRegisterGuard {164	fn drop(&mut self) {165		gc_unregister_my_thread();166	}167}168169pub struct NixContext(*mut c_context);170impl NixContext {171	pub fn set_err(&mut self, err: NixErrorKind, msg: &CStr) {172		unsafe { set_err_msg(self.0, err as c_int, msg.as_ptr()) };173	}174	pub fn new() -> Self {175		let ctx = unsafe { c_context_create() };176		Self(ctx)177	}178	fn error_kind(&self) -> Option<NixErrorKind> {179		let code = unsafe { err_code(self.0) };180		NixErrorKind::from_int(code)181	}182	fn error<'t>(&self) -> Option<Cow<'t, str>> {183		if let NixErrorKind::Generic = self.error_kind()? {184			let mut err_out = String::new();185			unsafe {186				err_info_msg(187					null_mut(),188					self.0,189					Some(copy_nix_str),190					(&raw mut err_out).cast(),191				)192			};193			return Some(Cow::Owned(err_out));194		};195196		// TODO: Can throw error (resulting in panic) if unable to retrieve error. Should be able to resolve by passing context as a first argument,197		// but it looks ugly198		let str = unsafe { err_msg(null_mut(), self.0, null_mut()) };199		Some(unsafe { CStr::from_ptr(str) }.to_string_lossy())200	}201	fn clean_err(&mut self) {202		unsafe {203			clear_err(self.0);204		}205	}206207	fn bail_if_error(&self) -> Result<()> {208		if let Some(err) = self.error() {209			bail!("{err}");210		};211		Ok(())212	}213214	fn run_in_context<T>(&mut self, f: impl FnOnce(*mut c_context) -> T) -> Result<T> {215		self.clean_err();216		let o = f(self.0);217		self.bail_if_error()?;218		self.clean_err();219		Ok(o)220	}221}222223impl Default for NixContext {224	fn default() -> Self {225		Self::new()226	}227}228impl Drop for NixContext {229	fn drop(&mut self) {230		unsafe {231			c_context_free(self.0);232		}233	}234}235struct GlobalState {236	// Store should be valid as long as EvalState is valid237	#[allow(dead_code)]238	store: Store,239	state: EvalState,240}241impl GlobalState {242	fn new() -> Result<Self> {243		let mut ctx = NixContext::new();244		let store = ctx245			.run_in_context(|c| unsafe { store_open(c, c"auto".as_ptr(), null_mut()) })246			.map(Store)?;247248		let builder = ctx.run_in_context(|c| unsafe { eval_state_builder_new(c, store.0) })?;249		ctx.run_in_context(|c| unsafe { eval_state_builder_load(c, builder) })?;250		ctx.run_in_context(|c| unsafe {251			eval_state_builder_set_eval_setting(252				c,253				builder,254				c"lazy-trees".as_ptr(),255				c"true".as_ptr(),256			)257		})?;258		ctx.run_in_context(|c| unsafe {259			eval_state_builder_set_eval_setting(260				c,261				builder,262				c"lazy-locks".as_ptr(),263				c"true".as_ptr(),264			)265		})?;266		let state = ctx267			.run_in_context(|c| unsafe { eval_state_build(c, builder) })268			.map(EvalState)?;269270		Ok(Self { store, state })271	}272}273274struct ThreadState {275	ctx: NixContext,276}277impl ThreadState {278	fn new() -> Result<Self> {279		let ctx = NixContext::new();280281		Ok(Self { ctx })282	}283}284285static GLOBAL_STATE: LazyLock<GlobalState> =286	LazyLock::new(|| GlobalState::new().expect("global state init shouldn't fail"));287288thread_local! {289	static THREAD_STATE: RefCell<ThreadState> = RefCell::new(ThreadState::new().expect("thread state init shouldn't fail"));290}291fn with_default_context<T>(f: impl FnOnce(*mut c_context, *mut c_eval_state) -> T) -> Result<T> {292	let global = &GLOBAL_STATE.state;293	let (ctx, state) = THREAD_STATE.with_borrow_mut(|w| (w.ctx.0, global.0));294	let mut ctx = NixContext(ctx);295	let v = ctx.run_in_context(|c| f(c, state));296	// It is reused for thread297	std::mem::forget(ctx);298	v299}300301pub fn set_setting(s: &CStr, v: &CStr) -> Result<()> {302	with_default_context(|c, _| unsafe { setting_set(c, s.as_ptr(), v.as_ptr()) }).map(|_| ())303}304305pub struct FetchSettings(*mut fetchers_settings);306impl FetchSettings {307	pub fn new() -> Self {308		Self::try_new().expect("allocation should not fail")309	}310	fn try_new() -> Result<Self> {311		with_default_context(|c, _| unsafe { fetchers_settings_new(c) }).map(Self)312	}313	pub fn set(&mut self, setting: &CStr, value: &CStr) {314		unsafe {315			set_fetcher_setting(self.0.cast(), setting.as_ptr(), value.as_ptr());316		};317	}318}319unsafe impl Send for FetchSettings {}320unsafe impl Sync for FetchSettings {}321322impl Default for FetchSettings {323	fn default() -> Self {324		Self::new()325	}326}327328impl Drop for FetchSettings {329	fn drop(&mut self) {330		unsafe { fetchers_settings_free(self.0) };331	}332}333pub struct FlakeSettings(*mut flake_settings);334impl FlakeSettings {335	pub fn new() -> Result<Self> {336		with_default_context(|c, _| unsafe { flake_settings_new(c) }).map(Self)337	}338}339unsafe impl Send for FlakeSettings {}340unsafe impl Sync for FlakeSettings {}341impl Drop for FlakeSettings {342	fn drop(&mut self) {343		unsafe {344			flake_settings_free(self.0);345		}346	}347}348349pub struct FlakeReferenceParseFlags(*mut flake_reference_parse_flags);350impl FlakeReferenceParseFlags {351	pub fn new(settings: &FlakeSettings) -> Result<Self> {352		with_default_context(|c, _| unsafe { flake_reference_parse_flags_new(c, settings.0) })353			.map(Self)354	}355	pub fn set_base_dir(&mut self, dir: &str) -> Result<()> {356		with_default_context(|c, _| {357			unsafe {358				flake_reference_parse_flags_set_base_directory(359					c,360					self.0,361					dir.as_ptr().cast(),362					dir.len(),363				)364			};365		})366	}367}368impl Drop for FlakeReferenceParseFlags {369	fn drop(&mut self) {370		unsafe {371			flake_reference_parse_flags_free(self.0);372		}373	}374}375pub struct FlakeLockFlags(*mut flake_lock_flags);376impl FlakeLockFlags {377	pub fn new(settings: &FlakeSettings) -> Result<Self> {378		let o = with_default_context(|c, _| unsafe { flake_lock_flags_new(c, settings.0) })379			.map(Self)?;380		// with_default_context(|c, _| unsafe { flake_lock_flags_set_mode_virtual(c, o.0) })?;381382		Ok(o)383	}384}385impl Drop for FlakeLockFlags {386	fn drop(&mut self) {387		unsafe {388			flake_lock_flags_free(self.0);389		}390	}391}392393unsafe extern "C" fn copy_nix_str(start: *const c_char, n: c_uint, user_data: *mut c_void) {394	let s = unsafe { slice::from_raw_parts(start.cast::<u8>(), n as usize) };395	let s = std::str::from_utf8(s).expect("c string has invalid utf-8");396	unsafe { *user_data.cast::<String>() = s.to_owned() };397}398399struct Store(*mut c_store);400unsafe impl Send for Store {}401unsafe impl Sync for Store {}402403impl Store {404	fn parse_path(&self, path: &CStr) -> Result<StorePath> {405		with_default_context(|c, _| {406			StorePath(unsafe { store_parse_path(c, self.0, path.as_ptr()) })407		})408	}409}410411struct EvalState(*mut c_eval_state);412unsafe impl Send for EvalState {}413unsafe impl Sync for EvalState {}414415impl Drop for EvalState {416	fn drop(&mut self) {417		unsafe {418			state_free(self.0);419		}420	}421}422423pub struct FlakeReference(*mut flake_reference);424impl FlakeReference {425	#[instrument(name = "new-flake-reference", skip(flake, parse, fetch))]426	pub fn new(427		s: &str,428		flake: &FlakeSettings,429		parse: &FlakeReferenceParseFlags,430		fetch: &FetchSettings,431	) -> Result<(Self, String)> {432		let mut out = null_mut();433		let mut fragment = String::new();434		// let fetch_settings = fetcher_settings;435		with_default_context(|c, _| unsafe {436			flake_reference_and_fragment_from_string(437				c,438				fetch.0,439				flake.0,440				parse.0,441				s.as_ptr().cast(),442				s.len(),443				&mut out,444				Some(copy_nix_str),445				(&raw mut fragment).cast(),446			)447		})?;448		assert!(!out.is_null());449450		Ok((Self(out), fragment))451	}452	#[instrument(name = "lock-flake", skip(self, fetch, flake, lock))]453	pub fn lock(454		&mut self,455		fetch: &FetchSettings,456		flake: &FlakeSettings,457		lock: &FlakeLockFlags,458	) -> Result<LockedFlake> {459		with_default_context(|c, es| unsafe { flake_lock(c, fetch.0, flake.0, es, lock.0, self.0) })460			.map(LockedFlake)461	}462}463unsafe impl Send for FlakeReference {}464unsafe impl Sync for FlakeReference {}465466pub struct LockedFlake(*mut locked_flake);467impl LockedFlake {468	pub fn get_attrs(&self, settings: &mut FlakeSettings) -> Result<Value> {469		with_default_context(|c, es| unsafe {470			locked_flake_get_output_attrs(c, settings.0, es, self.0)471		})472		.map(Value)473	}474}475unsafe impl Send for LockedFlake {}476unsafe impl Sync for LockedFlake {}477impl Drop for LockedFlake {478	fn drop(&mut self) {479		unsafe {480			locked_flake_free(self.0);481		};482	}483}484485type FieldName = [u8; 64];486fn init_field_name(v: &str) -> FieldName {487	let mut f = [0; 64];488	assert!(v.len() < 64, "max field name is 63 chars");489	assert!(490		v.bytes().all(|v| v != 0),491		"nul bytes are unsupported in field name"492	);493	f[0..v.len()].copy_from_slice(v.as_bytes());494	f495}496497pub struct RealisedString(*mut realised_string);498impl fmt::Debug for RealisedString {499	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {500		self.as_str().fmt(f)501	}502}503504impl RealisedString {505	pub fn as_str(&self) -> &str {506		let len = unsafe { realised_string_get_buffer_size(self.0) };507		let data: *const u8 = unsafe { realised_string_get_buffer_start(self.0) }.cast();508		let data = unsafe { slice::from_raw_parts(data, len) };509		std::str::from_utf8(data).expect("non-utf8 strings not supported")510	}511	pub fn path_count(&self) -> usize {512		unsafe { realised_string_get_store_path_count(self.0) }513	}514	pub fn path(&self, i: usize) -> String {515		assert!(i < self.path_count());516		let path = unsafe { realised_string_get_store_path(self.0, i) };517		let mut err_out = String::new();518		unsafe { store_path_name(path, Some(copy_nix_str), (&raw mut err_out).cast()) };519		err_out520	}521}522523unsafe impl Send for RealisedString {}524impl Drop for RealisedString {525	fn drop(&mut self) {526		unsafe { realised_string_free(self.0) }527	}528}529530pub struct Value(*mut value);531532unsafe impl Send for Value {}533unsafe impl Sync for Value {}534535pub trait AsFieldName {536	fn as_field_name<T>(&self, v: impl FnOnce(FieldName) -> Result<T>) -> Result<T>;537	fn to_field_name(&self) -> Result<String>;538}539impl AsFieldName for Value {540	fn as_field_name<T>(&self, v: impl FnOnce(FieldName) -> Result<T>) -> Result<T> {541		let f = self.to_string()?;542		v(init_field_name(&f))543	}544	fn to_field_name(&self) -> Result<String> {545		self.to_string()546	}547}548impl<E> AsFieldName for E549where550	E: AsRef<str>,551{552	fn as_field_name<T>(&self, v: impl FnOnce(FieldName) -> Result<T>) -> Result<T> {553		let f = self.as_ref();554		v(init_field_name(f))555	}556	fn to_field_name(&self) -> Result<String> {557		Ok(self.as_ref().to_owned())558	}559}560561struct AttrsBuilder(*mut c_bindings_builder);562impl AttrsBuilder {563	fn new(capacity: usize) -> Self {564		with_default_context(|c, es| unsafe { make_bindings_builder(c, es, capacity) })565			.map(Self)566			.expect("alloc should not fail")567	}568	fn insert(&mut self, k: &impl AsFieldName, v: Value) {569		k.as_field_name(|name| {570			with_default_context(|c, _| unsafe {571				bindings_builder_insert(c, self.0, name.as_ptr().cast(), v.0);572				// bindings_builder_insert doesn't do incref573			})574		})575		.expect("builder insert shouldn't fail");576	}577}578impl Drop for AttrsBuilder {579	fn drop(&mut self) {580		unsafe { bindings_builder_free(self.0) };581	}582}583584struct ListBuilder(*mut c_list_builder, c_uint);585impl ListBuilder {586	fn new(capacity: usize) -> Self {587		with_default_context(|c, es| unsafe { make_list_builder(c, es, capacity) })588			.map(|l| Self(l, 0))589			.expect("alloc should not fail")590	}591}592impl ListBuilder {593	fn push(&mut self, v: Value) {594		with_default_context(|c, _| unsafe {595			list_builder_insert(596				c,597				self.0,598				{599					let v = self.1;600					self.1 += 1;601					v602				},603				v.0,604			)605		})606		.expect("list insert shouldn't fail");607	}608}609impl Drop for ListBuilder {610	fn drop(&mut self) {611		unsafe { list_builder_free(self.0) };612	}613}614615impl Value {616	pub fn new_attrs(v: HashMap<&str, Value>) -> Self {617		let out = Self::new_uninit();618		let mut b = AttrsBuilder::new(v.len());619		for (k, v) in v {620			b.insert(&k, v);621		}622		with_default_context(|c, _| unsafe { make_attrs(c, out.0, b.0) })623			.expect("attrs initialization should not fail");624625		out626	}627	fn new_list<T: Into<Self>>(v: Vec<T>) -> Self {628		let out = Self::new_uninit();629		let mut b = ListBuilder::new(v.len());630		for v in v {631			b.push(v.into());632		}633		with_default_context(|c, _| unsafe { make_list(c, b.0, out.0) })634			.expect("list initialization should not fail");635636		out637	}638	fn new_uninit() -> Self {639		let out = with_default_context(|c, es| unsafe { alloc_value(c, es) })640			.expect("value allocation should not fail");641		Self(out)642	}643	pub fn new_str(v: &str) -> Self {644		let s = CString::new(v).expect("string should not contain NULs");645		let out = Self::new_uninit();646		// String is copied, `s` is free to be dropped647		with_default_context(|c, _| unsafe { init_string(c, out.0, s.as_ptr()) })648			.expect("string initialization should not fail");649		out650	}651	pub fn new_int(i: i64) -> Self {652		let out = Self::new_uninit();653		with_default_context(|c, _| unsafe { init_int(c, out.0, i) })654			.expect("int initialization should not fail");655		out656	}657	pub fn new_bool(v: bool) -> Self {658		let out = Self::new_uninit();659		with_default_context(|c, _| unsafe { init_bool(c, out.0, v) })660			.expect("bool initialization should not fail");661		out662	}663	// TODO: As far as I can see, there is no way to get Thunks from nix public C api, so this function is useless664	// fn force(&mut self, st: &mut EvalState) -> Result<()> {665	// 	with_default_context(|c, _| unsafe { value_force(c, st.0, self.0) })?;666	// 	Ok(())667	// }668	pub fn type_of(&self) -> NixType {669		let ty = with_default_context(|c, _| unsafe { get_type(c, self.0) })670			.expect("get_type should not fail");671		NixType::from_int(ty)672	}673	fn builtin_to_string(&self) -> Result<Self> {674		let builtin = Self::eval("builtins.toString")?;675		builtin.call(self.clone())676	}677	pub fn to_string(&self) -> Result<String> {678		let mut str_out = String::new();679		with_default_context(|c, _| unsafe {680			get_string(c, self.0, Some(copy_nix_str), (&raw mut str_out).cast())681		})?;682683		Ok(str_out)684	}685	pub fn to_realised_string(&self) -> Result<RealisedString> {686		with_default_context(|c, es| unsafe { string_realise(c, es, self.0, false) })687			.map(RealisedString)688689		// let store_paths = unsafe { nix_raw::realised_string_get_store_path_count(str) };690		// for i in 0..store_paths {691		// 	let store_path = unsafe { nix_raw::realised_string_get_store_path(str, i) };692		// 	nix_raw::store_path_name(store_path, callback, user_data);693		// }694		// dbg!(store_paths);695		// todo!();696	}697698	pub fn has_field(&self, field: &str) -> Result<bool> {699		let f = init_field_name(field);700		with_default_context(|c, es| unsafe { has_attr_byname(c, self.0, es, f.as_ptr().cast()) })701	}702	// pub fn derivation_path(&self) {703	// 	nix_raw::real704	// }705	pub fn list_fields(&self) -> Result<Vec<String>> {706		if !matches!(self.type_of(), NixType::Attrs) {707			bail!("invalid type: expected attrs");708		}709710		let len = with_default_context(|c, _| unsafe { get_attrs_size(c, self.0) })?;711		let mut out = Vec::with_capacity(len as usize);712713		for i in 0..len {714			let name =715				with_default_context(|c, es| unsafe { get_attr_name_byidx(c, self.0, es, i) })?;716			let c = unsafe { CStr::from_ptr(name) };717			out.push(c.to_str().expect("nix field names are utf-8").to_owned());718		}719		Ok(out)720	}721	pub fn get_elem(&self, v: usize) -> Result<Self> {722		if !matches!(self.type_of(), NixType::List) {723			bail!("invalid type: expected list");724		}725		let len = with_default_context(|c, _| unsafe { get_list_size(c, self.0) })? as usize;726		if v >= len {727			bail!("oob list get: {v} >= {len}");728		}729730		with_default_context(|c, es| unsafe { get_list_byidx(c, self.0, es, v as u32) }).map(Self)731	}732	pub fn attrs_update(self, other: Value /*, ignore_errors: bool*/) -> Result<Self> {733		let attrs_update_fn = Self::eval("a: b: a // b")?;734735		attrs_update_fn736			.call(self)?737			.call(other)738			.context("attrs update")739	}740	pub fn get_field(&self, name: impl AsFieldName) -> Result<Self> {741		if !matches!(self.type_of(), NixType::Attrs) {742			bail!("invalid type: expected attrs");743		}744745		name.as_field_name(|name| {746			with_default_context(|c, es| unsafe {747				get_attr_byname(c, self.0, es, name.as_ptr().cast())748			})749			.map(Self)750		})751		.with_context(|| format!("getting field {:?}", name.to_field_name()))752	}753	pub fn call(&self, v: Value) -> Result<Self> {754		let kind = self755			.functor_kind()756			.ok_or_else(|| anyhow!("can only call function or functor"))?;757758		let function = match kind {759			FunctorKind::Function => self.clone(),760			FunctorKind::Functor => {761				let f = self762					.get_field("__functor")763					.context("getting functor value")?;764				assert_eq!(765					f.type_of(),766					NixType::Function,767					"invalid functor encountered"768				);769				f770			}771		};772773		let out = Value::new_uninit();774		with_default_context(|c, es| unsafe { value_call(c, es, function.0, v.0, out.0) })?;775776		Ok(out)777	}778	pub fn eval(v: &str) -> Result<Self> {779		let s = CString::new(v).expect("expression shouldn't have internal NULs");780		let out = Self::new_uninit();781		with_default_context(|c, es| unsafe {782			expr_eval_from_string(c, es, s.as_ptr(), c"/root".as_ptr(), out.0)783		})?;784		Ok(out)785	}786	pub fn build(&self, output: &str) -> Result<PathBuf> {787		if !self.is_derivation() {788			bail!("expected derivation to build")789		}790		let output_name = self791			.get_field("outputName")792			.context("getting output name field")?793			.to_string()?;794		let v = if output_name != output {795			let out = self.get_field(output).context("getting target output")?;796			if !out.is_derivation() {797				bail!("unknown output: {output}");798			}799			out800		} else {801			self.clone()802		};803		// to_string here blocks until the path is built804		let s = v.builtin_to_string()?;805		let rs = s.to_realised_string()?;806		let drv_path = rs.as_str().to_owned();807		Ok(PathBuf::from(drv_path))808	}809	pub fn as_json<T: DeserializeOwned>(&self) -> Result<T> {810		let to_json = Self::eval("builtins.toJSON")?;811		let s = to_json.call(self.clone())?.to_string()?;812		Ok(serde_json::from_str(&s)?)813	}814	pub fn serialized<T: Serialize>(v: &T) -> Result<Self> {815		Self::eval(&nixlike::serialize(v)?)816	}817818	// Convert to string/evaluate derivations/etc819	// fn to_string_weak(&self) -> Result<String> {820	// 	// TODO: For now, it works exactly like to_string, see the comment for fn force()821	// 	self.to_string()822	// }823824	fn is_derivation(&self) -> bool {825		if !matches!(self.type_of(), NixType::Attrs) {826			return false;827		}828		let Some(ty) = self.get_field("type").ok() else {829			return false;830		};831		matches!(ty.to_string().as_deref(), Ok("derivation"))832	}833	fn functor_kind(&self) -> Option<FunctorKind> {834		match self.type_of() {835			NixType::Attrs => self836				.has_field("__functor")837				.expect("has_field shouldn't fail for attrs")838				.then_some(FunctorKind::Functor),839			NixType::Function => Some(FunctorKind::Function),840			_ => None,841		}842	}843	pub fn is_function(&self) -> bool {844		self.functor_kind().is_some()845	}846	pub fn is_null(&self) -> bool {847		matches!(self.type_of(), NixType::Null)848	}849}850851impl From<String> for Value {852	fn from(value: String) -> Self {853		Value::new_str(&value)854	}855}856impl From<bool> for Value {857	fn from(value: bool) -> Self {858		Value::new_bool(value)859	}860}861impl From<&str> for Value {862	fn from(value: &str) -> Self {863		Value::new_str(value)864	}865}866impl<T> From<Vec<T>> for Value867where868	T: Into<Value>,869{870	fn from(value: Vec<T>) -> Self {871		Value::new_list(value)872	}873}874875impl Clone for Value {876	fn clone(&self) -> Self {877		with_default_context(|c, _| unsafe { value_incref(c, self.0) })878			.expect("value incref should not fail");879		Self(self.0)880	}881}882impl Drop for Value {883	fn drop(&mut self) {884		with_default_context(|c, _| unsafe { value_decref(c, self.0) })885			.expect("value drop should not fail");886	}887}888889pub fn init_libraries() {890	unsafe { GC_allow_register_threads() };891892	let mut ctx = NixContext::new();893	ctx.run_in_context(|c| unsafe { libutil_init(c) })894		.expect("util init should not fail");895	ctx.run_in_context(|c| unsafe { libstore_init(c) })896		.expect("store init should not fail");897	ctx.run_in_context(|c| unsafe { libexpr_init(c) })898		.expect("expr init should not fail");899900	nix_logging_cxx::apply_tracing_logger();901}902903struct StorePath(*mut c_store_path);904impl StorePath {}905906impl Drop for StorePath {907	fn drop(&mut self) {908		unsafe { store_path_free(self.0) }909	}910}911912#[test_log::test]913fn test_native() -> Result<()> {914	init_libraries();915916	let mut fetch_settings = FetchSettings::new();917	fetch_settings.set(c"warn-dirty", c"false");918919	let manifest = format!("git+file://{}/../../", env!("CARGO_MANIFEST_DIR"));920	let flake = FlakeSettings::new()?;921	let parse = FlakeReferenceParseFlags::new(&flake)?;922	let (mut r, _) = FlakeReference::new(&manifest, &flake, &parse, &fetch_settings)?;923	let lock = FlakeLockFlags::new(&flake)?;924	let locked = r.lock(&fetch_settings, &flake, &lock)?;925	let attrs = locked.get_attrs(&mut FlakeSettings::new()?)?;926927	let builtins = Value::eval("builtins")?;928	assert_eq!(builtins.type_of(), NixType::Attrs);929930	assert_eq!(attrs.type_of(), NixType::Attrs);931	let test_data = nix_go!(attrs.testData);932933	let test_string: String = nix_go_json!(test_data.testString);934	assert_eq!(test_string, "hello");935936	let s = nix_go!(attrs.packages["x86_64-linux"].fleet.drvPath);937	let s = CString::new(s.to_string()?).expect("path str is cstring");938939	let nix_ctx = NixContext::new();940	let store = GLOBAL_STATE.store.parse_path(s.as_c_str())?;941942	// nix_raw::store_get_fs_closure(1);943944	Ok(())945}946947// pub struct GcAlloc;948// unsafe impl GlobalAlloc for GcAlloc {949// 	unsafe fn alloc(&self, l: Layout) -> *mut u8 {950// 		let ptr = unsafe { GC_malloc(l.size()) };951// 		ptr.cast()952// 	}953// 	unsafe fn dealloc(&self, ptr: *mut u8, _: Layout) {954// 		// unsafe { GC_free(ptr.cast()) };955// 	}956//957// 	unsafe fn realloc(&self, ptr: *mut u8, _: Layout, new_size: usize) -> *mut u8 {958// 		let ptr = unsafe { GC_realloc(ptr.cast(), new_size) };959// 		ptr.cast()960// 	}961// }962//963// #[global_allocator]964// static GC: GcAlloc = GcAlloc;
modifiedflake.nixdiffbeforeafterboth
--- a/flake.nix
+++ b/flake.nix
@@ -181,7 +181,7 @@
                 inputs'.nix.packages.nix-fetchers-c
                 inputs'.nix.packages.nix-store-c
 
-                (rage.overrideAttrs {cargoFeatures = ["plugin"];})
+                (rage.overrideAttrs { cargoFeatures = [ "plugin" ]; })
               ];
               environment.PROTOC = "${pkgs.protobuf}/bin/protoc";
             };
modifiedmodules/extras/tf.nixdiffbeforeafterboth
--- a/modules/extras/tf.nix
+++ b/modules/extras/tf.nix
@@ -38,17 +38,19 @@
       # will be somehow processed by fleet tf.
       sensitive = true;
     };
-    fleetConfigurations.default = {config, ...}: {
-      options.data = mkDataOption {
-        # host => hostData
-        options.extra.terraformHosts = mkOption {
-          default = { };
-          type = attrsOf (attrsOf unspecified);
-          description = "Hosts data provided by fleet tf";
+    fleetConfigurations.default =
+      { config, ... }:
+      {
+        options.data = mkDataOption {
+          # host => hostData
+          options.extra.terraformHosts = mkOption {
+            default = { };
+            type = attrsOf (attrsOf unspecified);
+            description = "Hosts data provided by fleet tf";
+          };
         };
+        config.hosts = config.data.extra.terraformHosts;
       };
-      config.hosts = config.data.extra.terraformHosts;
-    };
 
     perSystem.imports = [ ./tf-bootstrap.nix ];
   };
modifiedmodules/nixos/secrets.nixdiffbeforeafterboth
--- a/modules/nixos/secrets.nix
+++ b/modules/nixos/secrets.nix
@@ -6,11 +6,11 @@
   ...
 }:
 let
-  inherit (builtins) hashString;
+  inherit (builtins) hashString elemAt length toJSON filter;
   inherit (lib.stringsWithDeps) stringAfter;
   inherit (lib.options) mkOption literalExpression;
   inherit (lib.lists) optional;
-  inherit (lib.attrsets) mapAttrs;
+  inherit (lib.attrsets) mapAttrs mapAttrsToList;
   inherit (lib.modules) mkIf;
   inherit (lib.types)
     submodule
@@ -22,10 +22,29 @@
     uniq
     functionTo
     package
+    listOf
     ;
   inherit (fleetLib.strings) decodeRawSecret;
 
   sysConfig = config;
+  secretPartDataType = submodule {
+    options = {
+      raw = mkOption {
+        type = str;
+        internal = true;
+        description = "Encoded & Encrypted secret part data, passed from fleet.nix";
+      };
+    };
+  };
+  secretDataType = submodule {
+    freeformType = lazyAttrsOf secretPartDataType;
+    options = {
+      shared = mkOption {
+        description = "Is this secret owned by this machine, or propagated from shared secrets";
+        default = false;
+      };
+    };
+  };
   secretPartType =
     secretName:
     submodule (
@@ -35,11 +54,6 @@
       in
       {
         options = {
-          raw = mkOption {
-            type = str;
-            internal = true;
-            description = "Encoded & Encrypted secret part data, passed from fleet.nix";
-          };
           hash = mkOption {
             type = str;
             description = "Hash of secret in encoded format";
@@ -50,34 +64,50 @@
           };
           stablePath = mkOption {
             type = str;
-            description = "Path to secret part, incorporating data hash (thus it will be updated on secret change)";
+            description = "Path to secret part, stable path (users are expected to watch for file changes/re-read secret on demand)";
           };
           data = mkOption {
             type = str;
             description = "Secret public data (only available for plaintext)";
           };
         };
-        config = {
-          hash = hashString "sha1" config.raw;
-          data = decodeRawSecret config.raw;
-          path = "/run/secrets/${secretName}/${config.hash}-${partName}";
-          stablePath = "/run/secrets/${secretName}/${partName}";
-        };
+        config =
+          let
+            raw = sysConfig.data.secrets.${secretName}.${partName}.raw;
+          in
+          {
+            hash = hashString "sha1" raw;
+            data = decodeRawSecret raw;
+            path = "/run/secrets/${secretName}/${config.hash}-${partName}";
+            stablePath = "/run/secrets/${secretName}/${partName}";
+          };
       }
     );
   secretType = submodule (
-    { config, ... }:
+    {
+      config,
+      loc,
+      options,
+      ...
+    }:
     let
-      secretName = config._module.args.name;
+      secretName =
+        # Due to config definition for freeformType, we can't just use _module.args due to infinite recursion, instead
+        # extract the secret name the ugly way...
+        let
+          saLoc = options._module.specialArgs.loc;
+          comp = elemAt saLoc;
+        in
+        assert
+          (length saLoc == 2 ||
+          length saLoc == 4 &&
+          comp 0 == "secrets" && comp 2 == "_module" && comp 3 == "specialArgs") ||
+          throw "Unexpected module structure ${toJSON saLoc}";
+        if length saLoc == 2 then "documentation generator stub" else comp 1;
     in
     {
       freeformType = lazyAttrsOf (secretPartType secretName);
       options = {
-        shared = mkOption {
-          description = "Is this secret owned by this machine, or propagated from shared secrets";
-          default = false;
-        };
-
         generator = mkOption {
           type = uniq (nullOr (functionTo package));
           description = "Derivation to evaluate for secret generation";
@@ -104,18 +134,30 @@
           description = "Data that gets embedded into secret part";
           default = null;
         };
+        expectedPrivateParts = mkOption {
+          type = listOf str;
+          default = [ ];
+          description = "List of parts that are expected to be encrypted";
+        };
+        expectedPublicParts = mkOption {
+          type = listOf str;
+          default = [ ];
+          description = "List of parts that are expected to be public";
+        };
       };
+      config = mapAttrs (_: _: { }) (removeAttrs (sysConfig.data.secrets.${secretName} or {}) [ "shared" ]);
     }
   );
-  processPart = part: {
-    inherit (part) raw path stablePath;
+  processPart = secretName: partName: part: {
+    inherit (part) path stablePath;
+    raw = config.data.secrets.${secretName}.${partName}.raw;
   };
   processSecret =
-    secret:
+    secretName: secret:
     {
       inherit (secret) group mode owner;
     }
-    // (mapAttrs (_: processPart) (
+    // (mapAttrs (processPart secretName) (
       removeAttrs secret [
         "shared"
         "generator"
@@ -123,11 +165,14 @@
         "group"
         "owner"
         "expectedGenerationData"
+        "expectedPrivateParts"
+        "expectedPublicParts"
       ]
     ));
+  secretsData = (mapAttrs (processSecret) config.secrets);
   secretsFile = pkgs.writeTextFile {
     name = "secrets.json";
-    text = builtins.toJSON (mapAttrs (_: processSecret) config.secrets);
+    text = toJSON secretsData;
   };
   useSysusers =
     (config.systemd ? sysusers && config.systemd.sysusers.enable)
@@ -135,15 +180,38 @@
 in
 {
   options = {
+    data.secrets = mkOption {
+      type = attrsOf secretDataType;
+      default = { };
+      description = "Host-local secret data";
+    };
     secrets = mkOption {
       type = attrsOf secretType;
       default = { };
       description = "Host-local secrets";
     };
+    system.secretsData = mkOption {
+      type = unspecified;
+      default = {};
+      description = "secrets.json contents";
+    };
   };
   config = {
+    system = {inherit secretsData;};
     environment.systemPackages = [ pkgs.fleet-install-secrets ];
 
+    warnings = filter (v: v!=null) (mapAttrsToList (
+      name: secret:
+      if
+        secret.expectedPrivateParts == [ ]
+        && secret.expectedPublicParts == [ ]
+        && !(config.data.secrets.${name} or { shared = false; }).shared
+      then
+        "Secret ${name} has no expected parts defined, this is deprecated for better visibility"
+      else
+        null
+    ) config.secrets);
+
     systemd.services.fleet-install-secrets = mkIf useSysusers {
       wantedBy = [ "sysinit.target" ];
       after = [ "systemd-sysusers.service" ];
modifiedmodules/secrets-data.nixdiffbeforeafterboth
--- a/modules/secrets-data.nix
+++ b/modules/secrets-data.nix
@@ -151,8 +151,9 @@
           toJSON (config.data.sharedSecrets.${name} or { owners = [ ]; }).owners
         }. Run fleet secrets regenerate to fix";
       }) config.sharedSecrets)
+
       ++ (mapAttrsToList (name: secret: {
-        # TODO: Same aassertion should be in host secrets
+        # TODO: Same assertion should be in host secrets
         assertion =
           (config.data.sharedSecrets.${name} or { generationData = null; }).generationData
           == secret.expectedGenerationData;
@@ -160,6 +161,5 @@
           toJSON (config.data.sharedSecrets.${name} or { generationData = null; }).generationData
         }. Run fleet secrets regenerate to fix";
       }) config.sharedSecrets);
-    sharedSecrets = mapAttrs (_: _: { }) config.data.sharedSecrets;
   };
 }
modifiedmodules/secrets.nixdiffbeforeafterboth
--- a/modules/secrets.nix
+++ b/modules/secrets.nix
@@ -69,6 +69,16 @@
           description = "Contextual metadata embedded within the secret part value";
           default = null;
         };
+        expectedPrivateParts = mkOption {
+          type = listOf str;
+          default = [ ];
+          description = "List of parts that are expected to be encrypted";
+        };
+        expectedPublicParts = mkOption {
+          type = listOf str;
+          default = [ ];
+          description = "List of parts that are expected to be public";
+        };
       };
     };
 in
@@ -81,16 +91,25 @@
     };
   };
   config = {
-    hosts = mapAttrs (_: secretMap: {
-      nixos.secrets = mapAttrs (
-        _: s:
-        removeAttrs s [
-          "createdAt"
-          "expiresAt"
-          "generationData"
-        ]
-      ) secretMap;
-    }) config.data.hostSecrets;
+    hosts = mapAttrs (
+      _: secretMap:
+      let
+        partsOf =
+          s:
+          removeAttrs s [
+            "createdAt"
+            "expiresAt"
+            "generationData"
+          ];
+
+      in
+      {
+        nixos.data.secrets = mapAttrs (_: s: partsOf s) secretMap;
+        # nixos.secrets = mapAttrs (
+        #   _: s: mapAttrs (_: _: {}) (partsOf s)
+        # ) secretMap;
+      }
+    ) config.data.hostSecrets;
     nixpkgs.overlays = [
       (final: prev: {
         mkSecretGenerators =