git.delta.rocks / jrsonnet / refs/commits / 89d35672dcfd

difftreelog

refactor perform build using nix repl

Yaroslav Bolyukin2023-12-24parent: #e85b4da.patch.diff
in: trunk

8 files changed

modifiedcmds/fleet/src/better_nix_eval.rsdiffbeforeafterboth
--- a/cmds/fleet/src/better_nix_eval.rs
+++ b/cmds/fleet/src/better_nix_eval.rs
@@ -1,5 +1,7 @@
+use std::collections::HashMap;
 use std::ffi::{OsStr, OsString};
-use std::fmt::Display;
+use std::fmt::{self, Display};
+use std::path::PathBuf;
 use std::process::Stdio;
 use std::sync::{Arc, OnceLock};
 
@@ -8,7 +10,7 @@
 use itertools::Itertools;
 use r2d2::{Pool, PooledConnection};
 use serde::de::DeserializeOwned;
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
 use tokio::io::AsyncWriteExt;
 use tokio::process::{ChildStderr, ChildStdin, ChildStdout, Command};
 use tokio::select;
@@ -72,14 +74,20 @@
 		// 	s.split('\n').filter(|s| !s.trim().is_empty()).map(|v| v.)
 		// }
 		if !self.collected.is_empty() {
-			bail!("{}", self.collected.iter().map(|v| {
-				if let Some(f) = v.strip_prefix("\u{1b}[31;1merror:\u{1b}[0m ") {
-					let v = unindent::unindent(f.trim_start());
-					v.trim().to_owned()
-				} else {
-					v.to_owned()
-				}
-			}).join("\n"));
+			bail!(
+				"{}",
+				self.collected
+					.iter()
+					.map(|v| {
+						if let Some(f) = v.strip_prefix("\u{1b}[31;1merror:\u{1b}[0m ") {
+							let v = unindent::unindent(f.trim_start());
+							v.trim().to_owned()
+						} else {
+							v.to_owned()
+						}
+					})
+					.join("\n")
+			);
 		}
 		Ok(())
 	}
@@ -150,6 +158,13 @@
 	}
 }
 
+struct WarnHandler;
+impl Handler for WarnHandler {
+	fn handle_line(&mut self, e: &str) {
+		warn!(target: "nix", "{e}")
+	}
+}
+
 impl NixSessionInner {
 	async fn new(flake: &OsStr, extra_args: impl IntoIterator<Item = &OsStr>) -> Result<Self> {
 		let mut cmd = Command::new("nix");
@@ -174,12 +189,13 @@
 		stdin.flush().await?;
 		let nix_handler = NixHandler::default();
 		let mut full_delimiter = None;
+		let mut errors = vec![];
 		while let Some(line) = out.next().await {
 			let line = match line {
 				OutputLine::Out(o) => o,
 				OutputLine::Err(_e) => {
 					// Handle startup errors, but skip repl hello?
-					//nix_handler.handle_line(&e);
+					errors.push(_e);
 					continue;
 				}
 			};
@@ -190,6 +206,9 @@
 			}
 		}
 		let Some(full_delimiter) = full_delimiter else {
+			for e in errors {
+				error!("{e}");
+			}
 			bail!("failed to discover delimiter");
 		};
 		let mut res = Self {
@@ -342,21 +361,93 @@
 #[derive(Clone)]
 pub struct NixSession(Arc<tokio::sync::Mutex<PooledConnection<NixSessionPoolInner>>>);
 
+#[macro_export]
+macro_rules! nix_path {
+	(@o($o:ident) $var:ident $($tt:tt)*) => {{
+		$o.push(Index::var(stringify!($var)));
+		nix_path!(@o($o) $($tt)*);
+	}};
+	(@o($o:ident) . $var:ident $($tt:tt)*) => {{
+		$o.push(Index::attr(stringify!($var)));
+		nix_path!(@o($o) $($tt)*);
+	}};
+	(@o($o:ident) . $var:literal $($tt:tt)*) => {{
+		$o.push(Index::attr($var));
+		nix_path!(@o($o) $($tt)*);
+	}};
+	(@o($o:ident) . { $var:expr } $($tt:tt)*) => {{
+		$o.push(Index::attr($var));
+		nix_path!(@o($o) $($tt)*);
+	}};
+	(@o($o:ident) [ $var:literal ] $($tt:tt)*) => {{
+		$o.push(Index::idx($var));
+		nix_path!(@o($o) $($tt)*);
+	}};
+	(@o($o:ident) ($e:expr) $($tt:tt)*) => {
+		$o.push(Index::apply($e));
+		nix_path!(@o($o) $($tt)*);
+	};
+	(@o($o:ident)) => {};
+	($($tt:tt)+) => {{
+		use $crate::{nix_path, better_nix_eval::Index};
+		let mut out = vec![];
+		nix_path!(@o(out) $($tt)*);
+		out
+	}}
+}
+
 #[derive(Clone)]
-enum Index {
+pub enum Index {
+	Var(String),
 	String(String),
-	// Idx(u32),
+	Apply(String),
+	Idx(u32),
 }
+impl Index {
+	pub fn var(v: impl AsRef<str>) -> Self {
+		let v = v.as_ref();
+		assert!(
+			!(v.contains('.') | v.contains(' ')),
+			"bad variable name: {v}"
+		);
+		Self::Var(v.to_owned())
+	}
+	pub fn attr(v: impl AsRef<str>) -> Self {
+		Self::String(v.as_ref().to_owned())
+	}
+	pub fn idx(v: u32) -> Self {
+		Self::Idx(v)
+	}
+	pub fn apply(v: impl Serialize) -> Self {
+		let serialized = nixlike::serialize(v).expect("invalid value for apply");
+		Self::Apply(serialized)
+	}
+}
 impl Display for Index {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		match self {
+			Index::Var(v) => {
+				write!(f, "{v}")
+			}
 			Index::String(k) => {
 				let v = nixlike::format_identifier(k.as_str());
 				write!(f, ".{v}")
 			}
+			Index::Apply(o) => {
+				let v = nixlike::serialize(o).map_err(|_| fmt::Error)?;
+				write!(f, "<apply>({v})")
+			}
+			Index::Idx(i) => {
+				write!(f, "[{i}]")
+			}
 		}
 	}
 }
+impl fmt::Debug for Index {
+	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+		write!(f, "{self}")
+	}
+}
 struct PathDisplay<'i>(&'i [Index]);
 impl Display for PathDisplay<'_> {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -381,43 +472,49 @@
 		}
 	}
 	pub async fn field(session: NixSession, field: &str) -> Result<Self> {
-		Self::root(session).get_field_deep([field]).await
+		Self::root(session)
+			.select([Index::var(field)])
+			.await
 	}
 	pub async fn get_json_deep<'a, V: DeserializeOwned>(
 		&self,
-		name: impl IntoIterator<Item = &'a str>,
+		name: impl IntoIterator<Item = Index>,
 	) -> Result<V> {
-		let field = self.get_field_deep(name).await?;
+		let field = self.select(name).await?;
 		field.as_json().await
 	}
-	pub async fn get_field(&self, name: &str) -> Result<Self> {
-		self.get_field_deep([name]).await
-	}
-	pub async fn get_field_deep<'a>(
-		&self,
-		name: impl IntoIterator<Item = &'a str>,
-	) -> Result<Self> {
-		let mut iter = name.into_iter();
+	pub async fn select<'a>(&self, name: impl IntoIterator<Item = Index>) -> Result<Self> {
+		let mut name = name.into_iter();
 
 		let mut full_path = self.full_path.clone();
 		let mut query = if let Some(id) = self.value {
 			format!("sess_field_{id}")
 		} else {
-			let first = iter.next().expect("name not empty");
-			ensure!(
-				!(first.contains('.') | first.contains(' ')),
-				"bad name for root query: {first}"
-			);
-			full_path.push(Index::String(first.to_string()));
-			first.to_string()
+			let first = name.next();
+			if let Some(Index::Var(i)) = first {
+				full_path.push(Index::Var(i.clone()));
+				i.clone()
+			} else {
+				panic!("first path item should be variable, got {first:?}")
+			}
 		};
-		for v in iter {
-			full_path.push(Index::String(v.to_string()));
-			// Escape
-			let escaped = nixlike::serialize(v)?;
-			let escaped = escaped.trim();
-			query.push('.');
-			query.push_str(escaped);
+		for v in name {
+			full_path.push(v.clone());
+			match v {
+				Index::Var(_) => panic!("var item may only be first"),
+				Index::String(s) => {
+					let escaped = nixlike::serialize(s)?;
+					query.push('.');
+					query.push_str(escaped.trim());
+				}
+				Index::Apply(a) => {
+					query.push(' ');
+					query.push_str(&a);
+				}
+				Index::Idx(idx) => {
+					query = format!("builtins.elemAt ({query}) {idx}");
+				}
+			}
 		}
 
 		let vid = self
@@ -454,6 +551,28 @@
 			.await
 			.with_context(|| format!("full path: {}", PathDisplay(&self.full_path)))
 	}
+	pub async fn build(&self) -> Result<HashMap<String, PathBuf>> {
+		let id = self.value.expect("can't use build on not-value");
+		let vid = self
+			.session
+			.0
+			.lock()
+			.await
+			.execute_expression_raw(&format!(":b sess_field_{id}"), &mut NixHandler::default())
+			.await?;
+		ensure!(!vid.is_empty(), "build failed");
+		let Some(vid) = vid.strip_prefix("This derivation produced the following outputs:\n")
+		else {
+			panic!("unexpected build output: {vid:?}");
+		};
+		let outputs = vid
+			.split('\n')
+			.filter(|v| !v.is_empty())
+			.map(|v| v.split_once(" -> ").expect("unexpected build output"))
+			.map(|(a, b)| (a.trim_start().to_owned(), PathBuf::from(b)))
+			.collect();
+		Ok(outputs)
+	}
 }
 impl Drop for Field {
 	fn drop(&mut self) {
modifiedcmds/fleet/src/cmds/build_systems.rsdiffbeforeafterboth
--- a/cmds/fleet/src/cmds/build_systems.rs
+++ b/cmds/fleet/src/cmds/build_systems.rs
@@ -1,8 +1,10 @@
+use std::os::unix::fs::symlink;
 use std::path::PathBuf;
 use std::{env::current_dir, time::Duration};
 
 use crate::command::MyCommand;
 use crate::host::Config;
+use crate::nix_path;
 use anyhow::{anyhow, Result};
 use clap::Parser;
 use itertools::Itertools;
@@ -11,15 +13,9 @@
 
 #[derive(Parser, Clone)]
 pub struct BuildSystems {
-	/// Do not continue on error
-	#[clap(long)]
-	fail_fast: bool,
 	/// Disable automatic rollback
 	#[clap(long)]
 	disable_rollback: bool,
-	/// Run builds as sudo
-	#[clap(long)]
-	privileged_build: bool,
 	#[clap(subcommand)]
 	subcommand: Subcommand,
 }
@@ -294,34 +290,11 @@
 	async fn build_task(self, config: Config, host: String) -> Result<()> {
 		info!("building");
 		let action = Action::from(self.subcommand.clone());
-		let built = {
-			let dir = tempfile::tempdir()?;
-			dir.path().to_owned()
-		};
-
-		let mut nix_build = MyCommand::new("nix");
-		nix_build
-			.args([
-				"build",
-				"--impure",
-				"--json",
-				// "--show-trace",
-				"--no-link",
-			])
-			.comparg("--out-link", &built)
-			.arg(
-				config.configuration_attr_name(&format!(
-					"buildSystems.{}.{host}",
-					action.build_attr()
-				)),
-			)
-			.args(&config.nix_args);
-
-		if self.privileged_build {
-			nix_build = nix_build.sudo();
-		}
-
-		nix_build.run_nix().await.map_err(|e| {
+		let drv = config
+			.fleet_field
+			.select(nix_path!(.buildSystems.{action.build_attr()}.{&host}))
+			.await?;
+		let outputs = drv.build().await.map_err(|e| {
 			if action.build_attr() == "sdImage" {
 				info!("sd-image build failed");
 				info!("Make sure you have imported modulesPath/installer/sd-card/sd-image-<arch>[-installer].nix (For installer, you may want to check config)");
@@ -329,7 +302,9 @@
 			}
 			e
 		})?;
-		let built = std::fs::canonicalize(built)?;
+		let out_output = outputs
+			.get("out")
+			.ok_or_else(|| anyhow!("system build should produce \"out\" output"))?;
 
 		match action {
 			Action::Upload { action } => {
@@ -342,7 +317,7 @@
 							.arg("sign")
 							.comparg("--key-file", "/etc/nix/private-key")
 							.arg("-r")
-							.arg(&built);
+							.arg(out_output);
 						if let Err(e) = sign.sudo().run_nix().await {
 							warn!("Failed to sign store paths: {e}");
 						};
@@ -353,7 +328,7 @@
 						nix.arg("copy")
 							.arg("--substitute-on-destination")
 							.comparg("--to", format!("ssh-ng://{host}"))
-							.arg(&built);
+							.arg(out_output);
 						match nix.run_nix().await {
 							Ok(()) => break,
 							Err(e) if tries < 3 => {
@@ -366,53 +341,22 @@
 					}
 				}
 				if let Some(action) = action {
-					execute_upload(&self, &config, action, &host, built).await?
+					execute_upload(&self, &config, action, &host, out_output.clone()).await?
 				}
 			}
 			Action::Package(PackageAction::SdImage) => {
 				let mut out = current_dir()?;
 				out.push(format!("sd-image-{}", host));
 
-				info!("building sd image to {:?}", out);
-				let mut nix_build = MyCommand::new("nix");
-				nix_build
-					.args(["build", "--impure", "--no-link"])
-					.comparg("--out-link", &out)
-					.arg(config.configuration_attr_name(&format!("buildSystems.sdImage.{}", host,)))
-					.args(&config.nix_args);
-				if !self.fail_fast {
-					nix_build.arg("--keep-going");
-				}
-				if self.privileged_build {
-					nix_build = nix_build.sudo();
-				}
-
-				nix_build.run_nix().await?;
+				info!("linking sd image to {:?}", out);
+				symlink(out_output, out)?;
 			}
 			Action::Package(PackageAction::InstallationCd) => {
 				let mut out = current_dir()?;
 				out.push(format!("installation-cd-{}", host));
 
-				info!("building sd image to {:?}", out);
-				let mut nix_build = MyCommand::new("nix");
-				nix_build
-					.args(["build", "--impure", "--no-link"])
-					.comparg("--out-link", &out)
-					.arg(
-						config.configuration_attr_name(&format!(
-							"buildSystems.installationCd.{}",
-							host,
-						)),
-					)
-					.args(&config.nix_args);
-				if !self.fail_fast {
-					nix_build.arg("--keep-going");
-				}
-				if self.privileged_build {
-					nix_build = nix_build.sudo();
-				}
-
-				nix_build.run_nix().await?;
+				info!("linking iso image to {:?}", out);
+				symlink(out_output, out)?;
 			}
 		};
 		Ok(())
modifiedcmds/fleet/src/cmds/info.rsdiffbeforeafterboth
--- a/cmds/fleet/src/cmds/info.rs
+++ b/cmds/fleet/src/cmds/info.rs
@@ -1,6 +1,7 @@
 use std::collections::BTreeSet;
 
 use crate::host::Config;
+use crate::nix_path;
 use anyhow::{ensure, Result};
 use clap::Parser;
 
@@ -38,7 +39,7 @@
 					if !tagged.is_empty() {
 						let tags: Vec<String> = config
 							.fleet_field
-							.get_field_deep(["configuredSystems", &host.name, "config", "tags"])
+							.select(nix_path!(.configuredSystems.{&host.name}.config.tags))
 							.await?
 							.as_json()
 							.await?;
@@ -64,7 +65,7 @@
 				let host = config.system_config(&host).await?;
 				if external {
 					out.extend(
-						host.get_field_deep(["network", "externalIps"])
+						host.select(nix_path!(.network.externalIps))
 							.await?
 							.as_json::<Vec<String>>()
 							.await?,
@@ -72,7 +73,7 @@
 				}
 				if internal {
 					out.extend(
-						host.get_field_deep(["network", "internalIps"])
+						host.select(nix_path!(.network.internalIps))
 							.await?
 							.as_json::<Vec<String>>()
 							.await?,
modifiedcmds/fleet/src/cmds/secrets/mod.rsdiffbeforeafterboth
before · cmds/fleet/src/cmds/secrets/mod.rs
1use crate::{2	fleetdata::{FleetSecret, FleetSharedSecret},3	host::Config,4};5use anyhow::{bail, ensure, Context, Result};6use chrono::Utc;7use clap::Parser;8use futures::{StreamExt, TryStreamExt};9use owo_colors::OwoColorize;10use std::{11	collections::HashSet,12	io::{self, Cursor, Read},13	path::PathBuf,14};15use tabled::{Table, Tabled};16use tokio::fs::read_to_string;17use tracing::{error, info, info_span, warn};1819#[derive(Parser)]20pub enum Secrets {21	/// Force load keys for all defined hosts22	ForceKeys,23	/// Add secret, data should be provided in stdin24	AddShared {25		/// Secret name26		name: String,27		/// Secret owners28		machines: Vec<String>,29		/// Override secret if already present30		#[clap(long)]31		force: bool,32		#[clap(long)]33		public: Option<String>,34		#[clap(long)]35		public_file: Option<PathBuf>,3637		/// Secret with this name already exists, override its value while keeping the same owners.38		#[clap(long)]39		readd: bool,40	},41	/// Add secret, data should be provided in stdin42	Add {43		/// Secret name44		name: String,45		/// Secret owners46		machine: String,47		/// Override secret if already present48		#[clap(long)]49		force: bool,50		#[clap(long)]51		public: Option<String>,52		#[clap(long)]53		public_file: Option<PathBuf>,54	},55	/// Read secret from remote host, requires sudo on said host56	Read {57		name: String,58		machine: String,59		#[clap(long)]60		plaintext: bool,61	},62	UpdateShared {63		name: String,6465		#[clap(long)]66		machines: Option<Vec<String>>,6768		#[clap(long)]69		add_machines: Vec<String>,70		#[clap(long)]71		remove_machines: Vec<String>,7273		/// Which host should we use to decrypt74		#[clap(long)]75		prefer_identities: Vec<String>,76	},77	Regenerate {78		/// Which host should we use to decrypt, in case if reencryption is required, without79		/// regeneration80		#[clap(long)]81		prefer_identities: Vec<String>,82	},83	List {},84}8586impl Secrets {87	pub async fn run(self, config: &Config) -> Result<()> {88		match self {89			Secrets::ForceKeys => {90				for host in config.list_hosts().await? {91					if config.should_skip(&host.name) {92						continue;93					}94					config.key(&host.name).await?;95				}96			}97			Secrets::AddShared {98				mut machines,99				name,100				force,101				public,102				public_file,103				readd,104			} => {105				let exists = config.has_shared(&name);106				if exists && !force && !readd {107					bail!("secret already defined");108				}109				if readd {110					// Fixme: use clap to limit this usage111					ensure!(!force, "--force and --readd are not compatible");112					ensure!(exists, "secret doesn't exists");113					ensure!(114						machines.is_empty(),115						"you can't use machines argument for --readd"116					);117					let shared = config.shared_secret(&name)?;118					machines = shared.owners;119				}120121				let recipients = futures::stream::iter(machines.iter())122					.then(|m| config.recipient(m))123					.try_collect::<Vec<_>>()124					.await?;125126				let secret = {127					let mut input = vec![];128					io::stdin().read_to_end(&mut input)?;129130					if input.is_empty() {131						input132					} else {133						let mut encrypted = vec![];134						let recipients = recipients135							.iter()136							.cloned()137							.map(|r| Box::new(r) as Box<dyn age::Recipient + Send>)138							.collect();139						let mut encryptor = age::Encryptor::with_recipients(recipients)140							.expect("recipients provided")141							.wrap_output(&mut encrypted)?;142						io::copy(&mut Cursor::new(input), &mut encryptor)?;143						encryptor.finish()?;144						encrypted145					}146				};147				config.replace_shared(148					name,149					FleetSharedSecret {150						owners: machines,151						secret: FleetSecret {152							created_at: Utc::now(),153							expires_at: None,154							secret,155							public: match (public, public_file) {156								(Some(v), None) => Some(v),157								(None, Some(v)) => Some(read_to_string(v).await?),158								(Some(_), Some(_)) => {159									bail!("only public or public_file should be set")160								}161								(None, None) => None,162							},163						},164					},165				);166			}167			Secrets::Add {168				machine,169				name,170				force,171				public,172				public_file,173			} => {174				let recipient = config.recipient(&machine).await?;175176				let secret = {177					let mut input = vec![];178					io::stdin().read_to_end(&mut input)?;179					if input.is_empty() {180						bail!("no data provided")181					}182183					let mut encrypted = vec![];184					let recipient = Box::new(recipient) as Box<dyn age::Recipient + Send>;185					let mut encryptor = age::Encryptor::with_recipients(vec![recipient])186						.expect("recipients provided")187						.wrap_output(&mut encrypted)?;188					io::copy(&mut Cursor::new(input), &mut encryptor)?;189					encryptor.finish()?;190					encrypted191				};192193				if config.has_secret(&machine, &name) && !force {194					bail!("secret already defined");195				}196				config.insert_secret(197					&machine,198					name,199					FleetSecret {200						created_at: Utc::now(),201						expires_at: None,202						secret,203						public: match (public, public_file) {204							(Some(v), None) => Some(v),205							(None, Some(v)) => Some(std::fs::read_to_string(v)?),206							(Some(_), Some(_)) => bail!("only public or public_file should be set"),207							(None, None) => None,208						},209					},210				);211			}212			// TODO: Instead of using sudo, decode secret on remote machine213			#[allow(clippy::await_holding_refcell_ref)]214			Secrets::Read {215				name,216				machine,217				plaintext,218			} => {219				let secret = config.host_secret(&machine, &name)?;220				if secret.secret.is_empty() {221					bail!("no secret {name}");222				}223				let data = config.decrypt_on_host(&machine, secret.secret).await?;224				if plaintext {225					let s = String::from_utf8(data).context("output is not utf8")?;226					print!("{s}");227				} else {228					println!("{}", z85::encode(&data));229				}230			}231			Secrets::UpdateShared {232				name,233				machines,234				mut add_machines,235				mut remove_machines,236				prefer_identities,237			} => {238				if machines.is_none() && add_machines.is_empty() && remove_machines.is_empty() {239					bail!("no operation");240				}241242				let mut secret = config.shared_secret(&name)?;243				if secret.secret.secret.is_empty() {244					bail!("no secret");245				}246247				let initial_machines = secret.owners.clone();248				let mut target_machines = secret.owners.clone();249				info!("Currently encrypted for {initial_machines:?}");250251				// ensure!(machines.is_some() || !add_machines.is_empty() || )252				if let Some(machines) = machines {253					ensure!(254						add_machines.is_empty() && remove_machines.is_empty(),255						"can't combine --machines and --add-machines/--remove-machines"256					);257					let target = initial_machines.iter().collect::<HashSet<_>>();258					let source = machines.iter().collect::<HashSet<_>>();259					for removed in target.difference(&source) {260						remove_machines.push((*removed).clone());261					}262					for added in source.difference(&target) {263						add_machines.push((*added).clone());264					}265				}266267				for machine in &remove_machines {268					let mut removed = false;269					while let Some(pos) = target_machines.iter().position(|m| m == machine) {270						target_machines.swap_remove(pos);271						removed = true;272					}273					if !removed {274						warn!("secret is not enabled for {machine}");275					}276				}277				for machine in &add_machines {278					if target_machines.iter().any(|m| m == machine) {279						warn!("secret is already added to {machine}");280					} else {281						target_machines.push(machine.to_owned());282					}283				}284				if !remove_machines.is_empty() {285					warn!("secret will not be regenerated for removed machines, and until host rebuild, they will still possess the ability to decode secret");286				}287288				if target_machines.is_empty() {289					info!("no machines left for secret, removing it");290					config.remove_shared(&name);291					return Ok(());292				}293294				if target_machines == initial_machines {295					warn!("secret owners are already correct");296					return Ok(());297				}298299				let identity_holder = if !prefer_identities.is_empty() {300					prefer_identities301						.iter()302						.find(|i| initial_machines.iter().any(|s| s == *i))303				} else {304					secret.owners.first()305				};306				let Some(identity_holder) = identity_holder else {307					bail!("no available holder found");308				};309				let target_recipients = futures::stream::iter(&target_machines)310					.then(|m| async { config.key(m).await })311					.collect::<Vec<_>>()312					.await;313				let target_recipients =314					target_recipients.into_iter().collect::<Result<Vec<_>>>()?;315316				let encrypted = config317					.reencrypt_on_host(identity_holder, secret.secret.secret, target_recipients)318					.await?;319320				secret.owners = target_machines;321				secret.secret.secret = encrypted;322				config.replace_shared(name, secret);323			}324			Secrets::Regenerate { prefer_identities } => {325				{326					let expected_shared_set = config327						.list_configured_shared()328						.await?329						.into_iter()330						.collect::<HashSet<_>>();331					let shared_set = config.list_shared().into_iter().collect::<HashSet<_>>();332					for removed in expected_shared_set.difference(&shared_set) {333						error!("secret needs to be generated: {removed}")334					}335				}336				let mut to_remove = Vec::new();337				for name in &config.list_shared() {338					info!("updating secret: {name}");339					let mut data = config.shared_secret(name)?;340					let expected_owners: Vec<String> = config341						.config_field342						.get_json_deep(["sharedSecrets", name, "expectedOwners"])343						.await?;344					if expected_owners.is_empty() {345						warn!("secret was removed from fleet config: {name}, removing from data");346						to_remove.push(name.to_string());347						continue;348					}349					let set = data.owners.iter().collect::<HashSet<_>>();350					let expected_set = expected_owners.iter().collect::<HashSet<_>>();351					let should_remove = set.difference(&expected_set).next().is_some();352					if set != expected_set {353						let owner_dependent: bool = config354							.config_field355							.get_json_deep(["sharedSecrets", name, "ownerDependent"])356							.await?;357						if !owner_dependent {358							warn!("reencrypting secret '{name}' for new owner set");359							// TODO: force regeneration360							if should_remove {361								warn!("secret will not be regenerated for removed machines, and until host rebuild, they will still possess the ability to decode secret");362							}363364							let identity_holder = if !prefer_identities.is_empty() {365								prefer_identities366									.iter()367									.find(|i| data.owners.iter().any(|s| s == *i))368							} else {369								data.owners.first()370							};371							let Some(identity_holder) = identity_holder else {372								bail!("no available holder found");373							};374375							let target_recipients = futures::stream::iter(&expected_owners)376								.then(|m| async { config.key(m).await })377								.collect::<Vec<_>>()378								.await;379							let target_recipients =380								target_recipients.into_iter().collect::<Result<Vec<_>>>()?;381382							let encrypted = config383								.reencrypt_on_host(384									identity_holder,385									data.secret.secret,386									target_recipients,387								)388								.await?;389390							data.secret.secret = encrypted;391							data.owners = expected_owners;392							config.replace_shared(name.to_owned(), data);393						} else {394							error!("secret '{name}' should be regenerated manually");395						}396					} else {397						info!("secret data is ok")398					}399				}400				for k in to_remove {401					config.remove_shared(&k);402				}403			}404			Secrets::List {} => {405				let _span = info_span!("loading secrets").entered();406				let configured = config.list_configured_shared().await?;407				#[derive(Tabled)]408				struct SecretDisplay {409					#[tabled(rename = "Name")]410					name: String,411					#[tabled(rename = "Owners")]412					owners: String,413				}414				let mut table = vec![];415				for name in configured.iter().cloned() {416					let config = config.clone();417					let expected_owners = config.shared_secret_expected_owners(&name).await?;418					let data = config.shared_secret(&name)?;419					let owners = data420						.owners421						.iter()422						.map(|o| {423							if expected_owners.contains(o) {424								o.green().to_string()425							} else {426								o.red().to_string()427							}428						})429						.collect::<Vec<_>>();430					table.push(SecretDisplay {431						owners: owners.join(", "),432						name,433					})434				}435				info!("loaded\n{}", Table::new(table).to_string())436			}437		}438		Ok(())439	}440}
after · cmds/fleet/src/cmds/secrets/mod.rs
1use crate::{2	fleetdata::{FleetSecret, FleetSharedSecret},3	host::Config, nix_path,4};5use anyhow::{bail, ensure, Context, Result};6use chrono::Utc;7use clap::Parser;8use futures::{StreamExt, TryStreamExt};9use owo_colors::OwoColorize;10use std::{11	collections::HashSet,12	io::{self, Cursor, Read},13	path::PathBuf,14};15use tabled::{Table, Tabled};16use tokio::fs::read_to_string;17use tracing::{error, info, info_span, warn};1819#[derive(Parser)]20pub enum Secrets {21	/// Force load keys for all defined hosts22	ForceKeys,23	/// Add secret, data should be provided in stdin24	AddShared {25		/// Secret name26		name: String,27		/// Secret owners28		machines: Vec<String>,29		/// Override secret if already present30		#[clap(long)]31		force: bool,32		#[clap(long)]33		public: Option<String>,34		#[clap(long)]35		public_file: Option<PathBuf>,3637		/// Secret with this name already exists, override its value while keeping the same owners.38		#[clap(long)]39		readd: bool,40	},41	/// Add secret, data should be provided in stdin42	Add {43		/// Secret name44		name: String,45		/// Secret owners46		machine: String,47		/// Override secret if already present48		#[clap(long)]49		force: bool,50		#[clap(long)]51		public: Option<String>,52		#[clap(long)]53		public_file: Option<PathBuf>,54	},55	/// Read secret from remote host, requires sudo on said host56	Read {57		name: String,58		machine: String,59		#[clap(long)]60		plaintext: bool,61	},62	UpdateShared {63		name: String,6465		#[clap(long)]66		machines: Option<Vec<String>>,6768		#[clap(long)]69		add_machines: Vec<String>,70		#[clap(long)]71		remove_machines: Vec<String>,7273		/// Which host should we use to decrypt74		#[clap(long)]75		prefer_identities: Vec<String>,76	},77	Regenerate {78		/// Which host should we use to decrypt, in case if reencryption is required, without79		/// regeneration80		#[clap(long)]81		prefer_identities: Vec<String>,82	},83	List {},84}8586impl Secrets {87	pub async fn run(self, config: &Config) -> Result<()> {88		match self {89			Secrets::ForceKeys => {90				for host in config.list_hosts().await? {91					if config.should_skip(&host.name) {92						continue;93					}94					config.key(&host.name).await?;95				}96			}97			Secrets::AddShared {98				mut machines,99				name,100				force,101				public,102				public_file,103				readd,104			} => {105				let exists = config.has_shared(&name);106				if exists && !force && !readd {107					bail!("secret already defined");108				}109				if readd {110					// Fixme: use clap to limit this usage111					ensure!(!force, "--force and --readd are not compatible");112					ensure!(exists, "secret doesn't exists");113					ensure!(114						machines.is_empty(),115						"you can't use machines argument for --readd"116					);117					let shared = config.shared_secret(&name)?;118					machines = shared.owners;119				}120121				let recipients = futures::stream::iter(machines.iter())122					.then(|m| config.recipient(m))123					.try_collect::<Vec<_>>()124					.await?;125126				let secret = {127					let mut input = vec![];128					io::stdin().read_to_end(&mut input)?;129130					if input.is_empty() {131						input132					} else {133						let mut encrypted = vec![];134						let recipients = recipients135							.iter()136							.cloned()137							.map(|r| Box::new(r) as Box<dyn age::Recipient + Send>)138							.collect();139						let mut encryptor = age::Encryptor::with_recipients(recipients)140							.expect("recipients provided")141							.wrap_output(&mut encrypted)?;142						io::copy(&mut Cursor::new(input), &mut encryptor)?;143						encryptor.finish()?;144						encrypted145					}146				};147				config.replace_shared(148					name,149					FleetSharedSecret {150						owners: machines,151						secret: FleetSecret {152							created_at: Utc::now(),153							expires_at: None,154							secret,155							public: match (public, public_file) {156								(Some(v), None) => Some(v),157								(None, Some(v)) => Some(read_to_string(v).await?),158								(Some(_), Some(_)) => {159									bail!("only public or public_file should be set")160								}161								(None, None) => None,162							},163						},164					},165				);166			}167			Secrets::Add {168				machine,169				name,170				force,171				public,172				public_file,173			} => {174				let recipient = config.recipient(&machine).await?;175176				let secret = {177					let mut input = vec![];178					io::stdin().read_to_end(&mut input)?;179					if input.is_empty() {180						bail!("no data provided")181					}182183					let mut encrypted = vec![];184					let recipient = Box::new(recipient) as Box<dyn age::Recipient + Send>;185					let mut encryptor = age::Encryptor::with_recipients(vec![recipient])186						.expect("recipients provided")187						.wrap_output(&mut encrypted)?;188					io::copy(&mut Cursor::new(input), &mut encryptor)?;189					encryptor.finish()?;190					encrypted191				};192193				if config.has_secret(&machine, &name) && !force {194					bail!("secret already defined");195				}196				config.insert_secret(197					&machine,198					name,199					FleetSecret {200						created_at: Utc::now(),201						expires_at: None,202						secret,203						public: match (public, public_file) {204							(Some(v), None) => Some(v),205							(None, Some(v)) => Some(std::fs::read_to_string(v)?),206							(Some(_), Some(_)) => bail!("only public or public_file should be set"),207							(None, None) => None,208						},209					},210				);211			}212			// TODO: Instead of using sudo, decode secret on remote machine213			#[allow(clippy::await_holding_refcell_ref)]214			Secrets::Read {215				name,216				machine,217				plaintext,218			} => {219				let secret = config.host_secret(&machine, &name)?;220				if secret.secret.is_empty() {221					bail!("no secret {name}");222				}223				let data = config.decrypt_on_host(&machine, secret.secret).await?;224				if plaintext {225					let s = String::from_utf8(data).context("output is not utf8")?;226					print!("{s}");227				} else {228					println!("{}", z85::encode(&data));229				}230			}231			Secrets::UpdateShared {232				name,233				machines,234				mut add_machines,235				mut remove_machines,236				prefer_identities,237			} => {238				if machines.is_none() && add_machines.is_empty() && remove_machines.is_empty() {239					bail!("no operation");240				}241242				let mut secret = config.shared_secret(&name)?;243				if secret.secret.secret.is_empty() {244					bail!("no secret");245				}246247				let initial_machines = secret.owners.clone();248				let mut target_machines = secret.owners.clone();249				info!("Currently encrypted for {initial_machines:?}");250251				// ensure!(machines.is_some() || !add_machines.is_empty() || )252				if let Some(machines) = machines {253					ensure!(254						add_machines.is_empty() && remove_machines.is_empty(),255						"can't combine --machines and --add-machines/--remove-machines"256					);257					let target = initial_machines.iter().collect::<HashSet<_>>();258					let source = machines.iter().collect::<HashSet<_>>();259					for removed in target.difference(&source) {260						remove_machines.push((*removed).clone());261					}262					for added in source.difference(&target) {263						add_machines.push((*added).clone());264					}265				}266267				for machine in &remove_machines {268					let mut removed = false;269					while let Some(pos) = target_machines.iter().position(|m| m == machine) {270						target_machines.swap_remove(pos);271						removed = true;272					}273					if !removed {274						warn!("secret is not enabled for {machine}");275					}276				}277				for machine in &add_machines {278					if target_machines.iter().any(|m| m == machine) {279						warn!("secret is already added to {machine}");280					} else {281						target_machines.push(machine.to_owned());282					}283				}284				if !remove_machines.is_empty() {285					warn!("secret will not be regenerated for removed machines, and until host rebuild, they will still possess the ability to decode secret");286				}287288				if target_machines.is_empty() {289					info!("no machines left for secret, removing it");290					config.remove_shared(&name);291					return Ok(());292				}293294				if target_machines == initial_machines {295					warn!("secret owners are already correct");296					return Ok(());297				}298299				let identity_holder = if !prefer_identities.is_empty() {300					prefer_identities301						.iter()302						.find(|i| initial_machines.iter().any(|s| s == *i))303				} else {304					secret.owners.first()305				};306				let Some(identity_holder) = identity_holder else {307					bail!("no available holder found");308				};309				let target_recipients = futures::stream::iter(&target_machines)310					.then(|m| async { config.key(m).await })311					.collect::<Vec<_>>()312					.await;313				let target_recipients =314					target_recipients.into_iter().collect::<Result<Vec<_>>>()?;315316				let encrypted = config317					.reencrypt_on_host(identity_holder, secret.secret.secret, target_recipients)318					.await?;319320				secret.owners = target_machines;321				secret.secret.secret = encrypted;322				config.replace_shared(name, secret);323			}324			Secrets::Regenerate { prefer_identities } => {325				{326					let expected_shared_set = config327						.list_configured_shared()328						.await?329						.into_iter()330						.collect::<HashSet<_>>();331					let shared_set = config.list_shared().into_iter().collect::<HashSet<_>>();332					for removed in expected_shared_set.difference(&shared_set) {333						error!("secret needs to be generated: {removed}")334					}335				}336				let mut to_remove = Vec::new();337				for name in &config.list_shared() {338					info!("updating secret: {name}");339					let mut data = config.shared_secret(name)?;340					let expected_owners: Vec<String> = config341						.config_field342						.get_json_deep(nix_path!(sharedSecrets.{name}.expectedOwners))343						.await?;344					if expected_owners.is_empty() {345						warn!("secret was removed from fleet config: {name}, removing from data");346						to_remove.push(name.to_string());347						continue;348					}349					let set = data.owners.iter().collect::<HashSet<_>>();350					let expected_set = expected_owners.iter().collect::<HashSet<_>>();351					let should_remove = set.difference(&expected_set).next().is_some();352					if set != expected_set {353						let owner_dependent: bool = config354							.config_field355							.get_json_deep(nix_path!(.sharedSecrets.{name}.ownerDependent))356							.await?;357						if !owner_dependent {358							warn!("reencrypting secret '{name}' for new owner set");359							// TODO: force regeneration360							if should_remove {361								warn!("secret will not be regenerated for removed machines, and until host rebuild, they will still possess the ability to decode secret");362							}363364							let identity_holder = if !prefer_identities.is_empty() {365								prefer_identities366									.iter()367									.find(|i| data.owners.iter().any(|s| s == *i))368							} else {369								data.owners.first()370							};371							let Some(identity_holder) = identity_holder else {372								bail!("no available holder found");373							};374375							let target_recipients = futures::stream::iter(&expected_owners)376								.then(|m| async { config.key(m).await })377								.collect::<Vec<_>>()378								.await;379							let target_recipients =380								target_recipients.into_iter().collect::<Result<Vec<_>>>()?;381382							let encrypted = config383								.reencrypt_on_host(384									identity_holder,385									data.secret.secret,386									target_recipients,387								)388								.await?;389390							data.secret.secret = encrypted;391							data.owners = expected_owners;392							config.replace_shared(name.to_owned(), data);393						} else {394							error!("secret '{name}' should be regenerated manually");395						}396					} else {397						info!("secret data is ok")398					}399				}400				for k in to_remove {401					config.remove_shared(&k);402				}403			}404			Secrets::List {} => {405				let _span = info_span!("loading secrets").entered();406				let configured = config.list_configured_shared().await?;407				#[derive(Tabled)]408				struct SecretDisplay {409					#[tabled(rename = "Name")]410					name: String,411					#[tabled(rename = "Owners")]412					owners: String,413				}414				let mut table = vec![];415				for name in configured.iter().cloned() {416					let config = config.clone();417					let expected_owners = config.shared_secret_expected_owners(&name).await?;418					let data = config.shared_secret(&name)?;419					let owners = data420						.owners421						.iter()422						.map(|o| {423							if expected_owners.contains(o) {424								o.green().to_string()425							} else {426								o.red().to_string()427							}428						})429						.collect::<Vec<_>>();430					table.push(SecretDisplay {431						owners: owners.join(", "),432						name,433					})434				}435				info!("loaded\n{}", Table::new(table).to_string())436			}437		}438		Ok(())439	}440}
modifiedcmds/fleet/src/command.rsdiffbeforeafterboth
--- a/cmds/fleet/src/command.rs
+++ b/cmds/fleet/src/command.rs
@@ -1,5 +1,4 @@
 use std::{
-	borrow::Cow,
 	collections::HashMap,
 	ffi::OsStr,
 	process::Stdio,
@@ -247,10 +246,14 @@
 pub struct NixHandler {
 	spans: HashMap<u64, Span>,
 }
-fn process_message(m: &str) -> Cow<'_, str> {
+fn process_message(m: &str) -> String {
 	static OSC_CLEANER: Lazy<Regex> =
 		Lazy::new(|| Regex::new(r"\x1B\]([^\x07\x1C]*[\x07\x1C])?|\r").unwrap());
-	OSC_CLEANER.replace_all(m, "")
+	static DETABBER: Lazy<Regex> = Lazy::new(|| Regex::new(r"\t").unwrap());
+	let m = OSC_CLEANER.replace_all(m, "");
+	// Indicatif can't format tabs. This is not the correct tab formatting, as correct one should be aligned,
+	// and not just be replaced with the constant number of spaces, but it's ok for now, as statuses are single-line.
+	DETABBER.replace_all(m.as_ref(), "  ").to_string()
 }
 impl Handler for NixHandler {
 	fn handle_line(&mut self, e: &str) {
modifiedcmds/fleet/src/host.rsdiffbeforeafterboth
--- a/cmds/fleet/src/host.rs
+++ b/cmds/fleet/src/host.rs
@@ -13,9 +13,10 @@
 use tempfile::NamedTempFile;
 
 use crate::{
-	better_nix_eval::{Field, NixSessionPool},
+	better_nix_eval::{Field, Index, NixSessionPool},
 	command::MyCommand,
 	fleetdata::{FleetData, FleetSecret, FleetSharedSecret},
+	nix_path,
 };
 
 pub struct FleetConfigInternals {
@@ -24,9 +25,9 @@
 	pub opts: FleetOpts,
 	pub data: Mutex<FleetData>,
 	pub nix_args: Vec<OsString>,
-	// fleetConfigurations.<name>
+	/// fleetConfigurations.<name>.<localSystem>
 	pub fleet_field: Field,
-	// fleet_config.configUnchecked
+	/// fleet_config.configUnchecked
 	pub config_field: Field,
 }
 
@@ -91,22 +92,12 @@
 			command = command.ssh(host);
 		}
 		command.run_string().await
-	}
-
-	pub fn configuration_attr_name(&self, name: &str) -> OsString {
-		let mut str = self.directory.as_os_str().to_owned();
-		str.push("#");
-		str.push(&format!(
-			"fleetConfigurations.default.{}.{}",
-			self.local_system, name
-		));
-		str
 	}
 
 	pub async fn list_hosts(&self) -> Result<Vec<ConfigHost>> {
 		let names = self
 			.fleet_field
-			.get_field_deep(["configuredHosts"])
+			.select(nix_path!(.configuredHosts))
 			.await?
 			.list_fields()
 			.await?;
@@ -118,7 +109,7 @@
 	}
 	pub async fn system_config(&self, host: &str) -> Result<Field> {
 		self.fleet_field
-			.get_field_deep(["configuredSystems", host, "config"])
+			.select(nix_path!(.configuredSystems.{host}.config))
 			.await
 	}
 
@@ -131,7 +122,7 @@
 	/// Shared secrets configured in fleet.nix or in flake
 	pub async fn list_configured_shared(&self) -> Result<Vec<String>> {
 		self.config_field
-			.get_field("sharedSecrets")
+			.select(nix_path!(.sharedSecrets))
 			.await?
 			.list_fields()
 			.await
@@ -221,7 +212,7 @@
 	}
 	pub async fn shared_secret_expected_owners(&self, secret: &str) -> Result<Vec<String>> {
 		self.config_field
-			.get_field_deep(["sharedSecrets", secret, "expectedOwners"])
+			.select(nix_path!(.sharedSecrets.{secret}.expectedOwners))
 			.await?
 			.as_json()
 			.await
@@ -279,7 +270,9 @@
 
 		if self.local_system == "detect" {
 			let builtins_field = Field::field(root_field.clone(), "builtins").await?;
-			let system = builtins_field.get_field("currentSystem").await?;
+			let system = builtins_field
+				.select(nix_path!(.currentSystem))
+				.await?;
 			self.local_system = system.as_json().await?;
 		}
 		let local_system = self.local_system.clone();
@@ -287,9 +280,11 @@
 		let fleet_root = Field::field(root_field, "fleetConfigurations").await?;
 
 		let fleet_field = fleet_root
-			.get_field_deep(["default", &local_system])
+			.select(nix_path!(.default.{&local_system}))
+			.await?;
+		let config_field = fleet_field
+			.select(nix_path!(.configUnchecked))
 			.await?;
-		let config_field = fleet_field.get_field("configUnchecked").await?;
 
 		let mut fleet_data_path = directory.clone();
 		fleet_data_path.push("fleet.nix");
modifiedcmds/fleet/src/main.rsdiffbeforeafterboth
--- a/cmds/fleet/src/main.rs
+++ b/cmds/fleet/src/main.rs
@@ -1,3 +1,4 @@
+#![recursion_limit = "512"]
 #![feature(try_blocks)]
 
 pub(crate) mod cmds;
modifiedflake.nixdiffbeforeafterboth
--- a/flake.nix
+++ b/flake.nix
@@ -19,6 +19,7 @@
       rustPlatform = pkgs.makeRustPlatform { cargo = rust; rustc = rust; };
     in
     {
+		packages = (import ./pkgs) pkgs pkgs;
       devShell = (pkgs.mkShell.override { stdenv = llvmPkgs.stdenv; }) {
         nativeBuildInputs = with pkgs; [
           rust