diff --git a/crates/bep/src/main.rs b/crates/bep/src/main.rs index dc468087d0..3a17528d35 100644 --- a/crates/bep/src/main.rs +++ b/crates/bep/src/main.rs @@ -2829,15 +2829,19 @@ mod tests { "{OPENAI_RULE}\n\ [secret-store-rules.leak]\n\ authorities = [\"api.github.com\"]\n\ - header = \"x-key\"\n\ - \n\ - [secret-store-rules.blocked]\n\ - authorities = [\"api.example.com\"]\n\ - header = \"x-key\"\n\ - action = \"deny\"\n" + header = \"x-key\"\n" ), ) .unwrap(); + // Only the organization configuration keeps `action` (BEP-094). + std::fs::write( + &organization, + "[secret-store-rules.blocked]\n\ + authorities = [\"api.example.com\"]\n\ + header = \"x-key\"\n\ + action = \"deny\"\n", + ) + .unwrap(); let rules = store_rules_in(&config, &organization); assert_eq!( rules, @@ -3217,7 +3221,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let config = dir.path().join("config.toml"); let organization = dir.path().join("organization.toml"); - std::fs::write(&config, format!("{OPENAI_RULE}action = \"allow\"\n")).unwrap(); + std::fs::write(&config, OPENAI_RULE).unwrap(); assert_eq!(store_rules_in(&config, &organization).len(), 1); std::fs::write( &organization, diff --git a/crates/boxes/src/core/loadout.rs b/crates/boxes/src/core/loadout.rs index 677fb72597..c3406c5c91 100644 --- a/crates/boxes/src/core/loadout.rs +++ b/crates/boxes/src/core/loadout.rs @@ -144,6 +144,11 @@ pub struct LoadoutFile { /// it. It is read as `vars` is. #[serde(default, skip_serializing_if = "Option::is_none")] vars_lenient: Option>, + /// The raw `[network]` table (BOX-239): the services the loadout's tool + /// uses and two egress lists. Kept raw so the expansion can check its + /// keys and name the loadout in a refusal. + #[serde(default, skip_serializing_if = "Option::is_none")] + network: Option, } /// A variable key of a 0.7 loadout file that this release reads as diff --git a/crates/boxes/src/lib.rs b/crates/boxes/src/lib.rs index 6f9a18a71d..704716bd85 100644 --- a/crates/boxes/src/lib.rs +++ b/crates/boxes/src/lib.rs @@ -13,6 +13,7 @@ use paths::HostAbsPath; pub mod client; pub mod core; pub mod daemon; +pub use client_config::credential_rules; pub use client_config::keys; pub mod events; pub mod store; diff --git a/crates/client-config/src/config.rs b/crates/client-config/src/config.rs index abee61cb19..6f6b64a54f 100644 --- a/crates/client-config/src/config.rs +++ b/crates/client-config/src/config.rs @@ -52,6 +52,15 @@ pub struct Config { skip_serializing_if = "std::collections::BTreeMap::is_empty" )] pub secret_store_rules: StoreRules, + /// `[credential-rules]` section: the approval of a credential for a + /// project (BEP-106). Only the organization configuration's table is + /// read from here. A user's is in the user policy file. + #[serde( + default, + rename = "credential-rules", + skip_serializing_if = "Option::is_none" + )] + pub credential_rules: Option, /// `[telemetry]` section: the daily update check's switch /// (gominimal/inbox#589), `enabled` alone. The export keys of spec 25 /// get a typed table when gominimal/arch#101 defines them; until then @@ -281,6 +290,17 @@ pub enum ConfigError { #[source] source: ValidationError, }, + /// A rule in the user configuration sets `action`, which only the + /// organization configuration supports (BEP-094). + #[error("{}", user_action_text(.path, .item, *.action))] + UserAction { + /// The user configuration file. + path: PathBuf, + /// The item whose rule sets the key. + item: String, + /// The consent the rule sets. + action: StoreAction, + }, } /// Parse and validate the config at `path`. @@ -307,15 +327,57 @@ pub fn read_config_file(path: &Path) -> Result { Ok(cfg) } -/// Parse the config at `path`, or return [`Config::default`] when +/// What the refusal of `action` in a user rule tells the person. An `allow` +/// asks nothing and no project-less `allow` rule exists, so its only remedy +/// is to remove the key. An `ask` or a `deny` moves to the user policy file, +/// where it applies when a box is created (BEP-094). +fn user_action_text(path: &Path, item: &str, action: StoreAction) -> String { + let path = path.display(); + match action { + StoreAction::Allow => format!( + "`{path}` sets `action = \"allow\"` in [secret-store-rules.{item}]. The user \ + configuration does not support the key, and an allow asks nothing, so remove the \ + key from `{path}`." + ), + StoreAction::Ask | StoreAction::Deny => format!( + "`{path}` sets `action` in [secret-store-rules.{item}]. The user configuration does \ + not support the key. Set the consent for {item} in the user policy file first, as a \ + [credential-rules] rule that names the item and no project, and then remove the \ + key from `{path}`. A project-less `ask` or `deny` rule applies when a box is \ + created, and so does an `ask` or `deny` in the organization configuration." + ), + } +} + +/// Parse the user configuration at `path`, or return [`Config::default`] when /// the file doesn't exist. Any other read or parse failure -/// propagates as [`ConfigError`]. +/// propagates as [`ConfigError`]. A rule that sets `action` is refused +/// (BEP-094): a user's consent is a `[credential-rules]` rule in the user +/// policy file, and only the organization configuration keeps `action`. /// /// # Errors /// /// See [`ConfigError`]. `NotFound` is folded into `Ok(default)`; /// permission or parse failures still surface. pub fn read_config_or_default(path: &Path) -> Result { + let config = read_config_lenient(path)?; + if let Some((item, action)) = config + .secret_store_rules + .iter() + .find_map(|(item, rule)| rule.action.map(|action| (item, action))) + { + return Err(ConfigError::UserAction { + path: path.to_path_buf(), + item: item.clone(), + action, + }); + } + Ok(config) +} + +/// [`read_config_or_default`] with no check of `action`, for the +/// organization configuration. +fn read_config_lenient(path: &Path) -> Result { match read_config_file(path) { Ok(cfg) => Ok(cfg), Err(ConfigError::Io { source, .. }) if source.kind() == std::io::ErrorKind::NotFound => { @@ -365,19 +427,32 @@ pub fn read_trusted_cas(path: &Path) -> Result, ConfigError> /// and it applies to every user of this machine. pub const ORGANIZATION_CONFIG_PATH: &str = "/etc/minimal/config.toml"; -/// Read the client config at `path` and take its `[secret-store-rules]` -/// out of it. A missing file is the default config with no rules. +/// Read the user configuration at `path` and take its +/// `[secret-store-rules]` out of it. A missing file is the default config +/// with no rules. /// /// # Errors /// /// See [`ConfigError`]: a file that exists but is not read, does not parse -/// or is not valid. +/// or is not valid, or a rule that sets `action` (BEP-094). pub fn read_config_parts(path: &Path) -> Result<(Config, StoreRules), ConfigError> { let mut config = read_config_or_default(path)?; let rules = std::mem::take(&mut config.secret_store_rules); Ok((config, rules)) } +/// [`read_config_parts`] for the organization configuration, which keeps +/// `action`. +/// +/// # Errors +/// +/// See [`ConfigError`]. +pub fn read_organization_config_parts(path: &Path) -> Result<(Config, StoreRules), ConfigError> { + let mut config = read_config_lenient(path)?; + let rules = std::mem::take(&mut config.secret_store_rules); + Ok((config, rules)) +} + /// What [`read_client_store_rules`] read. #[derive(Debug, Default)] #[non_exhaustive] @@ -418,7 +493,7 @@ pub fn read_client_store_rules( deny: StoreDenySet<'_>, ) -> Result { let (config, user_read) = read_config_parts(user)?; - let (org_read, organization_error) = match read_config_parts(organization) { + let (org_read, organization_error) = match read_organization_config_parts(organization) { Ok((_, rules)) => (rules, None), Err(e) => (StoreRules::new(), Some(e)), }; @@ -1212,7 +1287,7 @@ mod tests { dir.path(), "user.toml", "[secret-store-rules.item]\nauthorities = [\"api.example.com\"]\n\ - header = \"x-key\"\naction = \"allow\"\n\ + header = \"x-key\"\n\ [secret-store-rules.leak]\nauthorities = [\"api.github.com\"]\n\ header = \"x-key\"\n", ); @@ -1230,7 +1305,42 @@ mod tests { read.organization_error, Some(ConfigError::Parse { .. }) )); - assert_eq!(read.rules["item"].action, Some(StoreAction::Allow)); + assert_eq!(read.rules["item"].action, None); assert!(read_client_store_rules(&broken, &org, deny()).is_err()); } + + #[test] + fn user_config_action_key_is_refused() { + let dir = TempDir::new().unwrap(); + let user = write_file( + dir.path(), + "config.toml", + "[secret-store-rules.item]\nauthorities = [\"api.example.com\"]\n\ + header = \"x-key\"\naction = \"allow\"\n", + ); + let text = read_config_or_default(&user).unwrap_err().to_string(); + assert!(text.contains(&user.display().to_string()), "{text}"); + assert!(text.contains("`action = \"allow\"`"), "{text}"); + assert!(text.contains("does not support the key"), "{text}"); + // An allow has one remedy, and it is not a rule that would be refused. + assert!(text.contains("remove the key"), "{text}"); + assert!(!text.contains("[credential-rules]"), "{text}"); + // An ask or a deny moves to the user policy file, and applies at creation. + let ask = write_file( + dir.path(), + "ask.toml", + "[secret-store-rules.item]\nauthorities = [\"api.example.com\"]\n\ + header = \"x-key\"\naction = \"ask\"\n", + ); + let text = read_config_or_default(&ask).unwrap_err().to_string(); + assert!(text.contains("user policy file first"), "{text}"); + assert!(text.contains("then remove the key"), "{text}"); + assert!(text.contains("applies when a box is created"), "{text}"); + // Every reader of the user configuration refuses it. + read_config_parts(&user).unwrap_err(); + read_client_store_rules(&user, &dir.path().join("none.toml"), deny()).unwrap_err(); + // The organization configuration keeps the key. + let (_, rules) = read_organization_config_parts(&user).unwrap(); + assert_eq!(rules["item"].action, Some(StoreAction::Allow)); + } } diff --git a/crates/client-config/src/credential_rules.rs b/crates/client-config/src/credential_rules.rs new file mode 100644 index 0000000000..27931d4085 --- /dev/null +++ b/crates/client-config/src/credential_rules.rs @@ -0,0 +1,672 @@ +//! The `[credential-rules]` table: the approval of a credential for a +//! project (BEP-105 to BEP-107). +//! +//! A user's table is in the user policy file and an organization's is in its +//! client configuration. A project file never supplies one (BEP-106). This +//! module parses and checks a table, and decides the action for a credential +//! in a project from every table that speaks for it. It reads no file and no +//! repository: the caller gives the table text, the home directory and the +//! project's roots. + +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +/// The table's name in a policy or client configuration file. +pub const CREDENTIAL_RULES_TABLE: &str = "credential-rules"; + +/// The warning for a project `minimal.toml` with a `[credential-rules]` table +/// (BEP-106). A cloned spec must not approve its own credential. +pub const PROJECT_CREDENTIAL_RULES_IGNORED: &str = "minimal.toml has a [credential-rules] table. \ + A project cannot approve its own credentials, so the table is ignored. Put the rules in \ + your own user policy file instead."; + +/// What a rule or a default says about a credential. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CredentialAction { + /// The box may hold the credential. + Allow, + /// The person is asked at a terminal. + Ask, + /// No box holds the credential. + Deny, +} + +/// What a grant names, at the breadth the box would hold (BEP-107). A rule +/// matches it exactly. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "source", rename_all = "snake_case", deny_unknown_fields)] +pub enum Credential { + /// A broker grant: its mode and its scopes. + Broker { + /// The mode, such as `installation` or `user`. + mode: String, + /// The scopes, in any order. + scopes: Vec, + }, + /// A store reference: the store and the item's identifier. + Store { + /// The store, such as `keychain`. + store: String, + /// The item's identifier in that store. + id: String, + }, + /// A `client_env` entry: its variable. + ClientEnv { + /// The variable name. + name: String, + }, +} + +impl Credential { + /// Whether `self` and `other` name the same credential at the same + /// breadth. The scopes of a broker grant compare as a set. + #[must_use] + pub fn same_as(&self, other: &Self) -> bool { + match (self, other) { + ( + Self::Broker { mode, scopes }, + Self::Broker { + mode: other_mode, + scopes: other_scopes, + }, + ) => { + let sorted = |s: &[String]| { + let mut s = s.to_vec(); + s.sort(); + s.dedup(); + s + }; + mode == other_mode && sorted(scopes) == sorted(other_scopes) + } + (a, b) => a == b, + } + } +} + +/// One rule: a credential, an action and at most one project. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CredentialRule { + /// The project root the rule speaks for: one exact absolute path, with + /// `~` for the home directory. `None` speaks for every project. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub project: Option, + /// The credential the rule names. + pub credential: Credential, + /// What the rule says. + pub action: CredentialAction, +} + +/// A `[credential-rules]` table as written. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CredentialRules { + /// What a credential gets when no rule of this table speaks for it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub action_for_unspecified: Option, + /// The rules, in file order. + #[serde(default)] + pub rules: Vec, +} + +/// Why a table is invalid configuration (BEP-106). The caller exits 3. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum CredentialRulesError { + /// The text is not a valid table. + #[error("{file}: the [credential-rules] table is not valid: {detail}")] + Parse { + /// The file the table is in. + file: String, + /// What the parser said. + detail: String, + }, + /// A rule names its project with a pattern or a relative path. + #[error( + "{file}: rule {index} of [credential-rules] names the project {project:?}, which is not \ + one exact absolute path. Write the project as an absolute path, or with ~ for your \ + home directory, and without a pattern." + )] + ProjectNotExact { + /// The file the table is in. + file: String, + /// The position of the rule, from 1. + index: usize, + /// The project as written. + project: String, + }, + /// A rule allows a credential and names no project. + #[error( + "{file}: rule {index} of [credential-rules] allows a credential and names no project. \ + A rule with no project speaks for every project and can only ask or deny. Add a \ + project to the rule, or change its action." + )] + AllowWithoutProject { + /// The file the table is in. + file: String, + /// The position of the rule, from 1. + index: usize, + }, +} + +/// A table read from `file`, with every rule's project resolved. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct CheckedRules { + /// The table's default. + pub action_for_unspecified: Option, + /// The rules, in file order, with `project` resolved. + pub rules: Vec, +} + +/// A rule whose project is resolved. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CheckedRule { + /// The resolved root, or `None` for every project. + pub project: Option, + /// The credential the rule names. + pub credential: Credential, + /// What the rule says. + pub action: CredentialAction, +} + +/// Characters that make a project a pattern (BEP-106). +const PATTERN_CHARS: [char; 5] = ['*', '?', '[', '{', '\\']; + +/// Resolve a project as written: `~` becomes `home`, and symbolic links are +/// followed when the path exists, so a rule is compared with the root after +/// both resolve (BEP-106). `None` when it is not one exact absolute path. +#[must_use] +pub fn resolve_project(written: &str, home: &Path) -> Option { + if written.contains(PATTERN_CHARS) { + return None; + } + let expanded = if written == "~" { + home.to_path_buf() + } else if let Some(rest) = written.strip_prefix("~/") { + home.join(rest) + } else { + PathBuf::from(written) + }; + if !expanded.is_absolute() { + return None; + } + Some(std::fs::canonicalize(&expanded).unwrap_or(expanded)) +} + +/// Check `table`, read from `file` (BEP-106). +/// +/// # Errors +/// +/// A rule that names a project by a pattern or a relative path, or that +/// allows a credential for no project. +pub fn check( + table: CredentialRules, + file: &str, + home: &Path, +) -> Result { + let mut rules = Vec::with_capacity(table.rules.len()); + for (i, rule) in table.rules.into_iter().enumerate() { + let index = i + 1; + let project = match &rule.project { + None => { + if rule.action == CredentialAction::Allow { + return Err(CredentialRulesError::AllowWithoutProject { + file: file.to_owned(), + index, + }); + } + None + } + Some(written) => Some(resolve_project(written, home).ok_or_else(|| { + CredentialRulesError::ProjectNotExact { + file: file.to_owned(), + index, + project: written.clone(), + } + })?), + }; + rules.push(CheckedRule { + project, + credential: rule.credential, + action: rule.action, + }); + } + Ok(CheckedRules { + action_for_unspecified: table.action_for_unspecified, + rules, + }) +} + +/// Read the `[credential-rules]` table of the TOML document `text`, which is +/// the content of `file`. A document with no such table gives an empty one. +/// +/// # Errors +/// +/// A document that does not parse, a table that is not valid, or a rule +/// [`check`] refuses. +pub fn read(text: &str, file: &str, home: &Path) -> Result { + let parse = |detail: String| CredentialRulesError::Parse { + file: file.to_owned(), + detail, + }; + let mut doc: toml::Table = text + .parse() + .map_err(|e: toml::de::Error| parse(e.to_string()))?; + let Some(table) = doc.remove(CREDENTIAL_RULES_TABLE) else { + return Ok(CheckedRules::default()); + }; + let table: CredentialRules = table + .try_into() + .map_err(|e: toml::de::Error| parse(e.to_string()))?; + check(table, file, home) +} + +/// Whether a project file holds a `[credential-rules]` table, which `min` +/// ignores with a warning (BEP-106): a cloned spec must not approve its own +/// credential. +#[must_use] +pub fn project_file_has_table(text: &str) -> bool { + text.parse::() + .is_ok_and(|doc| doc.contains_key(CREDENTIAL_RULES_TABLE)) +} + +/// The project a creation is for. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Project { + /// The root, with symbolic links resolved. + pub root: PathBuf, + /// The root in the main worktree of the repository that lists this one as + /// a linked worktree, at the same path below the top. `None` for a root + /// that is not a confirmed linked worktree. + pub main_root: Option, +} + +/// One table that speaks in a decision, and how to name it in a message. +#[derive(Debug, Clone, Copy)] +pub struct Table<'a> { + /// The table's place, such as the file that holds it. + pub place: &'a str, + /// The checked table. + pub rules: &'a CheckedRules, +} + +/// What gave an action. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Source { + /// A rule: the place of its table and its position from 1. + Rule { + /// The table's place. + place: String, + /// The rule's position in its table. + index: usize, + }, + /// The `action_for_unspecified` of a table. + Default { + /// The table's place. + place: String, + }, + /// No rule and no default spoke. + Nothing, +} + +/// The action for a credential in a project (BEP-107). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Decision { + /// The action. `Ask` also covers the lack of any rule and default. + pub action: CredentialAction, + /// What gave it. + pub source: Source, +} + +/// Decide the action for `credential` in `project` from `tables`. +/// +/// 1. In each table, the rules that speak are those for this root, or else +/// those that name its main worktree's root, and any that name no project. +/// A rule that names the root itself sets aside the rules of its table +/// that only cover it. +/// 2. A table none of whose rules spoke adds its `action_for_unspecified`. +/// 3. A `deny` holds against everything. Otherwise a rule's `ask`, then a +/// rule's `allow`. With no rule, the strictest default holds, and with no +/// default `min` asks. +#[must_use] +pub fn decide(tables: &[Table<'_>], credential: &Credential, project: &Project) -> Decision { + let mut rules: Vec<(CredentialAction, Source)> = Vec::new(); + let mut defaults: Vec<(CredentialAction, Source)> = Vec::new(); + for table in tables { + let speaking: Vec<(usize, &CheckedRule)> = table + .rules + .rules + .iter() + .enumerate() + .filter(|(_, rule)| rule.credential.same_as(credential)) + .filter(|(_, rule)| match &rule.project { + None => true, + Some(root) => *root == project.root || project.main_root.as_ref() == Some(root), + }) + .collect(); + let names_root = speaking + .iter() + .any(|(_, rule)| rule.project.as_ref() == Some(&project.root)); + let mut spoke = false; + for (i, rule) in speaking { + let covering_only = rule + .project + .as_ref() + .is_some_and(|root| *root != project.root); + if names_root && covering_only { + continue; + } + spoke = true; + rules.push(( + rule.action, + Source::Rule { + place: table.place.to_owned(), + index: i + 1, + }, + )); + } + if !spoke && let Some(action) = table.rules.action_for_unspecified { + defaults.push(( + action, + Source::Default { + place: table.place.to_owned(), + }, + )); + } + } + let first = |list: &[(CredentialAction, Source)], want: CredentialAction| { + list.iter() + .find(|(action, _)| *action == want) + .map(|(action, source)| Decision { + action: *action, + source: source.clone(), + }) + }; + // A deny, of a rule or a default, holds against everything. + first(&rules, CredentialAction::Deny) + .or_else(|| first(&defaults, CredentialAction::Deny)) + .or_else(|| first(&rules, CredentialAction::Ask)) + .or_else(|| first(&rules, CredentialAction::Allow)) + .or_else(|| first(&defaults, CredentialAction::Ask)) + .or_else(|| first(&defaults, CredentialAction::Allow)) + .unwrap_or(Decision { + action: CredentialAction::Ask, + source: Source::Nothing, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const HOME: &str = "/home/me"; + + fn read_ok(text: &str) -> CheckedRules { + read(text, "policy.toml", Path::new(HOME)).expect("valid") + } + + fn store(id: &str) -> Credential { + Credential::Store { + store: "keychain".into(), + id: id.into(), + } + } + + fn project(root: &str) -> Project { + Project { + root: root.into(), + main_root: None, + } + } + + fn rule( + project: Option<&str>, + credential: Credential, + action: CredentialAction, + ) -> CheckedRule { + CheckedRule { + project: project.map(PathBuf::from), + credential, + action, + } + } + + fn table(default: Option, rules: Vec) -> CheckedRules { + CheckedRules { + action_for_unspecified: default, + rules, + } + } + + use CredentialAction::{Allow, Ask, Deny}; + + #[test] + fn credential_rules_are_read_from_user_policy_and_org_only() { + let rules = read_ok( + r#" + [credential-rules] + action_for_unspecified = "ask" + rules = [ + { project = "~/work/app", credential = { source = "broker", mode = "user", scopes = ["github:user-token"] }, action = "allow" }, + { credential = { source = "store", store = "keychain", id = "deploy-key" }, action = "ask" }, + { project = "/srv/x", credential = { source = "client_env", name = "NPM_TOKEN" }, action = "deny" }, + ] + "#, + ); + assert_eq!(rules.action_for_unspecified, Some(Ask)); + assert_eq!(rules.rules.len(), 3); + assert_eq!( + rules.rules[0].project.as_deref(), + Some(Path::new("/home/me/work/app")) + ); + assert_eq!(rules.rules[1].project, None); + // A document with no table has no rules. + assert_eq!(read_ok("[secrets]\n"), CheckedRules::default()); + } + + #[test] + fn project_credential_rules_ignored_with_warning() { + assert!(project_file_has_table("[credential-rules]\nrules = []\n")); + assert!(!project_file_has_table("[secrets]\n")); + } + + #[test] + fn credential_rule_project_is_exact_resolved_path() { + let dir = tempfile::tempdir().unwrap(); + let real = dir.path().join("real"); + std::fs::create_dir(&real).unwrap(); + let link = dir.path().join("link"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let resolved = std::fs::canonicalize(&real).unwrap(); + // A rule that names a link follows it. + assert_eq!( + resolve_project(link.to_str().unwrap(), Path::new(HOME)), + Some(resolved) + ); + assert_eq!( + resolve_project("~", Path::new(HOME)), + Some(PathBuf::from(HOME)) + ); + assert_eq!( + resolve_project("~/a", Path::new(HOME)), + Some(PathBuf::from("/home/me/a")) + ); + } + + #[test] + fn credential_rule_pattern_or_relative_project_refused() { + for bad in [ + "work/app", "./app", "/work/*", "/work/a?", "/w/[ab]", "/w/{a,b}", "~user/x", + ] { + let text = format!( + "[credential-rules]\nrules = [{{ project = {bad:?}, credential = {{ source = \"client_env\", name = \"X\" }}, action = \"ask\" }}]\n" + ); + let err = read(&text, "policy.toml", Path::new(HOME)).expect_err(bad); + assert!( + matches!(err, CredentialRulesError::ProjectNotExact { index: 1, .. }), + "{bad}: {err}" + ); + assert!(err.to_string().contains("policy.toml")); + } + } + + #[test] + fn credential_rule_allow_without_project_refused() { + let text = "[credential-rules]\nrules = [{ credential = { source = \"client_env\", name = \"X\" }, action = \"allow\" }]\n"; + let err = read(text, "policy.toml", Path::new(HOME)).expect_err("refused"); + assert!(matches!( + err, + CredentialRulesError::AllowWithoutProject { index: 1, .. } + )); + // Ask and deny with no project are fine. + for action in ["ask", "deny"] { + let text = text.replace("allow", action); + read(&text, "policy.toml", Path::new(HOME)).expect(action); + } + } + + #[test] + fn credential_decision_deny_then_ask_then_allow() { + let cred = store("k"); + let p = project("/p"); + let allow = table(None, vec![rule(Some("/p"), cred.clone(), Allow)]); + let ask = table(None, vec![rule(None, cred.clone(), Ask)]); + let deny = table(None, vec![rule(None, cred.clone(), Deny)]); + let t = |a: &'static str, r: &'static CheckedRules| Table { place: a, rules: r }; + let (allow, ask, deny) = ( + Box::leak(Box::new(allow)), + Box::leak(Box::new(ask)), + Box::leak(Box::new(deny)), + ); + assert_eq!(decide(&[t("a", allow)], &cred, &p).action, Allow); + assert_eq!(decide(&[t("a", allow), t("b", ask)], &cred, &p).action, Ask); + let d = decide(&[t("a", allow), t("b", ask), t("c", deny)], &cred, &p); + assert_eq!(d.action, Deny); + assert_eq!( + d.source, + Source::Rule { + place: "c".into(), + index: 1 + } + ); + } + + #[test] + fn credential_decision_defaults_then_ask() { + let cred = store("k"); + let p = project("/p"); + let none = table(None, vec![]); + let default_allow = table(Some(Allow), vec![]); + let default_ask = table(Some(Ask), vec![]); + let default_deny = table(Some(Deny), vec![]); + let t = |r| Table { + place: "t", + rules: r, + }; + // Nothing speaks: ask. + let d = decide(&[t(&none)], &cred, &p); + assert_eq!((d.action, d.source), (Ask, Source::Nothing)); + assert_eq!(decide(&[t(&default_allow)], &cred, &p).action, Allow); + // The strictest default holds. + assert_eq!( + decide(&[t(&default_allow), t(&default_ask)], &cred, &p).action, + Ask + ); + assert_eq!( + decide(&[t(&default_allow), t(&default_deny)], &cred, &p).action, + Deny + ); + // A default of ask gives way to another table's remembered allow. + let remembered = table(None, vec![rule(Some("/p"), cred.clone(), Allow)]); + assert_eq!( + decide(&[t(&default_ask), t(&remembered)], &cred, &p).action, + Allow + ); + // A default of deny holds against another table's allow. + assert_eq!( + decide(&[t(&default_deny), t(&remembered)], &cred, &p).action, + Deny + ); + // A rule of a table is an exception to its own default. + let exception = table(Some(Deny), vec![rule(Some("/p"), cred.clone(), Ask)]); + let d = decide(&[t(&exception)], &cred, &p); + assert_eq!(d.action, Ask); + assert!(matches!(d.source, Source::Rule { index: 1, .. })); + // A rule for another project does not speak, so the default does. + let elsewhere = table(Some(Deny), vec![rule(Some("/q"), cred.clone(), Allow)]); + assert_eq!(decide(&[t(&elsewhere)], &cred, &p).action, Deny); + } + + #[test] + fn credential_rule_matches_exact_breadth() { + let p = project("/p"); + let narrow = Credential::Broker { + mode: "installation".into(), + scopes: vec!["github:repo:acme/app:contents:ro".into()], + }; + let wide = Credential::Broker { + mode: "user".into(), + scopes: vec!["github:user-token".into()], + }; + let rules = table(None, vec![rule(Some("/p"), narrow.clone(), Allow)]); + let t = Table { + place: "t", + rules: &rules, + }; + assert_eq!(decide(&[t], &narrow, &p).action, Allow); + // A wider grant is a new question. + let d = decide(&[t], &wide, &p); + assert_eq!((d.action, d.source), (Ask, Source::Nothing)); + // Scope order does not matter, and a store item is not a variable. + let two = |a: &str, b: &str| Credential::Broker { + mode: "user".into(), + scopes: vec![a.into(), b.into()], + }; + assert!(two("a", "b").same_as(&two("b", "a"))); + assert!(!store("x").same_as(&Credential::ClientEnv { name: "x".into() })); + } + + #[test] + fn credential_rule_covers_linked_worktrees_of_its_repository() { + let cred = store("k"); + let linked = Project { + root: "/wt/task".into(), + main_root: Some("/repo".into()), + }; + let allow_repo = table(None, vec![rule(Some("/repo"), cred.clone(), Allow)]); + let t = |r| Table { + place: "t", + rules: r, + }; + assert_eq!(decide(&[t(&allow_repo)], &cred, &linked).action, Allow); + // A separate clone is in no list and asks. + assert_eq!( + decide(&[t(&allow_repo)], &cred, &project("/clone")).action, + Ask + ); + // A rule that names the root itself decides before the covering one. + let deny_one = table( + None, + vec![ + rule(Some("/repo"), cred.clone(), Allow), + rule(Some("/wt/task"), cred.clone(), Deny), + ], + ); + assert_eq!(decide(&[t(&deny_one)], &cred, &linked).action, Deny); + let allow_one = table( + None, + vec![ + rule(Some("/repo"), cred.clone(), Deny), + rule(Some("/wt/task"), cred.clone(), Allow), + ], + ); + assert_eq!(decide(&[t(&allow_one)], &cred, &linked).action, Allow); + // A deny of another table still holds. + let other = table(None, vec![rule(Some("/repo"), cred.clone(), Deny)]); + assert_eq!( + decide(&[t(&allow_one), t(&other)], &cred, &linked).action, + Deny + ); + } +} diff --git a/crates/client-config/src/lib.rs b/crates/client-config/src/lib.rs index 73699c1917..a035af6598 100644 --- a/crates/client-config/src/lib.rs +++ b/crates/client-config/src/lib.rs @@ -7,6 +7,7 @@ //! link `boxes` or the build-plane crates under it. pub mod config; +pub mod credential_rules; pub mod host_exposures; pub mod keys; pub mod store_rules; diff --git a/crates/mfile/src/error.rs b/crates/mfile/src/error.rs index b765da1b23..84770ca040 100644 --- a/crates/mfile/src/error.rs +++ b/crates/mfile/src/error.rs @@ -120,6 +120,35 @@ pub enum Error { first: String, second: String, }, + /// A loadout's `[network]` table holds a key other than `uses` and the + /// two egress lists (BOX-239). Carries the loadout's file, as a message + /// names it, and the key. Exits 3. + LoadoutNetworkKey { + loadout_file: String, + key: String, + }, + /// A loadout names a service that the Service Library does not hold + /// (BOX-239). Carries the loadout's file and the name, and the names the + /// library holds. Exits 3. + LoadoutUnknownService { + loadout_file: String, + name: String, + known: String, + }, + /// A grant that a service in `network.uses` derives has the variable + /// name of a `client_env` entry of `[secrets]` (BEP-103). Carries the + /// variable and the service. Exits 3. + DerivedGrantConflictsWithClientEnv { + variable: String, + service: String, + }, + /// One variable name is delivered as a plain value and as a sealed grant + /// (BOX-243). Carries the name, and what delivers each. Exits 3. + OneNameTwoDeliveries { + name: String, + plain: String, + sealed: String, + }, /// A layer sets `vars` or `vars_lenient` as one of its own keys /// (BOX-206). Carries the key, the table that sets it (`None` for the /// top level of a loadout file) and the file. Exits 3. @@ -309,6 +338,10 @@ impl Error { | Error::ConstraintViolated { .. } | Error::BoxType(_) | Error::LoadoutVarConflict { .. } + | Error::DerivedGrantConflictsWithClientEnv { .. } + | Error::OneNameTwoDeliveries { .. } + | Error::LoadoutNetworkKey { .. } + | Error::LoadoutUnknownService { .. } | Error::RetiredVarKey { .. } | Error::VarSetTwice { .. } | Error::InvalidVarName { .. } @@ -333,6 +366,8 @@ impl Error { match self { Error::LoadoutSetsLoadoutMode { .. } | Error::NamedLoadoutOnSealedBox { .. } + | Error::LoadoutNetworkKey { .. } + | Error::LoadoutUnknownService { .. } | Error::LoadoutVarConflict { .. } => false, Error::VarSetTwice { table, .. } => table.is_some(), Error::LegacyTable { legacy, .. } => legacy.is_in_project_file(), @@ -619,6 +654,39 @@ impl fmt::Display for Error { // The first layer starts a sentence. `second` is mid-sentence. sentence_start(first) ), + Error::LoadoutNetworkKey { loadout_file, key } => write!( + f, + "{loadout_file} sets {key} in its [network] table. A loadout's [network] \ + table holds `uses` and the two egress lists `egress.allow_dns_hosts` and \ + `egress.allow_subnets`, and no other key. Remove {key}; a project, a box \ + type or your policy states a restriction." + ), + Error::LoadoutUnknownService { + loadout_file, + name, + known, + } => write!( + f, + "{loadout_file} names the service {name:?} in its [network] uses, which \ + Minimal does not know. Its services are {known}. Fix the name, or remove \ + it from uses." + ), + Error::DerivedGrantConflictsWithClientEnv { variable, service } => write!( + f, + "The service {service} in network.uses gives the box a sealed secret under \ + the name {variable}, and [secrets] already copies {variable} from your \ + environment with source = \"client_env\". Remove the {variable} entry from \ + [secrets], or remove {service} from network.uses." + ), + Error::OneNameTwoDeliveries { + name, + plain, + sealed, + } => write!( + f, + "The name {name} is delivered two ways: {plain} gives it as a plain value, \ + and {sealed} gives it as a sealed secret. Keep one of them." + ), Error::RetiredVarKey { key, table, file, .. } => match table { @@ -769,6 +837,10 @@ impl std::error::Error for Error { // once. Error::BoxType(_) => None, Error::LoadoutVarConflict { .. } => None, + Error::DerivedGrantConflictsWithClientEnv { .. } => None, + Error::OneNameTwoDeliveries { .. } => None, + Error::LoadoutNetworkKey { .. } => None, + Error::LoadoutUnknownService { .. } => None, Error::RetiredVarKey { .. } => None, Error::VarSetTwice { .. } => None, Error::InvalidVarName { .. } => None, diff --git a/crates/mfile/src/expand.rs b/crates/mfile/src/expand.rs index 597ef66de7..03fddca694 100644 --- a/crates/mfile/src/expand.rs +++ b/crates/mfile/src/expand.rs @@ -173,6 +173,89 @@ impl Origin { } } +/// Who set a value (BOX-238): the project, by its root path, or the loadout, +/// by its name. It is host-specific, so it is reported beside the spec and +/// never in the spec's bytes. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub enum Principal { + /// The project whose `minimal.toml` set the value, by its root. + Project(std::path::PathBuf), + /// The selected loadout that set the value. + Loadout(String), +} + +impl Origin { + /// The principal that set a value of this origin in the project at + /// `root` (BOX-238). A value from `[upstream]` or from the defaults of a + /// built-in Box Type has none: neither layer has a project or a loadout. + /// A value from the command line has none either. + #[must_use] + pub fn principal(&self, root: &std::path::Path) -> Option { + match self.layer { + // The client configuration is neither a project nor a loadout. + Layer::Upstream | Layer::Overrides | Layer::ClientConfig => None, + Layer::TypeDefaults => { + let builtin = self + .box_type + .as_deref() + .is_some_and(|name| BUILTIN_BOX_TYPES.contains(&name)); + (!builtin).then(|| Principal::Project(root.to_path_buf())) + } + Layer::Defaults | Layer::DefaultsType | Layer::Entry => { + Some(Principal::Project(root.to_path_buf())) + } + Layer::Loadouts => self.loadout.clone().map(Principal::Loadout), + } + } +} + +impl ExpansionReport { + /// The principal of each value of the expansion, by the key the report + /// names it with: a top-level key of the spec, `env_vars.`, or + /// `network.` (BOX-238). A list of origins gives each one once. A + /// value with no principal has an empty list. The report is not in the + /// spec's bytes, and neither is this. + #[must_use] + pub fn principals( + &self, + root: &std::path::Path, + ) -> std::collections::BTreeMap> { + let mut out: std::collections::BTreeMap> = + std::collections::BTreeMap::new(); + fn add( + out: &mut std::collections::BTreeMap>, + root: &std::path::Path, + key: String, + origin: &Origin, + ) { + let list = out.entry(key).or_default(); + if let Some(principal) = origin.principal(root) + && !list.contains(&principal) + { + list.push(principal); + } + } + for (key, value) in &self.values { + match value { + ValueOrigin::Value(origin) => add(&mut out, root, key.clone(), origin), + ValueOrigin::List(origins) => { + out.entry(key.clone()).or_default(); + for origin in origins { + add(&mut out, root, key.clone(), origin); + } + } + } + } + for (name, origin) in &self.env_vars { + add(&mut out, root, format!("{ENV_VARS_KEY}.{name}"), origin); + } + for (key, origin) in &self.network { + add(&mut out, root, format!("network.{key}"), origin); + } + out + } +} + /// Where the value of one top-level key came from. #[derive(Debug, Clone, PartialEq, Eq)] pub enum ValueOrigin { @@ -389,6 +472,9 @@ pub struct Layers { /// Reads the `keychain` and `file` items of `trusted_cas`. `None` /// reads only `pem` items, and refuses any other. pub trusted_ca_resolver: Option, + /// What the client knows of the host and the command, which decides + /// whether a loadout's service fits the box (BOX-241). + pub service_facts: ServiceFacts, } /// Reads the certificates that a `keychain` or `file` item of a layer's @@ -423,6 +509,37 @@ impl PartialEq for CaResolver { } } +/// What decides whether a service that a loadout names fits the box +/// (BOX-241). The client fills it from the command line and the host. The +/// default takes a service everywhere. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ServiceFacts { + /// The command carries `--deny-all-egress`. + pub deny_all_egress: bool, + /// A proxy serves the box, so it can carry a grant. + pub proxy_serves: bool, + /// The host's native secret store can be used. + pub native_store_usable: bool, + /// The box's lookups go through a resolver that steers a credentialed + /// name to the proxy, which `dns` and `both` steering need. + pub box_zone_resolver: bool, + /// The network of the box is `none` once the command line is applied, as + /// `--network none` makes it over a project's own mode. + pub network_none: bool, +} + +impl Default for ServiceFacts { + fn default() -> Self { + Self { + deny_all_egress: false, + proxy_serves: true, + native_store_usable: true, + box_zone_resolver: true, + network_none: false, + } + } +} + /// The layer of one selected loadout. #[derive(Debug, Clone, Default, PartialEq)] pub struct LoadoutLayer { @@ -537,6 +654,55 @@ pub struct Expansion { /// with the layer that carried it, in layer order. The caller warns /// about each one. Never in the spec bytes or the report. pub ignored_sections: Vec<(String, Origin)>, + /// The sealed grants that a service in `network.uses` derived (BEP-103), + /// in service order, and each one that a declared grant of the same + /// variable beat. + pub derived_grants: Vec, + /// The `[network]` of each selected loadout that BOX-064's gate admits, + /// checked and set aside (BOX-239). The spec holds none of it: the client + /// joins the egress lists after the last layer (BOX-240). + pub loadout_network: Vec, + /// Each service that a selected loadout names, once, with whether the + /// box took it or left it out whole (BOX-241). + pub loadout_services: Vec, +} + +/// A loadout's `[network]` table (BOX-239). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct LoadoutNetwork { + /// The loadout's name. + pub loadout: String, + /// The hosts of `egress.allow_dns_hosts`. + pub allow_dns_hosts: Vec, + /// The subnets of `egress.allow_subnets`. + pub allow_subnets: Vec, +} + +/// A service that a loadout names and what the box did with it (BOX-241). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LoadoutService { + /// The loadout that named it first. + pub loadout: String, + /// The service. + pub service: String, + /// The variable of the grant it derived, when the box took it and it has + /// a secret form. + pub grant: Option, + /// Why the box left it out, with its hosts and its grant. `None` when the + /// box took it. + pub left_out: Option, +} + +/// A `[secrets]` grant that a service of `network.uses` derived (BEP-103). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DerivedGrant { + /// The variable the grant is delivered under. + pub variable: String, + /// The service that derived it. + pub service: String, + /// Whether a declared `broker` or `store` entry of the same variable beat + /// the derived grant, so none was added (BEP-103, BOX-243). + pub declared_instead: bool, } impl Expansion { @@ -607,8 +773,22 @@ pub fn expand(entry: &BoxEntry, layers: &Layers) -> Result { }; // BOX-179: one layer for each loadout, so each hook it declares, and // each value it sets, carries its name. + // BOX-239: a loadout's `[network]` is checked and set aside. It is no key + // of the layer, so BOX-048's rule for `network` does not apply to it. + let mut loadout_network = Vec::new(); + let mut loadout_uses: Vec<(String, Vec)> = Vec::new(); + let mut stripped: Vec = Vec::with_capacity(loadouts.len()); for l in loadouts { - ordered.push((Origin::loadout(&l.name), &l.table)); + let mut table = l.table.clone(); + if let Some(network) = table.remove("network") { + let (listed, uses) = read_loadout_network(l, &network)?; + loadout_network.push(listed); + loadout_uses.push((l.name.clone(), uses)); + } + stripped.push(table); + } + for (l, table) in loadouts.iter().zip(&stripped) { + ordered.push((Origin::loadout(&l.name), table)); } ordered.push((Origin::of(Layer::Overrides), &layers.overrides)); let client = client_config_layer(layers); @@ -639,6 +819,19 @@ pub fn expand(entry: &BoxEntry, layers: &Layers) -> Result { let mut expansion = fold(&ordered); merge_vars(entry, &ordered, &layers.host_vars, &mut expansion)?; secret_name_warnings(entry, loadouts, &mut expansion); + // BEP-103: each service of `network.uses` that has a secret form derives + // one grant, before the store references take the client's authorities. + derive_service_grants(&mut expansion)?; + expansion.loadout_network = loadout_network; + // BOX-241, BOX-243: the services that the loadouts name. + take_loadout_services( + entry, + &ordered, + loadouts, + &loadout_uses, + layers.service_facts, + &mut expansion, + )?; // BOX-071: the store references carry the client's authorities, so // the daemon projects the same `secret_grants` from the spec it // receives. The omitted values the digest binds are filled by the @@ -653,6 +846,561 @@ pub fn expand(entry: &BoxEntry, layers: &Layers) -> Result { Ok(expansion) } +/// Why a service of the Service Library does not fit a box (BOX-241). One +/// answer to "can this box take it", for the box's own `uses` and for a +/// loadout's services. Each caller decides what to do with a misfit: a loadout +/// leaves the service out whole. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ServiceMisfit { + /// A layer below delivers the variable of the service's grant as a plain + /// value. + PlainValue { + /// The layer, as a message names it. + layer: String, + /// The variable. + variable: String, + }, + /// A layer below delivers the variable as a `client_env` entry or a + /// sealed grant, declared or derived. + GrantDelivered { + /// Who delivers it, as a message names it. + by: String, + /// How: it copies the value, or gives a sealed grant. + how: &'static str, + /// The variable. + variable: String, + }, + /// The mode is `none`, or the command carries `--deny-all-egress`. + NoNetwork, + /// The box is `host_ip` with an egress section, so it can declare no name + /// rule and the service's hosts cannot join its egress. + NoNameRules, + /// No proxy serves the box, so it cannot carry a grant. + NoProxy, + /// The grant needs the host's native secret store, and it is unusable. + NoNativeStore, + /// The steering is `dns` or `both`, and the host has no box DNS resolver. + NoResolver, +} + +impl std::fmt::Display for ServiceMisfit { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::PlainValue { layer, variable } => write!( + f, + "{layer} delivers {variable} as a plain value. Remove it there to take the \ + service from the loadout" + ), + Self::GrantDelivered { by, how, variable } => write!(f, "{by} {how} as {variable}"), + Self::NoNetwork => { + f.write_str("the box has no network, or the command carries --deny-all-egress") + } + Self::NoNameRules => f.write_str( + "a host_ip box can declare no name rule, so the service's hosts cannot join \ + its egress", + ), + Self::NoProxy => f.write_str("no proxy serves the box, so it cannot carry the grant"), + Self::NoNativeStore => f.write_str("this host cannot use its native secret store"), + Self::NoResolver => f.write_str( + "the steering is dns or both and this host has no box DNS resolver. Set \ + steering = \"proxy_env\" in a project layer to take the service", + ), + } + } +} + +/// What [`service_fits`] reads beyond the expansion's spec. +pub struct ServiceContext<'a> { + /// The expansion so far: its spec and the grants it derived. + pub expansion: &'a Expansion, + /// The variables that layers below the loadouts set as plain values, each + /// with the layer, as a message names it. + pub plain: &'a [(String, String)], + /// The layer that sets `[secrets]`, as a message names it. + pub secrets_layer: &'a str, + /// What the client knows of the host and the command. + pub facts: ServiceFacts, + /// The box's own `uses` already derived this service's grant, so no layer + /// delivering the variable is a conflict. + pub already_held: bool, +} + +/// The variable and the `[secrets]` grant that `service` derives, or `None` +/// for a service with no secret form (BEP-103). A stored secret is a store +/// reference to the item named for the service, in the host's store. A +/// module's secret is the module's broker grant at the breadth of the +/// sign-in, `github:user-token`. +#[must_use] +pub fn service_grant( + service: &boxes::core::services::Service, +) -> Option<(&'static str, toml::Table)> { + use boxes::core::services::ServiceSecret; + let variable = service.env?; + let mut grant = toml::Table::new(); + match service.secret { + ServiceSecret::Store { .. } => { + grant.insert("source".to_owned(), "store".into()); + grant.insert("store".to_owned(), boxes::core::bep::NATIVE_STORE.into()); + grant.insert("id".to_owned(), service.name.into()); + } + ServiceSecret::Module { module: "github" } => { + grant.insert("source".to_owned(), "broker".into()); + grant.insert( + "scopes".to_owned(), + toml::Value::Array(vec!["github:user-token".into()]), + ); + } + ServiceSecret::Module { .. } | ServiceSecret::None => return None, + } + Some((variable, grant)) +} + +/// Whether the box can take `service`: add its hosts and give it its secret +/// (BOX-241). The one answer for the box's own `uses` and a loadout's +/// services, in this order: +/// +/// 1. a layer below delivers the variable of its grant; +/// 2. the mode is `none`, or the command carries `--deny-all-egress`; +/// 3. it would add a name to a box that can declare no name rule; +/// 4. the host cannot carry the grant: no proxy, an unusable native store +/// that it needs, or `dns` or `both` steering with no box resolver. +/// +/// # Errors +/// +/// The first [`ServiceMisfit`] that applies. +pub fn service_fits( + service: &boxes::core::services::Service, + ctx: &ServiceContext<'_>, +) -> Result<(), ServiceMisfit> { + use boxes::core::services::ServiceSecret; + let spec = &ctx.expansion.spec; + let has_grant = !matches!(service.secret, ServiceSecret::None) && service.env.is_some(); + let variable = service.env.filter(|_| has_grant); + if let Some(variable) = variable.filter(|_| !ctx.already_held) { + if let Some((_, layer)) = ctx.plain.iter().find(|(var, _)| var == variable) { + return Err(ServiceMisfit::PlainValue { + layer: layer.clone(), + variable: variable.to_owned(), + }); + } + if let Some(grant) = spec + .get("secrets") + .and_then(toml::Value::as_table) + .and_then(|secrets| secrets.get(variable)) + { + let derived = ctx + .expansion + .derived_grants + .iter() + .any(|d| d.variable == variable && !d.declared_instead); + return Err(ServiceMisfit::GrantDelivered { + by: if derived { + "a service in network.uses".to_owned() + } else { + ctx.secrets_layer.to_owned() + }, + how: match grant.get("source").and_then(toml::Value::as_str) { + Some("client_env") => "copies it from your environment", + _ => "gives it as a sealed grant", + }, + variable: variable.to_owned(), + }); + } + } + let network = spec.get("network"); + // The spec still holds a legacy spelling here, since `canonicalize` runs + // after the expansion: read the mode, and the egress keys, as it will. + let mode = network + .and_then(|network| network.get("mode")) + .and_then(toml::Value::as_str) + .and_then(crate::network::canonical_mode); + if mode == Some("none") || ctx.facts.network_none || ctx.facts.deny_all_egress { + return Err(ServiceMisfit::NoNetwork); + } + let has_egress = network.is_some_and(|network| { + network.get("egress").is_some() + || crate::network::FLAT_EGRESS_KEYS + .iter() + .any(|(flat, _)| network.get(*flat).is_some()) + }); + if mode == Some("host_ip") && has_egress { + return Err(ServiceMisfit::NoNameRules); + } + if variable.is_some() { + if !ctx.facts.proxy_serves { + return Err(ServiceMisfit::NoProxy); + } + if matches!(service.secret, ServiceSecret::Store { .. }) && !ctx.facts.native_store_usable { + return Err(ServiceMisfit::NoNativeStore); + } + // An unset steering is `dns` (BEP-016). + let steering = network + .and_then(|network| network.get("bep")) + .and_then(|bep| bep.get("steering")) + .and_then(toml::Value::as_str); + if matches!(steering, None | Some("dns" | "both")) && !ctx.facts.box_zone_resolver { + return Err(ServiceMisfit::NoResolver); + } + } + Ok(()) +} + +/// Derives one `[secrets]` grant for each service of `network.uses` that has +/// a secret form, under the variable of its library entry (BEP-103). A +/// derived grant is a requirement as a declared one is. For a stored secret +/// it is a store reference to the item named for the service, in the host's +/// store. For a module's secret it is the module's broker grant at the +/// breadth of the sign-in, `github:user-token`. +/// +/// - A `broker` or `store` entry of the same variable is declared, and beats +/// the derived grant: none is derived, and the service still adds its hosts. +/// - A `client_env` entry of the variable is refused. +/// - A variable that `env_vars` also sets is refused (BOX-243). +/// +/// # Errors +/// +/// [`Error::DerivedGrantConflictsWithClientEnv`] and +/// [`Error::OneNameTwoDeliveries`]. Both exit 3. +fn derive_service_grants(expansion: &mut Expansion) -> Result<(), Error> { + use boxes::core::services::service; + let uses: Vec = expansion + .spec + .get("network") + .and_then(toml::Value::as_table) + .and_then(|network| network.get("uses")) + .and_then(toml::Value::as_array) + .map(|names| { + names + .iter() + .filter_map(toml::Value::as_str) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default(); + let plain_names: Vec = expansion + .spec + .get(ENV_VARS_KEY) + .and_then(toml::Value::as_table) + .map(|vars| vars.keys().cloned().collect()) + .unwrap_or_default(); + // BOX-243: one name, one delivery, for the grants the layers declare. + if let Some(secrets) = expansion + .spec + .get("secrets") + .and_then(toml::Value::as_table) + { + for (name, grant) in secrets { + if plain_names.contains(name) { + return Err(Error::OneNameTwoDeliveries { + name: name.clone(), + plain: "[env_vars]".to_owned(), + sealed: format!( + "a `{}` entry of [secrets]", + grant + .get("source") + .and_then(toml::Value::as_str) + .unwrap_or("secrets") + ), + }); + } + } + } + for name in uses { + let Some(entry) = service(&name) else { + continue; + }; + let Some((variable, grant)) = service_grant(entry) else { + continue; + }; + let declared = expansion + .spec + .get("secrets") + .and_then(toml::Value::as_table) + .and_then(|secrets| secrets.get(variable)) + .and_then(|grant| grant.get("source")) + .and_then(toml::Value::as_str) + .map(str::to_owned); + match declared.as_deref() { + Some("client_env") => { + return Err(Error::DerivedGrantConflictsWithClientEnv { + variable: variable.to_owned(), + service: name, + }); + } + Some(_) => { + expansion.derived_grants.push(DerivedGrant { + variable: variable.to_owned(), + service: name, + declared_instead: true, + }); + continue; + } + None => {} + } + if plain_names.iter().any(|plain| plain == variable) { + return Err(Error::OneNameTwoDeliveries { + name: variable.to_owned(), + plain: "[env_vars]".to_owned(), + sealed: format!("the service {name} in network.uses"), + }); + } + if let Some(secrets) = expansion + .spec + .entry("secrets".to_owned()) + .or_insert_with(|| toml::Value::Table(toml::Table::new())) + .as_table_mut() + { + secrets.insert(variable.to_owned(), toml::Value::Table(grant)); + } + // A `[secrets]` that only a service made has the origin of the `uses` + // that named it, so the report names who set it (BOX-238). + let uses_origin = expansion + .report + .network + .get("uses") + .cloned() + .unwrap_or_else(|| Origin::of(Layer::Entry)); + expansion + .report + .values + .entry("secrets".to_owned()) + .or_insert(ValueOrigin::Value(uses_origin)); + expansion.derived_grants.push(DerivedGrant { + variable: variable.to_owned(), + service: name, + declared_instead: false, + }); + } + Ok(()) +} + +/// Reads and checks a loadout's `[network]` table (BOX-239): `uses`, and +/// `egress` with `allow_dns_hosts` and `allow_subnets`, and no other key. +/// +/// # Errors +/// +/// [`Error::LoadoutNetworkKey`] and [`Error::LoadoutUnknownService`]. Both +/// exit 3 and name the loadout. +fn read_loadout_network( + loadout: &LoadoutLayer, + network: &toml::Value, +) -> Result<(LoadoutNetwork, Vec), Error> { + let file = loadout_file(&loadout.name, loadout.path.as_deref()); + let key_error = |key: &str| Error::LoadoutNetworkKey { + loadout_file: file.clone(), + key: format!("`{key}`"), + }; + let Some(network) = network.as_table() else { + return Err(key_error("network")); + }; + let mut listed = LoadoutNetwork { + loadout: loadout.name.clone(), + ..LoadoutNetwork::default() + }; + let mut uses = Vec::new(); + for (key, value) in network { + match key.as_str() { + "uses" => { + let names = value + .as_array() + .map(|items| { + items + .iter() + .map(toml::Value::as_str) + .collect::>>() + }) + .and_then(|names| names) + .ok_or_else(|| key_error("network.uses"))?; + for name in names { + if boxes::core::services::service(name).is_none() { + return Err(Error::LoadoutUnknownService { + loadout_file: file.clone(), + name: name.to_owned(), + known: boxes::core::services::service_names().join(", "), + }); + } + uses.push(name.to_owned()); + } + } + "egress" => { + let Some(egress) = value.as_table() else { + return Err(key_error("network.egress")); + }; + for (key, value) in egress { + let list = match key.as_str() { + "allow_dns_hosts" => &mut listed.allow_dns_hosts, + "allow_subnets" => &mut listed.allow_subnets, + other => return Err(key_error(&format!("network.egress.{other}"))), + }; + let items = value + .as_array() + .map(|items| { + items + .iter() + .map(|item| item.as_str().map(str::to_owned)) + .collect::>>() + }) + .and_then(|items| items) + .ok_or_else(|| key_error(&format!("network.egress.{key}")))?; + list.extend(items); + } + } + other => return Err(key_error(&format!("network.{other}"))), + } + } + Ok((listed, uses)) +} + +/// Decides, for each service that a selected loadout names, whether the box +/// takes it or leaves it out whole, with its hosts and its grant (BOX-241). +/// A service the box takes derives its grant as the box's own `uses` does +/// (BEP-103). Two loadouts that name one service give one decision. +/// +/// A service is left out where: +/// 1. a layer below the loadouts delivers the variable name of its grant, as a +/// plain value, a `client_env` entry, or a declared or derived sealed grant; +/// 2. the mode is `none`, or the command carries `--deny-all-egress`; +/// 3. it would add a name to a box that can declare no name rule; +/// 4. the host cannot carry the grant: no proxy serves the box, a native store +/// is needed and unusable, or the steering is `dns` or `both` with no box +/// resolver. +/// +/// A variable of a loadout that has the name of a grant of a layer or of any +/// loadout's service is refused first (BOX-243). +/// +/// # Errors +/// +/// [`Error::OneNameTwoDeliveries`] and [`Error::DerivedGrantConflictsWithClientEnv`]. +fn take_loadout_services( + entry: &BoxEntry, + ordered: &[(Origin, &toml::Table)], + loadouts: &[LoadoutLayer], + loadout_uses: &[(String, Vec)], + facts: ServiceFacts, + expansion: &mut Expansion, +) -> Result<(), Error> { + use boxes::core::services::{ServiceSecret, service}; + if loadout_uses.iter().all(|(_, uses)| uses.is_empty()) { + return Ok(()); + } + let grant_variable = |name: &str| { + service(name) + .filter(|entry| !matches!(entry.secret, ServiceSecret::None)) + .and_then(|entry| entry.env) + }; + // BOX-243: a variable of a loadout never has the name of a grant, even + // one that BOX-241 then leaves out. + let layer_grants: Vec = expansion + .spec + .get("secrets") + .and_then(toml::Value::as_table) + .map(|secrets| secrets.keys().cloned().collect()) + .unwrap_or_default(); + let loadout_grants: Vec<(&str, &str)> = loadout_uses + .iter() + .flat_map(|(_, uses)| uses.iter()) + .filter_map(|name| grant_variable(name).map(|variable| (variable, name.as_str()))) + .collect(); + for (origin, layer) in ordered.iter().filter(|(o, _)| o.layer == Layer::Loadouts) { + let Some(vars) = layer.get(ENV_VARS_KEY).and_then(toml::Value::as_table) else { + continue; + }; + let name_of = origin.loadout.as_deref().unwrap_or_default(); + let file = loadouts.iter().find(|l| l.name == name_of).map_or_else( + || loadout_file(name_of, None), + |l| loadout_file(&l.name, l.path.as_deref()), + ); + for var in vars.keys() { + let sealed = if layer_grants.contains(var) { + Some(format!("a grant in [secrets] named {var}")) + } else { + loadout_grants + .iter() + .find(|(variable, _)| variable == var) + .map(|(_, service)| format!("the service {service} that a loadout names")) + }; + if let Some(sealed) = sealed { + return Err(Error::OneNameTwoDeliveries { + name: var.clone(), + plain: file.clone(), + sealed, + }); + } + } + } + // What the layers below the loadouts deliver, by variable and by layer. + let layer_words = |origin: &Origin| { + let (table, file) = var_place(entry, origin, loadouts); + table.map_or(file.clone(), |table| format!("{table} in {file}")) + }; + let mut plain: Vec<(String, String)> = Vec::new(); + for (origin, layer) in ordered.iter().filter(|(o, _)| o.layer != Layer::Loadouts) { + if let Some(vars) = layer.get(ENV_VARS_KEY).and_then(toml::Value::as_table) { + plain.extend(vars.keys().map(|var| (var.clone(), layer_words(origin)))); + } + } + let secrets_layer = match expansion.report.values.get("secrets") { + Some(ValueOrigin::Value(origin)) => layer_words(origin), + _ => "a layer's [secrets]".to_owned(), + }; + let mut seen: Vec = Vec::new(); + for (loadout, uses) in loadout_uses { + for name in uses { + if seen.contains(name) { + continue; + } + seen.push(name.clone()); + let Some(entry_service) = service(name) else { + continue; + }; + let variable = grant_variable(name); + // The box's own `uses` already derived this service's grant. + let already = variable.is_some_and(|variable| { + expansion + .derived_grants + .iter() + .any(|d| d.variable == variable && d.service == *name && !d.declared_instead) + }); + let fits = service_fits( + entry_service, + &ServiceContext { + expansion, + plain: &plain, + secrets_layer: &secrets_layer, + facts, + already_held: already, + }, + ); + let left_out = fits.as_ref().err().map(ToString::to_string); + let mut grant_variable_taken = None; + if fits.is_ok() + && !already + && let Some((variable, grant)) = service_grant(entry_service) + && let Some(secrets) = expansion + .spec + .entry("secrets".to_owned()) + .or_insert_with(|| toml::Value::Table(toml::Table::new())) + .as_table_mut() + { + secrets.insert(variable.to_owned(), toml::Value::Table(grant)); + grant_variable_taken = Some(variable.to_owned()); + expansion + .report + .values + .entry("secrets".to_owned()) + .or_insert(ValueOrigin::Value(Origin::loadout(loadout))); + } + expansion.loadout_services.push(LoadoutService { + loadout: loadout.clone(), + service: name.clone(), + grant: grant_variable_taken, + left_out, + }); + } + } + Ok(()) +} + /// The path of one `[[file_exports]]` item: its `path` key, or the item /// itself when it is a bare string. `None` for an item that names no /// path. @@ -1264,7 +2012,8 @@ fn loadout_mode( /// The client sections that a project file can carry but never sets. The /// fold leaves each one out of the spec and lists it in /// [`Expansion::ignored_sections`], so the caller can warn (BOX-065). -pub const IGNORED_SECTIONS: [&str; 3] = [ +pub const IGNORED_SECTIONS: [&str; 4] = [ + "credential-rules", "loadout-file-rules", "package-file-rules", "secret-store-rules", @@ -1296,6 +2045,9 @@ fn fold(ordered: &[(Origin, &toml::Table)]) -> Expansion { spec, report, ignored_sections, + derived_grants: Vec::new(), + loadout_network: Vec::new(), + loadout_services: Vec::new(), } } @@ -2924,6 +3676,9 @@ mod tests { spec: reversed, report: first.report.clone(), ignored_sections: Vec::new(), + derived_grants: Vec::new(), + loadout_network: Vec::new(), + loadout_services: Vec::new(), }; assert_eq!(reversed.spec_bytes().expect("writes"), bytes); } @@ -3201,6 +3956,9 @@ mod tests { spec: e.spec.clone(), report: ExpansionReport::default(), ignored_sections: Vec::new(), + derived_grants: Vec::new(), + loadout_network: Vec::new(), + loadout_services: Vec::new(), }; assert_eq!(bytes, only_spec.spec_bytes().expect("writes")); for word in [ @@ -6017,4 +6775,647 @@ mod tests { "{err:?}" ); } + + // ---- BEP-103, BOX-243: the grants that `network.uses` derives ---- + + /// Expands the entry `name` of `file` with no other layers. + fn expand_uses(file: &str, name: &str) -> Result { + let Ok(entries) = crate::entry::read_entries(file.as_bytes()) else { + return Err(Error::NotFound); + }; + let entry = entries + .iter() + .find(|e| e.name == name) + .ok_or(Error::NotFound)?; + let layers = Layers::default().with_file_defaults( + &toml::Table::new(), + entry.box_type.as_deref(), + &std::collections::BTreeSet::new(), + ); + expand(entry, &layers) + } + + #[test] + fn uses_derives_one_grant_per_service_secret() { + let e = expand_uses( + "[sessions.dev]\nnetwork = { mode = \"own_ip\", uses = [\"github\", \ + \"anthropic-oauth-token\", \"claude-code\"] }\n", + "dev", + ) + .unwrap(); + let secrets = e.spec["secrets"].as_table().unwrap(); + // A module's secret is the sign-in's grant, and a stored secret is a + // reference to the item named for the service. A hosts-only service + // derives none. + assert_eq!( + secrets["GH_TOKEN"], + toml::Value::try_from(toml::toml! { + source = "broker" + scopes = ["github:user-token"] + }) + .unwrap() + ); + assert_eq!( + secrets["CLAUDE_CODE_OAUTH_TOKEN"], + toml::Value::try_from(toml::toml! { + source = "store" + store = "keychain" + id = "anthropic-oauth-token" + }) + .unwrap() + ); + assert_eq!(secrets.len(), 2, "{secrets:?}"); + assert_eq!( + e.derived_grants + .iter() + .map(|g| (g.variable.as_str(), g.service.as_str(), g.declared_instead)) + .collect::>(), + [ + ("GH_TOKEN", "github", false), + ("CLAUDE_CODE_OAUTH_TOKEN", "anthropic-oauth-token", false) + ] + ); + // A service sets no key of `network` but its hosts and grant. + assert_eq!(e.spec["network"]["mode"].as_str(), Some("own_ip")); + assert_eq!(e.spec["network"].as_table().unwrap().len(), 2); + } + + #[test] + fn declared_grant_beats_derived_grant() { + let e = expand_uses( + "[sessions.dev]\nnetwork = { mode = \"own_ip\", uses = [\"github\"] }\n\ + [sessions.dev.secrets.GH_TOKEN]\nsource = \"broker\"\n\ + scopes = [\"github:repo:acme/app:contents:ro\"]\n", + "dev", + ) + .unwrap(); + // The narrowed declared grant stays, and the service derives none. + assert_eq!( + e.spec["secrets"]["GH_TOKEN"]["scopes"], + toml::Value::Array(vec!["github:repo:acme/app:contents:ro".into()]) + ); + assert_eq!( + e.derived_grants, + [DerivedGrant { + variable: "GH_TOKEN".into(), + service: "github".into(), + declared_instead: true + }] + ); + // The service still adds its hosts: `uses` stays in the spec for the + // client to resolve. + assert!(e.spec["network"]["uses"].as_array().is_some()); + } + + #[test] + fn derived_grant_conflicts_with_client_env_of_same_name() { + let err = expand_uses( + "[sessions.dev]\nnetwork = { mode = \"own_ip\", uses = [\"github\"] }\n\ + [sessions.dev.secrets.GH_TOKEN]\nsource = \"client_env\"\n", + "dev", + ) + .expect_err("refused"); + assert_eq!(err.exit_code(), Some(3)); + let text = err.to_string(); + assert!( + text.contains("GH_TOKEN") && text.contains("github"), + "{text}" + ); + } + + #[test] + fn one_name_two_deliveries_refused_exit3() { + // A declared grant and a plain value of one name. + let err = expand_uses( + "[sessions.dev]\nnetwork = { mode = \"own_ip\", uses = [\"github\"] }\n\ + [sessions.dev.secrets.TOKEN]\nsource = \"broker\"\n\ + scopes = [\"github:user-token\"]\n\ + [sessions.dev.env_vars]\nTOKEN = \"plain\"\n", + "dev", + ) + .expect_err("refused"); + assert_eq!(err.exit_code(), Some(3)); + let text = err.to_string(); + assert!( + text.contains("TOKEN") && text.contains("[env_vars]"), + "{text}" + ); + // A derived grant and a plain value of its variable. + let err = expand_uses( + "[sessions.dev]\nnetwork = { mode = \"own_ip\", uses = [\"github\"] }\n\ + [sessions.dev.env_vars]\nGH_TOKEN = \"plain\"\n", + "dev", + ) + .expect_err("refused"); + assert_eq!(err.exit_code(), Some(3)); + assert!(err.to_string().contains("the service github"), "{err}"); + } + + #[test] + fn declared_sealed_grant_beats_derived_one() { + // Two sealed grants of one name: the declared one stays and the + // report says so. + let e = expand_uses( + "[sessions.dev]\nnetwork = { mode = \"own_ip\", uses = [\"anthropic-oauth-token\"] }\n\ + [sessions.dev.secrets.CLAUDE_CODE_OAUTH_TOKEN]\nsource = \"store\"\n\ + store = \"keychain\"\nid = \"claude\"\n", + "dev", + ) + .unwrap(); + assert_eq!( + e.spec["secrets"]["CLAUDE_CODE_OAUTH_TOKEN"]["id"].as_str(), + Some("claude") + ); + assert!(e.derived_grants.iter().all(|g| g.declared_instead)); + } + + // ---- BOX-239 to BOX-241, BOX-243: a loadout's `[network]` table ---- + + fn loadout(name: &str, body: &str) -> LoadoutLayer { + LoadoutLayer::new(name, body.parse::().expect("loadout parses")) + } + + /// Expands the entry `dev` of `file` with `loadouts` selected. + fn expand_with_loadouts( + file: &str, + loadouts: Vec, + facts: ServiceFacts, + ) -> Result { + let Ok(entries) = crate::entry::read_entries(file.as_bytes()) else { + return Err(Error::NotFound); + }; + let entry = entries + .iter() + .find(|e| e.name == "dev") + .ok_or(Error::NotFound)?; + let mut layers = Layers::default().with_file_defaults( + &toml::Table::new(), + entry.box_type.as_deref(), + &std::collections::BTreeSet::new(), + ); + layers.loadouts = loadouts; + layers.service_facts = facts; + expand(entry, &layers) + } + + const OPEN_BOX: &str = "[sessions.dev]\nloadout_mode = \"open\"\n\ + network = { mode = \"own_ip\" }\n"; + + #[test] + fn loadout_network_table_holds_uses_and_two_egress_lists() { + let e = expand_with_loadouts( + OPEN_BOX, + vec![loadout( + "claude", + "[network]\nuses = [\"claude-code\"]\n[network.egress]\n\ + allow_dns_hosts = [\"a.example\"]\nallow_subnets = [\"10.0.0.0/8\"]\n", + )], + ServiceFacts::default(), + ) + .unwrap(); + assert_eq!( + e.loadout_network, + [LoadoutNetwork { + loadout: "claude".into(), + allow_dns_hosts: vec!["a.example".into()], + allow_subnets: vec!["10.0.0.0/8".into()], + }] + ); + // The table is no key of a layer: the spec holds none of it. + assert_eq!(e.spec["network"]["mode"].as_str(), Some("own_ip")); + assert!(e.spec["network"].get("egress").is_none()); + assert!(e.spec["network"].get("uses").is_none()); + } + + #[test] + fn loadout_network_other_key_refused_exit3() { + for (body, key) in [ + ("[network]\nmode = \"none\"\n", "network.mode"), + ("[network]\ningress = []\n", "network.ingress"), + ("[network.bep]\nsteering = \"dns\"\n", "network.bep"), + ( + "[network.egress]\nallow_protocols = [\"tcp\"]\n", + "network.egress.allow_protocols", + ), + ( + "[network.egress]\ndeny_subnets = [\"10.0.0.0/8\"]\n", + "network.egress.deny_subnets", + ), + ] { + let err = expand_with_loadouts( + OPEN_BOX, + vec![loadout("claude", body)], + ServiceFacts::default(), + ) + .expect_err(key); + assert_eq!(err.exit_code(), Some(3), "{key}"); + let text = err.to_string(); + assert!(text.contains("the loadout `claude`"), "{text}"); + assert!(text.contains(key), "{text}"); + } + } + + #[test] + fn loadout_unknown_service_refused_exit3() { + let err = expand_with_loadouts( + OPEN_BOX, + vec![loadout("claude", "[network]\nuses = [\"openai\"]\n")], + ServiceFacts::default(), + ) + .expect_err("unknown"); + assert_eq!(err.exit_code(), Some(3)); + let text = err.to_string(); + assert!( + text.contains("the loadout `claude`") && text.contains("openai"), + "{text}" + ); + assert!(text.contains("github"), "{text}"); + } + + #[test] + fn non_open_loadout_mode_ignores_loadout_network() { + // A sealed box applies no loadout, so even a loadout whose table + // would be refused is not read. + let e = expand_with_loadouts( + "[sessions.dev]\nloadout_mode = \"sealed\"\nnetwork = { mode = \"own_ip\" }\n", + vec![loadout( + "claude", + "[network]\nmode = \"none\"\nuses = [\"github\"]\n", + )], + ServiceFacts::default(), + ) + .unwrap(); + assert!(e.loadout_network.is_empty()); + assert!(e.loadout_services.is_empty()); + assert!(e.spec.get("secrets").is_none()); + } + + #[test] + fn loadout_service_resolves_like_box_uses_or_is_left_out() { + let claude = || { + loadout( + "claude", + "[network]\nuses = [\"anthropic-oauth-token\", \"claude-code\"]\n", + ) + }; + // Taken: the grant is derived as the box's own `uses` derives it, and + // a hosts-only service derives none. + let e = expand_with_loadouts(OPEN_BOX, vec![claude()], ServiceFacts::default()).unwrap(); + assert_eq!( + e.spec["secrets"]["CLAUDE_CODE_OAUTH_TOKEN"]["id"].as_str(), + Some("anthropic-oauth-token") + ); + let summary: Vec<_> = e + .loadout_services + .iter() + .map(|s| (s.service.as_str(), s.grant.as_deref(), s.left_out.is_some())) + .collect(); + assert_eq!( + summary, + [ + ( + "anthropic-oauth-token", + Some("CLAUDE_CODE_OAUTH_TOKEN"), + false + ), + ("claude-code", None, false) + ] + ); + // Left out whole where the mode is none, or --deny-all-egress. + let none = "[sessions.dev]\nloadout_mode = \"open\"\nnetwork = { mode = \"none\" }\n"; + let e = expand_with_loadouts(none, vec![claude()], ServiceFacts::default()).unwrap(); + assert!(e.spec.get("secrets").is_none()); + assert!(e.loadout_services.iter().all(|s| s.left_out.is_some())); + let deny = ServiceFacts { + deny_all_egress: true, + ..ServiceFacts::default() + }; + let e = expand_with_loadouts(OPEN_BOX, vec![claude()], deny).unwrap(); + assert!(e.spec.get("secrets").is_none()); + assert!(e.loadout_services.iter().all(|s| s.left_out.is_some())); + } + + #[test] + fn loadout_grant_yields_to_layer_that_delivers_the_name() { + let claude = || loadout("claude", "[network]\nuses = [\"anthropic-oauth-token\"]\n"); + for (file, how) in [ + ( + "[sessions.dev]\nloadout_mode = \"open\"\nnetwork = { mode = \"own_ip\" }\n\ + [sessions.dev.env_vars]\nCLAUDE_CODE_OAUTH_TOKEN = \"plain\"\n", + "plain value", + ), + ( + "[sessions.dev]\nloadout_mode = \"open\"\nnetwork = { mode = \"own_ip\" }\n\ + [sessions.dev.secrets.CLAUDE_CODE_OAUTH_TOKEN]\nsource = \"client_env\"\n", + "your environment", + ), + ( + "[sessions.dev]\nloadout_mode = \"open\"\nnetwork = { mode = \"own_ip\" }\n\ + [sessions.dev.secrets.CLAUDE_CODE_OAUTH_TOKEN]\nsource = \"store\"\n\ + store = \"keychain\"\nid = \"mine\"\n", + "sealed grant", + ), + ] { + let e = expand_with_loadouts(file, vec![claude()], ServiceFacts::default()).unwrap(); + let left = e.loadout_services[0].left_out.as_deref().expect("left out"); + assert!(left.contains(how), "{left}"); + assert!(left.contains("[sessions.dev]"), "names the layer: {left}"); + // The layer's own value stands. + assert_ne!( + e.spec + .get("secrets") + .and_then(|s| s.get("CLAUDE_CODE_OAUTH_TOKEN")) + .and_then(|g| g.get("id")) + .and_then(toml::Value::as_str), + Some("anthropic-oauth-token") + ); + } + } + + #[test] + fn loadout_service_left_out_where_host_cannot_carry_grant() { + let claude = || loadout("claude", "[network]\nuses = [\"anthropic-oauth-token\"]\n"); + for facts in [ + ServiceFacts { + proxy_serves: false, + ..ServiceFacts::default() + }, + ServiceFacts { + native_store_usable: false, + ..ServiceFacts::default() + }, + ] { + let e = expand_with_loadouts(OPEN_BOX, vec![claude()], facts).unwrap(); + assert!(e.loadout_services[0].left_out.is_some(), "{facts:?}"); + assert!(e.spec.get("secrets").is_none()); + } + // `dns` steering with no box resolver. + let dns = "[sessions.dev]\nloadout_mode = \"open\"\n\ + network = { mode = \"own_ip\", bep = { steering = \"dns\" } }\n"; + let facts = ServiceFacts { + box_zone_resolver: false, + ..ServiceFacts::default() + }; + let e = expand_with_loadouts(dns, vec![claude()], facts).unwrap(); + let left = e.loadout_services[0].left_out.as_deref().expect("left out"); + assert!(left.contains("proxy_env"), "{left}"); + // A hosts-only service needs no grant, so the same host takes it. + let hosts = loadout("h", "[network]\nuses = [\"claude-code\"]\n"); + let e = expand_with_loadouts(dns, vec![hosts], facts).unwrap(); + assert!(e.loadout_services[0].left_out.is_none()); + } + + #[test] + fn loadout_service_left_out_for_box_without_name_rules() { + let host_ip = "[sessions.dev]\nloadout_mode = \"open\"\n\ + network = { mode = \"host_ip\", egress = { allow_dns_hosts = [\"a.example\"] } }\n"; + let e = expand_with_loadouts( + host_ip, + vec![loadout("claude", "[network]\nuses = [\"claude-code\"]\n")], + ServiceFacts::default(), + ) + .unwrap(); + let left = e.loadout_services[0].left_out.as_deref().expect("left out"); + assert!(left.contains("no name rule"), "{left}"); + } + + #[test] + fn two_loadouts_naming_one_service_give_one_grant() { + let uses = "[network]\nuses = [\"anthropic-oauth-token\"]\n"; + let e = expand_with_loadouts( + OPEN_BOX, + vec![loadout("a", uses), loadout("b", uses)], + ServiceFacts::default(), + ) + .unwrap(); + assert_eq!(e.loadout_services.len(), 1); + assert_eq!(e.spec["secrets"].as_table().unwrap().len(), 1); + } + + #[test] + fn loadout_variable_named_like_grant_refused_exit3() { + // A variable of a loadout named like a grant of a layer. + let err = expand_with_loadouts( + "[sessions.dev]\nloadout_mode = \"open\"\nnetwork = { mode = \"own_ip\" }\n\ + [sessions.dev.secrets.TOKEN]\nsource = \"client_env\"\n", + vec![loadout("l", "[env_vars]\nTOKEN = \"x\"\n")], + ServiceFacts::default(), + ) + .expect_err("refused"); + assert_eq!(err.exit_code(), Some(3)); + // Or like the grant of any loadout's service, even one that would be + // left out. + let none = "[sessions.dev]\nloadout_mode = \"open\"\nnetwork = { mode = \"none\" }\n"; + let err = expand_with_loadouts( + none, + vec![ + loadout("a", "[network]\nuses = [\"github\"]\n"), + loadout("b", "[env_vars]\nGH_TOKEN = \"x\"\n"), + ], + ServiceFacts::default(), + ) + .expect_err("refused"); + assert_eq!(err.exit_code(), Some(3)); + assert!(err.to_string().contains("GH_TOKEN"), "{err}"); + } + + // ---- BOX-238: the principal of each value ---- + + #[test] + fn expansion_reports_principal_per_value_outside_spec_bytes() { + let root = std::path::Path::new("/work/app"); + let e = expand_with_loadouts( + "[sessions.dev]\nloadout_mode = \"open\"\npackages = [\"git\"]\n\ + network = { mode = \"own_ip\" }\n", + vec![loadout("tool", "[env_vars]\nFROM_TOOL = \"1\"\n")], + ServiceFacts::default(), + ) + .unwrap(); + let principals = e.report.principals(root); + // The project by its root, and the loadout by its name. + assert_eq!( + principals["packages"], + [Principal::Project(root.to_path_buf())] + ); + assert_eq!( + principals["env_vars.FROM_TOOL"], + [Principal::Loadout("tool".into())] + ); + assert_eq!( + principals["network.mode"], + [Principal::Project(root.to_path_buf())] + ); + // The root is host-specific and is never in the spec's bytes. + let bytes = e.spec_bytes().unwrap(); + assert!(!bytes.contains("/work/app"), "{bytes}"); + } + + #[test] + fn expansion_reports_no_principal_for_upstream_and_builtin_type_defaults() { + let root = std::path::Path::new("/work/app"); + let upstream = Origin::of(Layer::Upstream); + assert_eq!(upstream.principal(root), None); + assert_eq!(Origin::type_defaults("session").principal(root), None); + // A type the project declares is the project's. + assert_eq!( + Origin::type_defaults("mine").principal(root), + Some(Principal::Project(root.to_path_buf())) + ); + // A command-line flag is no project and no loadout. + assert_eq!(Origin::of(Layer::Overrides).principal(root), None); + } + + // ---- the shared answer to "can this box take this service" ---- + + #[test] + fn box_uses_and_loadout_derive_the_same_grant() { + // One grant-building function: the box's own `uses` and a loadout + // give each service the same grant under the same variable. + for service in boxes::core::services::SERVICE_LIBRARY { + let by_box = expand_uses( + &format!( + "[sessions.dev]\nnetwork = {{ mode = \"own_ip\", uses = [{:?}] }}\n", + service.name + ), + "dev", + ) + .unwrap(); + let by_loadout = expand_with_loadouts( + OPEN_BOX, + vec![loadout( + "l", + &format!("[network]\nuses = [{:?}]\n", service.name), + )], + ServiceFacts::default(), + ) + .unwrap(); + assert_eq!( + by_box.spec.get("secrets"), + by_loadout.spec.get("secrets"), + "{}", + service.name + ); + assert_eq!( + service_grant(service), + by_box + .spec + .get("secrets") + .and_then(toml::Value::as_table) + .and_then(|secrets| secrets.iter().next()) + .and_then(|(variable, grant)| { + let variable = service.env.filter(|env| env == variable)?; + Some((variable, grant.as_table()?.clone())) + }), + "{}", + service.name + ); + } + } + + #[test] + fn service_fits_names_the_first_reason_that_applies() { + let spec = |mode: &str| { + let mut e = expand_uses( + &format!("[sessions.dev]\nnetwork = {{ mode = {mode:?} }}\n"), + "dev", + ) + .unwrap(); + e.spec.entry("x").or_insert(toml::Value::Boolean(true)); + e + }; + let fits = |e: &Expansion, name: &str, facts: ServiceFacts| { + service_fits( + boxes::core::services::service(name).unwrap(), + &ServiceContext { + expansion: e, + plain: &[], + secrets_layer: "[sessions.dev]", + facts, + already_held: false, + }, + ) + }; + let own_ip = spec("own_ip"); + assert_eq!( + fits(&own_ip, "anthropic-oauth-token", ServiceFacts::default()), + Ok(()) + ); + assert_eq!( + fits(&spec("none"), "claude-code", ServiceFacts::default()), + Err(ServiceMisfit::NoNetwork) + ); + let no_proxy = ServiceFacts { + proxy_serves: false, + ..ServiceFacts::default() + }; + assert_eq!( + fits(&own_ip, "anthropic-oauth-token", no_proxy), + Err(ServiceMisfit::NoProxy) + ); + // A service with no grant needs no proxy. + assert_eq!(fits(&own_ip, "claude-code", no_proxy), Ok(())); + // The mode comes before the host's facts. + assert_eq!( + fits(&spec("none"), "anthropic-oauth-token", no_proxy), + Err(ServiceMisfit::NoNetwork) + ); + } + + // BOX-241: the legacy spellings of a mode and of the egress keys, and a + // command-line `--network none`, are the same boxes as their current forms. + #[test] + fn service_fits_reads_legacy_spellings_and_the_network_flag() { + let claude = || loadout("claude", "[network]\nuses = [\"claude-code\"]\n"); + let left = |file: &str, facts: ServiceFacts| { + expand_with_loadouts(file, vec![claude()], facts) + .unwrap() + .loadout_services[0] + .left_out + .clone() + }; + // `no-net` is `none`. + let no_net = "[sessions.dev]\nloadout_mode = \"open\"\nnetwork = { mode = \"no-net\" }\n"; + assert!(left(no_net, ServiceFacts::default()).is_some()); + // A flat egress key is an egress section, so a host_ip box has no name rule. + let flat = "[sessions.dev]\nloadout_mode = \"open\"\n\ + network = { mode = \"host-net\", egress_allow_dns = [\"a.example\"] }\n"; + let reason = left(flat, ServiceFacts::default()).expect("left out"); + assert!(reason.contains("no name rule"), "{reason}"); + // `--network none` over a project that declares `own_ip`. + let flagged = ServiceFacts { + network_none: true, + ..ServiceFacts::default() + }; + assert!(left(OPEN_BOX, flagged).is_some()); + assert!(left(OPEN_BOX, ServiceFacts::default()).is_none()); + } + + #[test] + fn generated_grants_have_an_origin_in_the_report() { + let root = std::path::Path::new("/work/app"); + // A `[secrets]` that only the box's own `uses` made is the project's. + let e = expand_uses( + "[sessions.dev]\nnetwork = { mode = \"own_ip\", uses = [\"github\"] }\n", + "dev", + ) + .unwrap(); + assert_eq!( + e.report.principals(root)["secrets"], + [Principal::Project(root.to_path_buf())] + ); + // One that only a loadout's service made is the loadout's. + let e = expand_with_loadouts( + OPEN_BOX, + vec![loadout( + "tool", + "[network]\nuses = [\"anthropic-oauth-token\"]\n", + )], + ServiceFacts::default(), + ) + .unwrap(); + assert_eq!( + e.report.principals(root)["secrets"], + [Principal::Loadout("tool".into())] + ); + } } diff --git a/crates/mfile/src/lib.rs b/crates/mfile/src/lib.rs index b85f5d7776..485d283432 100644 --- a/crates/mfile/src/lib.rs +++ b/crates/mfile/src/lib.rs @@ -2917,6 +2917,14 @@ impl File { if self.extra.contains_key(boxes::core::bep::STORE_RULES_TABLE) { warn(boxes::core::bep::PROJECT_STORE_RULES_IGNORED.to_owned()); } + // BEP-106: a project cannot approve its own credential. The + // table is ignored with its own warning. + if self + .extra + .contains_key(boxes::credential_rules::CREDENTIAL_RULES_TABLE) + { + warn(boxes::credential_rules::PROJECT_CREDENTIAL_RULES_IGNORED.to_owned()); + } // NET-159: a project cannot open host ports to its boxes. The // table is ignored with its own warning, as the store rules are. if self @@ -2930,6 +2938,7 @@ impl File { keys.sort_unstable(); for key in keys.into_iter().filter(|key| { key.as_str() != boxes::core::bep::STORE_RULES_TABLE + && key.as_str() != boxes::credential_rules::CREDENTIAL_RULES_TABLE && key.as_str() != boxes::core::egress::HOST_EXPOSURES_TABLE // The entry tables and the project's Box Types are read // by `entry` and `expand`, not by this struct. @@ -5722,6 +5731,25 @@ mod tests { } } + /// BEP-106: a project's `[credential-rules]` table is ignored with its + /// own warning, not the generic unknown-field one. + #[test] + fn project_credential_rules_ignored_with_warning() { + let dir = tempdir().unwrap(); + std::fs::write( + dir.path().join(MFILE_NAME), + "[credential-rules]\nrules = [{ credential = { source = \"client_env\", name = \"X\" }, action = \"ask\" }]\n", + ) + .unwrap(); + let capture = Diags::of(&File::from_dir(dir.path()).expect("the file still reads")); + let out = capture.contents(); + assert!( + out.contains(boxes::credential_rules::PROJECT_CREDENTIAL_RULES_IGNORED), + "{out}" + ); + assert_eq!(count_unknown_warnings(&capture), 0, "{out}"); + } + /// BEP-037: a project's `[secret-store-rules]` table, at the top level /// or under `[session]`, is ignored with its own warning, not the /// generic unknown-field one. diff --git a/crates/mfile/src/spec.rs b/crates/mfile/src/spec.rs index 44796dc02f..1ff2846385 100644 --- a/crates/mfile/src/spec.rs +++ b/crates/mfile/src/spec.rs @@ -1511,6 +1511,9 @@ pub fn ignored_section_warning(section: &str) -> String { if section == boxes::core::bep::STORE_RULES_TABLE { return boxes::core::bep::PROJECT_STORE_RULES_IGNORED.to_owned(); } + if section == boxes::credential_rules::CREDENTIAL_RULES_TABLE { + return boxes::credential_rules::PROJECT_CREDENTIAL_RULES_IGNORED.to_owned(); + } format!( "minimal.toml has a [{section}] table. A project cannot set {section}, \ so the table is ignored. Put the rules in your own config.toml instead. \ diff --git a/crates/minimal/src/client_file.rs b/crates/minimal/src/client_file.rs new file mode 100644 index 0000000000..afb15af4e7 --- /dev/null +++ b/crates/minimal/src/client_file.rs @@ -0,0 +1,819 @@ +//! The one rule for writing a client file (spec 33, CFW-001 to CFW-014). +//! +//! A client file is `config.toml`, `user_policy.toml`, or the Cedar policy +//! file that replaces it. Every writer of such a file goes through +//! [`replace`], so a new writer cannot leave the rule out. The rule: +//! +//! - Test first whether the file can be replaced ([`can_replace`]). A write is +//! one rename, and a rename ignores the permissions of the file it replaces, +//! so a read-only file would be replaced without the test. +//! - Write through a symlink, to the file it names, and keep the link. +//! - Tell the two failures apart. [`WriteError::Unwritable`] is a supported +//! setup (a read-only file, as Nix leaves it). [`WriteError::Failed`] is a +//! write that went wrong, such as a full disk. +//! - Print the path, the reason and the lines to add or to remove +//! ([`Report`]), on standard error, and after the attach ends when the +//! command attaches a shell ([`defer`], [`flush_deferred`]). + +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use nix::unistd::{AccessFlags, access}; + +/// Why a client file was not written. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum WriteError { + /// `min` cannot replace the file (CFW-001). The file is unchanged. This + /// is a supported setup, not a failure of the command (CFW-003). + Unwritable { + /// The path the person knows the file by. + path: PathBuf, + /// What the permission test found. + reason: String, + }, + /// The write was tried and failed (CFW-006), or the file could not be + /// read to change it. The file keeps the content it had (CFW-009). + Failed { + /// The path the person knows the file by. + path: PathBuf, + /// The cause, as the operating system reports it. + cause: String, + }, +} + +impl WriteError { + /// The path of the file that was not written. + #[must_use] + pub fn path(&self) -> &Path { + match self { + Self::Unwritable { path, .. } | Self::Failed { path, .. } => path, + } + } + + /// Whether the file is one `min` cannot replace (CFW-003), as opposed to + /// a write that failed (CFW-008). + #[must_use] + pub fn is_unwritable(&self) -> bool { + matches!(self, Self::Unwritable { .. }) + } + + /// The reason or the cause, in the words the person reads. + #[must_use] + pub fn why(&self) -> &str { + match self { + Self::Unwritable { reason, .. } => reason, + Self::Failed { cause, .. } => cause, + } + } +} + +impl std::fmt::Display for WriteError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Unwritable { path, reason } => { + write!(f, "`{}` was not changed: {reason}", path.display()) + } + Self::Failed { path, cause } => { + write!(f, "write `{}` failed: {cause}", path.display()) + } + } + } +} + +impl std::error::Error for WriteError {} + +/// The file a write to `path` changes: the target when `path` is a symlink +/// (CFW-010), so the rename keeps the link. A dangling link resolves to the +/// path it names. +#[must_use] +pub fn target_of(path: &Path) -> PathBuf { + // A link that resolves all the way gives the file it ends at. + if std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_symlink()) + && let Ok(real) = std::fs::canonicalize(path) + { + return real; + } + // A link to a file that does not exist yet: follow every hop, up to a + // bound, so the write creates the file the last link names. A path that + // is no link, or a chain that runs out of bound, is returned as it + // stands; [`replace`] refuses the second, and never replaces a link. + let mut current = path.to_path_buf(); + for _ in 0..MAX_LINK_HOPS { + let is_link = + std::fs::symlink_metadata(¤t).is_ok_and(|meta| meta.file_type().is_symlink()); + if !is_link { + return current; + } + let Ok(link) = std::fs::read_link(¤t) else { + return current; + }; + current = match current.parent() { + Some(dir) => dir.join(link), + None => link, + }; + } + current +} + +/// How many links [`target_of`] follows before it stops. +const MAX_LINK_HOPS: usize = 40; + +/// The folder a file at `path` is created in. A bare file name lives in the +/// current directory. +fn folder_of(path: &Path) -> &Path { + match path.parent() { + Some(dir) if !dir.as_os_str().is_empty() => dir, + _ => Path::new("."), + } +} + +/// The test of CFW-001, on `path` as the person knows it. +/// +/// `min` can replace a client file when the file, or the target of a symlink +/// at its path, allows the person to write it, and the folder of the file +/// `min` writes allows the person to create a file. A missing folder is +/// created, so the nearest existing folder above it must allow the person to +/// create a folder. A file that does not exist needs only the folder test. +/// +/// The test asks the kernel what `open(..., O_WRONLY)` would answer +/// (`access(2)`), not what the mode bits suggest: a root-owned file with mode +/// 0644 is not writable for another user. The test passes for root on a file +/// with mode 0444 outside a read-only filesystem, as the spec's Generality +/// note says. +/// +/// # Errors +/// +/// [`WriteError::Unwritable`] naming `path` and the reason. +pub fn can_replace(path: &Path) -> Result<(), WriteError> { + let unwritable = |reason: String| WriteError::Unwritable { + path: path.to_path_buf(), + reason, + }; + let target = target_of(path); + match std::fs::metadata(&target) { + Ok(meta) if meta.is_dir() => { + return Err(unwritable("it is a folder, not a file".to_string())); + } + Ok(_) => { + if access(&target, AccessFlags::W_OK).is_err() { + return Err(unwritable(if target == path { + "the file is read-only".to_string() + } else { + format!("the file is read-only: it links to `{}`", target.display()) + })); + } + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(unwritable(format!("the file cannot be read: {e}"))), + } + let folder = folder_of(&target); + match std::fs::metadata(folder) { + Ok(meta) if meta.is_dir() => { + if access(folder, AccessFlags::W_OK | AccessFlags::X_OK).is_err() { + return Err(unwritable(format!( + "the folder `{}` does not allow a new file in it", + folder.display() + ))); + } + } + Ok(_) => { + return Err(unwritable(format!( + "`{}` is not a folder", + folder.display() + ))); + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + // The write creates the folder, so the nearest folder that + // exists must let a folder be created in it. + let mut nearest = folder.parent(); + while let Some(dir) = nearest { + let probe = if dir.as_os_str().is_empty() { + Path::new(".") + } else { + dir + }; + match std::fs::metadata(probe) { + Ok(meta) if meta.is_dir() => { + if access(probe, AccessFlags::W_OK | AccessFlags::X_OK).is_err() { + return Err(unwritable(format!( + "the folder `{}` does not allow a new folder in it", + probe.display() + ))); + } + return Ok(()); + } + Ok(_) => { + return Err(unwritable(format!("`{}` is not a folder", probe.display()))); + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => nearest = dir.parent(), + Err(e) => return Err(unwritable(format!("`{}`: {e}", probe.display()))), + } + } + return Err(unwritable("no folder above it exists".to_string())); + } + Err(e) => return Err(unwritable(format!("`{}`: {e}", folder.display()))), + } + Ok(()) +} + +/// Replace the client file at `path` with `bytes` in one rename (CFW-001, +/// CFW-009, CFW-010). A file that [`can_replace`] refuses stays as it is. +/// +/// The write goes to the target of a symlink and keeps the link. The new file +/// keeps the mode of the one it replaces. A missing folder is created. +/// +/// # Errors +/// +/// [`WriteError::Unwritable`] when the file cannot be replaced, and +/// [`WriteError::Failed`] when the write fails. Both leave the file as it was. +pub fn replace(path: &Path, bytes: &[u8]) -> Result<(), WriteError> { + can_replace(path)?; + let failed = |cause: String| WriteError::Failed { + path: path.to_path_buf(), + cause, + }; + let target = target_of(path); + // CFW-010: a write goes to the file at the end of a link and keeps the + // link. A chain too long to follow ends on a link, and replacing it would + // drop the link, so it is refused. + if std::fs::symlink_metadata(&target).is_ok_and(|meta| meta.file_type().is_symlink()) { + return Err(failed(format!( + "it is a chain of more than {MAX_LINK_HOPS} links, and min cannot tell which file \ + it names" + ))); + } + let folder = folder_of(&target); + std::fs::create_dir_all(folder) + .map_err(|e| failed(format!("create the folder `{}`: {e}", folder.display())))?; + let mut tmp = tempfile::NamedTempFile::new_in(folder).map_err(|e| failed(e.to_string()))?; + if let Ok(meta) = std::fs::metadata(&target) { + // Keep the old file's mode. A failure leaves the default mode. + if let Err(e) = tmp.as_file().set_permissions(meta.permissions()) { + tracing::debug!(file = %target.display(), error = %e, "mode of the old client file not kept"); + } + } + tmp.write_all(bytes) + .and_then(|()| tmp.as_file().sync_all()) + .map_err(|e| failed(e.to_string()))?; + tmp.persist(&target) + .map_err(|e| failed(e.error.to_string()))?; + Ok(()) +} + +/// The backup of the client file at `path`, `.bak` beside it (CFW-013). +#[must_use] +pub fn backup_path(path: &Path) -> PathBuf { + let mut name = path + .file_name() + .map_or_else(|| "client-file".into(), std::ffi::OsStr::to_os_string); + name.push(".bak"); + path.with_file_name(name) +} + +/// Copy the client file at `path` to its backup through a temporary file and a +/// rename, so a copy that fails leaves the earlier backup as it was +/// (CFW-013). A file that does not exist has nothing to back up. +/// +/// The backup is not a client file, so a failure is not a [`WriteError`] +/// with lines to add. The caller still saves the client file (CFW-014). +/// +/// # Errors +/// +/// The reason the backup was not written, naming the backup. +pub fn write_backup(path: &Path) -> Result<(), String> { + let target = target_of(path); + let bytes = match std::fs::read(&target) { + Ok(bytes) => bytes, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(e) => return Err(format!("read `{}`: {e}", target.display())), + }; + let bak = backup_path(path); + let folder = folder_of(&bak); + let write = || -> std::io::Result<()> { + let mut tmp = tempfile::NamedTempFile::new_in(folder)?; + tmp.write_all(&bytes)?; + tmp.as_file().sync_all()?; + tmp.persist(&bak).map_err(|e| e.error)?; + Ok(()) + }; + write().map_err(|e| format!("write the backup `{}`: {e}", bak.display())) +} + +/// Whether the lines of a [`Report`] are added to the file or taken out of it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Edit { + /// The person adds the lines (CFW-004, CFW-007). + Add, + /// The person removes the lines, as after `min secret rm` (BEP-053). + Remove, +} + +/// What the person reads when a client file was not written (CFW-004, +/// CFW-007). It never holds a secret value (CFW-005): the caller builds +/// `lines` from the fields of a rule. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Report { + /// Why the file was not written. + pub error: WriteError, + /// Whether the lines are added or removed. + pub edit: Edit, + /// The lines to add or to remove, one per element. + pub lines: Vec, + /// When the file already has an entry for the same item (CFW-011), what + /// the new lines replace, in words, such as `the [secret-store-rules.foo] + /// section`. + pub replaces: Option, +} + +impl Report { + /// A report for `error`, with `lines` to add. + #[must_use] + pub fn add(error: WriteError, lines: Vec) -> Self { + Self { + error, + edit: Edit::Add, + lines, + replaces: None, + } + } + + /// A report for `error`, with `lines` to remove. + #[must_use] + pub fn remove(error: WriteError, lines: Vec) -> Self { + Self { + error, + edit: Edit::Remove, + lines, + replaces: None, + } + } + + /// Say which existing entry the lines replace (CFW-011). + #[must_use] + pub fn replacing(mut self, existing: impl Into) -> Self { + self.replaces = Some(existing.into()); + self + } + + /// The text for standard error: the path, why the file did not change, + /// and the lines. + #[must_use] + pub fn render(&self) -> String { + let path = self.error.path().display(); + let mut text = match &self.error { + WriteError::Unwritable { reason, .. } => { + format!("`{path}` was not changed: {reason}.") + } + WriteError::Failed { cause, .. } => { + format!("`{path}` was not saved: {cause}. It keeps the content it had.") + } + }; + let (verb, lines) = match self.edit { + Edit::Add => ("Add", "these lines to it"), + Edit::Remove => ("Remove", "these lines from it"), + }; + if self.lines.is_empty() { + return text; + } + text.push(' '); + text.push_str(&format!("{verb} {lines}:\n\n")); + for line in &self.lines { + text.push_str(" "); + text.push_str(line); + text.push('\n'); + } + if let Some(existing) = &self.replaces { + text.push_str(&format!( + "\nThe file already has {existing}. Replace it with these lines, so the file \ + does not hold two entries for one item.\n" + )); + } + text + } + + /// Print the report on standard error at once. + pub fn eprint(&self) { + eprintln!("{}", self.render()); + } +} + +static DEFERRED: Mutex> = Mutex::new(Vec::new()); +static FAILED_WRITE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Keep `report` for [`flush_deferred`], for a command that attaches a shell. +/// The first paint of the shell replaces any line printed before it, so +/// nothing about a client file prints until the attach ends (CFW-012). +pub fn defer(report: &Report) { + if matches!(report.error, WriteError::Failed { .. }) { + FAILED_WRITE.store(true, std::sync::atomic::Ordering::SeqCst); + } + if let Ok(mut held) = DEFERRED.lock() { + held.push(report.render()); + } +} + +/// Print every deferred report on standard error, once the attach has ended +/// by exit or detach (CFW-012). Returns how many were printed. +pub fn flush_deferred() -> usize { + flush_deferred_into(&mut std::io::stderr()) +} + +/// [`flush_deferred`], writing to `out`. A command that fails before its +/// attach ends in the failure printer, which prints what was deferred beside +/// the error, so a saved answer that did not save still shows its lines. +pub fn flush_deferred_into(out: &mut dyn std::io::Write) -> usize { + let held = DEFERRED + .lock() + .map(|mut held| std::mem::take(&mut *held)) + .unwrap_or_default(); + for text in &held { + // A stream that cannot be written has nowhere else for the rest to go. + if writeln!(out, "{text}").is_err() { + break; + } + } + held.len() +} + +/// End a command that attached a shell (CFW-008, CFW-012): print what was +/// deferred, and turn a success into a failure when a write failed. A file +/// that `min` cannot replace does not fail the command (CFW-003). A +/// command's own error is kept as it is. +/// +/// # Errors +/// +/// `result`'s error, or one that says a file was not saved. +pub fn finish_after_attach(result: anyhow::Result<()>) -> anyhow::Result<()> { + flush_deferred(); + let failed = FAILED_WRITE.swap(false, std::sync::atomic::Ordering::SeqCst); + match result { + Ok(()) if failed => anyhow::bail!( + "a file that min writes was not saved. The path, the cause and the lines to change are printed above" + ), + other => other, + } +} + +/// Whether a report was deferred and not yet printed. A command that attaches +/// a shell exits non-zero for a failed write (CFW-008) after it flushes. +#[must_use] +pub fn has_deferred() -> bool { + DEFERRED.lock().is_ok_and(|held| !held.is_empty()) +} + +#[cfg(test)] +mod tests { + use std::os::unix::fs::PermissionsExt as _; + + use tempfile::TempDir; + + use super::*; + + /// The deferred reports and the failed-write flag are one queue for the + /// process, so the tests that use them take turns. + fn queue_lock() -> std::sync::MutexGuard<'static, ()> { + static LOCK: Mutex<()> = Mutex::new(()); + LOCK.lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + fn read_only(path: &Path) { + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o444)).unwrap(); + } + + /// Skip a test that needs a permission the process ignores, as root does. + fn root() -> bool { + nix::unistd::Uid::effective().is_root() + } + + #[test] + fn client_file_write_tests_writability_first() { + if root() { + return; + } + let dir = TempDir::new().unwrap(); + let path = dir.path().join("config.toml"); + std::fs::write(&path, "old\n").unwrap(); + read_only(&path); + let err = replace(&path, b"new\n").expect_err("a read-only file is not replaced"); + assert!(err.is_unwritable(), "{err}"); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "old\n"); + } + + #[test] + fn unwritable_client_file_is_left_unchanged() { + if root() { + return; + } + // A read-only file. + let dir = TempDir::new().unwrap(); + let file = dir.path().join("a.toml"); + std::fs::write(&file, "keep\n").unwrap(); + read_only(&file); + assert!(replace(&file, b"x").is_err()); + assert_eq!(std::fs::read_to_string(&file).unwrap(), "keep\n"); + // A writable file in a read-only folder. + let locked = dir.path().join("locked"); + std::fs::create_dir(&locked).unwrap(); + let inside = locked.join("b.toml"); + std::fs::write(&inside, "keep\n").unwrap(); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o555)).unwrap(); + let result = replace(&inside, b"x"); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap(); + let err = result.expect_err("a folder that refuses a new file"); + assert!(err.is_unwritable(), "{err}"); + assert!(err.why().contains("does not allow a new file"), "{err}"); + assert_eq!(std::fs::read_to_string(&inside).unwrap(), "keep\n"); + // A link to a read-only target in a read-only folder. + let store = dir.path().join("store"); + std::fs::create_dir(&store).unwrap(); + let real = store.join("c.toml"); + std::fs::write(&real, "keep\n").unwrap(); + read_only(&real); + std::fs::set_permissions(&store, std::fs::Permissions::from_mode(0o555)).unwrap(); + let link = dir.path().join("link.toml"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let result = replace(&link, b"x"); + std::fs::set_permissions(&store, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert!( + result + .expect_err("a link into a read-only place") + .is_unwritable() + ); + assert_eq!(std::fs::read_to_string(&real).unwrap(), "keep\n"); + assert!( + std::fs::symlink_metadata(&link) + .unwrap() + .file_type() + .is_symlink() + ); + } + + #[test] + fn missing_file_needs_only_the_folder_test() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("deep").join("er").join("config.toml"); + can_replace(&path).unwrap(); + replace(&path, b"hello\n").unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "hello\n"); + } + + #[test] + fn missing_folder_under_a_read_only_one_is_unwritable() { + if root() { + return; + } + let dir = TempDir::new().unwrap(); + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o555)).unwrap(); + let result = can_replace(&dir.path().join("new").join("config.toml")); + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o755)).unwrap(); + let err = result.expect_err("no folder can be created"); + assert!(err.why().contains("new folder"), "{err}"); + } + + #[test] + fn client_file_write_goes_through_symlink_and_keeps_it() { + let dir = TempDir::new().unwrap(); + let real = dir.path().join("real.toml"); + std::fs::write(&real, "old\n").unwrap(); + let link = dir.path().join("config.toml"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + replace(&link, b"new\n").unwrap(); + assert!( + std::fs::symlink_metadata(&link) + .unwrap() + .file_type() + .is_symlink(), + "the link stays a link" + ); + assert_eq!(std::fs::read_to_string(&real).unwrap(), "new\n"); + } + + #[test] + fn a_dangling_link_is_written_at_its_target() { + let dir = TempDir::new().unwrap(); + let link = dir.path().join("config.toml"); + std::os::unix::fs::symlink("real.toml", &link).unwrap(); + replace(&link, b"made\n").unwrap(); + assert!( + std::fs::symlink_metadata(&link) + .unwrap() + .file_type() + .is_symlink() + ); + assert_eq!( + std::fs::read_to_string(dir.path().join("real.toml")).unwrap(), + "made\n" + ); + } + + #[test] + fn replace_keeps_the_mode_of_the_old_file() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("config.toml"); + std::fs::write(&path, "old\n").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + replace(&path, b"new\n").unwrap(); + let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + } + + #[test] + fn failed_client_file_write_leaves_old_file() { + // The target is a folder at the file's path: the write fails and the + // old content cannot have changed. A file that cannot be created in + // a missing folder behind a regular file does the same. + let dir = TempDir::new().unwrap(); + let blocker = dir.path().join("blocker"); + std::fs::write(&blocker, "keep\n").unwrap(); + let err = replace(&blocker.join("config.toml"), b"x").expect_err("not a folder"); + assert!(err.is_unwritable() || matches!(err, WriteError::Failed { .. })); + assert_eq!(std::fs::read_to_string(&blocker).unwrap(), "keep\n"); + } + + #[test] + fn failed_backup_write_leaves_earlier_backup() { + if root() { + return; + } + let dir = TempDir::new().unwrap(); + let path = dir.path().join("user_policy.toml"); + std::fs::write(&path, "v2\n").unwrap(); + std::fs::write(backup_path(&path), "v1\n").unwrap(); + // A read-only folder refuses the temporary file, so the earlier + // backup stays. + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o555)).unwrap(); + let result = write_backup(&path); + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o755)).unwrap(); + assert!(result.is_err()); + assert_eq!(std::fs::read_to_string(backup_path(&path)).unwrap(), "v1\n"); + } + + #[test] + fn backup_is_a_copy_and_a_missing_file_has_none() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("user_policy.toml"); + write_backup(&path).unwrap(); + assert!(!backup_path(&path).exists()); + std::fs::write(&path, "v1\n").unwrap(); + write_backup(&path).unwrap(); + assert_eq!(std::fs::read_to_string(backup_path(&path)).unwrap(), "v1\n"); + } + + #[test] + fn read_only_client_file_prints_path_and_lines_on_stderr() { + let report = Report::add( + WriteError::Unwritable { + path: PathBuf::from("/home/p/.config/minimal/config.toml"), + reason: "the file is read-only".into(), + }, + vec![ + "[secret-store-rules.claude]".into(), + "authorities = [\"api.anthropic.com\"]".into(), + ], + ); + let text = report.render(); + assert!( + text.contains("/home/p/.config/minimal/config.toml"), + "{text}" + ); + assert!(text.contains("the file is read-only"), "{text}"); + assert!(text.contains("Add these lines"), "{text}"); + assert!(text.contains("[secret-store-rules.claude]"), "{text}"); + } + + #[test] + fn failed_client_file_write_prints_path_cause_and_lines() { + let _queue = queue_lock(); + let report = Report::remove( + WriteError::Failed { + path: PathBuf::from("/c/config.toml"), + cause: "No space left on device".into(), + }, + vec!["[secret-store-rules.claude]".into()], + ); + let text = report.render(); + assert!(text.contains("/c/config.toml"), "{text}"); + assert!(text.contains("No space left on device"), "{text}"); + assert!(text.contains("Remove these lines"), "{text}"); + } + + #[test] + fn printed_lines_say_which_existing_entry_they_replace() { + let report = Report::add( + WriteError::Unwritable { + path: PathBuf::from("/c/config.toml"), + reason: "the file is read-only".into(), + }, + vec!["[secret-store-rules.claude]".into()], + ) + .replacing("a [secret-store-rules.claude] section"); + let text = report.render(); + assert!( + text.contains("already has a [secret-store-rules.claude] section"), + "{text}" + ); + assert!(text.contains("Replace it"), "{text}"); + } + + #[test] + fn attach_prints_client_file_lines_after_shell_exits() { + let _queue = queue_lock(); + // Drain anything another test deferred, then defer one report. + flush_deferred(); + let report = Report::add( + WriteError::Unwritable { + path: PathBuf::from("/c/user_policy.toml"), + reason: "the file is read-only".into(), + }, + vec!["allow = [\"FOO\"]".into()], + ); + defer(&report); + assert!(has_deferred(), "held until the attach ends"); + assert_eq!(flush_deferred(), 1); + assert!(!has_deferred()); + // A file `min cannot replace` does not fail the command. + defer(&report); + finish_after_attach(Ok(())).unwrap(); + } + + #[test] + fn failed_client_file_write_exits_nonzero() { + let _queue = queue_lock(); + flush_deferred(); + defer(&Report::add( + WriteError::Failed { + path: PathBuf::from("/c/config.toml"), + cause: "No space left on device".into(), + }, + vec!["x = 1".into()], + )); + assert!(finish_after_attach(Ok(())).is_err()); + // The flag is spent: the next command starts clean. + finish_after_attach(Ok(())).unwrap(); + } + + #[test] + fn deferred_lines_print_beside_a_failure() { + let _queue = queue_lock(); + flush_deferred(); + defer(&Report::add( + WriteError::Failed { + path: "/tmp/user_policy.toml".into(), + cause: "disk full".into(), + }, + vec!["[credential-rules]".into()], + )); + let mut out = Vec::new(); + assert_eq!(flush_deferred_into(&mut out), 1); + let text = String::from_utf8(out).unwrap(); + assert!(text.contains("/tmp/user_policy.toml"), "{text}"); + assert!(text.contains("[credential-rules]"), "{text}"); + assert!(!has_deferred()); + // The failed-write flag is read and cleared by the attach path only. + drop(finish_after_attach(Ok(()))); + } + + #[test] + fn target_of_follows_every_hop_to_a_file_that_does_not_exist_yet() { + let dir = TempDir::new().unwrap(); + let real = dir.path().join("real.toml"); + let mid = dir.path().join("mid.toml"); + let first = dir.path().join("first.toml"); + std::os::unix::fs::symlink(&real, &mid).unwrap(); + std::os::unix::fs::symlink(&mid, &first).unwrap(); + assert_eq!(target_of(&first), real); + // A write through the chain creates the last file and keeps the links. + replace(&first, b"x\n").unwrap(); + assert_eq!(std::fs::read_to_string(&real).unwrap(), "x\n"); + assert!( + std::fs::symlink_metadata(&first) + .unwrap() + .file_type() + .is_symlink() + ); + assert!( + std::fs::symlink_metadata(&mid) + .unwrap() + .file_type() + .is_symlink() + ); + // A chain too long to follow is refused, and no link is replaced. + let mut previous = dir.path().join("loop0.toml"); + let start = previous.clone(); + for i in 1..=(MAX_LINK_HOPS + 2) { + let next = dir.path().join(format!("loop{i}.toml")); + std::os::unix::fs::symlink(&next, &previous).unwrap(); + previous = next; + } + let err = replace(&start, b"x").expect_err("too many links"); + assert!(matches!(err, WriteError::Failed { .. }), "{err}"); + assert!( + std::fs::symlink_metadata(&start) + .unwrap() + .file_type() + .is_symlink() + ); + } +} diff --git a/crates/minimal/src/cmd/box_spec.rs b/crates/minimal/src/cmd/box_spec.rs index 28cb4a0540..bf017a8bd0 100644 --- a/crates/minimal/src/cmd/box_spec.rs +++ b/crates/minimal/src/cmd/box_spec.rs @@ -468,7 +468,11 @@ fn project_rows(global: &GlobalArgs, args: &BoxSpecArgs, out: &mut Vec) -> a .with_context(|| format!("Cannot resolve the project path {}.", project.display()))?; let utf8_project = camino::Utf8Path::from_path(&absolute) .ok_or_else(|| anyhow::anyhow!("The project path {} is not UTF-8.", project.display()))?; - let (bep, secrets, quic443) = match crate::project_bep_and_grants(utf8_project, None) { + let (bep, secrets, quic443) = match crate::project_bep_and_grants( + utf8_project, + None, + &crate::SelectedLoadouts::default(), + ) { Ok((bep, secrets, _, quic443)) => (bep, secrets, quic443), // A project with several session entries and none named `default` // still gets its preview: the bare form never refuses for that @@ -942,6 +946,18 @@ pub(crate) fn expand_with_store_rules( Ok((expansion, Some(rules))) } +/// Something a selected loadout brought that the box left out, with the +/// reason (BCLI-088). +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +struct LeftOut { + /// The loadout that brought it. + loadout: String, + /// What was left out: a service, or the loadout's egress lists. + what: String, + /// Why the box left it out. + reason: String, +} + /// An entry's expanded spec, the source of each value, and the proxy rows /// of an entry with a credentialed upstream. struct EntrySpec { @@ -949,6 +965,14 @@ struct EntrySpec { box_type: String, spec: toml::Table, sources: std::collections::BTreeMap>, + /// The principal beside each value (BOX-238, BCLI-085), by the key + /// `sources` uses: the project by its root, or the loadout by its name. + /// A value from `[upstream]`, a built-in type's defaults or a flag has + /// none. + principals: std::collections::BTreeMap>, + /// What a selected loadout brought that the box left out, and why + /// (BOX-241, BCLI-088). The spec holds none of it. + left_out: Vec, proxy_rows: Vec, /// The names of the loadouts `min box start` selects for the entry, in /// the order it applies them, for a task entry too. Empty for a sealed @@ -995,6 +1019,13 @@ fn entry_spec( writeln!(text, "# Loadouts: {}.", loadouts.join(", "))?; } } + for left in &rendered.left_out { + writeln!( + text, + "# Left out: {} of the loadout {}: {}.", + left.what, left.loadout, left.reason + )?; + } write_toml(&rendered.spec, &rendered.sources, &mut text)?; if !rendered.proxy_rows.is_empty() { writeln!(text, "\n# Box Egress Proxy:")?; @@ -1031,6 +1062,41 @@ fn entry_spec( serde_json_lenient::to_value(&rendered.sources) .context("Cannot encode the sources")?, ); + // BCLI-085: the principal beside each value, by the key of + // `sources`. + let principals: std::collections::BTreeMap<_, Vec> = + rendered + .principals + .iter() + .map(|(key, list)| { + let list = list + .iter() + .map(|principal| match principal { + mfile::expand::Principal::Project(root) => { + serde_json_lenient::json!({ + "kind": "project", + "path": root.display().to_string() + }) + } + mfile::expand::Principal::Loadout(name) => { + serde_json_lenient::json!({ "kind": "loadout", "name": name }) + } + }) + .collect(); + (key.clone(), list) + }) + .collect(); + // BCLI-088: what a loadout brought that the box left out, and why. + doc.insert( + "left_out".to_owned(), + serde_json_lenient::to_value(&rendered.left_out) + .context("Cannot encode what the box left out")?, + ); + doc.insert( + "principals".to_owned(), + serde_json_lenient::to_value(&principals) + .context("Cannot encode the principals")?, + ); if !rendered.proxy_rows.is_empty() { doc.insert( "egress_proxy".to_owned(), @@ -1195,6 +1261,16 @@ fn expand_entry( // `min box start` builds its selected-loadouts layer. BOX-207: a // variable name that is not POSIX-shaped, a 0.7 key's included, fails // the start, so it fails the spec the same way. + // BOX-244, BCLI-088: the facts that decide whether a loadout's service + // fits the box are the creation's, so the render shows what a creation + // does. The network mode is the one a creation would settle on. + let early_mode: boxes::NetworkMode = match overrides.network { + Some(flag) => flag.into(), + None if box_type == boxes::TASK_BOX_TYPE => crate::cli::default_network_mode().into(), + None => super::box_verbs::project_egress(&root, Some(&entry.name))? + .mode + .unwrap_or_else(|| crate::cli::default_network_mode().into()), + }; let selected = crate::SelectedLoadouts { loadouts: active.loadouts, ignore: Some( @@ -1203,6 +1279,20 @@ fn expand_entry( .ignore() .clone(), ), + service_facts: mfile::expand::ServiceFacts::default(), + }; + // The store is probed only when a selected loadout names a stored secret. + let service_facts = super::box_verbs::service_facts_for( + global, + overrides.egress.deny_all_egress, + &bep::store::HostStore, + early_mode, + None, + super::box_verbs::selected_need_native_store(&selected), + ); + let selected = crate::SelectedLoadouts { + service_facts, + ..selected }; let loadout_layers = selected.layers()?; for layer in &loadout_layers { @@ -1220,6 +1310,7 @@ fn expand_entry( // gate did, and with this process's value of each `inherit` name // (BOX-183, BOX-184). layers.loadouts = loadout_layers; + layers.service_facts = selected.service_facts; (layers.type_defaults, layers.type_constraints) = crate::entry_type_layers(&doc, entry); layers.host_vars = mfile::expand::inherited_var_names(entry, &layers) .into_iter() @@ -1255,6 +1346,10 @@ fn expand_entry( .collect(); let ca_warnings = crate::trusted_cas::unanchored_warnings(&ca_pems); let secret_name_warnings = expansion.report.secret_name_warnings.clone(); + let loadout_network = expansion.loadout_network.clone(); + let loadout_services = expansion.loadout_services.clone(); + let derived_grants = expansion.derived_grants.clone(); + let mut principals = expansion.report.principals(root.as_std_path()); let mut spec = expansion.spec; let mut sources = std::collections::BTreeMap::new(); for (key, origin) in &expansion.report.values { @@ -1273,6 +1368,8 @@ fn expand_entry( if overrides.other.no_hooks { spec.remove("lifecycle_hooks"); sources.retain(|key, _| key != "lifecycle_hooks" && !key.starts_with("lifecycle_hooks.")); + principals + .retain(|key, _| key != "lifecycle_hooks" && !key.starts_with("lifecycle_hooks.")); } // gominimal/arch#188: `network` merges by key, so each key below it // names its own layer, and `network` names every layer that set one of @@ -1308,105 +1405,153 @@ fn expand_entry( let network_source = |key: &str| network_origins.get(key).cloned().unwrap_or_default(); let mut ingress_sources = vec![COMMAND_LINE.to_owned()]; let none_flag_cleared: bool; - let (mode, mode_source, egress, ingress, service_hosts, uses_layer) = if task_rooted { - let mut project_egress = - super::box_verbs::task_project_egress(&root, &entry.name, overrides.network)?; - // BCLI-024: as `min task run` does, `--network none` clears the - // egress and the ingress the task's layers set. - none_flag_cleared = super::box_verbs::clear_file_network_on_none_flag( - &mut project_egress, - overrides.network, - ); - let flags = super::box_verbs::flag_egress(&overrides.egress)?; - let mut egress = super::box_verbs::effective_egress( - project_egress.policy, - flags, - overrides.egress.deny_all_egress, - ); - let (mode, source) = match (overrides.network, project_egress.mode) { - (Some(flag), _) => (flag.into(), vec![COMMAND_LINE.to_owned()]), - (None, Some(mode)) => (mode, network_source("mode")), - (None, None) => ( - crate::cli::default_network_mode().into(), - vec![DEFAULT_SOURCE.to_owned()], - ), + let (mode, mode_source, egress, ingress, service_hosts, loadout_items, uses_layer) = + if task_rooted { + let mut project_egress = + super::box_verbs::task_project_egress(&root, &entry.name, overrides.network)?; + // BCLI-024: as `min task run` does, `--network none` clears the + // egress and the ingress the task's layers set. + none_flag_cleared = super::box_verbs::clear_file_network_on_none_flag( + &mut project_egress, + overrides.network, + ); + let flags = super::box_verbs::flag_egress(&overrides.egress)?; + let mut egress = super::box_verbs::effective_egress( + project_egress.policy, + flags, + overrides.egress.deny_all_egress, + ); + let (mode, source) = match (overrides.network, project_egress.mode) { + (Some(flag), _) => (flag.into(), vec![COMMAND_LINE.to_owned()]), + (None, Some(mode)) => (mode, network_source("mode")), + (None, None) => ( + crate::cli::default_network_mode().into(), + vec![DEFAULT_SOURCE.to_owned()], + ), + }; + // gominimal/arch#209: as `min task run` resolves them. + super::box_verbs::resolve_services( + &project_egress.uses, + mode, + overrides.egress.deny_all_egress, + &mut egress, + ); + ( + mode, + source, + egress.policy, + None, + egress.service_hosts, + Vec::new(), + project_egress.uses_layer, + ) + } else { + let mut activate = crate::ActivateArgs::unflagged(); + activate.network = overrides.network; + activate.ingress.clone_from(&overrides.ingress); + activate.egress.clone_from(&overrides.egress); + let (port_mappings, flags) = super::box_verbs::flag_network_overrides(&activate)?; + let mut project_egress = super::box_verbs::project_egress(&root, Some(&entry.name))?; + // gominimal/arch#200: as the start does, `--network none` drops the + // entry's `network.egress` and `network.ingress`. + none_flag_cleared = super::box_verbs::clear_file_network_on_none_flag( + &mut project_egress, + overrides.network, + ); + // #3238: as `min box start` sends them, the entry's `network.mode` + // applies when no `--network` replaces it, and each `--ingress` adds + // a mapping after the entry's `network.ingress`. + let file_ingress = project_egress.ingress.take(); + let (mode, source) = match (overrides.network, project_egress.mode) { + (Some(flag), _) => (flag.into(), vec![COMMAND_LINE.to_owned()]), + (None, Some(mode)) => (mode, network_source("mode")), + (None, None) => ( + activate.network_mode().into(), + vec![DEFAULT_SOURCE.to_owned()], + ), + }; + let mut ingress_source = Vec::new(); + if file_ingress.is_some() { + ingress_source.extend(network_source("ingress")); + } + if file_ingress.is_none() || !overrides.ingress.is_empty() { + ingress_source.push(COMMAND_LINE.to_owned()); + } + let port_mappings = match file_ingress { + Some(file_mappings) => { + super::box_verbs::union_ingress(file_mappings, port_mappings) + } + None => port_mappings, + }; + let mut egress = super::box_verbs::effective_egress( + project_egress.policy, + flags, + activate.egress.deny_all_egress, + ); + // gominimal/arch#209: as `min box start` resolves them. + super::box_verbs::resolve_services( + &project_egress.uses, + mode, + activate.egress.deny_all_egress, + &mut egress, + ); + // BOX-240, BOX-241: what the selected loadouts bring, as the start + // joins it after the box's own `uses`. + super::box_verbs::resolve_loadout_network( + &loadout_network, + &loadout_services, + mode, + activate.egress.deny_all_egress, + &mut egress, + ); + let service_hosts = std::mem::take(&mut egress.service_hosts); + let loadout_items = std::mem::take(&mut egress.loadout_items); + let policy = + super::box_verbs::network_override_policy(&activate, port_mappings, egress.policy); + ingress_sources = ingress_source; + ( + mode, + source, + policy.egress, + policy.ingress, + service_hosts, + loadout_items, + project_egress.uses_layer, + ) }; - // gominimal/arch#209: as `min task run` resolves them. - super::box_verbs::resolve_services( - &project_egress.uses, - mode, - overrides.egress.deny_all_egress, - &mut egress, - ); - ( - mode, - source, - egress.policy, - None, - egress.service_hosts, - project_egress.uses_layer, - ) - } else { - let mut activate = crate::ActivateArgs::unflagged(); - activate.network = overrides.network; - activate.ingress.clone_from(&overrides.ingress); - activate.egress.clone_from(&overrides.egress); - let (port_mappings, flags) = super::box_verbs::flag_network_overrides(&activate)?; - let mut project_egress = super::box_verbs::project_egress(&root, Some(&entry.name))?; - // gominimal/arch#200: as the start does, `--network none` drops the - // entry's `network.egress` and `network.ingress`. - none_flag_cleared = super::box_verbs::clear_file_network_on_none_flag( - &mut project_egress, - overrides.network, + // BCLI-088: what a loadout brought and the box left out, with the reason. + let mut left_out: Vec = loadout_services + .iter() + .filter_map(|service| { + service.left_out.as_ref().map(|reason| LeftOut { + loadout: service.loadout.clone(), + what: format!("the service {}", service.service), + reason: reason.clone(), + }) + }) + .collect(); + let no_network = overrides.egress.deny_all_egress || mode == boxes::NetworkMode::NoNet; + for listed in &loadout_network { + let (hosts, subnets) = ( + !listed.allow_dns_hosts.is_empty(), + !listed.allow_subnets.is_empty(), ); - // #3238: as `min box start` sends them, the entry's `network.mode` - // applies when no `--network` replaces it, and each `--ingress` adds - // a mapping after the entry's `network.ingress`. - let file_ingress = project_egress.ingress.take(); - let (mode, source) = match (overrides.network, project_egress.mode) { - (Some(flag), _) => (flag.into(), vec![COMMAND_LINE.to_owned()]), - (None, Some(mode)) => (mode, network_source("mode")), - (None, None) => ( - activate.network_mode().into(), - vec![DEFAULT_SOURCE.to_owned()], - ), - }; - let mut ingress_source = Vec::new(); - if file_ingress.is_some() { - ingress_source.extend(network_source("ingress")); + if no_network && (hosts || subnets) { + left_out.push(LeftOut { + loadout: listed.loadout.clone(), + what: "its egress lists".to_owned(), + reason: "the box has no network, or the command carries --deny-all-egress" + .to_owned(), + }); + } else if mode == boxes::NetworkMode::HostNet && hosts { + left_out.push(LeftOut { + loadout: listed.loadout.clone(), + what: "its egress hostnames".to_owned(), + reason: "a host_ip box can declare no name rule, so only the subnets join" + .to_owned(), + }); } - if file_ingress.is_none() || !overrides.ingress.is_empty() { - ingress_source.push(COMMAND_LINE.to_owned()); - } - let port_mappings = match file_ingress { - Some(file_mappings) => super::box_verbs::union_ingress(file_mappings, port_mappings), - None => port_mappings, - }; - let mut egress = super::box_verbs::effective_egress( - project_egress.policy, - flags, - activate.egress.deny_all_egress, - ); - // gominimal/arch#209: as `min box start` resolves them. - super::box_verbs::resolve_services( - &project_egress.uses, - mode, - activate.egress.deny_all_egress, - &mut egress, - ); - let service_hosts = std::mem::take(&mut egress.service_hosts); - let policy = - super::box_verbs::network_override_policy(&activate, port_mappings, egress.policy); - ingress_sources = ingress_source; - ( - mode, - source, - policy.egress, - policy.ingress, - service_hosts, - project_egress.uses_layer, - ) - }; + } let mut network = spec .get("network") .and_then(toml::Value::as_table) @@ -1437,8 +1582,23 @@ fn expand_entry( // gominimal/arch#209: each name a service added, with the // service and the table that named it in `uses`. let named_in = uses_layer.as_deref().unwrap_or(mfile::MFILE_NAME); + let uses_principals = principals.get("network.uses").cloned().unwrap_or_default(); for added in &service_hosts { - let label = format!("the service {}, which {named_in} uses", added.service); + principals.insert( + format!("network.egress.allow_dns_hosts[{}]", added.host), + match &added.loadout { + Some(loadout) => vec![mfile::expand::Principal::Loadout(loadout.clone())], + None => uses_principals.clone(), + }, + ); + // BCLI-088: a host a loadout's service added names the loadout. + let label = match &added.loadout { + Some(loadout) => format!( + "the service {}, which the loadout {loadout} names", + added.service + ), + None => format!("the service {}, which {named_in} uses", added.service), + }; if !source.contains(&label) { source.push(label.clone()); } @@ -1447,6 +1607,21 @@ fn expand_entry( vec![label], ); } + // BCLI-088: each host and subnet a loadout's own lists added. + for item in &loadout_items { + principals.insert( + format!("network.egress.{}[{}]", item.list, item.value), + vec![mfile::expand::Principal::Loadout(item.loadout.clone())], + ); + let label = format!("the loadout {}", item.loadout); + if !source.contains(&label) { + source.push(label.clone()); + } + sources.insert( + format!("network.egress.{}[{}]", item.list, item.value), + vec![label], + ); + } sources.insert("network.egress".to_owned(), source); } None => { @@ -1501,6 +1676,73 @@ fn expand_entry( // a refusal here. `min task run` makes no such check, so a task entry is // checked only for a credentialed grant, as before. Only a credentialed // grant prints rows. + // BCLI-088: each grant names the layer, the loadout or the service that + // asked for it, and whether the project is approved, undecided or denied + // for its credential, by the tables that decide a creation (BEP-107). + { + use boxes::credential_rules::{CredentialAction, Table, decide}; + let uses_label = uses_layer.as_deref().unwrap_or(mfile::MFILE_NAME); + let policy_path = crate::config::user_policy_path(global); + let organization = Path::new(crate::config::ORGANIZATION_CONFIG_PATH); + let (user, org) = crate::credential_approval::read_tables( + &policy_path, + organization, + &::dirs::home_dir().unwrap_or_default(), + )?; + let project = crate::credential_approval::project_of(root.as_std_path()); + let (place_user, place_org) = ( + policy_path.display().to_string(), + organization.display().to_string(), + ); + let tables = [ + Table { + place: &place_user, + rules: &user, + }, + Table { + place: &place_org, + rules: &org, + }, + ]; + for (var, credential) in crate::credential_approval::credentials(&grants) { + let derived = derived_grants + .iter() + .find(|g| g.variable == var && !g.declared_instead); + let by_loadout = loadout_services + .iter() + .find(|l| l.grant.as_deref() == Some(var.as_str())); + let asker = if let Some(derived) = derived { + vec![format!( + "the service {}, which {uses_label} uses", + derived.service + )] + } else if let Some(l) = by_loadout { + principals.insert( + format!("secrets.{var}"), + vec![mfile::expand::Principal::Loadout(l.loadout.clone())], + ); + vec![format!( + "the service {}, which the loadout {} names", + l.service, l.loadout + )] + } else { + sources.get("secrets").cloned().unwrap_or_default() + }; + if derived.is_some() { + principals.insert( + format!("secrets.{var}"), + principals.get("network.uses").cloned().unwrap_or_default(), + ); + } + sources.insert(format!("secrets.{var}"), asker); + let state = match decide(&tables, &credential, &project).action { + CredentialAction::Allow => "approved", + CredentialAction::Ask => "undecided", + CredentialAction::Deny => "denied", + }; + sources.insert(format!("secrets.{var}.approval"), vec![state.to_owned()]); + } + } let credentialed = grants.values().any(SecretGrant::is_credentialed); if task_rooted && !credentialed { return Ok(EntrySpec { @@ -1508,6 +1750,8 @@ fn expand_entry( box_type, spec, sources, + principals, + left_out, proxy_rows: Vec::new(), loadouts, secret_name_warnings, @@ -1558,6 +1802,8 @@ fn expand_entry( box_type, spec, sources, + principals, + left_out, proxy_rows: rows_text, loadouts, secret_name_warnings, @@ -1864,7 +2110,13 @@ fn write_toml( .iter() .filter(|(path, _)| *path == key || path.starts_with(&prefix)) { - writeln!(out, "# {path}: from {}", labels.join(", "))?; + // BCLI-088: an approval state is not a source, so it reads as + // the state and not as "from" it. + if path.ends_with(".approval") { + writeln!(out, "# {path}: {}", labels.join(", "))?; + } else { + writeln!(out, "# {path}: from {}", labels.join(", "))?; + } } let one = toml::Table::from_iter([(key.clone(), value.clone())]); let text = toml::to_string(&one).context("Cannot write the spec as TOML")?; diff --git a/crates/minimal/src/cmd/boxes/create.rs b/crates/minimal/src/cmd/boxes/create.rs index d85543ca28..0a32df5637 100644 --- a/crates/minimal/src/cmd/boxes/create.rs +++ b/crates/minimal/src/cmd/boxes/create.rs @@ -1544,6 +1544,15 @@ pub enum GrantNotDelivered { /// The minimal.toml table that declares the grant. table: String, }, + /// The item is a stored-secret service's, and the rule for it registers + /// other authorities or another injection form than the service does + /// (BEP-104), so the item is not the service's secret. + ServiceRuleDiffers { + /// The grant's name. + grant: String, + /// The item, which is the service's name. + item: String, + }, /// The reference reads the host's native store, and that store cannot /// be used on this host, so the proxy could read no value for it. StoreUnavailable { @@ -1610,6 +1619,13 @@ impl std::fmt::Display for GrantNotDelivered { "Cannot create the box: no sealed value was made for the secret \ {grant}, so {grant} would be empty in the box. No box was created." ), + Self::NoStoreRule { grant, item, .. } if is_stored_service(item) => write!( + f, + "Cannot create the box: the secret {grant} reads the item {item} from the \ + host's secret store, and no rule in [secret-store-rules] in your config.toml \ + names that item. Run `min secret set {item} --service {item}` to store the \ + item and write its rule." + ), Self::NoStoreRule { grant, item, table } => write!( f, "Cannot create the box: the secret {grant} in {declared} \ @@ -1619,6 +1635,13 @@ impl std::fmt::Display for GrantNotDelivered { declared = declared_in(table), remove = remove_from(table), ), + Self::ServiceRuleDiffers { grant, item } => write!( + f, + "Cannot create the box: the secret {grant} is the service {item}, and the \ + rule for {item} in [secret-store-rules] in your config.toml registers other \ + hosts or another injection form than the service. Run `min secret set {item} \ + --service {item}` to replace the rule." + ), Self::StoreUnavailable { grant, item, @@ -1631,6 +1654,14 @@ impl std::fmt::Display for GrantNotDelivered { store. {reason}", declared = declared_in(table), ), + Self::ItemNotStored { + grant, item, place, .. + } if is_stored_service(item) => write!( + f, + "Cannot create the box: the secret {grant} reads the item {item} from the \ + host's secret store, and no secret named {item} is stored in {place}. Run \ + `min secret set {item} --service {item}`, then create the box again." + ), Self::ItemNotStored { grant, item, @@ -1672,6 +1703,64 @@ impl std::fmt::Display for GrantNotDelivered { impl std::error::Error for GrantNotDelivered {} +/// Whether `item` is the name of a Service Library entry whose secret is a +/// stored value, so `min secret set --service ` supplies it. +fn is_stored_service(item: &str) -> bool { + use boxes::core::services::{ServiceSecret, service}; + service(item).is_some_and(|entry| matches!(entry.secret, ServiceSecret::Store { .. })) +} + +/// BEP-104: where a store reference is a stored-secret service's own grant, +/// the rule for its item must register what the service does. A rule with an +/// authority the service lacks, or another injection form, is refused. A rule +/// that lacks authorities of the service is used as written, and the missing +/// ones are returned for the person to see. +fn check_service_rule( + grant: &str, + item: &str, + rule: &boxes::core::bep::StoreRuleConfig, +) -> Result, GrantNotDelivered> { + use boxes::core::services::{ServiceSecret, service}; + let Some(entry) = service(item) else { + return Ok(Vec::new()); + }; + let ServiceSecret::Store { + authorities, + header, + prefix, + } = entry.secret + else { + return Ok(Vec::new()); + }; + if entry.env != Some(grant) { + return Ok(Vec::new()); + } + // As `min secret list` reads a rule: hosts as the proxy reads them, and + // the header in any case. + let same_form = crate::cmd::secret::same_injection(rule, header, prefix); + let foreign = rule.authorities.iter().any(|have| { + !authorities + .iter() + .any(|want| crate::cmd::secret::same_authority(have, want)) + }); + if !same_form || foreign { + return Err(GrantNotDelivered::ServiceRuleDiffers { + grant: grant.to_owned(), + item: item.to_owned(), + }); + } + Ok(authorities + .iter() + .filter(|want| { + !rule + .authorities + .iter() + .any(|have| crate::cmd::secret::same_authority(have, want)) + }) + .map(|want| (*want).to_owned()) + .collect()) +} + /// Where the session entry `entry` of the project declares its grants, as /// a refusal names it: the minimal.toml table of the layer that set the /// expanded spec's `secrets`, such as `[sessions.dev.secrets]` or @@ -1775,13 +1864,14 @@ const LEGACY_SESSION_SECRETS_TABLE: &str = "[session.secrets]"; pub(crate) fn project_bep_and_grants( project: &camino::Utf8Path, entry: Option<&str>, + selected: &SelectedLoadouts, ) -> anyhow::Result<( boxes::core::bep::BepSettings, boxes::core::bep::SecretGrants, Vec, Option, )> { - let expanded = match session_box_expansion(project, entry, true, &SelectedLoadouts::default()) { + let expanded = match session_box_expansion(project, entry, true, selected) { Ok(expanded) => expanded, Err(error) => { tracing::debug!( @@ -1846,6 +1936,8 @@ pub(crate) enum EgressSource { Flag, /// A service the box `uses` (gominimal/arch#209). Service, + /// A selected loadout's `[network]` table (BOX-240). + Loadout, } /// A box's effective egress (NET-060): the policy, and the source of each @@ -1858,6 +1950,20 @@ pub(crate) struct EffectiveEgress { /// with the service (gominimal/arch#209). Empty when the box names no /// service, or its egress already admits every name. pub(crate) service_hosts: Vec, + /// Each host and subnet a selected loadout's own lists added (BOX-240), + /// with the loadout, for the provenance `min box spec` prints. + pub(crate) loadout_items: Vec, +} + +/// A host or subnet that a loadout's `[network]` lists added to the egress. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct LoadoutItem { + /// The loadout. + pub(crate) loadout: String, + /// The list it joined: `allow_dns_hosts` or `allow_subnets`. + pub(crate) list: &'static str, + /// The host or the subnet. + pub(crate) value: String, } /// One name a service added to a box's `allow_dns_hosts`, for the @@ -1868,6 +1974,9 @@ pub(crate) struct ServiceHost { pub(crate) service: String, /// The name it added. pub(crate) host: String, + /// The loadout that named the service, when a loadout did and the box's + /// own `uses` did not. + pub(crate) loadout: Option, } /// A Service Library entry's host set (gominimal/arch#209): its hosts, @@ -1911,6 +2020,17 @@ pub(crate) fn resolve_services( network: boxes::NetworkMode, deny_all_egress: bool, egress: &mut EffectiveEgress, +) { + add_service_hosts(uses, None, network, deny_all_egress, egress); +} + +/// [`resolve_services`] for `uses`, with the loadout `via` that named them. +fn add_service_hosts( + uses: &[String], + via: Option<&str>, + network: boxes::NetworkMode, + deny_all_egress: bool, + egress: &mut EffectiveEgress, ) { if uses.is_empty() || deny_all_egress @@ -1934,6 +2054,7 @@ pub(crate) fn resolve_services( egress.service_hosts.push(ServiceHost { service: name.clone(), host, + loadout: via.map(str::to_owned), }); } } @@ -1949,6 +2070,110 @@ pub(crate) fn resolve_services( } } +/// Whether `subnet` is already admitted by `allowed`: listed, or covered by a +/// listed subnet (BOX-240). A subnet that does not parse is never covered. +fn subnet_covered(allowed: &[String], subnet: &str) -> bool { + let parse = |text: &str| -> Option<(u128, u32, bool)> { + let (addr, bits) = text.split_once('/')?; + let bits: u32 = bits.parse().ok()?; + match addr.parse::().ok()? { + std::net::IpAddr::V4(v4) if bits <= 32 => { + Some((u128::from(u32::from(v4)), bits, false)) + } + std::net::IpAddr::V6(v6) if bits <= 128 => Some((u128::from(v6), bits, true)), + _ => None, + } + }; + let Some((want, want_bits, want_v6)) = parse(subnet) else { + return false; + }; + allowed.iter().any(|have| { + let Some((addr, bits, v6)) = parse(have) else { + return false; + }; + if v6 != want_v6 || bits > want_bits { + return false; + } + let width = if v6 { 128 } else { 32 }; + let shift = width - bits; + shift >= 128 || (addr >> shift) == (want >> shift) + }) +} + +/// Joins what the selected loadouts bring to the box's egress, after every +/// layer and every flag, and after the box's own `uses` (BOX-240, BOX-241, +/// BEP-109). Each host and subnet a loadout lists joins its list unless the +/// egress already admits it. The services that the expansion took add their +/// hosts as the box's own do. Nothing is added with `--deny-all-egress` or a +/// network of `none`. A host_ip box can declare no name rule, so it takes the +/// subnets and not the names. `allow_protocols` is never touched, so an item +/// has the protocols that the box allows. +pub(crate) fn resolve_loadout_network( + listed: &[mfile::expand::LoadoutNetwork], + services: &[mfile::expand::LoadoutService], + network: boxes::NetworkMode, + deny_all_egress: bool, + egress: &mut EffectiveEgress, +) { + if deny_all_egress || network == boxes::NetworkMode::NoNet { + return; + } + let normal = |host: &str| host.trim_end_matches('.').to_ascii_lowercase(); + let admits_every_name = + boxes::core::bep::egress_admits_every_name(network, egress.policy.as_ref()); + let mut added = false; + for table in listed { + for subnet in &table.allow_subnets { + let policy = egress.policy.get_or_insert_with(Default::default); + let allowed = policy.allow_subnets.get_or_insert_with(Vec::new); + if !subnet_covered(allowed, subnet) { + allowed.push(subnet.clone()); + egress.loadout_items.push(LoadoutItem { + loadout: table.loadout.clone(), + list: "allow_subnets", + value: subnet.clone(), + }); + added = true; + } + } + if admits_every_name || network == boxes::NetworkMode::HostNet { + continue; + } + for host in &table.allow_dns_hosts { + let policy = egress.policy.get_or_insert_with(Default::default); + let allowed = policy.allow_dns_hosts.get_or_insert_with(Vec::new); + if !allowed.iter().any(|have| normal(have) == normal(host)) { + allowed.push(host.clone()); + egress.loadout_items.push(LoadoutItem { + loadout: table.loadout.clone(), + list: "allow_dns_hosts", + value: host.clone(), + }); + added = true; + } + } + } + if added + && !egress + .sources + .iter() + .any(|(field, _)| *field == "allow_dns_hosts") + { + egress + .sources + .push(("allow_dns_hosts", EgressSource::Loadout)); + } + for service in services.iter().filter(|s| s.left_out.is_none()) { + add_service_hosts( + std::slice::from_ref(&service.service), + Some(&service.loadout), + network, + deny_all_egress, + egress, + ); + } +} + /// The `network.egress` table that the project's `minimal.toml` declares for /// a session box or a task box (NET-060), with the hint for each legacy /// spelling that the file uses. @@ -2725,6 +2950,10 @@ pub(crate) struct SelectedLoadouts { /// The user policy's var `ignore` list. A loadout var it matches is /// dropped before the merge, so it never conflicts (BOX-183). pub(crate) ignore: Option, + /// What decides whether a service that a loadout names fits the box + /// (BOX-241). `check_project` fills it, so the grant checks, the mint and + /// the stored spec read one expansion (BOX-244). + pub(crate) service_facts: mfile::expand::ServiceFacts, } impl SelectedLoadouts { @@ -2748,13 +2977,15 @@ pub(crate) fn loadout_layer( loadout: &boxes::core::loadout::Loadout, ignore: Option<&boxes::core::policy::VarNameGlobs>, ) -> anyhow::Result { - const APPLIED: [&str; 6] = [ + const APPLIED: [&str; 7] = [ "packages", "patches", mfile::expand::ENV_VARS_KEY, "lifecycle_hooks", mfile::expand::TRUSTED_CAS_KEY, mfile::expand::INFRASTRUCTURE_CAS_KEY, + // BOX-239: the expansion reads, checks and sets aside this table. + "network", ]; let name = loadout.name().as_ref().to_owned(); let mut table = @@ -2792,6 +3023,13 @@ pub(crate) struct BoxEntryExpansion { /// Where the entry's `secrets` are declared, as a refusal names it /// ([`secrets_table`]). pub(crate) secrets_table: String, + /// The `[network]` of each selected loadout (BOX-239), which the client + /// joins to the egress after the last layer (BOX-240). + pub(crate) loadout_network: Vec, + /// Each service a selected loadout names, taken or left out (BOX-241). + pub(crate) loadout_services: Vec, + /// The grants that `network.uses` derived (BEP-103). + pub(crate) derived_grants: Vec, } impl BoxEntryExpansion { @@ -2966,6 +3204,7 @@ pub(crate) fn task_selected_loadouts( Ok(SelectedLoadouts { loadouts: active.loadouts, ignore: Some(ignore), + service_facts: mfile::expand::ServiceFacts::default(), }) } @@ -3081,6 +3320,7 @@ pub(crate) fn box_entry( // read. crate::trusted_cas::set_layers(&mut whole, Some(project.as_std_path()), global)?; layers.trusted_ca_resolver = whole.trusted_ca_resolver.clone(); + whole.service_facts = selected.service_facts; whole.host_vars = host_vars(&whole); let (mut full, _) = crate::cmd::box_spec::expand_with_store_rules(global, &entry, &mut whole)?; // With hooks off (`--no-hooks`), the spec carries no hook. @@ -3176,6 +3416,9 @@ pub(crate) fn box_entry( report: full.report, type_chain, secrets_table, + loadout_network: full.loadout_network, + loadout_services: full.loadout_services, + derived_grants: full.derived_grants, }) } @@ -3388,6 +3631,7 @@ pub(crate) fn effective_egress( }), sources, service_hosts: Vec::new(), + loadout_items: Vec::new(), } } @@ -3694,6 +3938,21 @@ fn accept_store_references_in( } .into()); }; + // BEP-104: the rule is used as written. A host it lacks is logged. + let missing = if reference.store == boxes::core::bep::NATIVE_STORE { + check_service_rule(&grant, reference.id, rule).inspect_err(|_| { + checked.push(format!("{item}: the rule differs from the service")); + })? + } else { + Vec::new() + }; + if !missing.is_empty() { + tracing::warn!( + %item, + missing = %missing.join(", "), + "the rule for the service's item lacks authorities of the service" + ); + } match store_consent(rule, can_ask) { StoreConsent::Allow => {} StoreConsent::Deny if rule.action == Some(boxes::core::bep::StoreAction::Ask) => { @@ -5534,6 +5793,79 @@ pub(crate) fn network_override_policy( } } +/// What decides whether a service that a loadout names fits the box +/// (BOX-241), read from the command and the host. `proxy_serves` says whether +/// a proxy serves the box, where `None` asks the host. `min box spec` reads +/// the same facts, so it shows what the creation does. +/// +/// The native secret store is probed only when `needs_store` says a selected +/// loadout names a stored-secret service. A probe opens the store, which can +/// print a warning about the file store, so a box that needs no store never +/// pays for one. +pub(crate) fn service_facts_for( + global: &GlobalArgs, + deny_all_egress: bool, + store: &dyn bep::store::SecretStore, + network: boxes::NetworkMode, + proxy_serves: Option, + needs_store: bool, +) -> mfile::expand::ServiceFacts { + mfile::expand::ServiceFacts { + deny_all_egress, + proxy_serves: proxy_serves.unwrap_or_else(|| host_proxy_absence(global).is_none()), + native_store_usable: !needs_store || store.check_available().is_ok(), + box_zone_resolver: host_resolves_box_names(daemon_host_kind(global), network), + network_none: network == boxes::NetworkMode::NoNet, + } +} + +/// Whether a selected loadout names a service whose secret is a stored value, +/// which needs the host's native store (BOX-241). +pub(crate) fn selected_need_native_store(selected: &SelectedLoadouts) -> bool { + selected.layers().is_ok_and(|layers| { + layers.iter().any(|layer| { + layer + .table + .get("network") + .and_then(|network| network.get("uses")) + .and_then(toml::Value::as_array) + .is_some_and(|names| { + names.iter().filter_map(toml::Value::as_str).any(|name| { + boxes::core::services::service(name).is_some_and(|service| { + matches!( + service.secret, + boxes::core::services::ServiceSecret::Store { .. } + ) + }) + }) + }) + }) + }) +} + +/// The loadouts a start selects, gated by the entry's `loadout_mode`, for the +/// checks that run before the loadouts are composed (BOX-244). +/// +/// # Errors +/// +/// A loadout that is missing or malformed, or a client configuration that +/// does not read. +fn selected_loadouts_for( + global: &GlobalArgs, + project: &camino::Utf8Path, + entry: Option<&str>, + args: &ActivateArgs, +) -> anyhow::Result { + let mode = session_loadout_mode(project, entry, &args.loadout)?; + let selection = loadouts::gate_selection(start_loadout_selection(args), mode); + let cfg = config::read_client_config(global)?; + Ok(SelectedLoadouts { + loadouts: loadouts::resolve_active_loadouts(selection, &cfg, global)?.loadouts, + ignore: Some(config::read_user_policy(global)?.vars().ignore().clone()), + service_facts: mfile::expand::ServiceFacts::default(), + }) +} + /// The loadouts an activation resolves (BCLI-073): each `--loadout` in /// place of the client config's `default_loadouts`, or none under /// `--no-loadouts`. `min box spec ` takes the same selection and @@ -5609,6 +5941,9 @@ pub(crate) struct ProjectChecks { pub(crate) policy: boxes::BoxPolicy, pub(crate) github_grants: Vec, pub(crate) store_grants: Vec, + /// The facts the loadouts' services were judged by (BOX-241), for the + /// later expansion that stores the spec (BOX-244). + pub(crate) service_facts: mfile::expand::ServiceFacts, } /// The `CheckProject` step of a create from the entry `entry` of the @@ -5634,16 +5969,64 @@ pub(crate) fn check_project( flag_overrides: (Vec, Option), prompts: ProjectPrompts, store: &dyn bep::store::SecretStore, + selected: &SelectedLoadouts, +) -> Result { + check_project_with( + global, + args, + project, + entry, + quic443, + flag_overrides, + prompts, + store, + selected, + None, + ) +} + +/// [`check_project`], with `proxy_serves` saying whether a proxy serves the +/// box, where `None` asks the host. A test says it. +#[expect( + clippy::too_many_arguments, + reason = "the arguments of check_project, and the proxy fact a test gives" +)] +pub(crate) fn check_project_with( + global: &GlobalArgs, + args: &mut ActivateArgs, + project: &camino::Utf8Path, + entry: Option<&str>, + quic443: Option, + flag_overrides: (Vec, Option), + prompts: ProjectPrompts, + store: &dyn bep::store::SecretStore, + selected: &SelectedLoadouts, + proxy_serves: Option, ) -> Result { let (port_mappings, egress) = flag_overrides; - let (project_bep, project_secrets, project_env, project_quic443) = - project_bep_and_grants(project, entry)?; // NET-060: the project's egress, with each field a flag names // replaced by the flag. let mut project_egress = project_egress(project, entry)?; let (network, port_mappings) = session_box_network(args, &mut project_egress, port_mappings)?; // Every later read of `args.network` sees the box's mode. args.network = Some(network); + // BOX-241, BOX-244: what decides whether a loadout's service fits the + // box, then the one expansion that includes the selected loadouts. The + // grant checks below, the mint and the stored spec read it. + let service_facts = service_facts_for( + global, + args.egress.deny_all_egress, + store, + network.into(), + proxy_serves, + selected_need_native_store(selected), + ); + let selected = SelectedLoadouts { + service_facts, + ..selected.clone() + }; + let (project_bep, project_secrets, project_env, project_quic443) = + project_bep_and_grants(project, entry, &selected)?; // A legacy key spelling still loads. A start with no terminal // prints its hint, and an interactive start logs it, so no line // prints before the box shell. @@ -5656,7 +6039,34 @@ pub(crate) fn check_project( tracing::warn!(hint = %hint, "the project's network keys use a legacy spelling"); } } - let egress = session_effective_egress(project_egress, egress, network.into(), &args.egress)?; + let uses_layer = project_egress.uses_layer.clone(); + let mut egress = + session_effective_egress(project_egress, egress, network.into(), &args.egress)?; + // BOX-240, BOX-241: what the selected loadouts bring joins after the + // box's own `uses`. A service a loadout names that the box left out adds + // nothing, and says why in the log. + let loadout_expansion = session_box_expansion(project, entry, true, &selected)?; + if let Some(expanded) = &loadout_expansion { + for service in expanded + .loadout_services + .iter() + .filter(|s| s.left_out.is_some()) + { + tracing::info!( + loadout = %service.loadout, + service = %service.service, + reason = service.left_out.as_deref().unwrap_or_default(), + "a loadout's service is left out of the box" + ); + } + resolve_loadout_network( + &expanded.loadout_network, + &expanded.loadout_services, + network.into(), + args.egress.deny_all_egress, + &mut egress, + ); + } tracing::debug!( egress = ?egress.policy, sources = ?egress.sources, @@ -5750,13 +6160,177 @@ pub(crate) fn check_project( ), &bep::signin::HostKeychain, )?; + // BEP-105, BEP-108: the credentials the box would hold are approved for + // this project, after every check that the user holds each one, so + // nobody is asked to approve a credential that is then refused. + // The approval is of the project root, which is where the `minimal.toml` + // is, and not of the directory the command runs in. + let approval_root = crate::cmd::project::resolve_upload_root_quiet(project) + .unwrap_or_else(|_| project.to_path_buf()); + let cannot_ask = if can_ask { + None + } else if prompts == ProjectPrompts::Dashboard { + Some(crate::credential_approval::CannotAsk::Dashboard) + } else if global.no_input { + Some(crate::credential_approval::CannotAsk::NoInput) + } else { + Some(crate::credential_approval::CannotAsk::NoTerminal) + }; + let askers = grant_askers( + &project_secrets, + loadout_expansion.as_ref(), + uses_layer.as_deref(), + &project_secrets_table(project, entry), + ); + approve_credentials( + global, + &approval_root, + &project_secrets, + cannot_ask, + &askers, + )?; Ok(ProjectChecks { policy, github_grants, store_grants, + service_facts, }) } +/// Approve every credential of `secrets` for the project at `project`, or +/// refuse the creation (BEP-105 to BEP-108): exit 5 for a denial or a no, exit +/// 2 for an `ask` that `can_ask` cannot answer, and exit 3 for a table that is +/// not valid. A project file never supplies a table. +fn approve_credentials( + global: &GlobalArgs, + project: &camino::Utf8Path, + secrets: &boxes::core::bep::SecretGrants, + cannot_ask: Option, + askers: &std::collections::BTreeMap, +) -> Result<(), anyhow::Error> { + if secrets.is_empty() { + return Ok(()); + } + let policy_path = crate::config::user_policy_path(global); + let organization = std::path::Path::new(crate::config::ORGANIZATION_CONFIG_PATH); + let home = ::dirs::home_dir().unwrap_or_default(); + let (user, organization_rules) = + crate::credential_approval::read_tables(&policy_path, organization, &home)?; + let project = crate::credential_approval::project_of(project.as_std_path()); + crate::credential_approval::approve( + secrets, + &project, + &crate::credential_approval::Tables { + user: &user, + organization: &organization_rules, + policy_path: &policy_path, + organization_path: organization, + }, + cannot_ask, + askers, + &mut crate::credential_approval::ask_at_terminal, + &mut |rule, error| { + crate::credential_approval::report_unsaved(&policy_path, rule, error); + }, + ) +} + +/// The approval of BEP-105 for the `[secrets]` of an expanded `spec` of a box +/// the command creates outside the session path, such as a task box. The +/// grants and the project root are read as the session path reads them, so a +/// task cannot hold a credential that a session could not. `project` is where +/// the command found the project. +/// +/// # Errors +/// +/// A `[secrets]` that does not parse, and the refusals of +/// [`crate::credential_approval`]. +pub(crate) fn approve_spec_secrets( + global: &GlobalArgs, + project: &camino::Utf8Path, + spec: &toml::Table, +) -> Result<(), anyhow::Error> { + let Some(secrets) = spec.get("secrets") else { + return Ok(()); + }; + let secrets: boxes::core::bep::SecretGrants = + boxes::core::bep::deserialize_project_secrets(secrets.clone()).map_err(|error| { + ProjectFileInvalid { + error: mfile::Error::Format(error), + } + })?; + let cannot_ask = if global.no_input { + Some(crate::credential_approval::CannotAsk::NoInput) + } else if !can_prompt_interactively() { + Some(crate::credential_approval::CannotAsk::NoTerminal) + } else { + None + }; + let root = crate::cmd::project::resolve_upload_root_quiet(project) + .unwrap_or_else(|_| project.to_path_buf()); + approve_credentials( + global, + &root, + &secrets, + cannot_ask, + &std::collections::BTreeMap::new(), + ) +} + +/// Who asked for each grant of `secrets`, for the approval's question and +/// refusal (BEP-108): a service of the box's `uses`, a loadout's service with +/// the hosts it adds, or the `[secrets]` table that declares it. +fn grant_askers( + secrets: &boxes::core::bep::SecretGrants, + expansion: Option<&BoxEntryExpansion>, + uses_layer: Option<&str>, + declared: &str, +) -> std::collections::BTreeMap { + use crate::credential_approval::Asker; + secrets + .keys() + .map(|variable| { + let derived = expansion.and_then(|e| { + e.derived_grants + .iter() + .find(|d| d.variable == *variable && !d.declared_instead) + }); + let by_loadout = expansion.and_then(|e| { + e.loadout_services + .iter() + .find(|l| l.grant.as_deref() == Some(variable.as_str())) + }); + let asker = if let Some(derived) = derived { + Asker { + who: format!( + "the service {}, which {} uses,", + derived.service, + uses_layer.unwrap_or(mfile::MFILE_NAME) + ), + ..Asker::default() + } + } else if let Some(l) = by_loadout { + Asker { + who: format!( + "the loadout {}, through its service {},", + l.loadout, l.service + ), + loadout: Some(l.loadout.clone()), + hosts: boxes::core::services::service(&l.service) + .map(service_host_set) + .unwrap_or_default(), + } + } else { + Asker { + who: format!("{},", declared_in(declared)), + ..Asker::default() + } + }; + (variable.clone(), asker) + }) + .collect() +} + /// The activation flow that bare `min` and `min session start` share. /// `options` carries `offer_scaffold`, which gates the `minimal.toml` /// scaffold offer. @@ -5788,10 +6362,15 @@ pub(crate) async fn activate_box( Ok::<_, anyhow::Error>((utf8_path, abs_path, port_mappings, egress)) }) .await?; + // BOX-244: the loadouts are read before the checks, so the checks see the + // grants and the hosts they bring. + let early_selected = + selected_loadouts_for(global, &utf8_path, options.entry.as_deref(), &args)?; let ProjectChecks { policy, github_grants, store_grants, + service_facts, } = ActivationStep::CheckProject .run(async { check_project( @@ -5803,6 +6382,7 @@ pub(crate) async fn activate_box( (port_mappings, egress), ProjectPrompts::Terminal, &bep::store::HostStore, + &early_selected, ) }) .await?; @@ -5895,9 +6475,14 @@ pub(crate) async fn activate_box( // BOX-064, BOX-179: the gated loadouts again, whole, for the // selected-loadouts layer of the entry's expansion. The read // above already refused a missing or malformed one. + // BOX-244: the selection the checks and the mint read, and not a + // second read of the loadout files, so the stored spec holds the + // grants that were checked, approved and minted. let selected = SelectedLoadouts { - loadouts: loadouts::resolve_active_loadouts(selection, &cfg, global)?.loadouts, + loadouts: early_selected.loadouts.clone(), ignore: Some(inputs.user_policy.vars().ignore().clone()), + // BOX-244: the facts check_project decided with. + service_facts, }; // Scaffold-offer a missing `minimal.toml` only after the loadouts @@ -6843,10 +7428,14 @@ pub(crate) async fn activate_box( // the true failure. match prompt::save_user_policy(&policy_path, &final_policy) { Ok(()) => eprintln!("Updated {}", policy_path.display()), - Err(e) => eprintln!( - "warning: failed to update {}: {e}", - policy_path.display() - ), + // CFW-004, CFW-007, CFW-012: the message waits for the + // end of the attach, so the shell's first paint does not + // replace it. + Err(e) => crate::client_file::defer(&prompt::policy_save_report( + &policy_path, + &final_policy, + &e, + )), } } if result.is_err() { @@ -7072,10 +7661,12 @@ pub(crate) async fn activate_box( let attach_args = AttachArgs { session: Some(id.to_string()), }; - return cmd_attach(global, attach_args).await; + let attached = cmd_attach(global, attach_args).await; + return crate::client_file::finish_after_attach(attached); } - Ok(()) + // No attach: nothing paints over the lines, so they print now (CFW-012). + crate::client_file::finish_after_attach(Ok(())) } /// The normalized form of each subnet flag entry, so the stored policy @@ -8210,7 +8801,8 @@ mod tests { ) .expect("write minimal.toml"); let path = camino::Utf8Path::from_path(project.path()).expect("utf-8 path"); - let (bep, secrets, spec_env, _) = project_bep_and_grants(path, None).expect("loads"); + let (bep, secrets, spec_env, _) = + project_bep_and_grants(path, None, &SelectedLoadouts::default()).expect("loads"); // The egress here is unset, so both runs refuse for that too. Only // the narrow-scope refusal depends on the acknowledgement. let narrow = |acknowledged: bool| { @@ -8257,7 +8849,8 @@ mod tests { ) .expect("write minimal.toml"); let path = camino::Utf8Path::from_path(project.path()).expect("utf-8 path"); - let (bep, secrets, spec_env, _) = project_bep_and_grants(path, None).expect("loads"); + let (bep, secrets, spec_env, _) = + project_bep_and_grants(path, None, &SelectedLoadouts::default()).expect("loads"); let egress = boxes::EgressPolicy { allow_dns_hosts: Some( bep::module::GITHUB @@ -8305,7 +8898,8 @@ mod tests { ) .expect("write minimal.toml"); let path = camino::Utf8Path::from_path(project.path()).expect("utf-8 path"); - let (bep, secrets, spec_env, _) = project_bep_and_grants(path, None).expect("loads"); + let (bep, secrets, spec_env, _) = + project_bep_and_grants(path, None, &SelectedLoadouts::default()).expect("loads"); assert_eq!(bep.steering, Some(boxes::core::bep::Steering::ProxyEnv)); assert!(credentialed_upstream_for(false, &bep, &secrets).is_none()); refuse_unhonourable_grants( @@ -8918,6 +9512,614 @@ mod tests { assert_ne!(jtis[0], jtis[1], "each member is its own handle"); } + /// A native store that must not be opened: probing it reports it unusable, + /// which the test that uses it catches. + struct UnopenedStore; + impl UnopenedStore { + fn refused() -> bep::store::StoreError { + bep::store::StoreError::Refused { + store: bep::store::NATIVE_STORE, + action: "open the store", + detail: "the test's store is never opened".into(), + } + } + } + impl bep::store::SecretStore for UnopenedStore { + fn name(&self) -> &'static str { + bep::store::NATIVE_STORE + } + fn check_available(&self) -> Result<(), bep::store::StoreError> { + Err(Self::refused()) + } + fn set( + &self, + _: &str, + _: &[u8], + _: &std::path::Path, + ) -> Result<(), bep::store::StoreError> { + Err(Self::refused()) + } + fn list( + &self, + _: &std::path::Path, + ) -> Result, bep::store::StoreError> { + Err(Self::refused()) + } + fn remove(&self, _: &str) -> Result { + Err(Self::refused()) + } + } + + // BOX-241: the host's native store is opened only when a selected loadout + // names a stored-secret service. Opening it can print a warning about the + // file store, so a box that needs no store never pays for one. + #[test] + fn service_facts_probe_the_native_store_only_when_a_loadout_needs_it() { + let global = crate::GlobalArgs::default(); + let facts = service_facts_for( + &global, + false, + &UnopenedStore, + boxes::NetworkMode::OwnIp, + Some(true), + false, + ); + assert!( + facts.native_store_usable, + "the store was probed with no need" + ); + // A loadout that does need it probes, and an unusable store shows. + let needed = service_facts_for( + &global, + false, + &UnopenedStore, + boxes::NetworkMode::OwnIp, + Some(true), + true, + ); + assert!(!needed.native_store_usable); + // The selection says what needs it. + let stored = SelectedLoadouts { + loadouts: vec![tool_loadout("[\"anthropic-oauth-token\"]")], + ..Default::default() + }; + let hosts_only = SelectedLoadouts { + loadouts: vec![tool_loadout("[\"claude-code\"]")], + ..Default::default() + }; + assert!(selected_need_native_store(&stored)); + assert!(!selected_need_native_store(&hosts_only)); + assert!(!selected_need_native_store(&SelectedLoadouts::default())); + } + + // ---- BOX-240, BOX-241, BEP-109: what a selected loadout brings ---- + + fn network_of( + hosts: &[&str], + subnets: &[&str], + uses: &[&str], + ) -> (Vec, Vec) { + ( + vec![mfile::expand::LoadoutNetwork { + loadout: "tool".into(), + allow_dns_hosts: hosts.iter().map(|h| (*h).to_owned()).collect(), + allow_subnets: subnets.iter().map(|h| (*h).to_owned()).collect(), + }], + uses.iter().map(|u| (*u).to_owned()).collect(), + ) + } + + fn effective(hosts: &[&str], subnets: &[&str]) -> EffectiveEgress { + EffectiveEgress { + policy: Some(boxes::EgressPolicy { + allow_dns_hosts: Some(hosts.iter().map(|h| (*h).to_owned()).collect()), + allow_subnets: Some(subnets.iter().map(|h| (*h).to_owned()).collect()), + ..boxes::EgressPolicy::default() + }), + ..Default::default() + } + } + + #[test] + fn open_loadout_network_joins_egress_after_last_layer() { + let (listed, _) = network_of( + &["A.example", "b.example."], + &["10.0.0.0/8", "10.1.0.0/16"], + &[], + ); + let mut egress = effective(&["a.example"], &["10.0.0.0/8"]); + resolve_loadout_network(&listed, &[], boxes::NetworkMode::OwnIp, false, &mut egress); + let policy = egress.policy.unwrap(); + // An item joins unless the egress already admits it, in any case or + // with a trailing dot, or a listed subnet covers it. + assert_eq!(policy.allow_dns_hosts.unwrap(), ["a.example", "b.example."]); + assert_eq!(policy.allow_subnets.unwrap(), ["10.0.0.0/8"]); + // Both lists join with nothing listed yet. + let mut egress = effective(&[], &[]); + resolve_loadout_network(&listed, &[], boxes::NetworkMode::OwnIp, false, &mut egress); + let policy = egress.policy.unwrap(); + // The second subnet is covered by the first once it joins. + assert_eq!(policy.allow_subnets.unwrap(), ["10.0.0.0/8"]); + assert!( + egress + .sources + .contains(&("allow_dns_hosts", EgressSource::Loadout)) + ); + } + + #[test] + fn loadout_egress_item_never_widens_allow_protocols() { + let (listed, _) = network_of(&["a.example"], &["10.0.0.0/8"], &[]); + let mut egress = effective(&[], &[]); + egress.policy.as_mut().unwrap().allow_protocols = Some(vec![boxes::IpProto::Tcp]); + resolve_loadout_network(&listed, &[], boxes::NetworkMode::OwnIp, false, &mut egress); + assert_eq!( + egress.policy.unwrap().allow_protocols, + Some(vec![boxes::IpProto::Tcp]) + ); + } + + #[test] + fn loadout_egress_lists_left_out_in_none_deny_all_and_names_only_without_name_rules() { + let (listed, _) = network_of(&["a.example"], &["10.0.0.0/8"], &[]); + // `none` and `--deny-all-egress` leave out both lists. + for (network, deny) in [ + (boxes::NetworkMode::NoNet, false), + (boxes::NetworkMode::OwnIp, true), + ] { + let mut egress = effective(&[], &[]); + resolve_loadout_network(&listed, &[], network, deny, &mut egress); + assert_eq!(egress, effective(&[], &[]), "{network:?} {deny}"); + } + // A host_ip box declares no name rule: it takes the subnets only. + let mut egress = effective(&[], &[]); + resolve_loadout_network( + &listed, + &[], + boxes::NetworkMode::HostNet, + false, + &mut egress, + ); + let policy = egress.policy.unwrap(); + assert_eq!(policy.allow_dns_hosts.unwrap(), Vec::::new()); + assert_eq!(policy.allow_subnets.unwrap(), ["10.0.0.0/8"]); + } + + #[test] + fn subnet_covering_follows_the_prefix() { + let cover = |allowed: &[&str], subnet: &str| { + subnet_covered( + &allowed.iter().map(|s| (*s).to_owned()).collect::>(), + subnet, + ) + }; + assert!(cover(&["0.0.0.0/0"], "10.1.2.0/24")); + assert!(cover(&["10.0.0.0/8"], "10.1.0.0/16")); + assert!(!cover(&["10.1.0.0/16"], "10.0.0.0/8")); + assert!(!cover(&["10.0.0.0/8"], "11.0.0.0/8")); + assert!(cover(&["::/0"], "fd00::/8")); + assert!(!cover(&["::/0"], "10.0.0.0/8"), "families never mix"); + assert!(!cover(&["10.0.0.0/8"], "not a subnet")); + } + + // ---- BEP-109: a selected loadout's service, through the checks ---- + + /// A loadout named `tool` that names `uses` in its `[network]`. + fn tool_loadout(uses: &str) -> boxes::core::loadout::Loadout { + toml::from_str(&format!("name = \"tool\"\n[network]\nuses = {uses}\n")).unwrap() + } + + struct LoadoutCreate { + _project: tempfile::TempDir, + config: tempfile::TempDir, + root: camino::Utf8PathBuf, + } + + impl LoadoutCreate { + fn new() -> Self { + let project = tempfile::tempdir().unwrap(); + std::fs::write( + project.path().join(mfile::MFILE_NAME), + "[sessions.dev]\nloadout_mode = \"open\"\n\ + network = { mode = \"own_ip\", egress = { allow_dns_hosts = [\"x.example\"] }, \ + bep = { steering = \"proxy_env\" } }\n", + ) + .unwrap(); + let config = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(config.path().join("minimal")).unwrap(); + let root = + camino::Utf8PathBuf::from_path_buf(std::fs::canonicalize(project.path()).unwrap()) + .unwrap(); + Self { + _project: project, + config, + root, + } + } + + fn rule(&self) { + std::fs::write( + self.config.path().join("minimal/config.toml"), + "[secret-store-rules.anthropic-oauth-token]\nauthorities = [\"api.anthropic.com\"]\n\ + header = \"Authorization\"\nprefix = \"Bearer \"\n", + ) + .unwrap(); + } + + fn approve(&self) { + std::fs::write( + self.config.path().join("minimal/user_policy.toml"), + format!( + "[credential-rules]\nrules = [{{ project = {:?}, credential = {{ source = \ + \"store\", store = \"keychain\", id = \"anthropic-oauth-token\" }}, \ + action = \"allow\" }}]\n", + self.root + ), + ) + .unwrap(); + } + + fn check( + &self, + loadout: boxes::core::loadout::Loadout, + ) -> Result { + self.check_from(&self.root, loadout) + } + + /// [`Self::check`] run from `dir`, a directory of the project. + fn check_from( + &self, + dir: &camino::Utf8Path, + loadout: boxes::core::loadout::Loadout, + ) -> Result { + let global = crate::GlobalArgs { + config_dir: Some(self.config.path().to_path_buf()), + no_input: true, + ..Default::default() + }; + let mut args = crate::cli::ActivateArgs::unflagged(); + check_project_with( + &global, + &mut args, + dir, + Some("dev"), + None, + (Vec::new(), None), + ProjectPrompts::Terminal, + &EveryItemStore, + &SelectedLoadouts { + loadouts: vec![loadout], + ..Default::default() + }, + Some(true), + ) + } + } + + #[test] + fn loadout_service_adds_hosts_and_derives_grant() { + let f = LoadoutCreate::new(); + f.rule(); + f.approve(); + let checks = f + .check(tool_loadout("[\"anthropic-oauth-token\"]")) + .unwrap(); + let hosts = checks.policy.egress.unwrap().allow_dns_hosts.unwrap(); + assert!(hosts.contains(&"api.anthropic.com".to_owned()), "{hosts:?}"); + assert_eq!(checks.store_grants.len(), 1); + } + + // BEP-105: the approval is of the project root. A creation run from a + // directory below it is the same project, so the same rule applies. + #[test] + fn approval_is_keyed_to_the_project_root_not_the_run_directory() { + let f = LoadoutCreate::new(); + f.rule(); + f.approve(); + let sub = f.root.join("crates").join("inner"); + std::fs::create_dir_all(&sub).unwrap(); + let checks = f + .check_from(&sub, tool_loadout("[\"anthropic-oauth-token\"]")) + .expect("the rule for the root covers a run from below it"); + assert_eq!(checks.store_grants.len(), 1); + // A rule that names the subdirectory is not the project's rule. + std::fs::write( + f.config.path().join("minimal/user_policy.toml"), + format!( + "[credential-rules]\nrules = [{{ project = {:?}, credential = {{ source = \ + \"store\", store = \"keychain\", id = \"anthropic-oauth-token\" }}, \ + action = \"allow\" }}]\n", + sub + ), + ) + .unwrap(); + let err = f + .check_from(&sub, tool_loadout("[\"anthropic-oauth-token\"]")) + .unwrap_err(); + assert!( + err.downcast_ref::() + .is_some(), + "{err:#}" + ); + } + + // BEP-106: a project file cannot approve its own credential. Its + // `[credential-rules]` is ignored, so the creation is refused as if no rule + // spoke, and nothing is asked. + #[test] + fn project_file_cannot_approve_its_own_credential() { + let f = LoadoutCreate::new(); + f.rule(); + let base = "[sessions.dev]\nloadout_mode = \"open\"\n\ + network = { mode = \"own_ip\", egress = { allow_dns_hosts = [\"x.example\"] }, \ + bep = { steering = \"proxy_env\" } }\n"; + for table in [ + format!( + "[credential-rules]\nrules = [{{ project = {:?}, credential = {{ source = \"store\", \ + store = \"keychain\", id = \"anthropic-oauth-token\" }}, action = \"allow\" }}]\n", + f.root + ), + "[credential-rules]\naction_for_unspecified = \"allow\"\n".to_owned(), + ] { + std::fs::write(f.root.join(mfile::MFILE_NAME), format!("{base}\n{table}")).unwrap(); + // No terminal and no `--no-input` answer: `check` never asks. + let err = f + .check(tool_loadout("[\"anthropic-oauth-token\"]")) + .unwrap_err(); + let refused = err + .downcast_ref::() + .unwrap_or_else(|| panic!("an approval refusal: {err:#}")); + assert_eq!(refused.exit_code(), 2, "{table}"); + } + } + + // BEP-105: a task box holds a credential only where a session box could. + #[test] + fn task_secrets_need_project_approval_like_a_session_box() { + let f = LoadoutCreate::new(); + let spec: toml::Table = toml::from_str( + "[secrets.CLAUDE_CODE_OAUTH_TOKEN]\nsource = \"store\"\nstore = \"keychain\"\n\ + id = \"anthropic-oauth-token\"\n", + ) + .unwrap(); + let global = crate::GlobalArgs { + config_dir: Some(f.config.path().to_path_buf()), + no_input: true, + ..Default::default() + }; + let err = approve_spec_secrets(&global, &f.root, &spec).unwrap_err(); + assert_eq!( + err.downcast_ref::() + .expect("an approval refusal") + .exit_code(), + 2 + ); + // A spec with no `[secrets]` asks nothing. + approve_spec_secrets(&global, &f.root, &toml::Table::new()).unwrap(); + // With the project approved, the task passes. + f.approve(); + approve_spec_secrets(&global, &f.root, &spec).unwrap(); + } + + #[test] + fn loadout_grant_needs_project_approval_like_any_grant() { + let f = LoadoutCreate::new(); + f.rule(); + // No terminal and no rule: refused with exit 2, naming the rule to add. + let err = f + .check(tool_loadout("[\"anthropic-oauth-token\"]")) + .unwrap_err(); + let refused = err + .downcast_ref::() + .expect("an approval refusal"); + assert_eq!(refused.exit_code(), 2); + assert!( + refused.to_string().contains("anthropic-oauth-token"), + "{refused}" + ); + } + + #[test] + fn loadout_grant_missing_credential_refuses_creation() { + // No rule: refused with exit 3 before any approval, with the command. + let f = LoadoutCreate::new(); + f.approve(); + let err = f + .check(tool_loadout("[\"anthropic-oauth-token\"]")) + .unwrap_err(); + let refused = err.downcast_ref::().expect("exit 3"); + assert!( + refused + .to_string() + .contains("min secret set anthropic-oauth-token --service anthropic-oauth-token"), + "{refused}" + ); + } + + #[test] + fn loadout_hosts_only_service_adds_hosts_and_asks_nothing() { + // No rule, no approval, no terminal: a hosts-only service has no + // grant, so nothing is checked and nothing is asked. + let f = LoadoutCreate::new(); + let checks = f.check(tool_loadout("[\"claude-code\"]")).unwrap(); + let hosts = checks.policy.egress.unwrap().allow_dns_hosts.unwrap(); + assert!( + hosts.contains(&"platform.claude.com".to_owned()), + "{hosts:?}" + ); + assert!(checks.store_grants.is_empty()); + } + + #[test] + fn grant_checks_mint_and_render_read_one_expansion() { + // The grants the checks read are the grants the stored spec holds. + let f = LoadoutCreate::new(); + f.rule(); + f.approve(); + let selected = SelectedLoadouts { + loadouts: vec![tool_loadout("[\"anthropic-oauth-token\"]")], + ..Default::default() + }; + let checked = f + .check(tool_loadout("[\"anthropic-oauth-token\"]")) + .unwrap(); + let expanded = session_box_expansion( + &f.root, + Some("dev"), + true, + &SelectedLoadouts { + service_facts: checked.service_facts, + ..selected + }, + ) + .unwrap() + .expect("the entry expands"); + assert_eq!( + expanded.spec["secrets"]["CLAUDE_CODE_OAUTH_TOKEN"]["id"].as_str(), + Some("anthropic-oauth-token") + ); + assert_eq!(expanded.loadout_services.len(), 1); + assert!(expanded.loadout_services[0].left_out.is_none()); + } + + /// The service's own grant: `CLAUDE_CODE_OAUTH_TOKEN` reading the item + /// `anthropic-oauth-token`. + fn service_grant() -> boxes::core::bep::SecretGrants { + boxes::core::bep::SecretGrants::from([( + "CLAUDE_CODE_OAUTH_TOKEN".into(), + store_reference("anthropic-oauth-token"), + )]) + } + + fn service_rule(authorities: &[&str], prefix: Option<&str>) -> boxes::core::bep::StoreRules { + boxes::core::bep::StoreRules::from([( + "anthropic-oauth-token".into(), + boxes::core::bep::StoreRuleConfig { + store: None, + authorities: authorities.iter().map(|a| (*a).to_owned()).collect(), + header: Some("Authorization".into()), + prefix: prefix.map(str::to_owned), + basic_auth: None, + action: None, + }, + )]) + } + + // BEP-104: a derived grant whose item, rule or sign-in the user lacks + // refuses the creation with exit 3 and names the command that supplies it. + #[test] + fn derived_grant_without_credential_names_command() { + let egress = egress_of(&["api.anthropic.com", "evil.example"]); + let accept = |store: &dyn bep::store::SecretStore, rules: &boxes::core::bep::StoreRules| { + accept_store_references_in( + &service_grant(), + boxes::NetworkMode::OwnIp, + Some(&egress), + rules, + false, + &mut never_ask, + store, + boxes::core::bep::SESSION_SECRETS_TABLE, + ) + }; + let command = "`min secret set anthropic-oauth-token --service anthropic-oauth-token`"; + // No rule. + let err = accept( + &bep::store::MemorySecretStore::default(), + &boxes::core::bep::StoreRules::new(), + ) + .expect_err("no rule"); + let text = err + .downcast_ref::() + .expect("exit 3") + .to_string(); + assert!(text.contains(command), "{text}"); + // A rule, and no item. + let rules = service_rule(&["api.anthropic.com"], Some("Bearer ")); + let err = accept(&bep::store::MemorySecretStore::default(), &rules).expect_err("no item"); + let text = err + .downcast_ref::() + .expect("exit 3") + .to_string(); + assert!(text.contains(command), "{text}"); + // A rule that registers another host, or another form, is not the + // service's secret. + for rules in [ + service_rule(&["api.anthropic.com", "evil.example"], Some("Bearer ")), + service_rule(&["api.anthropic.com"], None), + ] { + let err = accept(&EveryItemStore, &rules).expect_err("a different rule"); + let refused = err.downcast_ref::().expect("exit 3"); + assert!( + matches!(refused, GrantNotDelivered::ServiceRuleDiffers { .. }), + "{refused}" + ); + assert!(refused.to_string().contains(command), "{refused}"); + } + // The GitHub sign-in names `min auth login` (BEP-003). + let github = boxes::core::bep::SecretGrants::from([( + "GH_TOKEN".into(), + boxes::core::bep::SecretGrant { + source: boxes::core::bep::GrantSource::Broker, + scopes: vec!["github:user-token".into()], + mode: None, + }, + )]); + let err = boxes::core::bep::require_sign_in(&github, false).expect_err("no sign-in"); + assert!(err.to_string().contains("`min auth login`"), "{err}"); + } + + // BEP-104: a rule is compared as `min secret list` compares it, so a + // header in another case and an explicit default port are the service's. + #[test] + fn derived_grant_reads_a_rule_as_secret_list_reads_it() { + let mut rules = service_rule(&["API.Anthropic.com:443"], Some("Bearer ")); + rules.get_mut("anthropic-oauth-token").unwrap().header = Some("authorization".into()); + let rule = &rules["anthropic-oauth-token"]; + let missing = check_service_rule("CLAUDE_CODE_OAUTH_TOKEN", "anthropic-oauth-token", rule) + .expect("the same hosts and header in other spellings"); + assert!(missing.is_empty(), "{missing:?}"); + // Another port is another authority. + let other = service_rule(&["api.anthropic.com:8443"], Some("Bearer ")); + check_service_rule( + "CLAUDE_CODE_OAUTH_TOKEN", + "anthropic-oauth-token", + &other["anthropic-oauth-token"], + ) + .unwrap_err(); + } + + // BEP-104: a rule that lacks an authority of the service is used as + // written, and the missing authority is found. + #[test] + fn derived_grant_uses_rule_as_written_and_names_missing_authority() { + let rules = service_rule(&[], Some("Bearer ")); + let rule = &rules["anthropic-oauth-token"]; + let missing = check_service_rule("CLAUDE_CODE_OAUTH_TOKEN", "anthropic-oauth-token", rule) + .expect("a rule that only lacks a host is not refused"); + assert_eq!(missing, ["api.anthropic.com"]); + // The rule stands: the creation accepts it as it is. + let egress = egress_of(&["api.anthropic.com"]); + let accepted = accept_store_references_in( + &service_grant(), + boxes::NetworkMode::OwnIp, + Some(&egress), + &rules, + false, + &mut never_ask, + &EveryItemStore, + boxes::core::bep::SESSION_SECRETS_TABLE, + ) + .expect("accepted as written"); + assert_eq!(accepted, rules); + // A grant that is not the service's own is checked by no rule. + assert!( + check_service_rule("OTHER", "anthropic-oauth-token", rule) + .unwrap() + .is_empty() + ); + } + /// BEP-035: a store reference that no rule names is refused at /// creation, through the reader creation uses, with exit 3. A box with /// no store reference reads no configuration and passes. @@ -9297,7 +10499,8 @@ mod tests { ) .expect("write minimal.toml"); let path = camino::Utf8Path::from_path(project.path()).expect("utf-8 path"); - let (bep, secrets, spec_env, _) = project_bep_and_grants(path, None).expect("loads"); + let (bep, secrets, spec_env, _) = + project_bep_and_grants(path, None, &SelectedLoadouts::default()).expect("loads"); assert!(credentialed_upstream_for(false, &bep, &secrets).is_some()); assert_eq!(bep.resolved_steering().word(), word); assert_eq!(bep.resolved_steering() == Steering::Both, word == "both"); @@ -9504,7 +10707,8 @@ mod tests { argv.extend(flags); let mut args = parsed_activate_args(&argv); let path = camino::Utf8Path::from_path(project).expect("utf-8 path"); - let (bep, secrets, spec_env, _) = project_bep_and_grants(path, entry).expect("loads"); + let (bep, secrets, spec_env, _) = + project_bep_and_grants(path, entry, &SelectedLoadouts::default()).expect("loads"); let (port_mappings, flag_egress) = flag_network_overrides(&args).expect("flags parse"); let mut project_egress = project_egress(path, entry).expect("egress loads"); let (network, port_mappings) = diff --git a/crates/minimal/src/cmd/secret.rs b/crates/minimal/src/cmd/secret.rs index b8bdc93e4c..39a885da5f 100644 --- a/crates/minimal/src/cmd/secret.rs +++ b/crates/minimal/src/cmd/secret.rs @@ -126,6 +126,7 @@ pub fn cmd_secret_set(global: &GlobalArgs, args: SecretSetArgs) -> anyhow::Resul let id = args.id.clone(); let control = crate::mint::control_path(); let mut confirm = |change: &str| confirm_rule_change(&id, change); + let mut ask = |question: &str| confirm_store_anyway(&id, question); run_set_with_rule( &HostStore, &args, @@ -139,6 +140,8 @@ pub fn cmd_secret_set(global: &GlobalArgs, args: SecretSetArgs) -> anyhow::Resul confirm: &mut confirm, notice: &mut std::io::stderr(), control: control.as_deref(), + organization: Path::new(crate::config::ORGANIZATION_CONFIG_PATH), + ask: &mut ask, }), ) } @@ -153,6 +156,16 @@ fn confirm_rule_change(id: &str, change: &str) -> anyhow::Result { .context("min secret set did not read the answer from the terminal") } +/// Show `question` on stderr and ask on the terminal whether to store the +/// item `id` without its rule. The answer defaults to no. +fn confirm_store_anyway(id: &str, question: &str) -> anyhow::Result { + eprintln!("{question}"); + inquire::Confirm::new(&format!("Store {id} anyway?")) + .with_default(false) + .prompt() + .context("min secret set did not read the answer from the terminal") +} + /// The proxy path for `set`, after the store check. Review finding /// 4369647104: a host with no store refuses with the store message, and /// never sends the person to put `minvmd` on PATH first. @@ -293,8 +306,36 @@ fn refuse_set_args(args: &SecretSetArgs) -> anyhow::Result<()> { bail!("{VALUE_ARGUMENT_REFUSED}"); } check_id(SET, &args.id)?; - check_store(SET, args.store.as_deref())?; + // A name the library lacks, a sign-in and a service with no secret are + // refused first, with what the library holds. requested_rule(args)?; + if let Some(name) = &args.service { + refuse_service_args(args, name)?; + } + check_store(SET, args.store.as_deref())?; + Ok(()) +} + +/// The refusals of `--service ` that come from the other arguments +/// (BEP-079). A service resolves to the item of the native store whose +/// identifier is its name (BEP-103), so a rule for another identifier, or in +/// another store, would be one that no box uses. +fn refuse_service_args(args: &SecretSetArgs, name: &str) -> anyhow::Result<()> { + if let Some(store) = args.store.as_deref().filter(|s| *s != NATIVE_STORE) { + bail!( + "min secret set refused --store {store} with --service {name}: a service resolves to \ + an item of the host's own store, `{NATIVE_STORE}`. Run `min secret set {name} \ + --service {name}` without --store." + ); + } + if args.id != name { + bail!( + "min secret set refused the name {id} with --service {name}: a service resolves to \ + the item named {name}, so a rule under another name is one that no box uses. \ + Run `min secret set {name} --service {name}`.", + id = args.id + ); + } Ok(()) } @@ -424,6 +465,13 @@ pub(crate) struct RuleTarget<'a> { /// The proxy's control socket, which gets the re-certify request after /// the rule is written. `None` asks no proxy. pub control: Option<&'a Path>, + /// The organization configuration. Its rules apply with the user's, so + /// the rule that applies to an item is read from both (BEP-095). + pub organization: &'a Path, + /// Show `question` on the terminal and ask whether to store the item + /// anyway when the rule cannot be written (BEP-093, BEP-096). `true` is a + /// yes. The answer defaults to no. + pub ask: &'a mut dyn FnMut(&str) -> anyhow::Result, } /// The fields of `rule`, one per line, as the change prompt shows them. @@ -469,6 +517,129 @@ fn rule_diff(current: &StoreRuleConfig, new: &StoreRuleConfig) -> String { changes.join(", and ") } +/// Whether two rules send a value to the same authorities in the same form. +/// The consent `action` and the `store` are not fields of a rule that +/// `set` gives (BEP-079). +fn same_fields(a: &StoreRuleConfig, b: &StoreRuleConfig) -> bool { + a.authorities == b.authorities + && a.header == b.header + && a.prefix == b.prefix + && a.basic_auth == b.basic_auth +} + +/// The rule that applies to the native-store item `id`: the merge of the +/// user and the organization configurations, as `bep serve` reads it. +/// +/// # Errors +/// +/// A configuration that is not read: the user file, or the organization file +/// when it exists. `None` is a successful read that found no rule for `id`, so +/// nothing is accepted on a guess about a file that was not read. +fn applicable_rule(target: &RuleTarget<'_>, id: &str) -> anyhow::Result> { + let module_hosts = crate::config::store_module_hosts(); + let read = boxes::client::config::read_client_store_rules( + target.path, + target.organization, + crate::config::store_deny_set(&module_hosts), + ) + .map_err(|e| { + anyhow::anyhow!( + "min secret set stored nothing: it did not read the rules that apply to {id}: {e}" + ) + })?; + if let Some(e) = &read.organization_error { + anyhow::bail!( + "min secret set stored nothing: it did not read the organization rules that apply \ + to {id}: {e}" + ); + } + Ok(rule_for(&read.rules, NATIVE_STORE, id).cloned()) +} + +/// `set` could not write `rule` for `args.id` to the client configuration: +/// `error` says why. Print the lines to add (CFW-004, CFW-007), then decide +/// whether the item is stored without the rule. `Ok` is a go-ahead to store. +/// +/// - No rule applies (BEP-093): ask, and `--yes` answers. The item is unused +/// until the person adds the rule (BEP-095). +/// - The rule that applies has the same fields: store, and say so (BEP-095). +/// - The rule that applies has other fields (BEP-096): ask. Only a terminal +/// answers, because the new value would go to the old authorities. +fn store_without_rule( + args: &SecretSetArgs, + source: ValueSource, + target: &mut RuleTarget<'_>, + rule: &StoreRuleConfig, + error: crate::client_file::WriteError, + user_file_has_entry: bool, +) -> anyhow::Result<()> { + let id = &args.id; + let path = target.path.display().to_string(); + let applicable = applicable_rule(target, id)?; + if applicable.as_ref().is_some_and(|a| same_fields(a, rule)) { + let said = crate::client_file::Report::add(error, Vec::new()).render(); + writeln!( + target.notice, + "{said} The rule for {id} that applies already has these fields, so there is nothing to add." + )?; + return Ok(()); + } + let mut report = + crate::client_file::Report::add(error, crate::config::store_rule_lines(id, rule)); + if user_file_has_entry { + report = report.replacing(format!("a [secret-store-rules.{id}] section")); + } + write!(target.notice, "{}", report.render())?; + let can_ask = source == ValueSource::Terminal; + let question = match &applicable { + None => { + if args.yes { + return Ok(()); + } + if !can_ask { + bail!( + "min secret set stored nothing: it did not write the rule for {id}, and it \ + cannot ask you whether to store {id} without it. Run the command again \ + with --yes to store {id} anyway." + ); + } + format!( + "min secret set did not write the rule for {id}. No box uses {id} until you add \ + the rule." + ) + } + Some(existing) => { + let authorities = existing.authorities.join(", "); + if !can_ask { + bail!( + "min secret set stored nothing: the rule for {id} that applies sends the \ + value to {authorities}, and --yes does not answer a question about where a \ + value goes. Add the lines above to {path}, and run the command again." + ); + } + let (have, want) = (injection(existing), injection(rule)); + let form = if have == want { + String::new() + } else { + format!( + " It sends the value as {have}, and the rule you gave would send it as {want}." + ) + }; + format!( + "min secret set did not write the rule for {id}. The rule that applies sends \ + the new value of {id} to its own authorities, {authorities}.{form}" + ) + } + }; + if !(target.ask)(&question)? { + bail!( + "min secret set stored nothing, and {id} is unchanged. Add the lines above to {path}, \ + and run the command again." + ); + } + Ok(()) +} + /// Decide whether `set` writes a rule for `args.id` to `target`, before /// the value is read. `None` when the file already holds that rule. /// @@ -490,14 +661,39 @@ fn plan_rule( target.path.display() ) })?; - let Some(current) = rules.remove(id) else { - return Ok(Some((rule, None))); - }; - rule.action = current.action; - rule.store.clone_from(¤t.store); - if current == rule { + let current = rules.remove(id); + // `set` stores an item of the native store. A rule for this name that + // belongs to another store would keep its `store`, so the rule would stay + // for the other store's item and the native item would have none. + if let Some(other) = current + .as_ref() + .and_then(|rule| rule.store.as_deref()) + .filter(|store| *store != NATIVE_STORE) + { + bail!( + "min secret set stored nothing: {path} already has a rule for {id} in the store \ + `{other}`, and `set` stores {id} in the host's own store, `{NATIVE_STORE}`. Remove \ + or rename that rule, and run the command again.", + path = target.path.display() + ); + } + if let Some(current) = ¤t { + rule.action = current.action; + rule.store.clone_from(¤t.store); + if *current == rule { + return Ok(None); + } + } + // CFW-001: the file is tested before anything asks about replacing a rule + // in it. A file `min` cannot replace is not a failure (CFW-003), and the + // item can still be stored when the person says so (BEP-093, BEP-096). + if let Err(unwritable) = crate::client_file::can_replace(target.path) { + store_without_rule(args, source, target, &rule, unwritable, current.is_some())?; return Ok(None); } + let Some(current) = current else { + return Ok(Some((rule, None))); + }; if args.yes { let line = format!( "min secret set replaces the rule for {id} in {}: {}.", @@ -678,13 +874,11 @@ pub(crate) fn run_set_with_rule( } let control = target.as_ref().and_then(|target| target.control); // BEP-079: the rule is checked, and any change confirmed, before the - // value is read. + // value is read. BEP-093 and BEP-096 ask here too when the file cannot + // be replaced. let mut write = match (rule, target.as_mut()) { (None, _) => None, - (Some(rule), Some(target)) => match plan_rule(args, rule, source, target)? { - None => None, - Some((rule, line)) => Some((target.path, rule, line, &mut *target.notice)), - }, + (Some(rule), Some(target)) => plan_rule(args, rule, source, target)?, (Some(_), None) => bail!("min secret set has no configuration file to write the rule to"), }; let value = match source { @@ -709,29 +903,53 @@ pub(crate) fn run_set_with_rule( "min secret set stored nothing: the value is empty. Run the command again and give a value." ); } - let snapshot = match &mut write { - None => None, - Some((path, rule, line, notice)) => { - if let Some(line) = line { - writeln!(notice, "{line}")?; + let mut snapshot = None; + let mut written_rule = None; + // A write that fails on a file `min` could replace (CFW-006): the other + // steps still run, after the same question, and the command exits + // non-zero (CFW-008). + let mut failed_write = None; + if let (Some((rule, line)), Some(target)) = (write.take(), target.as_mut()) { + if let Some(line) = line { + writeln!(target.notice, "{line}")?; + } + match crate::config::write_store_rule(target.path, &args.id, &rule) { + Ok(done) => { + tracing::info!( + id = %args.id, + authorities = %rule.authorities.join(", "), + file = %target.path.display(), + "secret-store rule written" + ); + snapshot = Some((target.path, done)); + written_rule = Some(rule); } - let snapshot = - crate::config::write_store_rule(path, &args.id, rule).with_context(|| { - format!( + Err(e) => { + let Some(error) = e.downcast_ref::().cloned() + else { + return Err(e.context(format!( "min secret set stored nothing: it did not write the rule for {} to {}", args.id, - path.display() - ) - })?; - tracing::info!( - id = %args.id, - authorities = %rule.authorities.join(", "), - file = %path.display(), - "secret-store rule written" - ); - Some((*path, snapshot)) + target.path.display() + ))); + }; + let failed = !error.is_unwritable(); + let user_file_has_entry = crate::config::read_config_parts(target.path) + .is_ok_and(|(_, rules)| rules.contains_key(&args.id)); + store_without_rule( + args, + source, + target, + &rule, + error.clone(), + user_file_has_entry, + )?; + if failed { + failed_write = Some(error); + } + } } - }; + } if let Err(e) = store.set(&args.id, &value, proxy) { // The new value is stored, so "did not store" is not true, and the // rule stays with it. @@ -757,12 +975,44 @@ pub(crate) fn run_set_with_rule( } Err(restore) => { tracing::warn!(id = %args.id, error = %restore, "secret-store rule not restored"); + // BEP-098: the new rule is in force, and the item may + // still hold its old value, which would go to the new + // authorities. With no item, nothing is sent. + let id = &args.id; message.push_str(&format!( - ". The rule for {id} in {path} was not put back: {restore:#}. \ - Check [secret-store-rules.{id}] in {path}", - id = args.id, + ". The rule for {id} in {path} was not put back: {restore:#}", path = path.display() )); + // Only a rule that is still in force sends the old value + // to the new authorities. When another edit has removed + // it, the item is kept and the conflict reported. A file + // that cannot be read is treated as still in force. + let still_in_force = match crate::config::read_config_parts(path) { + Ok((_, mut rules)) => rules.remove(id).as_ref() == written_rule.as_ref(), + Err(_) => true, + }; + if !still_in_force { + message.push_str(&format!( + ". The rule that replaced it is no longer in {path}, so min kept \ + {id}. Check [secret-store-rules.{id}] in {path}", + path = path.display() + )); + } else { + match store.remove(id) { + Ok(_) => message.push_str(&format!( + ". min removed {id} from {place}, so nothing sends its old \ + value to the new rule's authorities. Run `min secret set {id}` \ + again", + place = store.place() + )), + Err(removal) => message.push_str(&format!( + ". min failed to remove {id}: {removal}. {id} can still send \ + its old value to the authorities of the rule in {path}. Run \ + `min secret rm {id}`", + path = path.display() + )), + } + } } } } @@ -770,8 +1020,15 @@ pub(crate) fn run_set_with_rule( } tracing::info!(store = store.name(), id = %args.id, "secret stored"); writeln!(out, "{}", args.id)?; - if let (Some(control), Some((_, rule, _, notice))) = (control, &mut write) { - recertify(control, &args.id, &rule.authorities, &mut **notice)?; + if let (Some(control), Some(rule), Some(target)) = (control, &written_rule, target.as_mut()) { + recertify(control, &args.id, &rule.authorities, &mut *target.notice)?; + } + if let Some(error) = failed_write { + bail!( + "min secret set stored {id}, and did not save its rule: {error}. \ + The lines to add are printed above.", + id = args.id + ); } // The value went to the encrypted file store only when this session // has no Secret Service keyring that takes it, and the command says so. @@ -938,6 +1195,28 @@ fn injection(rule: &StoreRuleConfig) -> String { /// entry. A rule lies within it when every authority it registers is one of /// the entry's and its injection form is the entry's. `None` when no /// stored-secret service has the item's name. +/// Whether two authorities are the same host and port as the proxy reads them: +/// the host in any case and with no trailing dot, and port 443 where none is +/// written. One that does not parse equals nothing. +pub(crate) fn same_authority(a: &str, b: &str) -> bool { + let key = |authority: &str| { + bep::handle::parse_authority(authority) + .map(|parsed| (parsed.host.trim_end_matches('.').to_owned(), parsed.port)) + }; + matches!((key(a), key(b)), (Some(a), Some(b)) if a == b) +} + +/// Whether `rule` injects the secret in the form of the service entry: the +/// header by name in any case, as HTTP compares it, the same prefix (none and +/// an empty one send the same header), and no basic authentication. +pub(crate) fn same_injection(rule: &StoreRuleConfig, header: &str, prefix: Option<&str>) -> bool { + rule.header + .as_deref() + .is_some_and(|name| name.eq_ignore_ascii_case(header)) + && rule.prefix.as_deref().unwrap_or("") == prefix.unwrap_or("") + && rule.basic_auth.is_none() +} + fn service_mark(id: &str, rule: Option<&StoreRuleConfig>) -> Option { let entry = services::service(id)?; let ServiceSecret::Store { @@ -951,24 +1230,12 @@ fn service_mark(id: &str, rule: Option<&StoreRuleConfig>) -> Option { let Some(rule) = rule else { return Some(format!("{id}, with no rule")); }; - // An authority is compared as the proxy reads it: the host in any case - // and with no trailing dot, and port 443 where none is written. - let key = |authority: &str| { - bep::handle::parse_authority(authority) - .map(|parsed| (parsed.host.trim_end_matches('.').to_owned(), parsed.port)) - }; let within = !rule.authorities.is_empty() - && rule.authorities.iter().all(|a| { - key(a).is_some_and(|a| authorities.iter().any(|e| key(e).as_ref() == Some(&a))) - }) - // A header name matches in any case, as HTTP compares it. && rule - .header - .as_deref() - .is_some_and(|name| name.eq_ignore_ascii_case(header)) - // No prefix and an empty one send the same header. - && rule.prefix.as_deref().unwrap_or("") == prefix.unwrap_or("") - && rule.basic_auth.is_none(); + .authorities + .iter() + .all(|a| authorities.iter().any(|e| same_authority(a, e))) + && same_injection(rule, header, prefix); Some(if within { format!( "{id}, and its rule sends the secret only to the service's hosts, in the service's header" @@ -985,7 +1252,8 @@ pub fn cmd_secret_rm(global: &GlobalArgs, args: SecretRmArgs) -> anyhow::Result< let path = crate::config::user_config_path(global); let can_ask = !global.no_input && std::io::stdin().is_terminal(); let id = args.id.clone(); - let mut confirm = |rule: &str| confirm_rule_removal(&id, rule); + let mut confirm = + |rule: &str, removes_rule: bool| confirm_rule_removal(&id, rule, removes_rule); run_rm_with_rule( &HostStore, &args, @@ -1000,10 +1268,16 @@ pub fn cmd_secret_rm(global: &GlobalArgs, args: SecretRmArgs) -> anyhow::Result< } /// Show `rule` on stderr and ask on the terminal whether to remove the -/// secret `id` and its rule. The answer defaults to no. -fn confirm_rule_removal(id: &str, rule: &str) -> anyhow::Result { +/// secret `id`, and its rule when `removes_rule` is set. The answer defaults +/// to no. +fn confirm_rule_removal(id: &str, rule: &str, removes_rule: bool) -> anyhow::Result { eprintln!("{rule}"); - inquire::Confirm::new(&format!("Remove the secret {id} and its rule?")) + let question = if removes_rule { + format!("Remove the secret {id} and its rule?") + } else { + format!("Remove the secret {id}?") + }; + inquire::Confirm::new(&question) .with_default(false) .prompt() .context("min secret rm did not read the answer from the terminal") @@ -1015,8 +1289,10 @@ pub(crate) struct RmRuleTarget<'a> { pub path: &'a Path, /// Whether a terminal can answer the question. pub can_ask: bool, - /// Show the rule and ask the person at the terminal. `true` removes it. - pub confirm: &'a mut dyn FnMut(&str) -> anyhow::Result, + /// Show the text and ask the person at the terminal. `true` removes the + /// secret. The flag says whether the rule goes with it: it does not when + /// `min` cannot replace the file (BEP-053). + pub confirm: &'a mut dyn FnMut(&str, bool) -> anyhow::Result, /// Where `--yes` says which rule it removes. pub notice: &'a mut dyn Write, } @@ -1159,6 +1435,27 @@ fn remove_rule_for_rm( path.display(), rule_lines(rule) ); + // CFW-001: a file `min` cannot replace keeps its rule. The lines to remove + // are printed, the same confirmation asks about the secret alone, and the + // secret goes only after a yes (BEP-053). + if let Err(unwritable) = crate::client_file::can_replace(path) { + let report = crate::client_file::Report::remove( + unwritable, + crate::config::store_rule_lines(id, rule), + ) + .render(); + if args.yes { + write!(target.notice, "{report}")?; + } else if !target.can_ask { + bail!( + "min secret rm removed nothing: it cannot ask you whether to remove {id} and \ + leave its rule.\n{report}\nRun the command again with --yes to remove {id}." + ); + } else if !(target.confirm)(&report, false)? { + bail!("min secret rm removed nothing: the secret {id} and its rule are unchanged."); + } + return Ok(None); + } if args.yes { writeln!( target.notice, @@ -1171,7 +1468,7 @@ fn remove_rule_for_rm( {shown}\n\ Run the command again with --yes to remove the secret and its rule." ); - } else if !(target.confirm)(&shown)? { + } else if !(target.confirm)(&shown, true)? { bail!("min secret rm removed nothing: the secret {id} and its rule are unchanged."); } let snapshot = crate::config::remove_store_rule(path, id, rule).with_context(|| { @@ -1726,6 +2023,8 @@ mod tests { confirm: &mut no_confirm, notice: &mut notice, control: None, + organization: Path::new("/nonexistent/org.toml"), + ask: &mut no_ask, }), ) .unwrap(); @@ -2104,7 +2403,7 @@ sentry let mut out = Vec::new(); let mut notice = Vec::new(); let mut shown = None; - let mut confirm = |rule: &str| { + let mut confirm = |rule: &str, _removes_rule: bool| { shown = Some(rule.to_owned()); Ok(answer) }; @@ -2595,6 +2894,8 @@ attributes: confirm, notice: &mut std::io::sink(), control: None, + organization: Path::new("/nonexistent/org.toml"), + ask: &mut no_ask, }), ); (result, String::from_utf8(out).unwrap()) @@ -2604,6 +2905,15 @@ attributes: panic!("the change prompt was shown") } + /// `EXISTING`, with the rule under the name of the service it matches. + fn existing_service() -> String { + EXISTING.replace("claude", "anthropic-oauth-token") + } + + fn no_ask(_: &str) -> anyhow::Result { + Err(anyhow::anyhow!("the store-anyway question was asked")) + } + /// The rules of the client configuration at `path`, as written. fn written_rules(path: &Path) -> StoreRules { crate::config::read_config_parts(path).expect("parses").1 @@ -2624,7 +2934,7 @@ attributes: /// rule for another item. const EXISTING: &str = "# my settings\n\ [secrets]\nacknowledge_full_breadth_unenrolled = true\n\n\ - [secret-store-rules.claude]\nauthorities = [\"api.anthropic.com\"]\nheader = \"x-api-key\"\naction = \"ask\"\n\n\ + [secret-store-rules.claude]\nauthorities = [\"api.anthropic.com\"]\nheader = \"x-api-key\"\n\n\ [secret-store-rules.other]\nauthorities = [\"api.example.com\"]\nbasic_auth = \"password\"\n"; #[test] @@ -2752,7 +3062,11 @@ attributes: let store = MemorySecretStore::default(); let (result, _) = set_with_rule( &store, - &["claude", "--service", "anthropic-oauth-token"], + &[ + "anthropic-oauth-token", + "--service", + "anthropic-oauth-token", + ], &proxy, ValueSource::Stdin, &path, @@ -2766,7 +3080,7 @@ attributes: assert!( String::from_utf8(written) .unwrap() - .contains("[secret-store-rules.claude]") + .contains("[secret-store-rules.anthropic-oauth-token]") ); assert_eq!(after, before, "only the user config.toml changed"); assert_eq!( @@ -2812,7 +3126,7 @@ attributes: ), ]; for (name, authorities, header, prefix) in expected { - let id = format!("key-{name}"); + let id = name.to_owned(); let (result, _) = set_with_rule( &store, &[&id, "--service", name], @@ -2839,7 +3153,7 @@ attributes: "min", "secret", "set", - "claude", + "anthropic-oauth-token", "--service", "anthropic-oauth-token", ]; @@ -2888,7 +3202,7 @@ attributes: let mut out = Vec::new(); let err = run_set_with_rule( &store, - &set_args(&["claude", "--service", name]), + &set_args(&["anthropic-oauth-token", "--service", name]), &proxy, source, &mut no_terminal, @@ -2899,6 +3213,8 @@ attributes: confirm: &mut no_confirm, notice: &mut std::io::sink(), control: None, + organization: Path::new("/nonexistent/org.toml"), + ask: &mut no_ask, }), ) .expect_err("refused"); @@ -2906,16 +3222,18 @@ attributes: assert!(out.is_empty()); } // The args check that `cmd_secret_set` runs first refuses it too. - assert!(refuse_set_args(&set_args(&["claude", "--service", name])).is_err()); + assert!( + refuse_set_args(&set_args(&["anthropic-oauth-token", "--service", name])).is_err() + ); } - assert!(store.value("claude").is_none()); + assert!(store.value("anthropic-oauth-token").is_none()); assert!(!path.exists()); let Err(err) = crate::Cli::try_parse_from([ "min", "secret", "set", - "claude", + "anthropic-oauth-token", "--preset", "anthropic-oauth-token", ]) else { @@ -2941,33 +3259,61 @@ attributes: assert!(!names.contains("github"), "{names}"); for (argv, want) in [ ( - &["min", "secret", "set", "claude", "--preset", "github"][..], + &[ + "min", + "secret", + "set", + "anthropic-oauth-token", + "--preset", + "github", + ][..], "--preset is replaced by --service, and github is a sign-in, not a stored \ secret. Run `min auth login` to sign in" .to_owned(), ), ( - &["min", "secret", "set", "claude", "--preset", "anthropic"][..], + &[ + "min", + "secret", + "set", + "anthropic-oauth-token", + "--preset", + "anthropic", + ][..], "--preset is replaced by --service. Run the command again with \ --service anthropic-oauth-token" .to_owned(), ), ( - &["min", "secret", "set", "claude", "--preset", "claude-code"], + &[ + "min", + "secret", + "set", + "anthropic-oauth-token", + "--preset", + "claude-code", + ], "--preset is replaced by --service, and claude-code gives hosts only, with no \ secret to store. To let a box reach its hosts, add \"claude-code\" to \ network.uses in minimal.toml, or start the box with --allow-service claude-code" .to_owned(), ), ( - &["min", "secret", "set", "claude", "--preset", "linear"], + &[ + "min", + "secret", + "set", + "anthropic-oauth-token", + "--preset", + "linear", + ], format!( "--preset is replaced by --service, and there is no service named linear. \ Run the command again with --service , where is one of: {names}" ), ), ( - &["min", "secret", "set", "claude", "--preset"], + &["min", "secret", "set", "anthropic-oauth-token", "--preset"], format!( "--preset is replaced by --service. Run the command again with \ --service , where is one of: {names}" @@ -3054,6 +3400,8 @@ attributes: confirm: &mut no_confirm, notice: &mut std::io::sink(), control: None, + organization: Path::new("/nonexistent/org.toml"), + ask: &mut no_ask, }), ) .expect_err("refused"); @@ -3078,11 +3426,15 @@ attributes: let store = MemorySecretStore::default(); // Declined: neither the item nor the rule is written. - std::fs::write(&path, EXISTING).unwrap(); + std::fs::write(&path, existing_service()).unwrap(); let mut shown = Vec::new(); let (result, out) = set_with_rule( &store, - &["claude", "--service", "anthropic-oauth-token"], + &[ + "anthropic-oauth-token", + "--service", + "anthropic-oauth-token", + ], &proxy, ValueSource::Terminal, &path, @@ -3092,20 +3444,23 @@ attributes: }, ); let text = format!("{:#}", result.expect_err("declined")); - assert!(text.contains("the rule for claude is unchanged"), "{text}"); assert!( - text.contains("`min secret set claude` without rule flags"), + text.contains("the rule for anthropic-oauth-token is unchanged"), + "{text}" + ); + assert!( + text.contains("`min secret set anthropic-oauth-token` without rule flags"), "{text}" ); assert!(out.is_empty()); - assert!(store.value("claude").is_none()); - assert_eq!(std::fs::read_to_string(&path).unwrap(), EXISTING); + assert!(store.value("anthropic-oauth-token").is_none()); + assert_eq!(std::fs::read_to_string(&path).unwrap(), existing_service()); assert_eq!( shown, [format!( - "{} has a different secret-store rule for claude.\n\ - Current rule:\n authorities: api.anthropic.com\n injection: header x-api-key\n consent: ask\n\ - New rule:\n authorities: api.anthropic.com\n injection: header Authorization, prefix \"Bearer \"\n consent: ask", + "{} has a different secret-store rule for anthropic-oauth-token.\n\ + Current rule:\n authorities: api.anthropic.com\n injection: header x-api-key\n consent: none\n\ + New rule:\n authorities: api.anthropic.com\n injection: header Authorization, prefix \"Bearer \"\n consent: none", path.display() )] ); @@ -3115,7 +3470,11 @@ attributes: let mut asked = 0; let (result, out) = set_with_rule( &store, - &["claude", "--service", "anthropic-oauth-token"], + &[ + "anthropic-oauth-token", + "--service", + "anthropic-oauth-token", + ], &proxy, ValueSource::Terminal, &path, @@ -3126,23 +3485,31 @@ attributes: ); result.unwrap(); assert_eq!(asked, 1); - assert_eq!(out, "claude\n"); - assert_eq!(store.value("claude").as_deref(), Some(&b"typed"[..])); + assert_eq!(out, "anthropic-oauth-token\n"); + assert_eq!( + store.value("anthropic-oauth-token").as_deref(), + Some(&b"typed"[..]) + ); let rules = written_rules(&path); - // The hand-set `ask` stays (review finding 4371881769). + // The rule carries no consent (BEP-094). assert_eq!( - rules.get("claude"), - Some(&StoreRuleConfig { - action: Some(StoreAction::Ask), - ..header_rule("api.anthropic.com", "Authorization", Some("Bearer ")) - }) + rules.get("anthropic-oauth-token"), + Some(&header_rule( + "api.anthropic.com", + "Authorization", + Some("Bearer ") + )) ); assert!(rules.contains_key("other")); // The same rule again is not a change, so nothing is asked. let (result, _) = set_with_rule( &store, - &["claude", "--service", "anthropic-oauth-token"], + &[ + "anthropic-oauth-token", + "--service", + "anthropic-oauth-token", + ], &proxy, ValueSource::Terminal, &path, @@ -3156,10 +3523,10 @@ attributes: let (_dir, proxy) = proxy(); let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("config.toml"); - std::fs::write(&path, EXISTING).unwrap(); + std::fs::write(&path, existing_service()).unwrap(); let store = MemorySecretStore::default(); store - .set("claude", b"old", &proxy) + .set("anthropic-oauth-token", b"old", &proxy) .expect("the old value is stored"); for source in [ ValueSource::Stdin, @@ -3169,7 +3536,11 @@ attributes: let mut out = Vec::new(); let err = run_set_with_rule( &store, - &set_args(&["claude", "--service", "anthropic-oauth-token"]), + &set_args(&[ + "anthropic-oauth-token", + "--service", + "anthropic-oauth-token", + ]), &proxy, source, &mut no_terminal, @@ -3180,6 +3551,8 @@ attributes: confirm: &mut no_confirm, notice: &mut std::io::sink(), control: None, + organization: Path::new("/nonexistent/org.toml"), + ask: &mut no_ask, }), ) .expect_err("refused"); @@ -3197,8 +3570,11 @@ attributes: ); assert!(out.is_empty()); } - assert_eq!(store.value("claude").as_deref(), Some(&b"old"[..])); - assert_eq!(std::fs::read_to_string(&path).unwrap(), EXISTING); + assert_eq!( + store.value("anthropic-oauth-token").as_deref(), + Some(&b"old"[..]) + ); + assert_eq!(std::fs::read_to_string(&path).unwrap(), existing_service()); } #[test] @@ -3208,31 +3584,40 @@ attributes: let path = dir.path().join("config.toml"); let store = MemorySecretStore::default(); for (source, flag) in [(ValueSource::Stdin, "--yes"), (ValueSource::Terminal, "-y")] { - std::fs::write(&path, EXISTING).unwrap(); + std::fs::write(&path, existing_service()).unwrap(); let (result, out) = set_with_rule( &store, - &["claude", "--service", "anthropic-oauth-token", flag], + &[ + "anthropic-oauth-token", + "--service", + "anthropic-oauth-token", + flag, + ], &proxy, source, &path, &mut no_confirm, ); result.unwrap(); - assert_eq!(out, "claude\n"); + assert_eq!(out, "anthropic-oauth-token\n"); let rules = written_rules(&path); // The rule changes from `x-api-key` to a Bearer `Authorization` // with no prompt, and the hand-set `ask` stays (review finding // 4371881769). assert_eq!( - rules.get("claude"), - Some(&StoreRuleConfig { - action: Some(StoreAction::Ask), - ..header_rule("api.anthropic.com", "Authorization", Some("Bearer ")) - }) + rules.get("anthropic-oauth-token"), + Some(&header_rule( + "api.anthropic.com", + "Authorization", + Some("Bearer ") + )) ); assert!(rules.contains_key("other")); } - assert_eq!(store.value("claude").as_deref(), Some(&b"typed"[..])); + assert_eq!( + store.value("anthropic-oauth-token").as_deref(), + Some(&b"typed"[..]) + ); } /// Review finding 4371881775: `--yes` with new rule flags keeps the @@ -3245,7 +3630,7 @@ attributes: std::fs::write( &path, "[secret-store-rules.claude]\nstore = \"keychain\"\n\ - authorities = [\"api.anthropic.com\"]\nheader = \"x-api-key\"\naction = \"deny\"\n", + authorities = [\"api.anthropic.com\"]\nheader = \"x-api-key\"\n", ) .unwrap(); let store = MemorySecretStore::default(); @@ -3273,6 +3658,8 @@ attributes: confirm: &mut no_confirm, notice: &mut notice, control: None, + organization: Path::new("/nonexistent/org.toml"), + ask: &mut no_ask, }), ) .unwrap(); @@ -3280,11 +3667,9 @@ attributes: assert_eq!(store.value("claude").as_deref(), Some(&b"piped"[..])); let written = written_rules(&path).remove("claude").expect("the rule"); assert_eq!(written.store.as_deref(), Some("keychain")); - // A test-only pin, not a spec 24 requirement (Karl, 2026-12-02): a - // hand-set `deny` survives the replacement, so `--yes` never loosens - // consent, until gominimal/inbox#1327 moves consent off the - // user-level `[secret-store-rules]` and this assertion goes with it. - assert_eq!(written.action, Some(StoreAction::Deny)); + // The user configuration carries no consent (BEP-094), so the + // rule `--yes` writes has none. + assert_eq!(written.action, None); assert_eq!( StoreRuleConfig { store: None, @@ -3389,7 +3774,7 @@ attributes: let (_dir, proxy) = proxy(); let store = MemorySecretStore::default(); for c in ['*', '?', '[', '{', '\\'] { - let id = format!("claude{c}"); + let id = format!("anthropic-oauth-token{c}"); for flags in [ vec!["--service", "anthropic-api-key"], vec![ @@ -3418,7 +3803,7 @@ attributes: ); } } - assert_eq!(store.value("claude"), None); + assert_eq!(store.value("anthropic-oauth-token"), None); } // Review finding 4759543025: when the store cannot say whether the item @@ -3459,10 +3844,15 @@ attributes: let (_dir, proxy) = proxy(); let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("config.toml"); - std::fs::write(&path, EXISTING).unwrap(); + std::fs::write(&path, existing_service()).unwrap(); let (result, out) = set_with_rule( &UnansweredStore, - &["claude", "--service", "anthropic-oauth-token", "--yes"], + &[ + "anthropic-oauth-token", + "--service", + "anthropic-oauth-token", + "--yes", + ], &proxy, ValueSource::Stdin, &path, @@ -3471,7 +3861,7 @@ attributes: assert_eq!( format!("{:#}", result.expect_err("no answer")), format!( - "min secret set cannot tell whether it stored claude. The rule for claude in {} \ + "min secret set cannot tell whether it stored anthropic-oauth-token. The rule for anthropic-oauth-token in {} \ is back as it was: Secret Service did not answer in 60 s. Secret Service can \ still make the change, or it made a part of it. Run the command again.", path.display() @@ -3480,7 +3870,7 @@ attributes: assert!(out.is_empty()); let args = SecretRmArgs { - id: "claude".into(), + id: "anthropic-oauth-token".into(), store: None, yes: false, }; @@ -3490,7 +3880,7 @@ attributes: "{:#}", run_rm(&UnansweredStore, &args, &mut out).unwrap_err() ), - "min secret rm cannot tell whether it removed claude: Secret Service did not answer \ + "min secret rm cannot tell whether it removed anthropic-oauth-token: Secret Service did not answer \ in 60 s. Secret Service can still make the change, or it made a part of it. Run \ the command again." ); @@ -3504,10 +3894,15 @@ attributes: // The item fails after the rule is written: the file is put back, // and the error names the item step. - std::fs::write(&path, EXISTING).unwrap(); + std::fs::write(&path, existing_service()).unwrap(); let (result, out) = set_with_rule( &RefusingStore, - &["claude", "--service", "anthropic-oauth-token", "--yes"], + &[ + "anthropic-oauth-token", + "--service", + "anthropic-oauth-token", + "--yes", + ], &proxy, ValueSource::Stdin, &path, @@ -3515,19 +3910,23 @@ attributes: ); let text = format!("{:#}", result.expect_err("store failed")); assert!( - text.starts_with("min secret set did not store claude"), + text.starts_with("min secret set did not store anthropic-oauth-token"), "{text}" ); assert!(text.contains("is back as it was"), "{text}"); assert!(text.contains("the keychain is locked"), "{text}"); assert!(out.is_empty()); - assert_eq!(std::fs::read_to_string(&path).unwrap(), EXISTING); + assert_eq!(std::fs::read_to_string(&path).unwrap(), existing_service()); // With no file before, no file after. std::fs::remove_file(&path).unwrap(); let (result, _) = set_with_rule( &RefusingStore, - &["claude", "--service", "anthropic-oauth-token"], + &[ + "anthropic-oauth-token", + "--service", + "anthropic-oauth-token", + ], &proxy, ValueSource::Stdin, &path, @@ -3541,10 +3940,14 @@ attributes: let inline = "secret-store-rules = {}\n"; std::fs::write(&path, inline).unwrap(); let store = MemorySecretStore::default(); - store.set("claude", b"old", &proxy).unwrap(); + store.set("anthropic-oauth-token", b"old", &proxy).unwrap(); let (result, out) = set_with_rule( &store, - &["claude", "--service", "anthropic-oauth-token"], + &[ + "anthropic-oauth-token", + "--service", + "anthropic-oauth-token", + ], &proxy, ValueSource::Stdin, &path, @@ -3552,12 +3955,17 @@ attributes: ); let text = format!("{:#}", result.expect_err("rule failed")); assert!( - text.starts_with("min secret set stored nothing: it did not write the rule for claude"), + text.starts_with( + "min secret set stored nothing: it did not write the rule for anthropic-oauth-token" + ), "{text}" ); assert!(text.contains("inline table"), "{text}"); assert!(out.is_empty()); - assert_eq!(store.value("claude").as_deref(), Some(&b"old"[..])); + assert_eq!( + store.value("anthropic-oauth-token").as_deref(), + Some(&b"old"[..]) + ); assert_eq!(std::fs::read_to_string(&path).unwrap(), inline); } @@ -3645,6 +4053,8 @@ attributes: confirm: &mut no_confirm, notice: &mut notice, control: Some(control), + organization: Path::new("/nonexistent/org.toml"), + ask: &mut no_ask, }), ); (result, String::from_utf8(notice).unwrap()) @@ -3698,4 +4108,651 @@ attributes: assert_eq!(notice, ""); assert!(written_rules(&dir.path().join("config.toml")).contains_key("openai")); } + + // ---- BEP-079 (--service), BEP-093 to BEP-098, BEP-053: a rule file that + // `min` cannot replace, and the failures around it ---- + + const SERVICE: &str = "anthropic-oauth-token"; + /// The value the tests store. It must never appear in what is printed + /// (CFW-005). + const SECRET: &str = "hunter2-the-secret-value"; + + fn root() -> bool { + nix::unistd::Uid::effective().is_root() + } + + fn read_only(path: &Path) { + use std::os::unix::fs::PermissionsExt as _; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o444)).unwrap(); + } + + /// What one run of `set` against a read-only `config.toml` did. + struct Ran { + result: anyhow::Result<()>, + out: String, + notice: String, + questions: Vec, + } + + /// Run `set` for the service with `extra` flags. `answer` is the reply to + /// the store-anyway question. The terminal and standard input both give + /// [`SECRET`]. + fn set_service( + store: &dyn SecretStore, + extra: &[&str], + source: ValueSource, + path: &Path, + organization: &Path, + answer: bool, + ) -> Ran { + let (_dir, proxy) = proxy(); + let mut argv = vec![SERVICE, "--service", SERVICE]; + argv.extend_from_slice(extra); + let mut out = Vec::new(); + let mut notice = Vec::new(); + let mut questions = Vec::new(); + let mut ask = |question: &str| { + questions.push(question.to_owned()); + Ok(answer) + }; + let result = run_set_with_rule( + store, + &set_args(&argv), + &proxy, + source, + &mut || Ok(Zeroizing::new(SECRET.to_owned())), + &mut format!("{SECRET}\n").as_bytes(), + &mut out, + Some(RuleTarget { + path, + confirm: &mut no_confirm, + notice: &mut notice, + control: None, + organization, + ask: &mut ask, + }), + ); + Ran { + result, + out: String::from_utf8(out).unwrap(), + notice: String::from_utf8(notice).unwrap(), + questions, + } + } + + /// A read-only `config.toml` holding `text`, and the path of an + /// organization file that does not exist. + fn read_only_config(text: &str) -> (tempfile::TempDir, PathBuf, PathBuf) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + std::fs::write(&path, text).unwrap(); + read_only(&path); + let organization = dir.path().join("org.toml"); + (dir, path, organization) + } + + fn store_with_old(proxy_dir: &Path) -> MemorySecretStore { + let store = MemorySecretStore::default(); + store + .set(SERVICE, b"old", &proxy_dir.join("bep")) + .expect("the old value is stored"); + store + } + + #[test] + fn secret_set_service_requires_id_equal_to_service_name() { + let err = refuse_set_args(&set_args(&["claude", "--service", SERVICE])) + .expect_err("a rule under another name is refused"); + assert_eq!( + format!("{err:#}"), + format!( + "min secret set refused the name claude with --service {SERVICE}: a service \ + resolves to the item named {SERVICE}, so a rule under another name is one that \ + no box uses. Run `min secret set {SERVICE} --service {SERVICE}`." + ) + ); + refuse_set_args(&set_args(&[SERVICE, "--service", SERVICE])).expect("the name matches"); + } + + #[test] + fn secret_set_service_refuses_non_native_store() { + for store in ["gatehouse", "vault"] { + let err = refuse_set_args(&set_args(&[ + SERVICE, + "--service", + SERVICE, + "--store", + store, + ])) + .expect_err("a service resolves to the native store"); + let text = format!("{err:#}"); + assert!( + text.contains(&format!("refused --store {store} with --service {SERVICE}")), + "{text}" + ); + assert!(text.contains("an item of the host's own store"), "{text}"); + } + refuse_set_args(&set_args(&[ + SERVICE, + "--service", + SERVICE, + "--store", + NATIVE_STORE, + ])) + .expect("the native store is the one a service resolves to"); + } + + #[test] + fn secret_set_asks_before_storing_when_rule_file_cannot_be_written() { + if root() { + return; + } + let (dir, path, org) = read_only_config("# mine\n"); + let store = MemorySecretStore::default(); + let ran = set_service(&store, &[], ValueSource::Terminal, &path, &org, true); + ran.result.expect("a yes stores the item and exits 0"); + assert_eq!(ran.questions.len(), 1); + assert_eq!(store.value(SERVICE).as_deref(), Some(SECRET.as_bytes())); + assert_eq!(ran.out, format!("{SERVICE}\n")); + // CFW-004: the path, the reason and the lines, on the notice stream. + assert!( + ran.notice.contains(&path.display().to_string()), + "{}", + ran.notice + ); + assert!(ran.notice.contains("was not changed"), "{}", ran.notice); + assert!( + ran.notice + .contains(&format!("[secret-store-rules.{SERVICE}]")), + "{}", + ran.notice + ); + assert!(ran.notice.contains("api.anthropic.com"), "{}", ran.notice); + // CFW-002: the file is as it was. + assert_eq!(std::fs::read_to_string(&path).unwrap(), "# mine\n"); + drop(dir); + } + + #[test] + fn added_lines_hold_no_secret_value() { + if root() { + return; + } + for source in [ValueSource::Terminal, ValueSource::Stdin] { + let (_dir, path, org) = read_only_config(""); + let store = MemorySecretStore::default(); + let ran = set_service(&store, &["--yes"], source, &path, &org, true); + ran.result.expect("stored"); + assert!(!ran.notice.contains(SECRET), "{}", ran.notice); + assert!(!ran.out.contains(SECRET), "{}", ran.out); + assert!(ran.questions.iter().all(|q| !q.contains(SECRET))); + } + } + + #[test] + fn secret_set_question_says_item_is_unused_without_rule() { + if root() { + return; + } + let (_dir, path, org) = read_only_config(""); + let ran = set_service( + &MemorySecretStore::default(), + &[], + ValueSource::Terminal, + &path, + &org, + true, + ); + ran.result.unwrap(); + assert_eq!( + ran.questions, + [format!( + "min secret set did not write the rule for {SERVICE}. No box uses {SERVICE} \ + until you add the rule." + )] + ); + } + + #[test] + fn secret_set_declined_store_leaves_item_and_value_unchanged() { + if root() { + return; + } + let (dir, path, org) = read_only_config(""); + let store = store_with_old(dir.path()); + let ran = set_service(&store, &[], ValueSource::Terminal, &path, &org, false); + let text = format!("{:#}", ran.result.expect_err("a no fails the command")); + assert!(text.starts_with("min secret set stored nothing"), "{text}"); + assert!(text.contains("Add the lines above"), "{text}"); + assert!(ran.out.is_empty()); + assert_eq!(store.value(SERVICE).as_deref(), Some(&b"old"[..])); + } + + #[test] + fn secret_set_without_terminal_needs_yes_to_store_without_rule() { + if root() { + return; + } + for source in [ + ValueSource::Stdin, + ValueSource::NoInput, + ValueSource::Absent, + ] { + let (dir, path, org) = read_only_config(""); + let store = store_with_old(dir.path()); + let ran = set_service(&store, &[], source, &path, &org, true); + let text = format!("{:#}", ran.result.expect_err("no terminal, no yes")); + assert!(text.contains("--yes"), "{text}"); + assert!(ran.questions.is_empty()); + assert_eq!(store.value(SERVICE).as_deref(), Some(&b"old"[..])); + // The lines are still printed, so the person can add them. + assert!( + ran.notice.contains("[secret-store-rules."), + "{}", + ran.notice + ); + } + } + + #[test] + fn secret_set_yes_stores_item_without_asking_when_rule_file_cannot_be_written() { + if root() { + return; + } + let (_dir, path, org) = read_only_config(""); + let store = MemorySecretStore::default(); + let ran = set_service(&store, &["--yes"], ValueSource::Stdin, &path, &org, false); + ran.result.expect("--yes answers the question"); + assert!(ran.questions.is_empty()); + assert_eq!(store.value(SERVICE).as_deref(), Some(SECRET.as_bytes())); + } + + /// An organization file with a rule for the service. + fn org_rule(dir: &Path, authority: &str) -> PathBuf { + let org = dir.join("org.toml"); + std::fs::write( + &org, + format!( + "[secret-store-rules.{SERVICE}]\nauthorities = [\"{authority}\"]\n\ + header = \"Authorization\"\nprefix = \"Bearer \"\n" + ), + ) + .unwrap(); + org + } + + #[test] + fn secret_set_says_existing_rule_already_has_the_fields() { + if root() { + return; + } + let (dir, path, _) = read_only_config(""); + let org = org_rule(dir.path(), "api.anthropic.com"); + let store = MemorySecretStore::default(); + let ran = set_service(&store, &[], ValueSource::Stdin, &path, &org, false); + ran.result + .expect("the same fields store without a question"); + assert!(ran.questions.is_empty()); + assert!( + ran.notice.contains("already has these fields"), + "{}", + ran.notice + ); + assert_eq!(store.value(SERVICE).as_deref(), Some(SECRET.as_bytes())); + } + + #[test] + fn secret_set_question_names_old_authorities_for_differing_rule() { + if root() { + return; + } + let (dir, path, _) = read_only_config(""); + let org = org_rule(dir.path(), "old.example.com"); + let store = MemorySecretStore::default(); + let ran = set_service(&store, &[], ValueSource::Terminal, &path, &org, true); + ran.result.expect("a yes stores the item"); + assert_eq!(ran.questions.len(), 1); + assert!( + ran.questions[0].contains("old.example.com"), + "{:?}", + ran.questions + ); + assert!( + ran.questions[0].contains("sends the new value"), + "{:?}", + ran.questions + ); + assert_eq!(store.value(SERVICE).as_deref(), Some(SECRET.as_bytes())); + } + + #[test] + fn secret_set_declined_differing_rule_store_leaves_item_and_value_unchanged() { + if root() { + return; + } + let (dir, path, _) = read_only_config(""); + let org = org_rule(dir.path(), "old.example.com"); + let store = store_with_old(dir.path()); + let ran = set_service(&store, &[], ValueSource::Terminal, &path, &org, false); + let text = format!("{:#}", ran.result.expect_err("a no fails the command")); + assert!(text.starts_with("min secret set stored nothing"), "{text}"); + assert_eq!(store.value(SERVICE).as_deref(), Some(&b"old"[..])); + } + + #[test] + fn secret_set_differing_rule_without_terminal_fails_even_with_yes() { + if root() { + return; + } + for source in [ValueSource::Stdin, ValueSource::NoInput] { + let (dir, path, _) = read_only_config(""); + let org = org_rule(dir.path(), "old.example.com"); + let store = store_with_old(dir.path()); + let ran = set_service(&store, &["--yes"], source, &path, &org, true); + let text = format!("{:#}", ran.result.expect_err("--yes does not answer")); + assert!(text.contains("--yes does not answer"), "{text}"); + assert!(text.contains("old.example.com"), "{text}"); + assert!(ran.questions.is_empty()); + assert_eq!(store.value(SERVICE).as_deref(), Some(&b"old"[..])); + } + } + + /// A store whose `set` edits the configuration at `edit` first, so the + /// rule cannot be put back, and then refuses. `remove` says whether the + /// removal that BEP-098 tries works. + struct FailingAfterEdit { + edit: PathBuf, + remove_works: bool, + /// Whether the other program leaves the replacement rule in the file. + /// When it does not, the rule that routed the old value is gone. + keeps_rule: bool, + } + impl SecretStore for FailingAfterEdit { + fn name(&self) -> &'static str { + NATIVE_STORE + } + fn set(&self, id: &str, value: &[u8], proxy: &Path) -> Result<(), StoreError> { + let refuse = |e: std::io::Error| StoreError::Refused { + store: NATIVE_STORE, + action: "store the item", + detail: e.to_string(), + }; + let edited = if self.keeps_rule { + let mut text = std::fs::read_to_string(&self.edit).map_err(refuse)?; + text.push_str("# edited by another program\n"); + text + } else { + "# edited by another program\n".to_owned() + }; + std::fs::write(&self.edit, edited).map_err(refuse)?; + RefusingStore.set(id, value, proxy) + } + fn list(&self, _: &Path) -> Result, StoreError> { + Ok(Vec::new()) + } + fn remove(&self, id: &str) -> Result { + if self.remove_works { + Ok(true) + } else { + RefusingStore.remove(id) + } + } + } + + fn failed_restore(remove_works: bool) -> (String, PathBuf) { + failed_restore_with(remove_works, true) + } + + fn failed_restore_with(remove_works: bool, keeps_rule: bool) -> (String, PathBuf) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + let store = FailingAfterEdit { + edit: path.clone(), + remove_works, + keeps_rule, + }; + let ran = set_service( + &store, + &[], + ValueSource::Stdin, + &path, + &dir.path().join("org.toml"), + false, + ); + let text = format!("{:#}", ran.result.expect_err("the store refuses")); + assert!(ran.out.is_empty()); + (text, path) + } + + #[test] + fn secret_set_failed_store_and_failed_restore_removes_item() { + let (text, _) = failed_restore(true); + assert!(text.contains("was not put back"), "{text}"); + assert!(text.contains("min removed"), "{text}"); + } + + #[test] + fn secret_set_restore_failure_message_names_file_and_next_step() { + let (text, path) = failed_restore(true); + assert!(text.contains(&path.display().to_string()), "{text}"); + assert!( + text.contains(&format!("Run `min secret set {SERVICE}` again")), + "{text}" + ); + } + + // BEP-098: only a replacement rule that is still in force makes the old + // value risky. When another edit has removed it, the item is kept. + #[test] + fn secret_set_failed_restore_with_replacement_rule_gone_keeps_item() { + // `remove_works = false` would fail a removal, so a kept item is the + // only way this message says so. + let (text, path) = failed_restore_with(false, false); + assert!(text.contains("is no longer in"), "{text}"); + assert!(text.contains("min kept"), "{text}"); + assert!(text.contains(&path.display().to_string()), "{text}"); + assert!(!text.contains("min removed"), "{text}"); + assert!(!text.contains("min failed to remove"), "{text}"); + } + + // A rule `set` could not write through a dangling link is created at the + // end of the chain, and a failed store takes it away again, leaving the + // links. + #[test] + fn secret_set_failure_rolls_back_a_rule_created_through_a_dangling_link() { + if nix::unistd::Uid::effective().is_root() { + return; + } + let dir = tempfile::tempdir().unwrap(); + let real = dir.path().join("real.toml"); + let mid = dir.path().join("mid.toml"); + let path = dir.path().join("config.toml"); + std::os::unix::fs::symlink(&real, &mid).unwrap(); + std::os::unix::fs::symlink(&mid, &path).unwrap(); + let (_proxy_dir, proxy) = proxy(); + let mut out = Vec::new(); + let result = run_set_with_rule( + &RefusingStore, + &set_args(&[SERVICE, "--service", SERVICE]), + &proxy, + ValueSource::Stdin, + &mut no_terminal, + &mut &b"value\n"[..], + &mut out, + Some(RuleTarget { + path: &path, + confirm: &mut no_confirm, + notice: &mut std::io::sink(), + control: None, + organization: Path::new("/nonexistent/org.toml"), + ask: &mut no_ask, + }), + ); + let text = format!("{:#}", result.expect_err("the store refuses")); + assert!(text.contains("is back as it was"), "{text}"); + // The rule is gone from the end of the chain, and both links stay. + assert!(!real.exists(), "the file the chain names was removed again"); + assert!( + std::fs::symlink_metadata(&path) + .unwrap() + .file_type() + .is_symlink() + ); + assert!( + std::fs::symlink_metadata(&mid) + .unwrap() + .file_type() + .is_symlink() + ); + } + + // BEP-079: a rule for this name that belongs to another store is not + // replaced by a native item's rule, and nothing is read or stored. + #[test] + fn secret_set_refuses_a_rule_that_belongs_to_another_store() { + if nix::unistd::Uid::effective().is_root() { + return; + } + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + std::fs::write( + &path, + format!( + "[secret-store-rules.{SERVICE}]\nstore = \"vault\"\n\ + authorities = [\"api.anthropic.com\"]\nheader = \"Authorization\"\n\ + prefix = \"Bearer \"\n" + ), + ) + .unwrap(); + let store = MemorySecretStore::default(); + let (result, out) = set_with_rule( + &store, + &[SERVICE, "--service", SERVICE], + &proxy().1, + ValueSource::Stdin, + &path, + &mut no_confirm, + ); + let text = format!("{:#}", result.expect_err("refused")); + assert!(text.contains("already has a rule"), "{text}"); + assert!(text.contains("`vault`"), "{text}"); + assert!(out.is_empty()); + assert!(store.value(SERVICE).is_none()); + } + + // BEP-093 to BEP-096: a configuration that cannot be read is not "no + // rule". Nothing is accepted on a guess. + #[test] + fn secret_set_refuses_when_the_effective_rules_cannot_be_read() { + if nix::unistd::Uid::effective().is_root() { + return; + } + let (dir, path, _) = read_only_config(""); + let org = dir.path().join("org.toml"); + std::fs::write(&org, "not toml [").unwrap(); + for extra in [&["--yes"][..], &[][..]] { + let store = MemorySecretStore::default(); + let ran = set_service(&store, extra, ValueSource::Stdin, &path, &org, true); + let text = format!("{:#}", ran.result.expect_err("refused")); + assert!( + text.contains("did not read the organization rules"), + "{text}" + ); + assert!(store.value(SERVICE).is_none(), "{extra:?}"); + } + } + + #[test] + fn secret_set_removal_failure_message_names_rm_command() { + let (text, path) = failed_restore(false); + assert!(text.contains("min failed to remove"), "{text}"); + assert!(text.contains("can still send its old value"), "{text}"); + assert!(text.contains(&path.display().to_string()), "{text}"); + assert!( + text.contains(&format!("Run `min secret rm {SERVICE}`")), + "{text}" + ); + } + + #[test] + fn secret_rm_unwritable_config_prints_lines_and_asks() { + if root() { + return; + } + let rule = format!( + "[secret-store-rules.{SERVICE}]\nauthorities = [\"api.anthropic.com\"]\n\ + header = \"Authorization\"\nprefix = \"Bearer \"\n" + ); + let args = rm_args(SERVICE, false); + // A yes removes the item only; the file stays. + let (dir, path, _) = read_only_config(&rule); + let store = store_with_old(dir.path()); + let (result, out, notice, shown) = rm_with_rule(&store, &args, &path, true, true); + result.expect("a yes removes the item"); + assert!(store.value(SERVICE).is_none()); + assert!(out.contains(&format!("Removed {SERVICE}")), "{out}"); + assert!(!out.contains("Removed the rule"), "{out}"); + assert_eq!(std::fs::read_to_string(&path).unwrap(), rule); + let shown = shown.expect("the person was asked"); + assert!(shown.contains(&path.display().to_string()), "{shown}"); + assert!(shown.contains("Remove these lines"), "{shown}"); + assert!( + shown.contains(&format!("[secret-store-rules.{SERVICE}]")), + "{shown}" + ); + assert_eq!(notice, ""); + // A no leaves the item. + let (dir, path, _) = read_only_config(&rule); + let store = store_with_old(dir.path()); + let (result, _, _, _) = rm_with_rule(&store, &args, &path, true, false); + result.expect_err("a no removes nothing"); + assert_eq!(store.value(SERVICE).as_deref(), Some(&b"old"[..])); + // No terminal and no --yes: refused, with the lines. + let (result, _, _, _) = rm_with_rule(&store, &args, &path, false, true); + let text = format!("{:#}", result.expect_err("cannot ask")); + assert!(text.contains("--yes"), "{text}"); + assert!(text.contains("Remove these lines"), "{text}"); + assert_eq!(store.value(SERVICE).as_deref(), Some(&b"old"[..])); + // --yes answers it, and prints the lines. + let (result, _, notice, shown) = + rm_with_rule(&store, &rm_args(SERVICE, true), &path, false, false); + result.expect("--yes removes the item"); + assert!(shown.is_none()); + assert!(notice.contains("Remove these lines"), "{notice}"); + assert!(store.value(SERVICE).is_none()); + } + + // The question names the injection form when it is the reason the rules + // differ, so the person knows what they are approving. + #[test] + fn secret_set_differing_rule_question_names_the_injection_forms() { + if nix::unistd::Uid::effective().is_root() { + return; + } + let (dir, path, _) = read_only_config(""); + let org = dir.path().join("org.toml"); + // The same authority, another header. + std::fs::write( + &org, + format!( + "[secret-store-rules.{SERVICE}]\nauthorities = [\"api.anthropic.com\"]\n\ + header = \"x-api-key\"\n" + ), + ) + .unwrap(); + let store = MemorySecretStore::default(); + let ran = set_service(&store, &[], ValueSource::Terminal, &path, &org, false); + ran.result.expect_err("declined"); + assert_eq!(ran.questions.len(), 1); + assert!( + ran.questions[0].contains("header x-api-key"), + "{:?}", + ran.questions + ); + assert!( + ran.questions[0].contains("header Authorization"), + "{:?}", + ran.questions + ); + } } diff --git a/crates/minimal/src/config.rs b/crates/minimal/src/config.rs index 18ef7dbb9c..d1aad886dc 100644 --- a/crates/minimal/src/config.rs +++ b/crates/minimal/src/config.rs @@ -294,12 +294,10 @@ fn write_target_outside_within( organization: &Path, passes: usize, ) -> Result { - let file = match std::fs::symlink_metadata(path) { - Ok(meta) if meta.file_type().is_symlink() => { - std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) - } - _ => path.to_path_buf(), - }; + // The file the shared writer replaces (CFW-010): the end of any chain of + // links, a file that does not exist yet included. The snapshot, and so the + // rollback, name that file and never the link. + let file = crate::client_file::target_of(path); // A relative path is made absolute first, so a leading `..` past a // missing directory is applied to the working directory and not lost. let absolute = std::path::absolute(&file).map_err(|error| { @@ -456,6 +454,23 @@ pub fn remove_store_rule( })) } +/// The lines of the `[secret-store-rules.]` section for `rule`, as the +/// person adds them to a client file that `min` cannot write (CFW-004). A rule +/// holds the authorities and the injection form of an item and never its value +/// (CFW-005). +#[must_use] +pub fn store_rule_lines(id: &str, rule: &boxes::core::bep::StoreRuleConfig) -> Vec { + let mut rules = toml_edit::Table::new(); + rules.set_implicit(true); + rules.insert(id, toml_edit::Item::Table(store_rule_table(rule))); + let mut doc = toml_edit::DocumentMut::new(); + doc.insert( + boxes::core::bep::STORE_RULES_TABLE, + toml_edit::Item::Table(rules), + ); + doc.to_string().lines().map(str::to_owned).collect() +} + /// `rule` as a TOML table, with the fields in the order the docs show. fn store_rule_table(rule: &boxes::core::bep::StoreRuleConfig) -> toml_edit::Table { let mut table = toml_edit::Table::new(); @@ -515,26 +530,12 @@ pub fn restore_config(snapshot: &ConfigSnapshot) -> Result<(), anyhow::Error> { } } -/// Replace the file at `path` with `bytes` in one rename, creating its -/// directory when it is missing. +/// Replace the client file at `path` with `bytes` by the one rule for client +/// files ([`crate::client_file::replace`]). The error holds a +/// [`crate::client_file::WriteError`], so a caller tells a file `min` cannot +/// replace from a write that failed. fn write_config_bytes(path: &Path, bytes: &[u8]) -> Result<(), anyhow::Error> { - let dir = match path.parent() { - Some(dir) if !dir.as_os_str().is_empty() => dir, - _ => Path::new("."), - }; - std::fs::create_dir_all(dir).map_err(|e| anyhow::anyhow!("create `{}`: {e}", dir.display()))?; - let mut tmp = tempfile::NamedTempFile::new_in(dir) - .map_err(|e| anyhow::anyhow!("write `{}`: {e}", path.display()))?; - if let Ok(meta) = std::fs::metadata(path) { - // Keep the old file's mode. A failure leaves the default mode. - let _ = tmp.as_file().set_permissions(meta.permissions()); - } - tmp.write_all(bytes) - .and_then(|()| tmp.as_file().sync_all()) - .map_err(|e| anyhow::anyhow!("write `{}`: {e}", path.display()))?; - tmp.persist(path) - .map_err(|e| anyhow::anyhow!("write `{}`: {}", path.display(), e.error))?; - Ok(()) + crate::client_file::replace(path, bytes).map_err(anyhow::Error::new) } /// The hosts of every deep module, for [`store_deny_set`]. diff --git a/crates/minimal/src/credential_approval.rs b/crates/minimal/src/credential_approval.rs new file mode 100644 index 0000000000..4dbd1130b7 --- /dev/null +++ b/crates/minimal/src/credential_approval.rs @@ -0,0 +1,1373 @@ +//! The approval of a credential for a project at box creation (BEP-105 to +//! BEP-108). +//! +//! A box holds a `[secrets]` credential only in a project the user approved +//! for it. The approval is a `[credential-rules]` table in the user policy +//! file and one in the organization configuration. [`approve`] decides each +//! credential the box would hold (BEP-107), asks once per credential at a +//! terminal and offers to remember the answer (BEP-108), and refuses +//! otherwise. `--yes` never answers the question. + +use std::path::{Path, PathBuf}; + +use boxes::core::bep::{GrantMode, GrantSource, SecretGrants}; +use boxes::credential_rules::{ + CheckedRules, Credential, CredentialAction, CredentialRule, Decision, Project, Source, Table, + decide, +}; + +/// Why the command cannot ask the person (BEP-108). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CannotAsk { + /// The command has no terminal. + NoTerminal, + /// The command carries `--no-input`. + NoInput, + /// `min dash` owns the terminal and has no place for this question. + Dashboard, +} + +/// Who asked for a credential, for the question and the refusal (BEP-108). +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Asker { + /// The layer, loadout or service that asked, in words, such as "the + /// loadout dev" or "the service github, which [sessions.dev] uses". + pub who: String, + /// The loadout that asked for it, when one did. The refusal then names + /// `--no-loadouts`. + pub loadout: Option, + /// The hosts that the service of a loadout would add to the box's egress. + pub hosts: Vec, +} + +/// Why a creation was refused for a credential. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CredentialRefusal { + /// A table denies the credential (BEP-108). Exit 5. + Denied { + /// The variables of the box that hold the credential. + variables: Vec, + /// The project root. + root: PathBuf, + /// What denies it, in words. + by: String, + }, + /// The decision is `ask`, and the command cannot ask (BEP-108). Exit 2. + NeedsApproval { + /// The variables of the box that hold the credential. + variables: Vec, + /// The project root. + root: PathBuf, + /// The user policy file that takes the rule. + policy: PathBuf, + /// Why the command cannot ask. + why: CannotAsk, + /// The rule to add, one line per element. `None` when no rule can name + /// the root, or when a rule gives the `ask` and no `allow` outranks it. + lines: Option>, + /// The rule that asks at every creation, in words, when one does. + asked_by: Option, + /// The loadout that asked for the credential, when one did. + loadout: Option, + }, + /// The person answered no. Exit 5. + Declined { + /// The variables of the box that hold the credential. + variables: Vec, + /// The project root. + root: PathBuf, + }, +} + +impl CredentialRefusal { + /// The exit code of the refusal. + #[must_use] + pub fn exit_code(&self) -> u8 { + match self { + Self::Denied { .. } | Self::Declined { .. } => 5, + Self::NeedsApproval { .. } => 2, + } + } +} + +/// `names` as one phrase: `A`, `A and B`, `A, B and C`. +fn list_of(names: &[String]) -> String { + match names { + [] => String::new(), + [one] => one.clone(), + [init @ .., last] => format!("{} and {last}", init.join(", ")), + } +} + +impl std::fmt::Display for CredentialRefusal { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Denied { + variables, + root, + by, + } => write!( + f, + "Cannot create the box: {by} denies the credential {vars} in {root}. \ + No box was created.", + vars = list_of(variables), + root = root.display() + ), + Self::NeedsApproval { + variables, + root, + policy, + why, + lines, + asked_by, + loadout, + } => { + let vars = list_of(variables); + let cause = match why { + CannotAsk::NoTerminal => "This command has no terminal, so it cannot ask.", + CannotAsk::NoInput => "--no-input is set, so this command cannot ask.", + CannotAsk::Dashboard => "min dash cannot ask this question.", + }; + match asked_by { + Some(rule) => write!( + f, + "Cannot create the box: {rule} asks for the credential {vars} at every \ + creation in {root}, and no answer is kept. {cause} Create the box where \ + a terminal can answer, or change that rule.", + root = root.display() + )?, + None => write!( + f, + "Cannot create the box: no rule approves the credential {vars} in \ + {root}. {cause}", + root = root.display() + )?, + } + match lines { + Some(lines) => { + match why { + CannotAsk::Dashboard => write!( + f, + " Add this to {policy}, or run `min box start ` at a \ + terminal to answer the question:\n\n", + policy = policy.display() + )?, + _ => write!( + f, + " Add this to {policy}, and run the command again:\n\n", + policy = policy.display() + )?, + } + for line in lines { + writeln!(f, " {line}")?; + } + } + None if asked_by.is_none() => write!( + f, + " The project path holds one of the characters * ? [ {{ or \\, which a \ + rule cannot name, so no rule can approve it." + )?, + None => {} + } + if let Some(loadout) = loadout { + write!( + f, + "\nThe loadout {loadout} asked for this credential. To create the box \ + without it, run the command again with --no-loadouts." + )?; + } + Ok(()) + } + Self::Declined { variables, root } => write!( + f, + "Cannot create the box: you did not approve the credential {vars} in {root}. \ + No box was created.", + vars = list_of(variables), + root = root.display() + ), + } + } +} + +impl std::error::Error for CredentialRefusal {} + +/// The credentials a box with `secrets` would hold, by variable: each grant +/// at the breadth the box would hold (BEP-107). A narrowed GitHub grant on an +/// un-enrolled host is minted `full`, so it is the sign-in's grant, `mode = +/// "user"` with the scope `github:user-token`. +#[must_use] +pub fn credentials(secrets: &SecretGrants) -> Vec<(String, Credential)> { + secrets + .iter() + .map(|(variable, grant)| { + let credential = match &grant.source { + GrantSource::Store { store, id } => Credential::Store { + store: store.clone(), + id: id.clone(), + }, + GrantSource::ClientEnv => Credential::ClientEnv { + name: variable.clone(), + }, + GrantSource::Broker if grant.is_narrower_than_full() => Credential::Broker { + mode: "user".to_owned(), + scopes: vec!["github:user-token".to_owned()], + }, + GrantSource::Broker => Credential::Broker { + mode: match grant.mode.unwrap_or_default() { + GrantMode::User => "user", + GrantMode::Installation => "installation", + } + .to_owned(), + scopes: grant.scopes.clone(), + }, + }; + (variable.clone(), credential) + }) + .collect() +} + +/// The project at `root`, with the root a rule would name when `root` is a +/// linked worktree that its repository lists (BEP-107). The list is the one +/// the repository keeps in its own directory. What the `.git` of `root` says +/// of itself decides nothing, so a directory cannot claim its way into an +/// approval. +#[must_use] +pub fn project_of(root: &Path) -> Project { + let root = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); + let main_root = main_worktree_root(&root); + Project { root, main_root } +} + +fn main_worktree_root(root: &Path) -> Option { + // The top of this worktree: the nearest folder with a `.git`. + let top = root.ancestors().find(|dir| dir.join(".git").exists())?; + let dot_git = top.join(".git"); + if dot_git.is_dir() { + return None; + } + // A linked worktree's `.git` is a file that names its own folder in the + // repository: `/worktrees/`. + let text = std::fs::read_to_string(&dot_git).ok()?; + let named = text.trim().strip_prefix("gitdir:")?.trim(); + let own = std::fs::canonicalize(top.join(named)).ok()?; + let worktrees = own.parent()?; + if worktrees.file_name()? != "worktrees" { + return None; + } + let common = worktrees.parent()?; + // The repository's list confirms this worktree: its entry points back at + // this `.git`. + // Git writes a backlink relative to its own folder when it keeps + // worktree paths relative, and absolute otherwise: `join` takes both. + let back = std::fs::read_to_string(own.join("gitdir")).ok()?; + let back = std::fs::canonicalize(own.join(back.trim())).ok()?; + // It must name the `.git` of this very folder. A `.git` that is a link to + // another worktree's `.git` resolves to that one, which is not this folder's. + if back != std::fs::canonicalize(top).ok()?.join(".git") { + return None; + } + // A bare repository has no main worktree. + if common.file_name()? != ".git" { + return None; + } + let main_top = std::fs::canonicalize(common.parent()?).ok()?; + let below = root.strip_prefix(top).ok()?; + Some(main_top.join(below)) +} + +/// What the person answers at the question (BEP-108). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Answer { + /// Whether the credential is approved for the creation. + pub approve: bool, + /// Whether the answer is written to the user policy file. + pub remember: bool, +} + +/// What the question tells the person (BEP-108). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Question { + /// The question and what an approval lets the box do. + pub text: String, + /// What the person is told about a remembered answer. + pub remember_text: String, + /// Whether the person can have the answer remembered. Not under a rule + /// that asks at every creation, and not for a root that no rule can name. + pub can_remember: bool, +} + +/// The tables that decide, and the place a remembered answer goes. +pub struct Tables<'a> { + /// The user's table, from the user policy file. + pub user: &'a CheckedRules, + /// The organization's table, from its client configuration. + pub organization: &'a CheckedRules, + /// The user policy file. + pub policy_path: &'a Path, + /// The organization configuration, for a refusal's words. + pub organization_path: &'a Path, +} + +/// The credential in words, for a question and a refusal. `widened` says a +/// GitHub grant that the file declared narrower is minted as the whole +/// sign-in, because this host is not enrolled. +fn describe(credential: &Credential, widened: bool) -> String { + match credential { + Credential::Store { store, id } => format!("the item {id} in the {store} store"), + Credential::ClientEnv { name } => format!("your environment variable {name}"), + Credential::Broker { mode, scopes } + if mode == "user" && scopes == &["github:user-token".to_owned()] => + { + if widened { + "your whole GitHub sign-in (`full`). It is wider than the scopes the file \ + declares, because this host is not enrolled and cannot narrow it" + .to_owned() + } else { + "your whole GitHub sign-in (`full`)".to_owned() + } + } + Credential::Broker { mode, scopes } => { + format!("a {mode} grant with the scopes {}", scopes.join(", ")) + } + } +} + +/// What an approval lets the code of the box do, at the breadth of the grant. +fn effect(credential: &Credential) -> String { + match credential { + Credential::Store { store, id } => format!( + "use the item {id} from your {store} store: the Box Egress Proxy sends its value to \ + the hosts of the item's rule, and the code in the box can make requests that carry it" + ), + Credential::ClientEnv { name } => { + format!("read the value of {name}, which min copies from your environment into the box") + } + Credential::Broker { mode, scopes } => format!( + "act with a {mode} grant of the scopes {}, and the code in the box can make requests \ + that use it", + scopes.join(", ") + ), + } +} + +/// The rule a remembered answer writes (BEP-108): it names the root a rule +/// would name, which is the main worktree's root for a linked worktree. +#[must_use] +pub fn remembered_rule( + project: &Project, + credential: &Credential, + approve: bool, +) -> CredentialRule { + let root = project.main_root.as_ref().unwrap_or(&project.root); + CredentialRule { + project: Some(root.display().to_string()), + credential: credential.clone(), + action: if approve { + CredentialAction::Allow + } else { + CredentialAction::Deny + }, + } +} + +/// The lines of `rule` as the person adds them to the user policy file at +/// `path` (CFW-004). A file that already holds `rules` under +/// `[credential-rules]` takes one more entry in that array, and a file that +/// does not takes the whole table, so pasting never makes a second table. +#[must_use] +pub fn rule_lines(path: &Path, rule: &CredentialRule) -> Vec { + let entry = rule_inline(rule); + let has_array = std::fs::read_to_string(crate::client_file::target_of(path)) + .ok() + .and_then(|text| text.parse::().ok()) + .and_then(|doc| { + doc.get(boxes::credential_rules::CREDENTIAL_RULES_TABLE) + .and_then(|table| table.get("rules")) + .map(toml_edit::Item::is_array) + }) + .unwrap_or(false); + if has_array { + vec![ + "# add this entry to `rules` under [credential-rules]".to_owned(), + format!(" {entry},"), + ] + } else { + vec![ + "[credential-rules]".to_owned(), + "rules = [".to_owned(), + format!(" {entry},"), + "]".to_owned(), + ] + } +} + +/// `rule` as an inline table, `{ project = "...", credential = { ... }, +/// action = "..." }`. +fn rule_table(rule: &CredentialRule) -> toml_edit::InlineTable { + let mut credential = toml_edit::InlineTable::new(); + match &rule.credential { + Credential::Store { store, id } => { + credential.insert("source", "store".into()); + credential.insert("store", store.as_str().into()); + credential.insert("id", id.as_str().into()); + } + Credential::ClientEnv { name } => { + credential.insert("source", "client_env".into()); + credential.insert("name", name.as_str().into()); + } + Credential::Broker { mode, scopes } => { + credential.insert("source", "broker".into()); + credential.insert("mode", mode.as_str().into()); + credential.insert( + "scopes", + scopes + .iter() + .map(String::as_str) + .collect::() + .into(), + ); + } + } + let mut table = toml_edit::InlineTable::new(); + if let Some(project) = &rule.project { + table.insert("project", project.as_str().into()); + } + table.insert("credential", credential.into()); + let action = match rule.action { + CredentialAction::Allow => "allow", + CredentialAction::Ask => "ask", + CredentialAction::Deny => "deny", + }; + table.insert("action", action.into()); + table +} + +fn rule_inline(rule: &CredentialRule) -> String { + rule_table(rule).to_string().trim().to_owned() +} + +/// Add `rule` to the `[credential-rules]` table of the user policy file at +/// `path`. Every other line of the file stays as it is. +/// +/// # Errors +/// +/// A [`crate::client_file::WriteError`] when the file cannot be replaced or +/// the write fails, and the parse failure of a file that does not parse. +pub fn write_rule(path: &Path, rule: &CredentialRule) -> Result<(), anyhow::Error> { + use crate::client_file::{self, WriteError}; + let failed = |cause: String| { + anyhow::Error::new(WriteError::Failed { + path: path.to_path_buf(), + cause, + }) + }; + let existing = match std::fs::read_to_string(client_file::target_of(path)) { + Ok(text) => text, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(), + Err(e) => return Err(failed(format!("it cannot be read: {e}"))), + }; + // CFW-001: test first, so nothing else is written beside a file that + // cannot be replaced. + client_file::can_replace(path).map_err(anyhow::Error::new)?; + let mut doc: toml_edit::DocumentMut = existing + .parse() + .map_err(|e| failed(format!("it does not parse: {e}")))?; + let table = doc + .entry(boxes::credential_rules::CREDENTIAL_RULES_TABLE) + .or_insert_with(|| toml_edit::Item::Table(toml_edit::Table::new())) + .as_table_mut() + .ok_or_else(|| failed("[credential-rules] is not a table".to_owned()))?; + let rules = table + .entry("rules") + .or_insert_with(|| toml_edit::value(toml_edit::Array::new())) + .as_array_mut() + .ok_or_else(|| failed("`rules` in [credential-rules] is not an array".to_owned()))?; + rules.push(rule_table(rule)); + if let Err(why) = client_file::write_backup(path) { + tracing::warn!(file = %path.display(), %why, "user policy backup not written"); + } + client_file::replace(path, doc.to_string().as_bytes()).map_err(anyhow::Error::new) +} + +/// Read the user's and the organization's `[credential-rules]` (BEP-106). A +/// missing file has no rules. A project file is never read here. +/// +/// # Errors +/// +/// A table that is not valid, or a file that exists and is not read or does +/// not parse, naming its file. +pub fn read_tables( + policy_path: &Path, + organization_path: &Path, + home: &Path, +) -> Result<(CheckedRules, CheckedRules), anyhow::Error> { + let user = match std::fs::read_to_string(policy_path) { + Ok(text) => boxes::credential_rules::read(&text, &policy_path.display().to_string(), home)?, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => CheckedRules::default(), + Err(e) => anyhow::bail!("read `{}`: {e}", policy_path.display()), + }; + let organization = + match boxes::client::config::read_organization_config_parts(organization_path) { + Ok((config, _)) => match config.credential_rules { + Some(table) => boxes::credential_rules::check( + table, + &organization_path.display().to_string(), + home, + )?, + None => CheckedRules::default(), + }, + // An organization file that exists and cannot be read or parsed + // refuses, so an organization `deny` is never skipped. A missing + // file has no rules (BEP-106). + Err(e) => anyhow::bail!("{e}"), + }; + Ok((user, organization)) +} + +/// Say what gave a decision, in words, for a refusal. +fn by(source: &Source, tables: &Tables<'_>) -> String { + match source { + Source::Rule { place, index } => format!("rule {index} of [credential-rules] in {place}"), + Source::Default { place } => { + format!("the action_for_unspecified of [credential-rules] in {place}") + } + Source::Nothing => format!("{}", tables.policy_path.display()), + } +} + +/// Approve every credential of `secrets` for `project`, or refuse the +/// creation (BEP-105, BEP-107, BEP-108). +/// +/// Each credential's action comes from [`decide`]. Every credential that a +/// table denies refuses the creation first, and every `ask` with +/// `cannot_ask` set refuses it next, so nobody is asked about a creation that +/// a later credential refuses. Then `ask` is called once for each credential +/// with an `ask`, naming every variable that holds it and who asked. Under a +/// rule that asks, no answer is kept, so no rule is offered and none is +/// written. Otherwise `remember` writes an answer the person chose to keep. A +/// remembered answer that cannot be saved holds for this creation and is +/// reported by `unsaved` (BEP-108, CFW-004). +/// +/// # Errors +/// +/// [`CredentialRefusal`], or the error of `ask`. +pub fn approve( + secrets: &SecretGrants, + project: &Project, + tables: &Tables<'_>, + cannot_ask: Option, + askers: &std::collections::BTreeMap, + ask: &mut dyn FnMut(&Question) -> anyhow::Result, + unsaved: &mut dyn FnMut(&CredentialRule, &anyhow::Error), +) -> Result<(), anyhow::Error> { + let all = credentials(secrets); + let place_user = tables.policy_path.display().to_string(); + let place_org = tables.organization_path.display().to_string(); + let table_list = [ + Table { + place: &place_user, + rules: tables.user, + }, + Table { + place: &place_org, + rules: tables.organization, + }, + ]; + // One decision for each distinct credential, with every variable that + // holds it, in variable order. + let mut decided: Vec<(Vec, Credential, Decision)> = Vec::new(); + for (variable, credential) in all { + if let Some((variables, _, _)) = decided + .iter_mut() + .find(|(_, seen, _)| seen.same_as(&credential)) + { + variables.push(variable); + continue; + } + let decision = decide(&table_list, &credential, project); + decided.push((vec![variable], credential, decision)); + } + let shown_root = project.main_root.as_ref().unwrap_or(&project.root); + // A rule can name a root only when it is one exact path (BEP-106). + let nameable = + boxes::credential_rules::resolve_project(&shown_root.display().to_string(), Path::new("/")) + .is_some(); + let asker_of = |variables: &[String]| -> Asker { + let mut found = Asker::default(); + for variable in variables { + if let Some(asker) = askers.get(variable) { + if found.who.is_empty() { + found.who.clone_from(&asker.who); + } + if found.loadout.is_none() { + found.loadout.clone_from(&asker.loadout); + } + for host in &asker.hosts { + if !found.hosts.contains(host) { + found.hosts.push(host.clone()); + } + } + } + } + found + }; + for (variables, credential, decision) in &decided { + let root = project.root.clone(); + match decision.action { + CredentialAction::Deny => { + tracing::info!(?variables, "credential denied by a rule or a default"); + return Err(CredentialRefusal::Denied { + variables: variables.clone(), + root, + by: by(&decision.source, tables), + } + .into()); + } + CredentialAction::Ask if cannot_ask.is_some() => { + let rule_asks = matches!(decision.source, Source::Rule { .. }); + let lines = (nameable && !rule_asks).then(|| { + rule_lines( + tables.policy_path, + &remembered_rule(project, credential, true), + ) + }); + return Err(CredentialRefusal::NeedsApproval { + variables: variables.clone(), + root, + policy: tables.policy_path.to_path_buf(), + why: cannot_ask.unwrap_or(CannotAsk::NoTerminal), + lines, + asked_by: rule_asks.then(|| by(&decision.source, tables)), + loadout: asker_of(variables).loadout, + } + .into()); + } + _ => {} + } + } + for (variables, credential, decision) in &decided { + if decision.action != CredentialAction::Ask { + continue; + } + let widened = variables + .iter() + .any(|v| secrets.get(v).is_some_and(|g| g.is_narrower_than_full())); + let asker = asker_of(variables); + let rule_asks = matches!(decision.source, Source::Rule { .. }); + let can_remember = nameable && !rule_asks; + let holds = format!( + "The credential{} {}", + if variables.len() == 1 { "" } else { "s" }, + list_of(variables) + ); + let who = if asker.who.is_empty() { + String::new() + } else { + format!(" {} asked for it.", asker.who) + }; + let hosts = if asker.hosts.is_empty() { + String::new() + } else { + format!( + " Its service would add the hosts {}.", + asker.hosts.join(", ") + ) + }; + let question = Question { + text: format!( + "{holds} {verb} {what}.{who}{hosts} Approve it for the project {project}? \ + An approval lets the code in the box {effect}.{worktree}", + verb = if variables.len() == 1 { "is" } else { "are" }, + what = describe(credential, widened), + project = project.root.display(), + effect = effect(credential), + worktree = if shown_root == &project.root { + String::new() + } else { + format!( + " A remembered answer names {}, the root of this worktree's repository.", + shown_root.display() + ) + }, + ), + remember_text: if rule_asks { + format!( + "{} asks for this credential at every creation, so no answer is kept.", + by(&decision.source, tables) + ) + } else if !nameable { + "The project path holds one of the characters * ? [ { or \\, which a rule \ + cannot name, so min cannot remember an answer for it." + .to_owned() + } else { + format!( + "A remembered answer applies to later creations in {} for this credential, \ + and min writes it to {}.", + shown_root.display(), + tables.policy_path.display() + ) + }, + can_remember, + }; + let answer = ask(&question)?; + if answer.remember && can_remember { + let rule = remembered_rule(project, credential, answer.approve); + if let Err(e) = write_rule(tables.policy_path, &rule) { + // The answer holds for this creation, and the lines to add + // are reported (BEP-108). + unsaved(&rule, &e); + } + } + if !answer.approve { + return Err(CredentialRefusal::Declined { + variables: variables.clone(), + root: project.root.clone(), + } + .into()); + } + } + Ok(()) +} + +/// Ask at the terminal (BEP-108). "No" comes first, so Enter never approves +/// and never writes a lasting `allow`. A question with no place to keep an +/// answer offers two choices. `--yes` is never consulted. +/// +/// # Errors +/// +/// A terminal that gives no answer. +pub fn ask_at_terminal(question: &Question) -> anyhow::Result { + use anyhow::Context as _; + eprintln!("{}", question.text); + eprintln!("{}", question.remember_text); + let all = [ + ("No", false, false), + ("No, and remember", false, true), + ("Yes, for this box only", true, false), + ("Yes, and remember", true, true), + ]; + let choices: Vec<(&str, bool, bool)> = all + .into_iter() + .filter(|(_, _, remember)| question.can_remember || !remember) + .collect(); + let picked = inquire::Select::new( + "Approve this credential?", + choices.iter().map(|c| c.0).collect(), + ) + .raw_prompt() + .context("min did not read the answer from the terminal")?; + let (_, approve, remember) = choices + .get(picked.index) + .copied() + .context("the terminal gave an answer that is not a choice")?; + Ok(Answer { approve, remember }) +} + +/// Report a remembered answer that was not saved: the lines to add, on +/// standard error after the attach ends (CFW-004, CFW-007, CFW-012). +pub fn report_unsaved(policy_path: &Path, rule: &CredentialRule, error: &anyhow::Error) { + use crate::client_file::{Report, WriteError}; + let write_error = error + .downcast_ref::() + .cloned() + .unwrap_or_else(|| WriteError::Failed { + path: policy_path.to_path_buf(), + cause: format!("{error:#}"), + }); + crate::client_file::defer(&Report::add(write_error, rule_lines(policy_path, rule))); +} + +#[cfg(test)] +mod tests { + use boxes::core::bep::SecretGrant; + + use super::*; + + fn store_grant(id: &str) -> SecretGrant { + SecretGrant { + source: GrantSource::Store { + store: "keychain".into(), + id: id.into(), + }, + scopes: vec![], + mode: None, + } + } + + fn secrets() -> SecretGrants { + SecretGrants::from([("NPM_TOKEN".to_owned(), store_grant("npm"))]) + } + + fn project(root: &str) -> Project { + Project { + root: root.into(), + main_root: None, + } + } + + struct Fixture { + dir: tempfile::TempDir, + policy: PathBuf, + org: PathBuf, + user: CheckedRules, + organization: CheckedRules, + } + + impl Fixture { + fn new(policy_text: &str, org_text: &str) -> Self { + let dir = tempfile::tempdir().unwrap(); + let policy = dir.path().join("user_policy.toml"); + let org = dir.path().join("org.toml"); + if !policy_text.is_empty() { + std::fs::write(&policy, policy_text).unwrap(); + } + if !org_text.is_empty() { + std::fs::write(&org, org_text).unwrap(); + } + let (user, organization) = read_tables(&policy, &org, Path::new("/home/me")).unwrap(); + Self { + dir, + policy, + org, + user, + organization, + } + } + + fn tables(&self) -> Tables<'_> { + Tables { + user: &self.user, + organization: &self.organization, + policy_path: &self.policy, + organization_path: &self.org, + } + } + + fn run( + &self, + can_ask: bool, + answer: Option, + ) -> (Result<(), anyhow::Error>, Vec, usize) { + let mut questions = Vec::new(); + let mut unsaved = 0; + let result = approve( + &secrets(), + &project("/work/app"), + &self.tables(), + (!can_ask).then_some(CannotAsk::NoTerminal), + &std::collections::BTreeMap::new(), + &mut |q| { + questions.push(q.clone()); + answer.ok_or_else(|| anyhow::anyhow!("asked when it must not")) + }, + &mut |_, _| unsaved += 1, + ); + (result, questions, unsaved) + } + } + + const YES: Answer = Answer { + approve: true, + remember: false, + }; + + fn refusal(result: Result<(), anyhow::Error>) -> CredentialRefusal { + result + .expect_err("refused") + .downcast::() + .expect("a credential refusal") + } + + const ALLOW_HERE: &str = "[credential-rules]\nrules = [{ project = \"/work/app\", \ + credential = { source = \"store\", store = \"keychain\", id = \"npm\" }, action = \"allow\" }]\n"; + + #[test] + fn box_holds_credential_only_in_approved_project() { + let f = Fixture::new(ALLOW_HERE, ""); + // The approved project asks nothing. + let (result, questions, _) = f.run(false, None); + result.unwrap(); + assert!(questions.is_empty()); + // Another project is a new question, and off a terminal it is refused. + let mut asked = false; + let err = approve( + &secrets(), + &project("/work/other"), + &f.tables(), + Some(CannotAsk::NoTerminal), + &std::collections::BTreeMap::new(), + &mut |_| { + asked = true; + Ok(YES) + }, + &mut |_, _| {}, + ) + .unwrap_err(); + assert!(!asked); + assert_eq!(err.downcast::().unwrap().exit_code(), 2); + } + + #[test] + fn undecided_credential_asks_once_and_can_remember() { + let f = Fixture::new("", ""); + // Two variables for one credential are one question. + let mut both = secrets(); + both.insert("NPM_ALIAS".to_owned(), store_grant("npm")); + let mut questions = 0; + approve( + &both, + &project("/work/app"), + &f.tables(), + None, + &std::collections::BTreeMap::new(), + &mut |_| { + questions += 1; + Ok(Answer { + approve: true, + remember: true, + }) + }, + &mut |_, _| panic!("the file is writable"), + ) + .unwrap(); + assert_eq!(questions, 1); + // The answer is a rule that names the root, and the next creation + // asks nothing. + let written = std::fs::read_to_string(&f.policy).unwrap(); + assert!(written.contains("project = \"/work/app\""), "{written}"); + assert!(written.contains("action = \"allow\""), "{written}"); + let (user, organization) = read_tables(&f.policy, &f.org, Path::new("/home/me")).unwrap(); + let again = Tables { + user: &user, + organization: &organization, + policy_path: &f.policy, + organization_path: &f.org, + }; + approve( + &secrets(), + &project("/work/app"), + &again, + Some(CannotAsk::NoTerminal), + &std::collections::BTreeMap::new(), + &mut |_| panic!("asked again"), + &mut |_, _| {}, + ) + .unwrap(); + } + + #[test] + fn undecided_credential_off_terminal_refuses_exit2() { + let f = Fixture::new("", ""); + let (result, questions, _) = f.run(false, None); + assert!(questions.is_empty()); + let refused = refusal(result); + assert_eq!(refused.exit_code(), 2); + let text = refused.to_string(); + assert!(text.contains("[credential-rules]"), "{text}"); + assert!(text.contains("project = \"/work/app\""), "{text}"); + assert!(text.contains(&f.policy.display().to_string()), "{text}"); + } + + #[test] + fn remembered_answer_unsaved_holds_for_this_creation_and_prints_lines() { + use std::os::unix::fs::PermissionsExt as _; + if nix::unistd::Uid::effective().is_root() { + return; + } + let f = Fixture::new("# mine\n", ""); + std::fs::set_permissions(&f.policy, std::fs::Permissions::from_mode(0o444)).unwrap(); + let remember = |approve| Answer { + approve, + remember: true, + }; + // An approval that cannot be saved still creates the box. + let mut unsaved = Vec::new(); + approve( + &secrets(), + &project("/work/app"), + &f.tables(), + None, + &std::collections::BTreeMap::new(), + &mut |_| Ok(remember(true)), + &mut |rule, error| unsaved.push((rule.clone(), format!("{error:#}"))), + ) + .unwrap(); + assert_eq!(unsaved.len(), 1); + assert!(unsaved[0].1.contains("was not changed"), "{}", unsaved[0].1); + assert_eq!(std::fs::read_to_string(&f.policy).unwrap(), "# mine\n"); + // A denial that cannot be saved still refuses. + let mut unsaved = 0; + let err = approve( + &secrets(), + &project("/work/app"), + &f.tables(), + None, + &std::collections::BTreeMap::new(), + &mut |_| Ok(remember(false)), + &mut |_, _| unsaved += 1, + ) + .unwrap_err(); + assert_eq!(unsaved, 1); + assert_eq!(err.downcast::().unwrap().exit_code(), 5); + // The lines name the rule to add. + let rule = remembered_rule(&project("/work/app"), &credentials(&secrets())[0].1, true); + let lines = rule_lines(Path::new("/nonexistent/user_policy.toml"), &rule).join("\n"); + assert!(lines.contains("[credential-rules]"), "{lines}"); + assert!(lines.contains("\"/work/app\""), "{lines}"); + } + + #[test] + fn approval_question_states_project_credential_and_effect() { + let f = Fixture::new("", ""); + let (_, questions, _) = f.run(true, Some(YES)); + let text = &questions[0].text; + assert!(text.contains("/work/app"), "{text}"); + assert!(text.contains("NPM_TOKEN"), "{text}"); + assert!( + text.contains("the item npm in the keychain store"), + "{text}" + ); + assert!(text.contains("lets the code in the box"), "{text}"); + // A narrowed credential and a wider one are different questions. + let grant = |scopes: &[&str]| SecretGrant { + source: GrantSource::Broker, + scopes: scopes.iter().map(|s| (*s).to_owned()).collect(), + mode: Some(GrantMode::Installation), + }; + let c = |g: SecretGrant| { + credentials(&SecretGrants::from([("TOKEN".to_owned(), g)]))[0] + .1 + .clone() + }; + assert!(!c(grant(&["svc:read"])).same_as(&c(grant(&["svc:read", "svc:write"])))); + assert!(c(grant(&["svc:a", "svc:b"])).same_as(&c(grant(&["svc:b", "svc:a"])))); + let narrow = grant(&["github:repo:acme/app:contents:ro"]); + // An un-enrolled host mints a narrowed user grant `full`, and the + // credential names that. + let narrowed_user = SecretGrant { + mode: None, + ..narrow + }; + assert_eq!( + c(narrowed_user), + Credential::Broker { + mode: "user".into(), + scopes: vec!["github:user-token".into()], + } + ); + } + + #[test] + fn approval_question_states_where_remembered_answer_is_kept() { + let f = Fixture::new("", ""); + let (_, questions, _) = f.run(true, Some(YES)); + let text = &questions[0].remember_text; + assert!(text.contains("later creations in /work/app"), "{text}"); + assert!(text.contains("for this credential"), "{text}"); + assert!(text.contains(&f.policy.display().to_string()), "{text}"); + } + + #[test] + fn yes_flag_does_not_approve_a_credential() { + // `approve` takes no `--yes`: with no terminal the creation is + // refused whatever the flag says, and with a terminal the person + // answers. + let f = Fixture::new("", ""); + let refused = refusal(f.run(false, None).0); + assert_eq!(refused.exit_code(), 2); + } + + #[test] + fn denied_credential_refuses_exit5_and_names_rule() { + let org = "[credential-rules]\nrules = [{ credential = { source = \"store\", \ + store = \"keychain\", id = \"npm\" }, action = \"deny\" }]\n"; + let f = Fixture::new(ALLOW_HERE, org); + // The organization's deny holds against the user's allow, and + // nothing is asked. + let (result, questions, _) = f.run(true, Some(YES)); + assert!(questions.is_empty()); + let refused = refusal(result); + assert_eq!(refused.exit_code(), 5); + let text = refused.to_string(); + assert!(text.contains("rule 1 of [credential-rules]"), "{text}"); + assert!(text.contains(&f.org.display().to_string()), "{text}"); + // A default that denies is named too. + let f = Fixture::new( + "[credential-rules]\naction_for_unspecified = \"deny\"\n", + "", + ); + let text = refusal(f.run(true, Some(YES)).0).to_string(); + assert!(text.contains("action_for_unspecified"), "{text}"); + } + + #[test] + fn project_credential_rules_are_not_read() { + // Only the two tables are read: a project file is never an input. + let f = Fixture::new("", ""); + assert!(f.dir.path().exists()); + assert_eq!(f.user, CheckedRules::default()); + } + + #[test] + fn linked_worktree_root_is_confirmed_by_the_repository_list() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("repo"); + let wt = dir.path().join("wt"); + let own = main.join(".git/worktrees/task"); + std::fs::create_dir_all(&own).unwrap(); + std::fs::create_dir_all(wt.join("sub")).unwrap(); + std::fs::create_dir_all(main.join("sub")).unwrap(); + std::fs::write(wt.join(".git"), format!("gitdir: {}\n", own.display())).unwrap(); + // Unlisted: the entry does not point back, so it is no worktree. + assert_eq!(project_of(&wt).main_root, None); + std::fs::write( + own.join("gitdir"), + format!("{}\n", wt.join(".git").display()), + ) + .unwrap(); + let p = project_of(&wt.join("sub")); + let main = std::fs::canonicalize(&main).unwrap(); + assert_eq!(p.main_root, Some(main.join("sub"))); + // A directory that claims a worktree the repository does not list. + let claimed = dir.path().join("claimed"); + std::fs::create_dir_all(&claimed).unwrap(); + std::fs::write(claimed.join(".git"), format!("gitdir: {}\n", own.display())).unwrap(); + assert_eq!(project_of(&claimed).main_root, None); + } + + // ---- review of #4009 ---- + + const ORG_ASKS: &str = "[credential-rules]\nrules = [{ credential = { source = \"store\", \ + store = \"keychain\", id = \"npm\" }, action = \"ask\" }]\n"; + + #[test] + fn a_rule_that_asks_keeps_no_answer() { + // Interactive: the question offers no remembering, and nothing is + // written whatever the answer claims. + let f = Fixture::new("", ORG_ASKS); + let mut questions = Vec::new(); + approve( + &secrets(), + &project("/work/app"), + &f.tables(), + None, + &std::collections::BTreeMap::new(), + &mut |q| { + questions.push(q.clone()); + Ok(Answer { + approve: true, + remember: true, + }) + }, + &mut |_, _| panic!("nothing is written under a rule that asks"), + ) + .unwrap(); + assert!(!questions[0].can_remember); + assert!(questions[0].remember_text.contains("no answer is kept")); + assert!(!f.policy.exists()); + // Off a terminal: the refusal names the rule and offers no `allow` + // that would never take effect. + let refused = refusal(f.run(false, None).0); + assert_eq!(refused.exit_code(), 2); + let text = refused.to_string(); + assert!(text.contains("rule 1 of [credential-rules]"), "{text}"); + assert!(text.contains("no answer is kept"), "{text}"); + assert!(!text.contains("Add this to"), "{text}"); + } + + #[test] + fn unreadable_organization_policy_refuses() { + let dir = tempfile::tempdir().unwrap(); + let org = dir.path().join("org.toml"); + std::fs::write(&org, "not toml [").unwrap(); + let err = read_tables(&dir.path().join("none.toml"), &org, Path::new("/home/me")) + .expect_err("an organization file that does not parse refuses"); + assert!(format!("{err:#}").contains("org.toml"), "{err:#}"); + // A missing organization file has no rules. + read_tables( + &dir.path().join("none.toml"), + &dir.path().join("absent.toml"), + Path::new("/home/me"), + ) + .unwrap(); + } + + #[test] + fn a_root_no_rule_can_name_is_never_remembered_or_printed() { + let f = Fixture::new("", ""); + let odd = project("/work/app[old]"); + let mut questions = Vec::new(); + approve( + &secrets(), + &odd, + &f.tables(), + None, + &std::collections::BTreeMap::new(), + &mut |q| { + questions.push(q.clone()); + Ok(YES) + }, + &mut |_, _| {}, + ) + .unwrap(); + assert!(!questions[0].can_remember); + assert!(questions[0].remember_text.contains("cannot name")); + let err = approve( + &secrets(), + &odd, + &f.tables(), + Some(CannotAsk::NoTerminal), + &std::collections::BTreeMap::new(), + &mut |_| panic!("asked"), + &mut |_, _| {}, + ) + .unwrap_err(); + let text = format!("{err}"); + assert!( + !text.contains("[credential-rules]"), + "no rule is printed: {text}" + ); + assert!(text.contains("cannot name"), "{text}"); + } + + #[test] + fn question_names_every_variable_and_who_asked() { + let f = Fixture::new("", ""); + let mut both = secrets(); + both.insert("NPM_ALIAS".to_owned(), store_grant("npm")); + let askers = std::collections::BTreeMap::from([( + "NPM_ALIAS".to_owned(), + Asker { + who: "the loadout tool, through its service npm,".into(), + loadout: Some("tool".into()), + hosts: vec!["registry.npmjs.org".into()], + }, + )]); + let mut text = String::new(); + approve( + &both, + &project("/work/app"), + &f.tables(), + None, + &askers, + &mut |q| { + text.clone_from(&q.text); + Ok(YES) + }, + &mut |_, _| {}, + ) + .unwrap(); + assert!(text.contains("NPM_ALIAS and NPM_TOKEN"), "{text}"); + assert!(text.contains("the loadout tool"), "{text}"); + assert!(text.contains("registry.npmjs.org"), "{text}"); + // Off a terminal the refusal names the loadout flag. + let err = approve( + &both, + &project("/work/app"), + &f.tables(), + Some(CannotAsk::NoInput), + &askers, + &mut |_| panic!("asked"), + &mut |_, _| {}, + ) + .unwrap_err(); + let text = format!("{err}"); + assert!(text.contains("--no-loadouts"), "{text}"); + assert!(text.contains("--no-input is set"), "{text}"); + } + + #[test] + fn dashboard_refusal_names_the_dashboard_and_a_next_step() { + let f = Fixture::new("", ""); + let err = approve( + &secrets(), + &project("/work/app"), + &f.tables(), + Some(CannotAsk::Dashboard), + &std::collections::BTreeMap::new(), + &mut |_| panic!("asked"), + &mut |_, _| {}, + ) + .unwrap_err(); + let text = format!("{err}"); + assert!(text.contains("min dash cannot ask this question"), "{text}"); + assert!(text.contains("min box start "), "{text}"); + assert!(!text.contains("no terminal"), "{text}"); + assert!(!text.contains("--no-input"), "{text}"); + } + + #[test] + fn the_whole_github_sign_in_is_named_in_plain_words() { + let f = Fixture::new("", ""); + let narrowed = SecretGrants::from([( + "GH_TOKEN".to_owned(), + SecretGrant { + source: GrantSource::Broker, + scopes: vec!["github:repo:acme/app:contents:ro".into()], + mode: None, + }, + )]); + let mut text = String::new(); + approve( + &narrowed, + &project("/work/app"), + &f.tables(), + None, + &std::collections::BTreeMap::new(), + &mut |q| { + text.clone_from(&q.text); + Ok(YES) + }, + &mut |_, _| {}, + ) + .unwrap(); + assert!( + text.contains("your whole GitHub sign-in (`full`)"), + "{text}" + ); + assert!( + text.contains("wider than the scopes the file declares"), + "{text}" + ); + } + + #[test] + fn printed_lines_fit_the_file_they_are_added_to() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("user_policy.toml"); + let rule = remembered_rule(&project("/work/app"), &credentials(&secrets())[0].1, true); + // No table yet: the whole table. + let whole = rule_lines(&path, &rule); + assert_eq!(whole[0], "[credential-rules]"); + // A `rules` array already there: one entry for it, and no second table. + std::fs::write(&path, "[credential-rules]\nrules = []\n").unwrap(); + let entry = rule_lines(&path, &rule); + assert_eq!(entry.len(), 2, "{entry:?}"); + assert!( + entry.iter().all(|line| line != "[credential-rules]"), + "{entry:?}" + ); + } + + #[test] + fn worktree_backlinks_are_read_from_the_worktree_folder_and_name_its_git_file() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("repo"); + let wt = dir.path().join("wt"); + let own = main.join(".git/worktrees/task"); + std::fs::create_dir_all(&own).unwrap(); + std::fs::create_dir_all(&wt).unwrap(); + std::fs::write(wt.join(".git"), format!("gitdir: {}\n", own.display())).unwrap(); + // A relative backlink is read against the worktree's folder in the + // repository, as Git writes it. + std::fs::write(own.join("gitdir"), "../../../../wt/.git\n").unwrap(); + let main = std::fs::canonicalize(&main).unwrap(); + assert_eq!(project_of(&wt).main_root, Some(main)); + // A `.git` that only links to the registered worktree's `.git` is not + // that folder's own. + let claimed = dir.path().join("claimed"); + std::fs::create_dir_all(&claimed).unwrap(); + std::os::unix::fs::symlink(wt.join(".git"), claimed.join(".git")).unwrap(); + assert_eq!(project_of(&claimed).main_root, None); + } +} diff --git a/crates/minimal/src/dash/app.rs b/crates/minimal/src/dash/app.rs index 48d00c333d..d1924891f7 100644 --- a/crates/minimal/src/dash/app.rs +++ b/crates/minimal/src/dash/app.rs @@ -1350,6 +1350,7 @@ fn prepare_create( loadouts: crate::loadouts::resolve_active_loadouts(loadouts, client_config, global)? .loadouts, ignore: Some(inputs.user_policy.vars().ignore().clone()), + service_facts: mfile::expand::ServiceFacts::default(), }, global: Some(global.clone()), }; diff --git a/crates/minimal/src/dash/rpc.rs b/crates/minimal/src/dash/rpc.rs index 8e17cc206c..1f82d55518 100644 --- a/crates/minimal/src/dash/rpc.rs +++ b/crates/minimal/src/dash/rpc.rs @@ -1066,6 +1066,7 @@ fn put_picked_entry_with( (Vec::new(), None), crate::ProjectPrompts::Dashboard, store, + &picked.selected, )?; request.config.network = args.network_mode().into(); request.config.policy = checks.policy; @@ -1077,6 +1078,11 @@ fn put_picked_entry_with( store_grants = checks.store_grants.len(), "dashboard create: the request takes the entry's network and secret settings" ); + // BOX-244: the stored spec reads the expansion the checks read. + let selected = crate::SelectedLoadouts { + service_facts: checks.service_facts, + ..picked.selected.clone() + }; crate::put_session_entry( request, contribution, @@ -1085,7 +1091,7 @@ fn put_picked_entry_with( project_root: upload_root, entry: Some(&entry), box_name: box_name.as_deref(), - selected: &picked.selected, + selected: &selected, global: picked.global.as_ref(), }, )?; @@ -2081,6 +2087,55 @@ mod tests { assert_eq!(request.config.project_path.as_str(), sub.as_str()); } + /// BEP-108: the dashboard cannot ask the approval question, so a create + /// whose credential no rule approves is refused with words that are true + /// there: it names `min dash`, and a next step that exists, and not a + /// missing terminal or `--no-input`. + #[test] + fn dashboard_refusal_for_an_unapproved_credential_names_the_dashboard() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join(mfile::MFILE_NAME), + "[sessions.dev.network]\nmode = \"own_ip\"\n\ + [sessions.dev.network.egress]\nallow_dns_hosts = [\"registry.npmjs.org\"]\n\ + [sessions.dev.network.bep]\nsteering = \"proxy_env\"\n\ + [sessions.dev.secrets.NPM_TOKEN]\nsource = \"store\"\n\ + store = \"keychain\"\nid = \"npm-token\"\n", + ) + .unwrap(); + let config = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(config.path().join("minimal")).unwrap(); + std::fs::write( + config.path().join("minimal/config.toml"), + "[secret-store-rules.npm-token]\nauthorities = [\"registry.npmjs.org\"]\n\ + header = \"Authorization\"\nprefix = \"Bearer \"\n", + ) + .unwrap(); + let global = crate::GlobalArgs { + config_dir: Some(config.path().to_path_buf()), + ..Default::default() + }; + let root = camino::Utf8PathBuf::from_path_buf(dir.path().to_path_buf()).unwrap(); + let mut args = crate::cli::ActivateArgs::unflagged(); + let err = crate::check_project( + &global, + &mut args, + &root, + Some("dev"), + None, + (Vec::new(), None), + crate::ProjectPrompts::Dashboard, + &crate::EveryItemStore, + &crate::SelectedLoadouts::default(), + ) + .expect_err("no rule approves the credential"); + let text = format!("{err}"); + assert!(text.contains("min dash cannot ask this question"), "{text}"); + assert!(text.contains("min box start "), "{text}"); + assert!(!text.contains("--no-input"), "{text}"); + assert!(!text.contains("no terminal"), "{text}"); + } + /// A box created from `min dash` with the entry `dev` stores the spec, /// and the projection digest, that `min box start dev` stores for the /// same project, and the contribution carries the same expansion. The @@ -2109,6 +2164,16 @@ mod tests { header = \"Authorization\"\nprefix = \"Bearer \"\n", ) .unwrap(); + // BEP-105: the project is approved for its credential. + std::fs::write( + config.path().join("minimal/user_policy.toml"), + format!( + "[credential-rules]\nrules = [{{ project = {:?}, credential = {{ source = \ + \"store\", store = \"keychain\", id = \"npm-token\" }}, action = \"allow\" }}]\n", + dir.path() + ), + ) + .unwrap(); let global = crate::GlobalArgs { config_dir: Some(config.path().to_path_buf()), no_input: true, @@ -2149,6 +2214,7 @@ mod tests { flags, crate::ProjectPrompts::Terminal, &crate::EveryItemStore, + &crate::SelectedLoadouts::default(), ) .expect("min box start dev passes its project checks"); let mut started = fresh(args.network_mode().into(), checks.policy); diff --git a/crates/minimal/src/lib.rs b/crates/minimal/src/lib.rs index 958e82e70c..81f8f6bdc8 100644 --- a/crates/minimal/src/lib.rs +++ b/crates/minimal/src/lib.rs @@ -10,9 +10,11 @@ pub mod autospawn; // by the TUI as well); re-exported here so internal `crate::client::...` // paths and downstream users of `minimal::client` keep working. pub use minimal_client as client; +pub mod client_file; pub mod completion; pub mod completions; pub mod config; +pub mod credential_approval; pub mod dash; pub mod diag; pub mod dirs; diff --git a/crates/minimal/src/main.rs b/crates/minimal/src/main.rs index 204c99202c..480bf185fe 100644 --- a/crates/minimal/src/main.rs +++ b/crates/minimal/src/main.rs @@ -256,6 +256,9 @@ fn answer_failure( return ExitCode::from(minimal::BoxTimedOut::EXIT_CODE); } let _ = writeln!(stderr, "error: {e:#}"); + // CFW-004, CFW-007: a client file that was not saved before the command + // failed still gets its path, its cause and the lines to change. + minimal::client_file::flush_deferred_into(stderr); // BCLI-013: a wait that its `--timeout` ended gives the next step on // its own line, as the machine-mode object gives it in `hint`. if let Some(timed_out) = e.downcast_ref::() @@ -431,6 +434,17 @@ fn failure_exit_code(e: &anyhow::Error) -> u8 { if e.downcast_ref::().is_some() { return 3; } + // BEP-108: a credential that no rule approves for the project (2), or + // that a rule or the person denies (5). + if let Some(refused) = e.downcast_ref::() { + return refused.exit_code(); + } + // BEP-106: a `[credential-rules]` table that is not valid. + if e.downcast_ref::() + .is_some() + { + return 3; + } if e.downcast_ref::() .is_some() { diff --git a/crates/minimal/src/mint.rs b/crates/minimal/src/mint.rs index d232dfb97d..12b82f38fe 100644 --- a/crates/minimal/src/mint.rs +++ b/crates/minimal/src/mint.rs @@ -2961,6 +2961,16 @@ pub(crate) mod tests { let (bep_config, organization, over) = bep_files(dir.path()); std::fs::write( &bep_config, + "[secret-store-rules.npm-token]\n\ + authorities = [\"registry.npmjs.org\"]\n\ + header = \"Authorization\"\n\ + prefix = \"Bearer \"\n", + ) + .unwrap(); + // Only the organization configuration keeps `action` (BEP-094). + std::fs::create_dir_all(organization.parent().unwrap()).unwrap(); + std::fs::write( + &organization, "[secret-store-rules.npm-token]\n\ authorities = [\"registry.npmjs.org\"]\n\ header = \"Authorization\"\n\ @@ -2974,8 +2984,9 @@ pub(crate) mod tests { err.to_string(), format!( "min did not mint a store handle for npm-token: the store rules that bep serve \ - reads from {} set action = \"deny\" for npm-token.", - bep_config.display() + reads from {} and {} set action = \"deny\" for npm-token.", + bep_config.display(), + organization.display() ) ); } diff --git a/crates/minimal/src/prompt.rs b/crates/minimal/src/prompt.rs index 7e55d4943d..23732256c3 100644 --- a/crates/minimal/src/prompt.rs +++ b/crates/minimal/src/prompt.rs @@ -23,7 +23,7 @@ use std::cell::RefCell; #[cfg(test)] use std::collections::VecDeque; use std::io; -use std::path::{Path, PathBuf}; +use std::path::Path; use boxes::core::decision::ItemDecision; use boxes::core::hooks::{HookResult, PolicyHooks, Unapproved}; @@ -189,7 +189,7 @@ impl InteractivePrompt { let (vars, patches, hooks) = initial.into_parts(); Self { prompter: Box::new(InquirePrompter), - can_persist: is_writable(policy_path), + can_persist: crate::client_file::can_replace(policy_path).is_ok(), vars_policy: RefCell::new(vars), patches_policy: RefCell::new(patches), hooks_policy: RefCell::new(hooks), @@ -234,61 +234,6 @@ impl InteractivePrompt { } } -/// Whether the current user could actually write `path` — the guard -/// for offering permanent policy edits. -/// -/// The check has to reflect the *effective* access of the caller, -/// not just the file's mode bits: a root-owned `user_policy.toml` -/// with mode `0o644` looks writable to `std::fs::Permissions::readonly` -/// (owner-write is set) but a non-root user can't rewrite it, and -/// offering the permanent choices only for `save_user_policy` to die -/// with `EACCES` after the daemon has been prompted through is the -/// specific outcome this filter exists to avoid. `access(2)` with -/// `W_OK` asks the kernel the same question `open(..., O_WRONLY)` -/// would answer. -/// -/// If `path` doesn't exist, walk *every* missing ancestor: a fresh -/// install where `~/.config/minimal/` doesn't exist yet still needs -/// the permanent choices offered, because `save_user_policy` calls -/// `create_dir_all(parent)` and lands the file only if the first -/// existing ancestor is writable. -/// -/// Falls back to "not writable" on any unexpected failure — better -/// to hide choices we can't honor than to promise persistence and -/// fail. -fn is_writable(path: &Path) -> bool { - use nix::unistd::{AccessFlags, access}; - match access(path, AccessFlags::W_OK) { - Ok(()) => true, - Err(nix::errno::Errno::ENOENT) => { - let mut cur = path.parent(); - while let Some(dir) = cur { - // A relative path like `user_policy.toml` has parent - // `""` (per `Path::parent` semantics). Treat empty as - // "the current working directory" via `.` so - // `access(2)` gets a real path to consult instead of - // returning ENOENT and terminating the walk with a - // spurious false. Without this, any caller resolving - // the policy to a bare filename (test harnesses, - // `MINIMAL_CONFIG_DIR=.`) permanently loses the - // *Permanent choices. - let probe: &Path = if dir.as_os_str().is_empty() { - Path::new(".") - } else { - dir - }; - match access(probe, AccessFlags::W_OK) { - Ok(()) => return true, - Err(nix::errno::Errno::ENOENT) => cur = dir.parent(), - Err(_) => return false, - } - } - false - } - Err(_) => false, - } -} - /// Human-readable name for a provenance source, e.g. `Project /foo` /// or `Package "go"`. Fed into the prompt message so the user knows /// who's asking. @@ -887,86 +832,71 @@ pub fn save_user_policy( policy_path: &Path, policy: &boxes::core::policy::UserPolicy, ) -> Result<(), anyhow::Error> { + use crate::client_file::{self, WriteError}; + let failed = |cause: String| { + anyhow::Error::new(WriteError::Failed { + path: policy_path.to_path_buf(), + cause, + }) + }; // Parse the existing file if present. A missing file yields an // empty document, which the merge logic treats identically to a // freshly-created file. let existing = match std::fs::read_to_string(policy_path) { Ok(s) => s, Err(e) if e.kind() == io::ErrorKind::NotFound => String::new(), - Err(e) => { - return Err(anyhow::anyhow!("reading {}: {e}", policy_path.display())); - } + Err(e) => return Err(failed(format!("it cannot be read: {e}"))), }; let mut doc: toml_edit::DocumentMut = existing .parse() - .map_err(|e| anyhow::anyhow!("parsing {}: {e}", policy_path.display()))?; + .map_err(|e| failed(format!("it does not parse: {e}")))?; merge_policy_into_document(&mut doc, policy); let serialized = doc.to_string(); - // Ensure the parent dir exists. `create_dir_all` is idempotent - // so a re-run doesn't churn. - if let Some(parent) = policy_path.parent() { - std::fs::create_dir_all(parent) - .map_err(|e| anyhow::anyhow!("creating {}: {e}", parent.display()))?; - } - - // Backup the existing file. On a fresh install nothing to back up. - if policy_path.exists() { - let bak = with_extension_bak(policy_path); - std::fs::copy(policy_path, &bak) - .map_err(|e| anyhow::anyhow!("backing up to {}: {e}", bak.display()))?; - } - - let tmp = with_extension_tmp(policy_path); - // Unlink the tmp on any early return between `write` and a - // successful `rename` — a failed rename (cross-device, EACCES, - // ENOSPC) would otherwise leave a stale `.tmp` next to - // the real file every time the caller aborts the activation. - // Uses `RemoveOnDrop` rather than a manual `let _ = - // std::fs::remove_file(&tmp)` on every error branch so we can't - // forget it if a new fallible step is inserted later. On the - // rename-succeeded path the guard is disarmed so the moved file - // stays put. - let mut guard = RemoveOnDrop::arm(&tmp); - std::fs::write(&tmp, serialized.as_bytes()) - .map_err(|e| anyhow::anyhow!("writing {}: {e}", tmp.display()))?; - std::fs::rename(&tmp, policy_path).map_err(|e| { - anyhow::anyhow!( - "atomic rename {} → {}: {e}", - tmp.display(), - policy_path.display() - ) - })?; - guard.disarm(); - Ok(()) -} - -/// Deletes `path` when dropped unless [`Self::disarm`] was called. -/// Used by [`save_user_policy`] to guarantee the tmp file doesn't -/// outlive a failed rename. -struct RemoveOnDrop<'p> { - path: &'p Path, - armed: bool, -} + // CFW-001: a file that cannot be replaced is left as it is, with no + // backup written beside it either. + client_file::can_replace(policy_path).map_err(anyhow::Error::new)?; -impl<'p> RemoveOnDrop<'p> { - fn arm(path: &'p Path) -> Self { - Self { path, armed: true } + // CFW-013, CFW-014: the backup goes through a temporary file, and a + // backup that fails does not stop the save, which is one rename that + // keeps the old file when it fails. + if let Err(why) = client_file::write_backup(policy_path) { + tracing::warn!(file = %policy_path.display(), %why, "user policy backup not written"); } - fn disarm(&mut self) { - self.armed = false; - } + client_file::replace(policy_path, serialized.as_bytes()).map_err(anyhow::Error::new) } -impl Drop for RemoveOnDrop<'_> { - fn drop(&mut self) { - if self.armed { - let _ = std::fs::remove_file(self.path); - } +/// What the person reads when [`save_user_policy`] did not save `policy` to +/// `policy_path`, built from `error` (CFW-004, CFW-007, CFW-011). The lines +/// are the rule arrays the policy holds, which come from rule patterns and +/// never from a secret value (CFW-005). +#[must_use] +pub fn policy_save_report( + policy_path: &Path, + policy: &boxes::core::policy::UserPolicy, + error: &anyhow::Error, +) -> crate::client_file::Report { + use crate::client_file::{Report, WriteError}; + let write_error = error + .downcast_ref::() + .cloned() + .unwrap_or_else(|| WriteError::Failed { + path: policy_path.to_path_buf(), + cause: format!("{error:#}"), + }); + let mut doc = toml_edit::DocumentMut::new(); + merge_policy_into_document(&mut doc, policy); + let lines = doc.to_string().lines().map(str::to_string).collect(); + let mut report = Report::add(write_error, lines); + if policy_path.exists() { + report = report.replacing( + "rule arrays under [vars], [patches] or [hooks]. Each array here holds the whole list, not only the new entries, so it replaces the array of the same name", + ); } + report } /// Upsert the nine rule arrays (`vars`, `patches`, and `hooks`, each @@ -1057,34 +987,6 @@ fn remove_empty_section(doc: &mut toml_edit::DocumentMut, section: &str) { } } -fn with_extension_bak(path: &Path) -> PathBuf { - let mut p = path.to_path_buf(); - let new_name = match path.file_name() { - Some(name) => { - let mut n = name.to_os_string(); - n.push(".bak"); - n - } - None => "user_policy.toml.bak".into(), - }; - p.set_file_name(new_name); - p -} - -fn with_extension_tmp(path: &Path) -> PathBuf { - let mut p = path.to_path_buf(); - let new_name = match path.file_name() { - Some(name) => { - let mut n = name.to_os_string(); - n.push(".tmp"); - n - } - None => "user_policy.toml.tmp".into(), - }; - p.set_file_name(new_name); - p -} - // ===================================================================== // Tests // ===================================================================== @@ -1559,34 +1461,63 @@ allow = [\"DIAGRAM\"] ); } - // ---- is_writable ---- - - /// Non-existent file with writable parent → we can create it. + /// A read-only policy file is left as it is, with no backup beside it + /// (CFW-001, CFW-002), and the error says the file cannot be replaced. #[test] - fn is_writable_missing_file_writable_parent_returns_true() { + fn unwritable_policy_file_is_left_unchanged_and_not_backed_up() { + if nix::unistd::Uid::effective().is_root() { + return; + } + use std::os::unix::fs::PermissionsExt as _; let tmp = TempDir::new().unwrap(); - let path = tmp.path().join("does-not-exist.toml"); - assert!(is_writable(&path)); - } - - /// A file that exists and is writable → true. + let path = tmp.path().join("user_policy.toml"); + std::fs::write(&path, "# old\n").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o444)).unwrap(); + let policy = + UserPolicy::empty().with_vars(VarsPolicy::empty().try_with_allow(["FOO"]).unwrap()); + let err = save_user_policy(&path, &policy).expect_err("read-only"); + let write_error = err + .downcast_ref::() + .unwrap(); + assert!(write_error.is_unwritable(), "{err:#}"); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "# old\n"); + assert!(!tmp.path().join("user_policy.toml.bak").exists()); + let report = policy_save_report(&path, &policy, &err).render(); + assert!(report.contains("user_policy.toml"), "{report}"); + assert!(report.contains("FOO"), "{report}"); + } + + /// A symlinked policy file keeps its link (CFW-010). #[test] - fn is_writable_existing_writable_file_returns_true() { + fn save_user_policy_keeps_a_symlink() { let tmp = TempDir::new().unwrap(); - let path = tmp.path().join("policy.toml"); - std::fs::write(&path, "").unwrap(); - assert!(is_writable(&path)); + let real = tmp.path().join("real.toml"); + std::fs::write(&real, "# old\n").unwrap(); + let link = tmp.path().join("user_policy.toml"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let policy = + UserPolicy::empty().with_vars(VarsPolicy::empty().try_with_allow(["FOO"]).unwrap()); + save_user_policy(&link, &policy).unwrap(); + assert!( + std::fs::symlink_metadata(&link) + .unwrap() + .file_type() + .is_symlink() + ); + assert!(std::fs::read_to_string(&real).unwrap().contains("FOO")); } - /// A file with the read-only bit set → false. + /// A backup that cannot be written does not stop the save (CFW-014). #[test] - fn is_writable_readonly_file_returns_false() { + fn failed_backup_write_does_not_stop_client_file_save() { let tmp = TempDir::new().unwrap(); - let path = tmp.path().join("policy.toml"); - std::fs::write(&path, "").unwrap(); - let mut perms = std::fs::metadata(&path).unwrap().permissions(); - perms.set_readonly(true); - std::fs::set_permissions(&path, perms).unwrap(); - assert!(!is_writable(&path)); + let path = tmp.path().join("user_policy.toml"); + std::fs::write(&path, "# old\n").unwrap(); + // A folder where the backup goes makes the backup rename fail. + std::fs::create_dir(tmp.path().join("user_policy.toml.bak")).unwrap(); + let policy = + UserPolicy::empty().with_vars(VarsPolicy::empty().try_with_allow(["FOO"]).unwrap()); + save_user_policy(&path, &policy).unwrap(); + assert!(std::fs::read_to_string(&path).unwrap().contains("FOO")); } } diff --git a/crates/minimal/src/task.rs b/crates/minimal/src/task.rs index abf78af116..19609e3280 100644 --- a/crates/minimal/src/task.rs +++ b/crates/minimal/src/task.rs @@ -1151,10 +1151,19 @@ pub(crate) fn gate_task_env( if after != user_policy { match crate::prompt::save_user_policy(policy_path, &after) { Ok(()) => eprintln!("Updated {}", policy_path.display()), - Err(e) => eprintln!("warning: failed to update {}: {e}", policy_path.display()), + Err(e) => { + crate::client_file::defer(&crate::prompt::policy_save_report( + policy_path, + &after, + &e, + )); + } } } - Ok((task_env?, after)) + let task_env = task_env?; + // CFW-007, CFW-008: print what was not saved, and fail for a write that failed. + crate::client_file::finish_after_attach(Ok(()))?; + Ok((task_env, after)) } } @@ -1752,6 +1761,13 @@ pub(crate) async fn run_entry( // Interim until #3679: with no root certificate, the daemon refuses a // brokered task secret also where a proxy serves boxes. refuse_unserved_broker_secrets(request.spec.as_ref(), || crate::host_proxy_absence(global))?; + // BEP-105, BEP-108: a task box holds a `[secrets]` credential only in a + // project the user approved for it, as a session box does. The checks that + // the box can hold the credential at all come first, so nobody is asked to + // approve one that is then refused. + if let Some(expanded) = &expanded { + crate::approve_spec_secrets(global, &upload_root, &expanded.spec)?; + } // Loadouts and user policy, resolved before the daemon connection so a // broken loadout fails loudly client-side, and through the same shared @@ -1972,10 +1988,17 @@ pub(crate) async fn run_entry( if final_policy != initial_policy { match crate::prompt::save_user_policy(&policy_path, &final_policy) { Ok(()) => eprintln!("Updated {}", policy_path.display()), - Err(e) => eprintln!("warning: failed to update {}: {e}", policy_path.display()), + Err(e) => { + crate::client_file::defer(&crate::prompt::policy_save_report( + &policy_path, + &final_policy, + &e, + )); + } } } result?; + crate::client_file::finish_after_attach(Ok(()))?; } } let _ = initial_policy; diff --git a/crates/minimal/src/tests.rs b/crates/minimal/src/tests.rs index 0482df30e5..8591f26d1f 100644 --- a/crates/minimal/src/tests.rs +++ b/crates/minimal/src/tests.rs @@ -4168,13 +4168,15 @@ async fn start_typed_session_entry_stores_its_own_body() { // The activation grants dev's own secret. let (_, secrets, _, _) = - crate::project_bep_and_grants(root, Some("dev")).expect("the project loads"); + crate::project_bep_and_grants(root, Some("dev"), &crate::SelectedLoadouts::default()) + .expect("the project loads"); assert_eq!( secrets.keys().map(ToString::to_string).collect::>(), vec!["DEV_TOKEN".to_owned()] ); let (_, secrets, _, _) = - crate::project_bep_and_grants(root, Some("default")).expect("the project loads"); + crate::project_bep_and_grants(root, Some("default"), &crate::SelectedLoadouts::default()) + .expect("the project loads"); assert!(secrets.is_empty(), "default has no secret: {secrets:?}"); // The `default` entry keeps its own body. @@ -18302,6 +18304,7 @@ lifecycle_hooks = [{ on_activate = { type = "inline", value = "echo project" } } "[[lifecycle_hooks]]\non_activate = { type = \"inline\", value = \"echo rust\" }\n", )], ignore: None, + ..Default::default() }; let expanded = crate::session_box_expansion(root, None, true, &selected) .expect("the entry expands") @@ -18377,6 +18380,7 @@ lifecycle_hooks = [{ on_activate = { type = "inline", value = "echo project" } } "[[lifecycle_hooks]]\non_activate = { type = \"inline\", value = \"echo rust\" }\n", )], ignore: None, + ..Default::default() }; let expanded = crate::session_box_expansion(root, None, true, &selected) .expect("the entry expands") @@ -18482,6 +18486,7 @@ env_vars = { PROJECT = "yes" } "packages = [\"ripgrep\"]\nenv_vars = { RUST_LOG = \"debug\" }\n", )], ignore: None, + ..Default::default() }; let start = parsed_start(&["min", "box", "start"]); let StartPlan::Session { args, options, .. } = @@ -18540,6 +18545,7 @@ fn conflicting_loadout_var_refused_before_create() { let mut selected = crate::SelectedLoadouts { loadouts: vec![named_loadout("ed", "env_vars = { EDITOR = \"vi\" }\n")], ignore: None, + ..Default::default() }; let error = crate::session_box_expansion(root, None, true, &selected) .expect_err("the loadout conflicts with the entry"); @@ -18648,6 +18654,7 @@ fn loadout_0_7_vars_read_as_env_vars_with_hint() { let selected = crate::SelectedLoadouts { loadouts: active.loadouts, ignore: None, + ..Default::default() }; let expanded = crate::session_box_expansion(&root, None, true, &selected) .unwrap_or_else(|e| panic!("{selection:?}: the entry expands: {e:#}")) @@ -21262,7 +21269,10 @@ async fn box_spec_renders_formats_secrets_as_refs() { ); assert!( toml.contains( - "# secrets: from [sessions.default]\n[secrets.API_KEY]\nsource = \"client_env\"\n" + "# secrets: from [sessions.default]\n\ + # secrets.API_KEY: from [sessions.default]\n\ + # secrets.API_KEY.approval: undecided\n\ + [secrets.API_KEY]\nsource = \"client_env\"\n" ), "{toml}" ); @@ -21300,9 +21310,10 @@ async fn box_spec_renders_formats_secrets_as_refs() { .await .expect("the entry renders"); assert!( - yaml.starts_with("entry: default\nloadouts:\n - default\nschema: min/v1/spec\nsources:\n"), + yaml.starts_with("entry: default\nleft_out: []\nloadouts:\n - default\nprincipals:\n"), "{yaml}" ); + assert!(yaml.contains("\nschema: min/v1/spec\nsources:\n"), "{yaml}"); // The built-in `default` loadout folds its `env_vars` into the spec // before `network` (BCLI-021). assert!(yaml.contains("\nspec:\n env_vars:\n"), "{yaml}"); @@ -21872,7 +21883,8 @@ async fn box_spec_bare_reads_defaults_network_bep_matches_start_projection() { ); let path = camino::Utf8Path::from_path(project.path()).expect("a UTF-8 path"); let (start_bep, start_secrets, _, start_quic443) = - crate::project_bep_and_grants(path, Some("one")).expect("the start projection"); + crate::project_bep_and_grants(path, Some("one"), &crate::SelectedLoadouts::default()) + .expect("the start projection"); assert_eq!( start_bep.steering, Some(boxes::core::bep::Steering::ProxyEnv) @@ -22234,6 +22246,7 @@ async fn box_spec_entry_folds_selected_loadouts_as_start() { .expect("the loadout resolves") .loadouts, ignore: None, + ..Default::default() }; let start = crate::session_box_expansion(root, Some("default"), true, &selected) .expect("the entry expands") @@ -22779,6 +22792,7 @@ on_detach = { type = "external", value = "./cleanup.sh" } "#, )], ignore: None, + ..Default::default() }; let expanded = crate::session_box_expansion(root, None, true, &selected) .expect("the entry expands") @@ -29824,6 +29838,252 @@ async fn box_spec_entry_shows_the_hosts_each_service_added() { } } +/// A project whose default session `uses` the service of a stored secret and +/// whose config holds a `dev` loadout with a `[network]` table. +fn spec_project_with_loadout() -> (tempfile::TempDir, GlobalArgs) { + let (project, global) = spec_project( + "[sessions.default]\nnetwork = { mode = \"own_ip\", \ + bep = { steering = \"proxy_env\" }, uses = [\"anthropic-oauth-token\"] }\n", + ); + let config = global.config_dir.clone().unwrap().join("minimal"); + std::fs::create_dir_all(config.join("loadouts")).unwrap(); + std::fs::write( + config.join("loadouts/dev.toml"), + "[network]\nuses = [\"claude-code\"]\n[network.egress]\n\ + allow_dns_hosts = [\"tool.example\"]\nallow_subnets = [\"10.9.0.0/16\"]\n", + ) + .unwrap(); + std::fs::write( + config.join("config.toml"), + "[secret-store-rules.anthropic-oauth-token]\nauthorities = [\"api.anthropic.com\"]\n\ + header = \"Authorization\"\nprefix = \"Bearer \"\n", + ) + .unwrap(); + (project, global) +} + +async fn spec_json(global: &GlobalArgs) -> serde_json_lenient::Value { + let json = box_spec_text( + global, + &[ + "min", + "box", + "spec", + "default", + "--loadout", + "dev", + "-o", + "json", + ], + ) + .await + .expect("the entry renders"); + serde_json_lenient::from_str(&json).expect("JSON") +} + +// BCLI-088: each host a service or a loadout's list added names who added +// it, and each grant a service derived names the service. +#[tokio::test] +async fn box_spec_shows_service_hosts_and_derived_grants_with_source() { + let (_project, global) = spec_project_with_loadout(); + let doc = spec_json(&global).await; + let sources = &doc["sources"]; + // A host the loadout's own list added, and the subnet. + assert_eq!( + sources["network.egress.allow_dns_hosts[tool.example]"], + serde_json_lenient::json!(["the loadout dev"]), + "{doc}" + ); + assert_eq!( + sources["network.egress.allow_subnets[10.9.0.0/16]"], + serde_json_lenient::json!(["the loadout dev"]), + "{doc}" + ); + // A host a loadout's service added names the loadout, and a host the + // box's own `uses` added names its table. + assert_eq!( + sources["network.egress.allow_dns_hosts[platform.claude.com]"], + serde_json_lenient::json!(["the service claude-code, which the loadout dev names"]), + "{doc}" + ); + assert_eq!( + sources["network.egress.allow_dns_hosts[api.anthropic.com]"], + serde_json_lenient::json!([ + "the service anthropic-oauth-token, which [sessions.default] uses" + ]), + "{doc}" + ); + // The grant the service derived names the service. + assert_eq!( + sources["secrets.CLAUDE_CODE_OAUTH_TOKEN"], + serde_json_lenient::json!([ + "the service anthropic-oauth-token, which [sessions.default] uses" + ]), + "{doc}" + ); + assert_eq!( + doc["spec"]["secrets"]["CLAUDE_CODE_OAUTH_TOKEN"]["id"], + "anthropic-oauth-token" + ); +} + +// BCLI-088: each grant says whether the project is approved, undecided or +// denied for its credential. +#[tokio::test] +async fn box_spec_shows_each_grant_asker_and_approval_state() { + let (project, global) = spec_project_with_loadout(); + let policy = global + .config_dir + .clone() + .unwrap() + .join("minimal/user_policy.toml"); + let rule = |action: &str| { + format!( + "[credential-rules]\nrules = [{{ project = {:?}, credential = {{ source = \"store\", \ + store = \"keychain\", id = \"anthropic-oauth-token\" }}, action = \"{action}\" }}]\n", + std::fs::canonicalize(project.path()).unwrap() + ) + }; + for (policy_text, state) in [ + (None, "undecided"), + (Some(rule("allow")), "approved"), + (Some(rule("deny")), "denied"), + ] { + match &policy_text { + Some(text) => std::fs::write(&policy, text).unwrap(), + None => drop(std::fs::remove_file(&policy)), + } + let doc = spec_json(&global).await; + assert_eq!( + doc["sources"]["secrets.CLAUDE_CODE_OAUTH_TOKEN.approval"], + serde_json_lenient::json!([state]), + "{doc}" + ); + } +} + +// BCLI-088: what a loadout brought that the box left out is reported beside the +// spec with its reason, and is not in the spec. +#[tokio::test] +async fn box_spec_names_what_a_loadout_left_out_and_why() { + // A project with no grant of its own, so `--deny-all-egress` refuses nothing. + let (_project, global) = spec_project("[sessions.default]\nnetwork = { mode = \"own_ip\" }\n"); + let config = global.config_dir.clone().unwrap().join("minimal"); + std::fs::create_dir_all(config.join("loadouts")).unwrap(); + std::fs::write( + config.join("loadouts/dev.toml"), + "[network]\nuses = [\"claude-code\"]\n[network.egress]\n\ + allow_dns_hosts = [\"tool.example\"]\nallow_subnets = [\"10.9.0.0/16\"]\n", + ) + .unwrap(); + let json = box_spec_text( + &global, + &[ + "min", + "box", + "spec", + "default", + "--loadout", + "dev", + "--deny-all-egress", + "-o", + "json", + ], + ) + .await + .expect("the entry renders"); + let doc: serde_json_lenient::Value = serde_json_lenient::from_str(&json).expect("JSON"); + let left = doc["left_out"].as_array().expect("a list"); + let find = |what: &str| { + left.iter() + .find(|l| l["what"] == what) + .unwrap_or_else(|| panic!("{what} not reported: {doc}")) + }; + let service = find("the service claude-code"); + assert_eq!(service["loadout"], "dev"); + assert!( + service["reason"] + .as_str() + .is_some_and(|r| r.contains("--deny-all-egress")), + "{service}" + ); + assert!( + find("its egress lists")["reason"] + .as_str() + .is_some_and(|r| r.contains("no network")) + ); + // Nothing the loadout left out is in the spec. + assert!(!doc["spec"].to_string().contains("tool.example"), "{doc}"); + // The TOML form says it in a comment. + let toml = box_spec_text( + &global, + &[ + "min", + "box", + "spec", + "default", + "--loadout", + "dev", + "--deny-all-egress", + ], + ) + .await + .expect("the entry renders"); + assert!( + toml.contains("# Left out: the service claude-code of the loadout dev: "), + "{toml}" + ); + // A box that takes everything reports nothing left out. + let json = box_spec_text( + &global, + &[ + "min", + "box", + "spec", + "default", + "--loadout", + "dev", + "-o", + "json", + ], + ) + .await + .expect("the entry renders"); + let doc: serde_json_lenient::Value = serde_json_lenient::from_str(&json).expect("JSON"); + assert_eq!(doc["left_out"], serde_json_lenient::json!([]), "{doc}"); +} + +// BCLI-085: `-o json` names beside each value the principal that BOX-238 +// reports: the project by its root, the loadout by its name. +#[tokio::test] +async fn box_spec_json_names_principal_per_value() { + let (project, global) = spec_project_with_loadout(); + let doc = spec_json(&global).await; + let root = std::fs::canonicalize(project.path()).unwrap(); + let principals = &doc["principals"]; + assert_eq!( + principals["network.mode"], + serde_json_lenient::json!([{ "kind": "project", "path": root.display().to_string() }]), + "{doc}" + ); + assert_eq!( + principals["network.egress.allow_dns_hosts[tool.example]"], + serde_json_lenient::json!([{ "kind": "loadout", "name": "dev" }]), + "{doc}" + ); + // A derived grant is the project's: its `uses` asked for it. + assert_eq!( + principals["secrets.CLAUDE_CODE_OAUTH_TOKEN"][0]["kind"], "project", + "{doc}" + ); + // The root is host-specific, so it is never in the spec. + assert!( + !doc["spec"] + .to_string() + .contains(&root.display().to_string()) + ); +} + /// gominimal/arch#209: `--allow-service ` is `--allow-dns-hosts` with /// the service's host set written out, and derives no secret. An unknown /// name, and the flag with `--deny-all-egress`, are usage errors. @@ -30633,6 +30893,7 @@ fn task_entry_takes_its_loadouts_trusted_cas() { &format!("trusted_cas = [{{ pem = '''\n{}''' }}]\n", ca.pem), )], ignore: None, + ..Default::default() }; let expanded = crate::task_box_entry(root_path, "check", true, &selected, None) .expect("the task entry expands") @@ -30688,6 +30949,7 @@ fn no_project_box_trusts_client_and_loadout_cas() { ), )], ignore: None, + ..Default::default() }; let dir_path = camino::Utf8Path::from_path(dir.path()).expect("a UTF-8 path"); diff --git a/docs/specs/24-spec-box-egress-proxy/24-spec-box-egress-proxy.md b/docs/specs/24-spec-box-egress-proxy/24-spec-box-egress-proxy.md index c84c8ccd8d..3a2121a4cc 100644 --- a/docs/specs/24-spec-box-egress-proxy/24-spec-box-egress-proxy.md +++ b/docs/specs/24-spec-box-egress-proxy/24-spec-box-egress-proxy.md @@ -5,7 +5,7 @@ owner: norrietaylor epic: gominimal/inbox#625 arch: https://github.com/gominimal/arch/blob/5c1201517ba07347344fb9725efb06ee39d5c03e/specs/authn-authz/gatehouse-spec.md arch_sha: "5c1201517ba07347344fb9725efb06ee39d5c03e" -updated: 2026-12-01 +updated: 2026-12-02 --- # BEP — Local Box Egress Proxy — sealed GitHub credentials and host-store secrets without Gatehouse @@ -83,15 +83,28 @@ the host stores a store reference can name, and leaves the Linux default open. This document closes it for the native store alone. The other stores on that list stay follow-on work (Non-goals). +A box can name a service in `[network] uses`, and a loadout can name one too +(BEP-099 to BEP-104, BEP-109). The service library built into `min` holds the +hosts of each service and at most one secret form, so a user writes the name +and not the hostnames. A box holds a credential only in a project that the user +approved for it (BEP-105 to BEP-108). The user policy file records the +approval. The expansion of a loadout's network is in spec 29 (BOX-239 to +BOX-244). + ## Users and stories **Roles:** developer on an un-enrolled laptop, developer working in a box, developer reviewing what a box may reach +The stories on named services, default loadouts and approval of a project come from gominimal/inbox#1327 and #1328, which also own BEP-099 to BEP-109. The others come from the epic of this document. + - AS A developer using Minimal on a laptop with no Gatehouse, I WANT to sign in to GitHub once with `min`, SO THAT every box I start afterwards can reach my repositories without me handling a token. - AS A developer who signed in yesterday, I WANT today's boxes, and the boxes I left running overnight, to have working GitHub credentials without signing in again or re-creating anything, SO THAT the 8-hour life of a GitHub token asks nothing of me. - AS A developer working in a box, I WANT `git clone`, `git push` and `gh` to work against my repositories, SO THAT I do real work without configuring any tool. - AS A developer with an API key in my macOS Keychain, I WANT to reference it by identifier in a box spec, SO THAT requests from the box to that key's upstream carry it without the key entering the box. - AS A developer with a third-party API key, such as a Claude OAuth token or an MCP server credential, I WANT to store it once with `min secret`, SO THAT box specs reference it by identifier and its value never appears in `min` output, a spec, or a box. +- AS A developer who uses a third-party service, I WANT to write its name once, SO THAT the box gets its hosts and its sealed credential without me typing hostnames. +- AS A developer with a default loadout, I WANT the loadout to bring a tool's service with the tool, SO THAT no project repeats the same grant. +- AS A developer who clones a project, I WANT no project file to approve its own credential, SO THAT a cloned repository cannot take a token from me. - AS A developer, I WANT the proxy to refuse any use of a sealed or referenced secret outside its declared authority, SO THAT a compromised workload cannot redirect my credential. - AS A developer, I WANT a sealed value copied out of a box to be worthless anywhere else, SO THAT exfiltration of the box environment yields nothing usable. - AS A developer reviewing what a box may reach, I WANT the expanded box spec to show the interception CA and the derived credentialed upstream set, SO THAT interception is declared, not discovered. @@ -724,19 +737,19 @@ Store references tier: T0 verify: cargo nextest run -p boxes ask_rule_without_tty_denies -- **BEP-094** THE SYSTEM SHALL read a store item's consent, `allow`, `ask` or `deny`, from the user policy file as well as from the `action` of a `[secret-store-rules]` rule. +- **BEP-094** THE SYSTEM SHALL read a store item's consent, `allow`, `ask` or `deny`, from the user policy file as well as from the `action` of a `[secret-store-rules]` rule. In the user policy file the consent is a `[credential-rules]` rule that names the item and no project, and it is `ask` or `deny`. tier: T0 verify: cargo nextest run -p boxes store_consent_is_read_from_user_policy_file - - - WHERE the format of the user policy file defines a consent table, IF the user configuration sets `action` in a `[secret-store-rules]` rule THEN THE SYSTEM SHALL refuse every command that reads the client configuration. The message SHALL name the key and the file, say the user configuration does not support the key, and tell the person to set the consent in the user policy file first and then remove the key. The message SHALL also say that the consent of the item then comes from the user policy file and from the organization configuration. It SHALL say that a box uses the item without a prompt only when neither asks for consent or denies it, and that a consent of `ask` or `deny` in either applies. + + - IF the user configuration sets `action` in a `[secret-store-rules]` rule THEN THE SYSTEM SHALL refuse every command that reads the client configuration. The message SHALL name the key and the file, say the user configuration does not support the key, and tell the person to set the consent in the user policy file first and then remove the key. The message SHALL also say that the consent of the item then comes from the user policy file and from the organization configuration, and that a consent of `ask` or `deny` in either applies. tier: T0 - verify: cargo nextest run -p client-config user_config_action_key_is_refused_once_policy_table_exists - + verify: cargo nextest run -p client-config user_config_action_key_is_refused + - **BEP-097** THE SYSTEM SHALL apply to a store item the strictest consent that the organization's `action`, the user's `action` or the consent in the user policy file gives, with `deny` stricter than `ask`, and `ask` stricter than `allow`. tier: T0 verify: cargo nextest run -p boxes strictest_store_consent_wins_across_org_user_and_policy_file - + - IF the organization configuration sets `deny` or `ask` for a store item THEN THE SYSTEM SHALL apply that consent although the user configuration sets a looser one. tier: T0 verify: cargo nextest run -p client-config read_client_store_rules_keeps_the_organization_deny @@ -973,6 +986,10 @@ Setting secrets - IF `min secret rm` removed a rule and the store cannot tell whether it removed the item THEN THE SYSTEM SHALL keep the rule removed and say that the item's state is unknown. tier: T0 verify: cargo nextest run -p minimal secret_rm_unsettled_keeps_the_rule_removed + - IF `min` cannot replace the user-level client configuration, and it holds the rule for ``, THEN THE SYSTEM SHALL print the lines to remove, and ask in the same confirmation, which `--yes` answers, and remove the item only after a yes. + tier: T0 + verify: cargo nextest run -p minimal secret_rm_unwritable_config_prints_lines_and_asks + - **BEP-091** WHERE the host is Linux THE SYSTEM SHALL keep each item of the host's native store in the user's Secret Service where the session has one, and otherwise in the encrypted file store, under its identifier, for `min secret set`, `min secret list` and `min secret rm` and for the proxy's read of a store reference. tier: T0 @@ -1087,6 +1104,21 @@ Setting secrets - WHEN `min secret list` lists an item whose identifier is the name of a stored-secret service THE SYSTEM SHALL name the service and say whether the item's rule sends the value only to the entry's authorities, in the entry's injection form, with header names compared in any case. tier: T0 verify: cargo nextest run -p minimal secret_list_marks_service_items + - IF `--service` names an entry that holds hosts only THEN THE SYSTEM SHALL refuse the command before reading the value and say that the service has no secret. + tier: T0 + verify: cargo nextest run -p minimal secret_set_service_without_secret_refused + - IF `--service` is given with `--store` naming a store other than the host's native store THEN THE SYSTEM SHALL refuse the command before reading the value, and say that a service resolves to an item of the native store. + tier: T0 + verify: cargo nextest run -p minimal secret_set_service_refuses_non_native_store + + - IF `--service ` is given and `` is not `` THEN THE SYSTEM SHALL refuse the command before reading the value, and tell the person to run `min secret set --service `. + tier: T0 + verify: cargo nextest run -p minimal secret_set_service_requires_id_equal_to_service_name + + - IF a rule flag is given and `` holds `*`, `?`, `[`, `{` or `\` THEN THE SYSTEM SHALL refuse the command before reading the value, and say that the identifier holds a character that a rule cannot name. + tier: T0 + verify: cargo nextest run -p minimal secret_set_rule_refuses_id_with_glob_character + - IF the configuration reader refuses the rule that `min secret set` writes (BEP-034) THEN THE SYSTEM SHALL refuse the command, naming what the rule names, before reading the value and before writing the item or the rule. tier: T0 verify: cargo nextest run -p minimal secret_set_refuses_deny_set_rule_before_reading_value @@ -1164,6 +1196,183 @@ Setting secrets verify: cargo nextest run -p minimal secret_set_removal_failure_message_names_rm_command +- **BEP-099** THE SYSTEM SHALL hold in `min` one library of named services. Each entry holds the exact hosts of one service and at most one secret form. + tier: T0 + verify: cargo nextest run -p client-config service_library_entry_holds_hosts_and_one_secret_form + + - THE SYSTEM SHALL read the library from the `min` binary alone, and never from a project file, a loadout, a Box Spec or the client configuration. + tier: T0 + verify: cargo nextest run -p client-config service_library_is_not_read_from_project_or_loadout + + +- **BEP-100** WHEN `min` is built, and WHEN `min` loads the library, THE SYSTEM SHALL check each entry and refuse a library that fails a check. + tier: T0 + verify: cargo nextest run -p client-config service_library_checks_refuse_a_bad_entry + + - THE SYSTEM SHALL require every host and every authority of an entry to be an exact name, and to be outside the fixed deny set of the proxy. + tier: T0 + verify: cargo nextest run -p client-config service_library_hosts_are_exact_names_outside_deny_set + - THE SYSTEM SHALL require the injection form of an entry to be one that the proxy allows. + tier: T0 + verify: cargo nextest run -p client-config service_library_injection_form_is_allowed + - THE SYSTEM SHALL mark an authority that two entries share, in both entries, as an alternate form of one provider. + tier: T0 + verify: cargo nextest run -p client-config service_library_marks_shared_authority_as_alternate_form + + - THE SYSTEM SHALL require the host set and the injection form of every entry to match a reviewed list of those values for each name, so that a change to an entry shows in review. + tier: T0 + verify: cargo nextest run -p client-config service_library_matches_reviewed_list + + - WHEN a release withdraws an authority from an entry as wrong, THE SYSTEM SHALL add that authority to the fixed deny set in the same release. + tier: T0 + verify: cargo nextest run -p minimal withdrawn_library_authority_joins_deny_set + + - THE SYSTEM SHALL require the variable of an entry to be a name that a `[secrets]` entry can have, to be used by no other entry, and to be a variable that the runtime of the box does not use. + tier: T0 + verify: cargo nextest run -p client-config service_library_variable_is_valid_and_unique + + +- **BEP-101** THE SYSTEM SHALL include in the library an entry for each of `github`, `anthropic-api-key`, `anthropic-oauth-token`, `cloudflare-api-token`, `linear-api-key` and `sentry-auth-token`. + tier: T0 + verify: cargo nextest run -p client-config service_library_ships_the_named_roster + + - THE SYSTEM SHALL give the `github` entry the deep module of the GitHub sign-in and no host of the module. + tier: T0 + verify: cargo nextest run -p client-config service_library_github_entry_names_module_and_no_host + + +- **BEP-102** WHEN a box names a service in `[network] uses` THE SYSTEM SHALL add each name of the host set of that service to the `egress.allow_dns_hosts` of the expanded spec, unless the egress of the box already admits the name. + tier: T0 + verify: cargo nextest run -p mfile uses_adds_service_hosts_to_allow_dns_hosts + + - WHERE the egress of the box admits every name, THE SYSTEM SHALL add no host and write no egress rule. + tier: T0 + verify: cargo nextest run -p mfile uses_adds_nothing_where_egress_admits_every_name + + - IF a service would add a name to a box that can declare no name rule THEN THE SYSTEM SHALL refuse the expansion with exit 3, as the validation of a declared grant refuses a literal name (BEP-008). + tier: T0 + verify: cargo nextest run -p mfile uses_refused_for_box_that_cannot_declare_name_rules + - IF `uses` names a service that the library does not hold THEN THE SYSTEM SHALL refuse the expansion with exit 3 and list the names the library holds. + tier: T0 + verify: cargo nextest run -p mfile uses_unknown_service_refused_with_known_names + - IF a layer sets `network.mode` to `none` and sets `uses` to name a service, in the same layer or in a more specific one, THEN THE SYSTEM SHALL refuse the expansion with exit 3. + tier: T0 + verify: cargo nextest run -p mfile uses_refused_in_network_none + + +- **BEP-103** WHEN a box names a service that has a secret form in `[network] uses` THE SYSTEM SHALL derive one grant for it under the variable of the entry. + tier: T0 + verify: cargo nextest run -p mfile uses_derives_one_grant_per_service_secret + + - WHERE `[secrets]` holds a `broker` or `store` entry of the same variable name, THE SYSTEM SHALL derive no grant and still add the hosts of the service. + tier: T0 + verify: cargo nextest run -p mfile declared_grant_beats_derived_grant + + - IF `[secrets]` holds a `client_env` entry of the variable name of a derived grant THEN THE SYSTEM SHALL refuse the expansion with exit 3, naming both. + tier: T0 + verify: cargo nextest run -p mfile derived_grant_conflicts_with_client_env_of_same_name + - THE SYSTEM SHALL give a service no key of `network` other than the hosts and the grant. + tier: T0 + verify: cargo nextest run -p mfile service_sets_no_mode_and_no_steering + +- **BEP-104** IF the grant that a service derives needs a sign-in, an item or a rule that the user does not hold THEN THE SYSTEM SHALL refuse the creation with exit 3 and name the command that supplies it. + tier: T0 + verify: cargo nextest run -p minimal derived_grant_without_credential_names_command + + - WHERE the rule for the item lacks an authority that the entry has, THE SYSTEM SHALL use the rule as written and tell the person which authority is missing. + tier: T0 + verify: cargo nextest run -p minimal derived_grant_uses_rule_as_written_and_names_missing_authority + + +- **BEP-105** THE SYSTEM SHALL create a box that holds a `[secrets]` credential only in a project that the user approved for that credential. + tier: T0 + verify: cargo nextest run -p minimal box_holds_credential_only_in_approved_project + + +- **BEP-106** THE SYSTEM SHALL record the approval in `[credential-rules]` of the user policy file and of the organization configuration, and read both, and never read it from a project file. + tier: T0 + verify: cargo nextest run -p client-config credential_rules_are_read_from_user_policy_and_org_only + + - IF a project file contains `[credential-rules]` THEN THE SYSTEM SHALL ignore it and warn. + tier: T0 + verify: cargo nextest run -p client-config project_credential_rules_ignored_with_warning + + - THE SYSTEM SHALL name a project in a rule by one exact absolute path, with `~` as the home directory, and compare it with the root of the project after it resolves symbolic links. + tier: T0 + verify: cargo nextest run -p client-config credential_rule_project_is_exact_resolved_path + - IF a rule names a project with a pattern or a relative path THEN THE SYSTEM SHALL refuse the configuration with exit 3. + tier: T0 + verify: cargo nextest run -p client-config credential_rule_pattern_or_relative_project_refused + + - IF a rule has `action = "allow"` and names no project THEN THE SYSTEM SHALL refuse the configuration with exit 3. + tier: T0 + verify: cargo nextest run -p client-config credential_rule_allow_without_project_refused + + +- **BEP-107** THE SYSTEM SHALL decide the action for a credential in a project from every table that speaks for it. A `deny` SHALL hold against everything. Otherwise an `ask` of a rule SHALL hold, and otherwise an `allow` of a rule. + tier: T0 + verify: cargo nextest run -p client-config credential_decision_deny_then_ask_then_allow + + - THE SYSTEM SHALL match a rule to a credential exactly, at the breadth that the box would hold, so that an approval of a narrowed credential does not cover a wider one. + tier: T0 + verify: cargo nextest run -p client-config credential_rule_matches_exact_breadth + + - WHERE no rule of a table speaks, THE SYSTEM SHALL add the `action_for_unspecified` of that table. A default SHALL count only when no rule of its own table speaks, so that a rule of that table is an exception to its default. Where no rule and no default exists, THE SYSTEM SHALL ask. + tier: T0 + verify: cargo nextest run -p client-config credential_decision_defaults_then_ask + + - THE SYSTEM SHALL treat a worktree that a rule's repository lists as the project of the rule, and where a table holds a rule that names the root itself, THE SYSTEM SHALL use that rule and not the rules that cover the root as a worktree. + tier: T0 + verify: cargo nextest run -p client-config credential_rule_covers_linked_worktrees_of_its_repository + + +- **BEP-108** WHEN the decision of BEP-107 for a credential of a creation is `ask`, whether a rule, a default or the lack of both gives it, a terminal is attached and `--no-input` is not given, THE SYSTEM SHALL ask once for each project root and credential, and offer to remember the answer. + tier: T0 + verify: cargo nextest run -p minimal undecided_credential_asks_once_and_can_remember + + - IF the decision of BEP-107 for a credential of a creation is `ask`, and no terminal is attached or `--no-input` is given, THEN THE SYSTEM SHALL refuse the creation with exit 2, name the `[credential-rules]` rule to add, and ask nothing. + tier: T0 + verify: cargo nextest run -p minimal undecided_credential_off_terminal_refuses_exit2 + + - THE SYSTEM SHALL check that the user holds the credential of a grant, by BEP-104, before it asks or refuses under BEP-108. + tier: T0 + verify: cargo nextest run -p minimal missing_credential_refuses_before_approval_is_asked + + - IF `min` cannot save a remembered answer to the user policy file THEN THE SYSTEM SHALL hold the answer for the current creation, print the lines to add as CFW-004 and CFW-007 say, and create the box only when the answer approves the credential. WHERE the answer denies it, THE SYSTEM SHALL refuse the creation, as BEP-105 requires. + tier: T0 + verify: cargo nextest run -p minimal remembered_answer_unsaved_holds_for_this_creation_and_prints_lines + + - THE SYSTEM SHALL tell the person in the question which project root and which credential it concerns, and what an approval lets the code of the box do with the credential, at the breadth of the grant. + tier: T0 + verify: cargo nextest run -p minimal approval_question_states_project_credential_and_effect + + - WHERE the person chooses to remember the answer, THE SYSTEM SHALL tell the person in the question that the answer applies to later creations in that project for that credential, and that `min` writes it to the user policy file. + tier: T0 + verify: cargo nextest run -p minimal approval_question_states_where_remembered_answer_is_kept + - THE SYSTEM SHALL NOT let `--yes` answer the question. + tier: T0 + verify: cargo nextest run -p minimal yes_flag_does_not_approve_a_credential + + - IF a table denies the credential THEN THE SYSTEM SHALL refuse the creation with exit 5 and name the rule or the default that denies it. + + tier: T0 + verify: cargo nextest run -p minimal denied_credential_refuses_exit5_and_names_rule + +- **BEP-109** WHEN a selected loadout names a service whose box can take it THE SYSTEM SHALL add the hosts of the service and derive its grant, as for the box's own `uses`. + tier: T0 + verify: cargo nextest run -p minimal loadout_service_adds_hosts_and_derives_grant + + - THE SYSTEM SHALL require the approval of BEP-105 for the grant of a loadout, by the procedure and with the exit codes that a grant of the project has. + tier: T0 + verify: cargo nextest run -p minimal loadout_grant_needs_project_approval_like_any_grant + + - IF the user holds no credential for a service of a loadout, or a type constraint, a policy or the mint refuses the grant, THEN THE SYSTEM SHALL refuse the creation as for any other grant. + tier: T0 + verify: cargo nextest run -p minimal loadout_grant_missing_credential_refuses_creation + - WHERE a loadout names a service that has no secret form, THE SYSTEM SHALL add its hosts, ask no question, and say so in the creation output. + tier: T0 + verify: cargo nextest run -p minimal loadout_hosts_only_service_adds_hosts_and_asks_nothing + ## Non-goals - Caching public artifacts through the proxy: a separate story, not yet filed. @@ -1423,6 +1632,8 @@ give the API hosts that a client of the credential's environment variable calls. The presets gave MCP hosts, which a client of that variable never calls, so Karl ruled them out of 0.8. +**One name, one approval, and the loadout.** Decided on 2026-12-02 by the architecture of gominimal/arch#209, in the owner rulings that gominimal/inbox#1327 and #1328 cite. Reaching a service took three acts. The user wrote a rule for its secret, a grant, and each of its hostnames. A library entry joins the three under one name (BEP-099 to BEP-104). The library is part of the `min` binary, so a user can rely on an entry as on the binary, and no project file or loadout can choose where a secret goes. A box that names a service gets its hosts, because the box named it. The first form of #1327 gave a loadout a grant and never a host. That worked only where the egress already admitted the hosts, so a loadout now brings the hosts of its service (BEP-109 and spec 29). A holder of a credential is a project, so one approval covers every layer that asks (BEP-105 to BEP-108). A table with no project may only ask or deny. Otherwise a cloned project could inherit an approval. The architecture puts the table in the user policy file, because it is policy, and the ticket puts it in `config.toml`. I followed the architecture, as the Cedar file of spec 32 replaces the policy file. An undecided loadout grant refuses the creation off a terminal, as a project grant does. The ticket says the grant is left out with a notice. I followed the architecture, and the author can change it. `--yes` never answers the approval, because a script would approve every project. The library sits in the `client-config` crate, which `mfile` and `bep` both depend on. Expansion resolves a service name in `mfile`, and `--service` copies an entry into a store rule, which `client-config` already holds. The deny set belongs to `bep`, so the checks take it as an argument, as the store rules do. + **Prior art.** The `docs/spec-credential-lane` branch's policy gate, resolver seam, `min session credentials` review surface and the "tasks stop mapping credentials" fix carry over in intent; its lane endpoint, bearer token store and @@ -1656,12 +1867,29 @@ per-request Keychain access control. enforced by: expiry in the sealed context; revocation records consulted per request before any resolution; sign-in and store items resolved per request, so deletion revokes covered by: BEP-024, BEP-043, BEP-044, BEP-045, BEP-060, BEP-068, BEP-069, BEP-071 +- **Invariant:** THE SYSTEM SHALL let no project file, no loadout and no Box Spec approve a credential for a project. + enforced by: the approval is read from the user policy file and the organization configuration only, and a project file that holds `[credential-rules]` is ignored with a warning. + covered by: BEP-105, BEP-106 + +- **Invariant:** THE SYSTEM SHALL let no rule that names no project allow a credential. + enforced by: configuration validation refuses `allow` without a project (exit 3), so that no rule approves a credential for whatever is cloned next. + covered by: BEP-106, BEP-107 + +- **Invariant:** THE SYSTEM SHALL read the authorities and injection form of a service from the library in the `min` binary alone. + enforced by: the library is not read from a project file, a loadout or a Box Spec, and `min` checks each entry at build and at load. + covered by: BEP-099, BEP-100 + Architecture threats this document must hold: T28, T31, T32 (Gatehouse §11); AT7 and AT25 (architecture threat model). ## Open questions +- [NEEDS CLARIFICATION (MEDIUM): can a user still state a consent for a pattern of items, such as `payments/*`? Today a `[secret-store-rules]` rule states consent with an `id_glob`. A `[credential-rules]` rule names one exact `id` (BEP-106), so the pattern form of BEP-094 has no home in the policy file.] +- [NEEDS CLARIFICATION (MEDIUM): what is the project of a box that starts outside a project, restarts, resumes, or that the daemon creates (BEP-105)? The approval is keyed to a project root, and the architecture does not say.] +- [NEEDS CLARIFICATION (MEDIUM): what exit code does a creation return when the person answers no at the question of BEP-108? The architecture gives exit 5 for a `deny` and exit 2 for an `ask` that no terminal can answer.] +- [NEEDS CLARIFICATION (MEDIUM): does the approval of BEP-105 need a rollout for unattended creations that hold a credential today, such as `scripts/session-e2e.sh`, which renders a demo project with grants, and any script or CI job that creates such a box? BEP-107 and BEP-108 refuse them with exit 2 until a rule or a default allows them. A runner can set `action_for_unspecified = "allow"`. The architecture states no transition.] +- [NEEDS CLARIFICATION (MEDIUM): where does the organization's `[credential-rules]` table live (BEP-106)? The architecture puts it in the organization-level client configuration until an organization has a policy file of its own.] +- [NEEDS CLARIFICATION (MEDIUM): which rule applies to an item when several rules of the client configuration match it (gominimal/arch#212)? BEP-095 and BEP-096 say `the rule that applies`.] - [NEEDS CLARIFICATION (MEDIUM): When does local repository narrowing land? The path is recorded, the §6.4 scoped-token endpoint against the local App under the embedded client secret (Gatehouse §14.4 item 7), and until it does the member is `full` breadth and the T28 residual is the signed-in account's manifest-capped reach for the reference's life.] - [NEEDS CLARIFICATION (MEDIUM): Does every intended client accept the sealed handle as its bearer unmodified? Claude Code with an OAuth token and MCP clients send `Authorization: Bearer `, which BEP-032 substitutes, but a client that validates token shape before sending, or sends the credential in a header the rule does not name, needs the harness adapter ([gominimal/inbox#345](https://github.com/gominimal/inbox/issues/345)); unmeasured, a plan spike.] - [NEEDS CLARIFICATION (MEDIUM): How long is the root valid ([gominimal/arch#85](https://github.com/gominimal/arch/issues/85))? Its remaining validity at mint is the expiry of every sign-in reference and store handle (BEP-005, BEP-063), so it is the ceiling on a box's credentialed life and on the T28 window of a stolen reference, and the point at which a running box has to be re-created.] -- [NEEDS CLARIFICATION (HIGH): what table in the user policy file holds the consent of a store item (BEP-094)? gominimal/arch#209 proposes a table keyed by project root, and a store's consent has no project. The shape must map to one Cedar rule when the policy moves to Cedar.] diff --git a/docs/specs/28-spec-box-cli/28-spec-box-cli.md b/docs/specs/28-spec-box-cli/28-spec-box-cli.md index 7d6c0a0406..52efbb06ed 100644 --- a/docs/specs/28-spec-box-cli/28-spec-box-cli.md +++ b/docs/specs/28-spec-box-cli/28-spec-box-cli.md @@ -5,7 +5,7 @@ owner: mitodrummer epic: gominimal/inbox#731 arch: https://github.com/gominimal/arch/blob/4f2eb87d5d12485906e73e2dcaeeae1c56e76d66/architecture.md arch_sha: "4f2eb87d5d12485906e73e2dcaeeae1c56e76d66" -updated: 2026-12-01 +updated: 2026-12-02 --- # BCLI — The box grammar (`min box`, the type nouns, and the migration from the session verbs) @@ -256,6 +256,39 @@ The box model is `docs/specs/29-spec-box-local-first` (BOX): the record, the spe tier: T0 verify: cargo nextest run -p minimal box_spec_json_names_principal_per_value +- **BCLI-086** WHERE `--allow-service ` is given THE SYSTEM SHALL add the hosts of the library service `` to `egress.allow_dns_hosts` as `--allow-dns-hosts` does, and add no grant. + tier: T0 + verify: cargo nextest run -p minimal allow_service_flag_adds_service_hosts + + - IF `--allow-service` is given together with `--deny-all-egress` THEN THE SYSTEM SHALL fail with exit 2, naming both flags, and create nothing. + tier: T0 + verify: cargo nextest run -p minimal allow_service_with_deny_all_egress_exit2 + + - IF `--allow-service` would add a name to a box that can declare no name rule THEN THE SYSTEM SHALL refuse the creation with exit 3, as BEP-102 does for `uses`. + tier: T0 + verify: cargo nextest run -p minimal allow_service_refused_for_box_that_cannot_declare_name_rules + - IF `--allow-service` names a service that the library does not hold THEN THE SYSTEM SHALL fail with exit 2 and list the names the library holds. + tier: T0 + verify: cargo nextest run -p minimal allow_service_unknown_name_exit2_lists_names + +- **BCLI-087** WHEN `--deny-all-egress` or `--network none` is given THE SYSTEM SHALL empty the `uses` of the layers below the command line. + tier: T0 + verify: cargo nextest run -p minimal deny_all_egress_and_network_none_empty_uses + + +- **BCLI-088** WHEN `min box spec ` runs THE SYSTEM SHALL show each host that a service or a loadout's list added, with the service or the loadout that added it, and each grant that a service derived, with the service that derived it. + tier: T0 + verify: cargo nextest run -p minimal box_spec_shows_service_hosts_and_derived_grants_with_source + + - THE SYSTEM SHALL show each grant with the layer or loadout that asked for it, and whether the project is approved, undecided or denied for its credential. + tier: T0 + verify: cargo nextest run -p minimal box_spec_shows_each_grant_asker_and_approval_state + + - THE SYSTEM SHALL list each service and each list of a loadout that was left out, with the reason. + tier: T0 + verify: cargo nextest run -p minimal box_spec_lists_left_out_loadout_services_with_reason + + - **BCLI-078** IF expanding an entry fails under BOX-172, BOX-174, BOX-181, BOX-182, BOX-183, BOX-206 or BOX-207 THEN THE SYSTEM SHALL fail `min box spec `, `min box start`, `min box run`, `min session start` and `min task run` with exit 3, and print the error that requirement states. It SHALL create nothing and render nothing. -- **BOX-064** THE SYSTEM SHALL expand an entry in the order `[upstream]`, type defaults, `[defaults]`, `[defaults.]`, entry, selected loadouts, then command-line overrides where BCLI provides them, then the client configuration's `trusted_cas`, unioning lists in that order and replacing scalars and tables wholesale, except `env_vars`, which BOX-180 merges by name, and except that the command-line override layer merges as the sub-bullets below state. `trusted_cas` is one of the unioned lists: before the union, THE SYSTEM SHALL read each layer's `keychain`, `file` and `pem` items into one `pem` item per certificate, in that certificate's canonical PEM form, and union them by value. It SHALL fail the expansion with exit 3, naming the item and its layer, where an item names other than exactly one of those sources as a string, where a source holds anything but certificates, where a certificate is not a CA's or is outside its validity, where a type's defaults or the command-line override layer sets `trusted_cas`, and where any layer sets `infrastructure_cas`. +- **BOX-064** THE SYSTEM SHALL expand an entry in the order `[upstream]`, type defaults, `[defaults]`, `[defaults.]`, entry, selected loadouts, then command-line overrides where BCLI provides them, then the client configuration's `trusted_cas`, unioning lists in that order and replacing scalars and tables wholesale, except `env_vars`, which BOX-180 merges by name and except that the command-line override layer merges as the sub-bullets below state. `trusted_cas` is one of the unioned lists: before the union, THE SYSTEM SHALL read each layer's `keychain`, `file` and `pem` items into one `pem` item per certificate, in that certificate's canonical PEM form, and union them by value. It SHALL fail the expansion with exit 3, naming the item and its layer, where an item names other than exactly one of those sources as a string, where a source holds anything but certificates, where a certificate is not a CA's or is outside its validity, where a type's defaults or the command-line override layer sets `trusted_cas`, and where any layer sets `infrastructure_cas`. tier: T1 verify: cargo nextest run -p mfile expansion_order_and_merge_rules @@ -575,6 +575,78 @@ After this ships, a developer on a stock install with no identity plane runs ses tier: T0 verify: cargo nextest run -p mfile open_spec_applies_whole_loadout +- **BOX-239** THE SYSTEM SHALL accept in a loadout file a `[network]` table that holds `uses` and the two lists `egress.allow_dns_hosts` and `egress.allow_subnets`, and no other key. + tier: T0 + verify: cargo nextest run -p mfile loadout_network_table_holds_uses_and_two_egress_lists + + - IF a loadout's `[network]` table holds another key THEN THE SYSTEM SHALL refuse the expansion with exit 3 and name the loadout and the key. + tier: T0 + verify: cargo nextest run -p mfile loadout_network_other_key_refused_exit3 + - IF a loadout names a service that the library does not hold THEN THE SYSTEM SHALL refuse the expansion with exit 3 and name the loadout and the names the library holds. + tier: T0 + verify: cargo nextest run -p mfile loadout_unknown_service_refused_exit3 + +- **BOX-240** WHERE the `loadout_mode` that BOX-064's layers up to and including the entry set is `open` THE SYSTEM SHALL add the hosts and subnets that a selected loadout's `[network]` table gives to the box's egress at BOX-064's selected-loadouts layer, after the keys of every earlier layer and before the command-line overrides, and add to what the layers gave and replace none of it. + tier: T0 + verify: cargo nextest run -p mfile open_loadout_network_joins_egress_after_last_layer + + - WHERE the `loadout_mode` is `sealed` or `upstream-only`, THE SYSTEM SHALL ignore the `[network]` table of every selected loadout. + tier: T0 + verify: cargo nextest run -p mfile non_open_loadout_mode_ignores_loadout_network + + - THE SYSTEM SHALL give an item that a loadout adds the protocols that the box allows, and never widen `allow_protocols`. + tier: T0 + verify: cargo nextest run -p mfile loadout_egress_item_never_widens_allow_protocols + + - THE SYSTEM SHALL leave out the lists of a loadout where the mode is `none` or the command line gives `--deny-all-egress`, and SHALL leave out only the hostnames of the lists where the box can declare no name rule, and still add the subnets. + tier: T0 + verify: cargo nextest run -p mfile loadout_egress_lists_left_out_in_none_deny_all_and_names_only_without_name_rules + + +- **BOX-241** WHERE a selected loadout names a service, THE SYSTEM SHALL resolve the service as the box's own `uses` resolves it (BEP-102 and BEP-103), and leave the service out whole, with its hosts and its grant, where the box cannot take it. + tier: T0 + verify: cargo nextest run -p mfile loadout_service_resolves_like_box_uses_or_is_left_out + + - THE SYSTEM SHALL leave the service out where a layer below the loadouts delivers the variable name of its grant, as a plain value, a `client_env` entry, or a declared or derived sealed grant, and say which layer. + tier: T0 + verify: cargo nextest run -p mfile loadout_grant_yields_to_layer_that_delivers_the_name + + - THE SYSTEM SHALL leave the service out where the mode is `none` or the command line gives `--deny-all-egress`. + tier: T0 + verify: cargo nextest run -p mfile loadout_service_left_out_in_none_or_deny_all_egress + - THE SYSTEM SHALL leave the service out where it would add a name to a box that can declare no name rule. + tier: T0 + verify: cargo nextest run -p mfile loadout_service_left_out_for_box_without_name_rules + - THE SYSTEM SHALL leave the service out where the host cannot carry the grant: no proxy serves the box, a store reference needs a native store that the host lacks, or the steering is `dns` or `both` on a host with no box DNS resolver. + tier: T0 + verify: cargo nextest run -p mfile loadout_service_left_out_where_host_cannot_carry_grant + + - WHERE two selected loadouts name one service, THE SYSTEM SHALL give one host set and one grant. + tier: T0 + verify: cargo nextest run -p mfile two_loadouts_naming_one_service_give_one_grant + +- **BOX-242** THE SYSTEM SHALL treat `uses` as a key of `network`, as BOX-048 states, and let a layer that sets `uses = []` drop the services it inherits. + tier: T0 + verify: cargo nextest run -p mfile uses_merges_as_a_whole_network_key + + +- **BOX-243** IF the merged result holds a variable name in both `[env_vars]` and `[secrets]`, or the layers ask for it as a plain value and as a sealed grant, THEN THE SYSTEM SHALL refuse the expansion with exit 3 and name both. This requirement SHALL NOT refuse a grant that a selected loadout's service derives, because BOX-241 leaves that grant out in favour of the value of a layer. + tier: T0 + verify: cargo nextest run -p mfile one_name_two_deliveries_refused_exit3 + + - IF a variable of a selected loadout has the name of a grant of a layer or of any loadout THEN THE SYSTEM SHALL refuse the expansion with exit 3 before it leaves any loadout grant out. + tier: T0 + verify: cargo nextest run -p mfile loadout_variable_named_like_grant_refused_exit3 + + - WHERE two sealed grants of one name come from the layers, THE SYSTEM SHALL keep the declared grant, leave out the derived one and say so. + tier: T0 + verify: cargo nextest run -p mfile declared_sealed_grant_beats_derived_one + +- **BOX-244** THE SYSTEM SHALL give the grant checks, the mint and the Box Spec that `min box spec` renders one expansion that includes the selected loadouts. + tier: T0 + verify: cargo nextest run -p mfile grant_checks_mint_and_render_read_one_expansion + + - **BOX-168** THE SYSTEM SHALL supply `loadout_mode = "open"` as the type default of the `session` built-in root. tier: T0 verify: cargo nextest run -p mfile builtin_roots_default_loadout_mode diff --git a/docs/specs/33-spec-client-file-writes/33-spec-client-file-writes.md b/docs/specs/33-spec-client-file-writes/33-spec-client-file-writes.md index 4d98ec6fa5..91fe012b6f 100644 --- a/docs/specs/33-spec-client-file-writes/33-spec-client-file-writes.md +++ b/docs/specs/33-spec-client-file-writes/33-spec-client-file-writes.md @@ -47,15 +47,15 @@ These stories come from the author's description of the work. They do not come f verify: cargo nextest run -p minimal unwritable_client_file_is_left_unchanged -- **CFW-003** IF `min` cannot replace a client file THEN THE SYSTEM SHALL finish the other steps of the command and exit with their status. +- **CFW-003** IF `min` cannot replace a client file THEN THE SYSTEM SHALL finish the other steps of the command and exit with their status, except for a command whose only purpose is the write, which SHALL fail. tier: T0 verify: cargo nextest run -p minimal read_only_client_file_completes_command_and_succeeds - + -- **CFW-004** IF `min` cannot replace a client file THEN THE SYSTEM SHALL print on standard error the path of the file, the reason it did not change, and the lines to add. +- **CFW-004** IF `min` cannot replace a client file THEN THE SYSTEM SHALL print on standard error the path of the file, the reason it did not change, and the lines to add or to remove. tier: T0 verify: cargo nextest run -p minimal read_only_client_file_prints_path_and_lines_on_stderr - + - **CFW-005** THE SYSTEM SHALL leave every secret value out of the lines it asks the person to add to a client file. tier: T0 @@ -67,10 +67,10 @@ These stories come from the author's description of the work. They do not come f verify: cargo nextest run -p minimal failed_client_file_write_completes_other_steps -- **CFW-007** IF a write to a client file fails on a file that `min` can replace THEN THE SYSTEM SHALL print on standard error the path of the file and the cause, with the lines to add. +- **CFW-007** IF a write to a client file fails on a file that `min` can replace THEN THE SYSTEM SHALL print on standard error the path of the file and the cause, with the lines to add or to remove. tier: T0 verify: cargo nextest run -p minimal failed_client_file_write_prints_path_cause_and_lines - + - **CFW-008** IF a write to a client file fails on a file that `min` can replace THEN THE SYSTEM SHALL exit with a non-zero status, after the attach ends when the command attaches a shell. tier: T0 @@ -108,8 +108,8 @@ These stories come from the author's description of the work. They do not come f ## Non-goals -- What a remembered approval does when `min` cannot save the policy file. The approval flow that gominimal/arch#209 proposes has no requirement yet. CFW-003 and CFW-004 cover the write failure itself. A later spec adds the approval behaviour. -- The layout of the consent table in the user policy file: [BEP-094](../24-spec-box-egress-proxy/24-spec-box-egress-proxy.md) and the open question below. +- The approval flow itself, and what a remembered approval does when `min` cannot save the policy file. [BEP-108](../24-spec-box-egress-proxy/24-spec-box-egress-proxy.md) states both. CFW-003 and CFW-004 cover the write failure. +- The layout of the consent table in the user policy file: [BEP-094](../24-spec-box-egress-proxy/24-spec-box-egress-proxy.md) and [BEP-106](../24-spec-box-egress-proxy/24-spec-box-egress-proxy.md). - Writing a project `minimal.toml` or an organization configuration. `min` never writes them: [BEP-079](../24-spec-box-egress-proxy/24-spec-box-egress-proxy.md). - The contents of the Cedar policy file are in [spec 32](../32-spec-cedar-user-policy/32-spec-cedar-user-policy.md). This spec covers only how `min` writes it. @@ -143,4 +143,4 @@ These stories come from the author's description of the work. They do not come f ## Open questions -- [NEEDS CLARIFICATION (MEDIUM): what does a remembered approval do when the user policy file refuses writes? The author ruled that the answer holds for the current run and the lines print, with no failure. The approval flow from gominimal/arch#209 must carry this as a requirement, and it has none yet.] +None. diff --git a/scripts/session-e2e.sh b/scripts/session-e2e.sh index 91a68731e1..8ba7681da5 100755 --- a/scripts/session-e2e.sh +++ b/scripts/session-e2e.sh @@ -856,6 +856,24 @@ fi # orientation banner (built-in `default` loadout). An operator's own # `default_loadouts`/`default.toml` must not leak into the canonical proof. export XDG_CONFIG_HOME="$WORK/config" + +# BEP-105: a box that holds a [secrets] credential needs an approval for its +# project, and a project file cannot supply one. The sessions below start +# headless and cannot answer the question, so this runner's own policy file +# allows every credential it holds, as a CI runner for trusted jobs does +# (arch D6, "Deciding a credential"). Every write of user_policy.toml in this +# script goes through e2e_policy, so no case drops the rule: it writes the +# policy text it is given, if any, and then the rule. +e2e_policy() { + mkdir -p "$XDG_CONFIG_HOME/minimal" + { + if [ "$#" -gt 0 ]; then + printf '%s\n' "$1" + fi + printf '[credential-rules]\naction_for_unspecified = "allow"\n' + } >"$XDG_CONFIG_HOME/minimal/user_policy.toml" +} +e2e_policy if [ -n "$E2E_VM" ]; then mkdir -p "$XDG_CONFIG_HOME/minimal" printf '[host-exposures]\ne2e = { proto = "tcp", port = %s }\n' "$E2E_HOST_EXPOSURE_PORT" \ @@ -1636,7 +1654,7 @@ fail() { # the other side. hook_allow() { mkdir -p "$XDG_CONFIG_HOME/minimal" - printf '[hooks]\nallow = ["%s"]\n' "$1" > "$XDG_CONFIG_HOME/minimal/user_policy.toml" + e2e_policy "$(printf '[hooks]\nallow = ["%s"]' "$1")" } # `mktemp -d`, then resolve it. macOS's /tmp is a symlink to /private/tmp, # and `min session start` reports the project by its RESOLVED path — @@ -7588,7 +7606,8 @@ if [ -n "$SEED_DIR" ] || [ -n "$SEEDED_MFILE" ]; then # against — not in the run's subshell, where it would reach `min` just the # same but read as an accident (SC2030). mkdir -p "$XDG_CONFIG_HOME/minimal" - printf '[vars]\nallow = ["E2E_INHERIT_MARKER"]\n' > "$XDG_CONFIG_HOME/minimal/user_policy.toml" + e2e_policy '[vars] +allow = ["E2E_INHERIT_MARKER"]' export E2E_INHERIT_MARKER=hello-from-the-host env_out="$(cd "$TASK_SEED_DIR" && mnl task run e2e-envprint 2>"$WORK/env-inherit.err")" rc=$? @@ -7618,7 +7637,7 @@ if [ -n "$SEED_DIR" ] || [ -n "$SEEDED_MFILE" ]; then # Without the allow entry the var is refused at the policy gate, and the # error carries the `[vars] allow` snippet to paste. - rm -f "$XDG_CONFIG_HOME/minimal/user_policy.toml" + e2e_policy export E2E_INHERIT_MARKER=hello-from-the-host (cd "$TASK_SEED_DIR" && mnl task run e2e-envprint >/dev/null 2>"$WORK/env-ungranted.err") rc=$? @@ -8444,7 +8463,7 @@ exit' TERM=vt220 python3 "$ROOT/scripts/e2e-attach-pty.py" - \ # execution: it must refuse, and the error must carry a snippet the user # can act on. Asserting the snippet's CONTENT is what catches a regression # to an unmatchable project path. - rm -f "$XDG_CONFIG_HOME/minimal/user_policy.toml" + e2e_policy if (cd "$HOOK_SEED_DIR" && mnl session start --detach --no-input >/dev/null 2>"$WORK/hooks-gate.err"); then echo "::error::activation with un-allow-listed project hooks should have refused" fail @@ -8498,7 +8517,7 @@ exit' TERM=vt220 python3 "$ROOT/scripts/e2e-attach-pty.py" - \ mnl box rm --force "$nohooks_sid" >/dev/null 2>&1 || true echo "--no-hooks suppresses execution and composition OK" rm -rf "$HOOK_SEED_DIR"; HOOK_SEED_DIR="" - rm -f "$XDG_CONFIG_HOME/minimal/user_policy.toml" + e2e_policy echo "::endgroup::" # -- Loadout-declared hooks ------------------------------------------------ @@ -9098,7 +9117,7 @@ if [ -n "$SEED_DIR" ] || [ -n "$SEEDED_MFILE" ]; then echo "--- stderr ---"; cat "$WORK/hooks-restart.err" 2>/dev/null || true fail } - rm -f "$XDG_CONFIG_HOME/minimal/user_policy.toml" + e2e_policy fi # Shut the daemon down; it must not survive. @@ -20342,7 +20361,8 @@ GOA_TCP_PROBE_EOF # mirroring the task proof's [vars] allow idiom, and remove the entry # once the box is up so nothing later reads it as standing policy. mkdir -p "$XDG_CONFIG_HOME/minimal" - printf '[vars]\nallow = ["NPM_CONFIG_CACHE"]\n' > "$XDG_CONFIG_HOME/minimal/user_policy.toml" + e2e_policy '[vars] +allow = ["NPM_CONFIG_CACHE"]' # ---- the hostname-only box ---------------------------------------------- goa_t_args="" @@ -20359,7 +20379,7 @@ GOA_TCP_PROBE_EOF fail } goa_t_sid="$(printf '%s\n' "$goa_t_sid" | tail -n1 | tr -d '\r')" - rm -f "$XDG_CONFIG_HOME/minimal/user_policy.toml" + e2e_policy echo "hostname-only box: $goa_t_sid ($GOA_T_NAME)" # The box must be able to run a probe at all — a host that is itself a @@ -20550,18 +20570,19 @@ $(cat "$WORK/goa-$label-1.err" "$WORK/goa-$label-2.err" 2>/dev/null || true)" # it needs the public internet. The rule is minvmd's, so a target without # a VM has nothing to prove here. if [ -n "$E2E_VM" ]; then - printf '[vars]\nallow = ["NPM_CONFIG_CACHE"]\n' > "$XDG_CONFIG_HOME/minimal/user_policy.toml" + e2e_policy '[vars] +allow = ["NPM_CONFIG_CACHE"]' goa_r_sid="$(cd "$GOA_T_SEED_DIR" && mnl session start --detach --no-input \ --name "$GOA_R_NAME" --network own_ip \ --allow-subnets 0.0.0.0/0 --allow-dns-hosts github.com \ 2>"$WORK/goa-activate-r.err")" || { - rm -f "$XDG_CONFIG_HOME/minimal/user_policy.toml" + e2e_policy echo "::error::'min session start' for the resolver-reach box failed" echo "--- stderr ---"; cat "$WORK/goa-activate-r.err" 2>/dev/null || true fail } goa_r_sid="$(printf '%s\n' "$goa_r_sid" | tail -n1 | tr -d '\r')" - rm -f "$XDG_CONFIG_HOME/minimal/user_policy.toml" + e2e_policy echo "resolver-reach box: $goa_r_sid ($GOA_R_NAME)" goa_tcp_out="$(mnl box exec "$goa_r_sid" -- \ bash -c "/usr/bin/timeout 30 python3 /workbench/e2e-dns-tcp-probe.py github.com" \