| 1 | //! Portable config bundles: `codewhale config import` / `config export --portable`. |
| 2 | //! |
| 3 | //! A bundle is a TOML or JSON document carrying a portable subset of a |
| 4 | //! CodeWhale configuration (preferences, harness profiles, provider |
| 5 | //! non-secret settings, project/global sections) between machines. The |
| 6 | //! envelope is versioned and strict (`deny_unknown_fields`), secrets are |
| 7 | //! rejected by key name and value shape (never echoed), parsing is bounded, |
| 8 | //! and application is transactional with a timestamped backup and rollback. |
| 9 | //! |
| 10 | //! Security contract: |
| 11 | //! - No secret ever round-trips: fields whose key matches |
| 12 | //! [`codewhale_config::is_sensitive_config_key`] are rejected on import and |
| 13 | //! dropped on export, and bare credential-shaped values are rejected by |
| 14 | //! value shape. Rejection messages name the field, never the value. |
| 15 | //! - Input size is capped (5 MiB, matching the skill installer's cap). |
| 16 | //! - HTTPS only for remote fetch, except plain `http` on loopback; redirects |
| 17 | //! are followed at most a bounded number of times within the same scheme. |
| 18 | //! The first request and every redirect honor the `[network]` policy and |
| 19 | //! refuse loopback, private, link-local and cloud-metadata destinations, |
| 20 | //! except a visibly local host the person listed or typed as the URL. |
| 21 | //! - Bundle-declared file paths must resolve inside the target config |
| 22 | //! directory; traversal and symlink escapes are refused. |
| 23 | //! - Project scope never mutates the user-global document and vice versa. |
| 24 | |
| 25 | use std::io::{IsTerminal, Read}; |
| 26 | use std::path::{Path, PathBuf}; |
| 27 | |
| 28 | use anyhow::{Context, Result, anyhow, bail}; |
| 29 | use serde::{Deserialize, Serialize}; |
| 30 | |
| 31 | use codewhale_config::{ConfigToml, is_sensitive_config_key}; |
| 32 | |
| 33 | /// Maximum accepted bundle size, both for reads and remote fetches. |
| 34 | /// Matches the skill installer's 5 MiB cap. |
| 35 | pub const MAX_BUNDLE_BYTES: u64 = 5 * 1024 * 1024; |
| 36 | |
| 37 | /// Envelope `kind` value required by every bundle. |
| 38 | pub const BUNDLE_KIND: &str = "codewhale.portable-config"; |
| 39 | |
| 40 | /// Envelope `schema_version` accepted by this build. |
| 41 | pub const BUNDLE_SCHEMA_VERSION: u64 = 1; |
| 42 | |
| 43 | /// Maximum number of HTTP redirects followed during a remote fetch. |
| 44 | const MAX_REDIRECTS: usize = 5; |
| 45 | |
| 46 | /// Timeout for the remote fetch, in seconds. |
| 47 | const FETCH_TIMEOUT_SECS: u64 = 30; |
| 48 | |
| 49 | /// Credential-shaped value prefixes rejected even under a benign key name. |
| 50 | /// Conservative on purpose: only well-known provider token shapes. |
| 51 | const SECRET_VALUE_PREFIXES: [&str; 6] = ["sk-", "Bearer ", "ghp_", "xoxb-", "AKIA", "eyJ"]; |
| 52 | |
| 53 | // --------------------------------------------------------------------------- |
| 54 | // Envelope |
| 55 | // --------------------------------------------------------------------------- |
| 56 | |
| 57 | /// Strict portable-bundle envelope. Unknown fields fail the parse: a bundle |
| 58 | /// written by a newer schema must not be silently half-applied. |
| 59 | #[derive(Debug, Clone, Deserialize, Serialize)] |
| 60 | #[serde(deny_unknown_fields)] |
| 61 | pub struct PortableBundle { |
| 62 | pub schema_version: u64, |
| 63 | pub kind: String, |
| 64 | #[serde(default)] |
| 65 | pub metadata: BundleMetadata, |
| 66 | #[serde(default)] |
| 67 | pub preferences: BundleTable, |
| 68 | #[serde(default)] |
| 69 | pub profiles: BundleTable, |
| 70 | #[serde(default)] |
| 71 | pub plugins: BundleTable, |
| 72 | #[serde(default)] |
| 73 | pub project: BundleTable, |
| 74 | #[serde(default)] |
| 75 | pub global: BundleTable, |
| 76 | } |
| 77 | |
| 78 | #[derive(Debug, Clone, Default, Deserialize, Serialize)] |
| 79 | #[serde(deny_unknown_fields)] |
| 80 | pub struct BundleMetadata { |
| 81 | #[serde(default)] |
| 82 | pub name: Option<String>, |
| 83 | #[serde(default)] |
| 84 | pub created_at: Option<String>, |
| 85 | #[serde(default)] |
| 86 | pub generator: Option<String>, |
| 87 | } |
| 88 | |
| 89 | /// One bundle section: a flat table of config keys to values. Keys inside a |
| 90 | /// section are data, not schema, so unknown keys parse here — credential |
| 91 | /// rejection happens at plan time by name and value shape. |
| 92 | #[derive(Debug, Clone, Default, Deserialize, Serialize)] |
| 93 | pub struct BundleTable { |
| 94 | #[serde(flatten)] |
| 95 | pub entries: std::collections::BTreeMap<String, toml::Value>, |
| 96 | } |
| 97 | |
| 98 | // --------------------------------------------------------------------------- |
| 99 | // Parsing (bounded) |
| 100 | // --------------------------------------------------------------------------- |
| 101 | |
| 102 | /// Parse a bundle from raw bytes, rejecting oversize input before parse. |
| 103 | pub fn parse_bundle_bytes(raw: &[u8], source: &str) -> Result<PortableBundle> { |
| 104 | if raw.len() as u64 > MAX_BUNDLE_BYTES { |
| 105 | bail!( |
| 106 | "bundle at {source} is {} bytes; the limit is {MAX_BUNDLE_BYTES} bytes", |
| 107 | raw.len() |
| 108 | ); |
| 109 | } |
| 110 | let text = std::str::from_utf8(raw) |
| 111 | .with_context(|| format!("bundle at {source} is not valid UTF-8"))?; |
| 112 | parse_bundle_str(text, source) |
| 113 | } |
| 114 | |
| 115 | /// Parse a bundle document: TOML by default, JSON when the source ends in |
| 116 | /// `.json` or the document starts with `{`. |
| 117 | pub fn parse_bundle_str(text: &str, source: &str) -> Result<PortableBundle> { |
| 118 | let trimmed = text.trim_start(); |
| 119 | let bundle = if trimmed.starts_with('{') || source.ends_with(".json") { |
| 120 | // serde_json keeps the last of two identical object keys. A bundle is |
| 121 | // a reviewed plan, so a repeated key must fail before anything is |
| 122 | // planned or written, exactly as TOML already refuses duplicates. |
| 123 | reject_duplicate_json_keys(text) |
| 124 | .with_context(|| format!("bundle at {source} is not valid JSON"))?; |
| 125 | serde_json::from_str::<PortableBundle>(text) |
| 126 | .with_context(|| format!("bundle at {source} is not valid JSON"))? |
| 127 | } else { |
| 128 | toml::from_str::<PortableBundle>(text) |
| 129 | .with_context(|| format!("bundle at {source} is not valid TOML"))? |
| 130 | }; |
| 131 | validate_bundle(&bundle, source)?; |
| 132 | Ok(bundle) |
| 133 | } |
| 134 | |
| 135 | /// Fail closed on a JSON document that repeats an object key at any depth. |
| 136 | /// |
| 137 | /// The document is walked with a deserializer seed that never materializes |
| 138 | /// values, so the check costs one pass and reports the first offending key |
| 139 | /// path without echoing any value. |
| 140 | fn reject_duplicate_json_keys(text: &str) -> Result<()> { |
| 141 | use serde::de::{DeserializeSeed, Error as _, MapAccess, SeqAccess, Visitor}; |
| 142 | use std::fmt; |
| 143 | |
| 144 | struct NoDuplicates<'a> { |
| 145 | path: &'a mut Vec<String>, |
| 146 | } |
| 147 | |
| 148 | impl<'de> DeserializeSeed<'de> for NoDuplicates<'_> { |
| 149 | type Value = (); |
| 150 | |
| 151 | fn deserialize<D>(self, deserializer: D) -> Result<(), D::Error> |
| 152 | where |
| 153 | D: serde::Deserializer<'de>, |
| 154 | { |
| 155 | deserializer.deserialize_any(self) |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | impl<'de> Visitor<'de> for NoDuplicates<'_> { |
| 160 | type Value = (); |
| 161 | |
| 162 | fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 163 | f.write_str("a JSON value without duplicate object keys") |
| 164 | } |
| 165 | |
| 166 | fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<(), E> { |
| 167 | Ok(()) |
| 168 | } |
| 169 | fn visit_i64<E: serde::de::Error>(self, _: i64) -> Result<(), E> { |
| 170 | Ok(()) |
| 171 | } |
| 172 | fn visit_u64<E: serde::de::Error>(self, _: u64) -> Result<(), E> { |
| 173 | Ok(()) |
| 174 | } |
| 175 | fn visit_f64<E: serde::de::Error>(self, _: f64) -> Result<(), E> { |
| 176 | Ok(()) |
| 177 | } |
| 178 | fn visit_str<E: serde::de::Error>(self, _: &str) -> Result<(), E> { |
| 179 | Ok(()) |
| 180 | } |
| 181 | fn visit_unit<E: serde::de::Error>(self) -> Result<(), E> { |
| 182 | Ok(()) |
| 183 | } |
| 184 | fn visit_none<E: serde::de::Error>(self) -> Result<(), E> { |
| 185 | Ok(()) |
| 186 | } |
| 187 | |
| 188 | fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<(), A::Error> { |
| 189 | let mut index = 0usize; |
| 190 | loop { |
| 191 | self.path.push(format!("[{index}]")); |
| 192 | let next = seq.next_element_seed(NoDuplicates { path: self.path }); |
| 193 | self.path.pop(); |
| 194 | if next?.is_none() { |
| 195 | return Ok(()); |
| 196 | } |
| 197 | index += 1; |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> { |
| 202 | let mut seen = std::collections::BTreeSet::new(); |
| 203 | while let Some(key) = map.next_key::<String>()? { |
| 204 | if !seen.insert(key.clone()) { |
| 205 | let mut path = self.path.clone(); |
| 206 | path.push(key); |
| 207 | return Err(A::Error::custom(format!( |
| 208 | "duplicate key {:?}", |
| 209 | path.join(".") |
| 210 | ))); |
| 211 | } |
| 212 | self.path.push(key); |
| 213 | let nested = map.next_value_seed(NoDuplicates { path: self.path }); |
| 214 | self.path.pop(); |
| 215 | nested?; |
| 216 | } |
| 217 | Ok(()) |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | let mut deserializer = serde_json::Deserializer::from_str(text); |
| 222 | let mut path = Vec::new(); |
| 223 | NoDuplicates { path: &mut path } |
| 224 | .deserialize(&mut deserializer) |
| 225 | .map_err(|error| anyhow::anyhow!("{error}"))?; |
| 226 | deserializer |
| 227 | .end() |
| 228 | .map_err(|error| anyhow::anyhow!("{error}"))?; |
| 229 | Ok(()) |
| 230 | } |
| 231 | |
| 232 | fn validate_bundle(bundle: &PortableBundle, source: &str) -> Result<()> { |
| 233 | if bundle.kind != BUNDLE_KIND { |
| 234 | bail!( |
| 235 | "bundle at {source} has kind {:?}; expected {BUNDLE_KIND:?}", |
| 236 | bundle.kind |
| 237 | ); |
| 238 | } |
| 239 | if bundle.schema_version != BUNDLE_SCHEMA_VERSION { |
| 240 | bail!( |
| 241 | "bundle at {source} has schema_version {}; this build understands {BUNDLE_SCHEMA_VERSION}", |
| 242 | bundle.schema_version |
| 243 | ); |
| 244 | } |
| 245 | Ok(()) |
| 246 | } |
| 247 | |
| 248 | // --------------------------------------------------------------------------- |
| 249 | // Secret rejection |
| 250 | // --------------------------------------------------------------------------- |
| 251 | |
| 252 | /// One rejected entry: the dotted key path and the reason. Values are never |
| 253 | /// included — the reason and path are all a reviewer needs. |
| 254 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 255 | pub struct RejectedEntry { |
| 256 | pub key: String, |
| 257 | pub reason: String, |
| 258 | } |
| 259 | |
| 260 | /// Scan every section of the bundle for non-portable entries. Import and |
| 261 | /// export use the same path predicate, so machine-local route/execution/trust |
| 262 | /// authority cannot be stripped in one direction but accepted in the other. |
| 263 | /// String leaves are additionally rejected by credential shape. |
| 264 | pub fn find_rejected_entries(bundle: &PortableBundle) -> Vec<RejectedEntry> { |
| 265 | let mut rejected = Vec::new(); |
| 266 | for (section, table) in [ |
| 267 | ("preferences", &bundle.preferences), |
| 268 | ("profiles", &bundle.profiles), |
| 269 | ("plugins", &bundle.plugins), |
| 270 | ("project", &bundle.project), |
| 271 | ("global", &bundle.global), |
| 272 | ] { |
| 273 | for (key, value) in &table.entries { |
| 274 | let dotted = format!("{section}.{key}"); |
| 275 | if let Some(reason) = nonportable_path_reason(key) { |
| 276 | rejected.push(RejectedEntry { |
| 277 | key: dotted, |
| 278 | reason: reason.to_string(), |
| 279 | }); |
| 280 | continue; |
| 281 | } |
| 282 | if let Some(reason) = value_rejection_reason(key, value) { |
| 283 | rejected.push(RejectedEntry { |
| 284 | key: dotted, |
| 285 | reason, |
| 286 | }); |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | rejected |
| 291 | } |
| 292 | |
| 293 | /// Maximum nesting depth the export walkers descend. Config files are |
| 294 | /// shallow; anything deeper is pathological and fails closed. |
| 295 | const MAX_EXPORT_WALK_DEPTH: usize = 64; |
| 296 | |
| 297 | /// Why a value carries nested non-portable authority or looks like a bare |
| 298 | /// credential, or `None` when it is safe to move between machines. |
| 299 | fn value_rejection_reason(path: &str, value: &toml::Value) -> Option<String> { |
| 300 | value_rejection_reason_at(path, value, 0) |
| 301 | } |
| 302 | |
| 303 | fn value_rejection_reason_at(path: &str, value: &toml::Value, depth: usize) -> Option<String> { |
| 304 | if depth > MAX_EXPORT_WALK_DEPTH { |
| 305 | return Some(format!( |
| 306 | "nested more than {MAX_EXPORT_WALK_DEPTH} levels deep" |
| 307 | )); |
| 308 | } |
| 309 | if let Some(reason) = nonportable_value_reason(path, value) { |
| 310 | return Some(reason.to_string()); |
| 311 | } |
| 312 | match value { |
| 313 | toml::Value::String(text) => string_secret_reason(text), |
| 314 | toml::Value::Array(items) => items |
| 315 | .iter() |
| 316 | .find_map(|value| value_rejection_reason_at(path, value, depth + 1)) |
| 317 | .map(|reason| format!("array contains an entry where {reason}")), |
| 318 | toml::Value::Table(map) => { |
| 319 | for (key, nested_value) in map { |
| 320 | let child_path = if path.is_empty() { |
| 321 | key.clone() |
| 322 | } else { |
| 323 | format!("{path}.{key}") |
| 324 | }; |
| 325 | if let Some(reason) = nonportable_path_reason(&child_path) { |
| 326 | return Some(format!("nested key {key:?} {reason}")); |
| 327 | } |
| 328 | if let Some(reason) = |
| 329 | value_rejection_reason_at(&child_path, nested_value, depth + 1) |
| 330 | { |
| 331 | return Some(format!("nested under {key:?}, {reason}")); |
| 332 | } |
| 333 | } |
| 334 | None |
| 335 | } |
| 336 | _ => None, |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | fn string_secret_reason(text: &str) -> Option<String> { |
| 341 | if let Some(prefix) = SECRET_VALUE_PREFIXES |
| 342 | .iter() |
| 343 | .find(|prefix| text.trim().starts_with(*prefix)) |
| 344 | { |
| 345 | return Some(format!( |
| 346 | "value has the shape of a credential (prefix {prefix:?} redacted)" |
| 347 | )); |
| 348 | } |
| 349 | if text.contains(codewhale_config::persistence::REDACTED) { |
| 350 | // A placeholder is the residue of redaction, never a real setting; |
| 351 | // exporting it would carry nothing and importing it would write the |
| 352 | // placeholder into the live document. |
| 353 | return Some("value contains a redaction placeholder".to_string()); |
| 354 | } |
| 355 | if codewhale_config::persistence::redact_secrets(text) != text { |
| 356 | return Some("value contains credential-shaped text".to_string()); |
| 357 | } |
| 358 | if url_carries_credential(text.trim()) { |
| 359 | return Some("value is a URL that carries a credential".to_string()); |
| 360 | } |
| 361 | None |
| 362 | } |
| 363 | |
| 364 | /// Webhook endpoints whose path is itself the bearer credential. |
| 365 | const CREDENTIAL_PATH_WEBHOOKS: [(&str, &str); 4] = [ |
| 366 | ("hooks.slack.com", "/services/"), |
| 367 | ("discord.com", "/api/webhooks/"), |
| 368 | ("discordapp.com", "/api/webhooks/"), |
| 369 | ("webhook.office.com", "/webhookb2/"), |
| 370 | ]; |
| 371 | |
| 372 | /// True for a URL with userinfo, a credential-named query parameter, or a |
| 373 | /// known webhook host whose path is the secret. |
| 374 | fn url_carries_credential(text: &str) -> bool { |
| 375 | let Ok(url) = reqwest::Url::parse(text) else { |
| 376 | return false; |
| 377 | }; |
| 378 | if !url.username().is_empty() || url.password().is_some() { |
| 379 | return true; |
| 380 | } |
| 381 | // The shared display redactor masks credential-named query values with |
| 382 | // `***`; count masks rather than compare bytes, because it re-encodes the |
| 383 | // query and would otherwise flag benign URLs. |
| 384 | let masks = |value: &str| value.matches("***").count(); |
| 385 | if masks(&codewhale_sanitize::sanitize::redact_url_for_display(text)) > masks(text) { |
| 386 | return true; |
| 387 | } |
| 388 | let host = url.host_str().unwrap_or_default().to_ascii_lowercase(); |
| 389 | CREDENTIAL_PATH_WEBHOOKS.iter().any(|(webhook_host, path)| { |
| 390 | (host == *webhook_host || host.ends_with(&format!(".{webhook_host}"))) |
| 391 | && url.path().starts_with(path) |
| 392 | }) |
| 393 | } |
| 394 | |
| 395 | fn is_sensitive_bundle_key(key: &str) -> bool { |
| 396 | if is_sensitive_config_key(key) || is_credential_authority_key(key) { |
| 397 | return true; |
| 398 | } |
| 399 | // Normalize the complete dotted path, not only its final component. A |
| 400 | // quoted TOML key such as `"api.key"` reaches us without its quotes and |
| 401 | // is otherwise indistinguishable from two structural components. Either |
| 402 | // representation names credential material and must fail closed. |
| 403 | let normalized = normalize_bundle_key(key); |
| 404 | |
| 405 | matches!( |
| 406 | normalized.as_str(), |
| 407 | "access_key" |
| 408 | | "access_token" |
| 409 | | "api_key" |
| 410 | | "api_keys" |
| 411 | | "apikey" |
| 412 | | "authorization" |
| 413 | | "bearer" |
| 414 | | "client_secret" |
| 415 | | "cookie" |
| 416 | | "credential" |
| 417 | | "credentials" |
| 418 | | "id_token" |
| 419 | | "password" |
| 420 | | "passwords" |
| 421 | | "passwd" |
| 422 | | "private_key" |
| 423 | | "proxy_authorization" |
| 424 | | "refresh_token" |
| 425 | | "secret" |
| 426 | | "secrets" |
| 427 | | "set_cookie" |
| 428 | | "token" |
| 429 | | "tokens" |
| 430 | ) || normalized.ends_with("_access_key") |
| 431 | || normalized.ends_with("_api_key") |
| 432 | || normalized.ends_with("_authorization") |
| 433 | || normalized.ends_with("_cookie") |
| 434 | || normalized.ends_with("_password") |
| 435 | || normalized.ends_with("_private_key") |
| 436 | || normalized.ends_with("_secret") |
| 437 | || normalized.ends_with("_token") |
| 438 | } |
| 439 | |
| 440 | fn normalize_bundle_key(key: &str) -> String { |
| 441 | let segment = key.trim().trim_matches('"'); |
| 442 | let chars: Vec<char> = segment.chars().collect(); |
| 443 | let mut normalized = String::with_capacity(segment.len()); |
| 444 | for (index, character) in chars.iter().copied().enumerate() { |
| 445 | if !character.is_ascii_alphanumeric() { |
| 446 | if !normalized.ends_with('_') { |
| 447 | normalized.push('_'); |
| 448 | } |
| 449 | continue; |
| 450 | } |
| 451 | if character.is_ascii_uppercase() { |
| 452 | let previous = index.checked_sub(1).and_then(|index| chars.get(index)); |
| 453 | let next = chars.get(index + 1); |
| 454 | let starts_word = previous.is_some_and(|character| { |
| 455 | character.is_ascii_lowercase() || character.is_ascii_digit() |
| 456 | }) || (previous |
| 457 | .is_some_and(|character| character.is_ascii_uppercase()) |
| 458 | && next.is_some_and(|character| character.is_ascii_lowercase())); |
| 459 | if starts_word && !normalized.ends_with('_') { |
| 460 | normalized.push('_'); |
| 461 | } |
| 462 | normalized.push(character.to_ascii_lowercase()); |
| 463 | } else { |
| 464 | normalized.push(character.to_ascii_lowercase()); |
| 465 | } |
| 466 | } |
| 467 | normalized.trim_matches('_').to_string() |
| 468 | } |
| 469 | |
| 470 | fn is_credential_authority_key(key: &str) -> bool { |
| 471 | let normalized = normalize_bundle_key(key); |
| 472 | if normalized == "external_credentials" |
| 473 | || normalized.ends_with("_external_credentials") |
| 474 | || normalized == "oauth_credential_generation" |
| 475 | || normalized.ends_with("_oauth_credential_generation") |
| 476 | { |
| 477 | return true; |
| 478 | } |
| 479 | // `auth_mode` is a declarative protocol selection; an `auth` table is |
| 480 | // executable or secret-store authority and is intentionally non-portable. |
| 481 | key.split('.') |
| 482 | .map(normalize_bundle_key) |
| 483 | .any(|segment| segment == "auth") |
| 484 | } |
| 485 | |
| 486 | fn is_machine_bound_top_level_key(key: &str) -> bool { |
| 487 | key.split('.') |
| 488 | .next() |
| 489 | .map(normalize_bundle_key) |
| 490 | .is_some_and(|root| { |
| 491 | matches!( |
| 492 | root.as_str(), |
| 493 | // Trust posture: a bundle must not widen what the agent may |
| 494 | // run or approve on the receiving machine. |
| 495 | "allow_shell" |
| 496 | | "approval_policy" |
| 497 | | "sandbox_mode" |
| 498 | | "sandbox_network_access" |
| 499 | | "yolo" |
| 500 | // Machine-local read-denylist paths. |
| 501 | | "sandbox_denied_read_paths" |
| 502 | | "sandbox_read_denylist_defaults" |
| 503 | | "sandbox_read_denylist_exempt" |
| 504 | // Local executables, outbound event sinks, and control |
| 505 | // endpoints. |
| 506 | | "control_socket" |
| 507 | | "extension_host" |
| 508 | | "lifecycle_outbox" |
| 509 | | "auto_review" |
| 510 | | "hooks" |
| 511 | | "instructions" |
| 512 | | "managed_config_path" |
| 513 | | "project_instruction_imports" |
| 514 | | "projects" |
| 515 | | "requirements_path" |
| 516 | | "route_preferences_version" |
| 517 | | "route_preferences_migration" |
| 518 | | "runtime_api" |
| 519 | | "workspace" |
| 520 | ) |
| 521 | }) |
| 522 | } |
| 523 | |
| 524 | fn is_nonportable_lsp_authority_key(key: &str) -> bool { |
| 525 | let mut segments = key.split('.').map(normalize_bundle_key); |
| 526 | matches!(segments.next().as_deref(), Some("lsp")) |
| 527 | && matches!(segments.next().as_deref(), Some("custom" | "servers")) |
| 528 | } |
| 529 | |
| 530 | fn is_nonportable_nested_authority_key(key: &str) -> bool { |
| 531 | let segments = key.split('.').map(normalize_bundle_key).collect::<Vec<_>>(); |
| 532 | match segments.as_slice() { |
| 533 | [root, field, ..] |
| 534 | if root == "tools" && matches!(field.as_str(), "overrides" | "plugin_dir") => |
| 535 | { |
| 536 | true |
| 537 | } |
| 538 | [root, field, ..] if root == "update" && field == "update_uri" => true, |
| 539 | [root, field, ..] if root == "notifications" && field == "sound_file" => true, |
| 540 | [root, field, ..] if root == "speech" && field == "output_dir" => true, |
| 541 | [root, .., field] if root == "providers" && field == "api_key_env" => true, |
| 542 | _ => false, |
| 543 | } |
| 544 | } |
| 545 | |
| 546 | fn is_machine_specific_config_path(path: &str) -> bool { |
| 547 | let path = normalize_bundle_key(path); |
| 548 | MACHINE_SPECIFIC_KEYS.iter().any(|key| { |
| 549 | let key = normalize_bundle_key(key); |
| 550 | path == key |
| 551 | || path |
| 552 | .strip_suffix(&key) |
| 553 | .is_some_and(|prefix| prefix.ends_with('_')) |
| 554 | }) |
| 555 | } |
| 556 | |
| 557 | fn nonportable_path_reason(path: &str) -> Option<&'static str> { |
| 558 | if is_machine_bound_top_level_key(path) { |
| 559 | return Some("carries machine-bound execution or trust authority"); |
| 560 | } |
| 561 | if is_nonportable_lsp_authority_key(path) { |
| 562 | return Some("carries executable LSP authority"); |
| 563 | } |
| 564 | if is_nonportable_nested_authority_key(path) { |
| 565 | return Some("carries machine-local route or execution authority"); |
| 566 | } |
| 567 | if is_machine_specific_config_path(path) { |
| 568 | return Some("carries machine-local route or filesystem authority"); |
| 569 | } |
| 570 | if is_credential_authority_key(path) { |
| 571 | return Some("carries machine-local credential authority"); |
| 572 | } |
| 573 | if is_sensitive_bundle_key(path) { |
| 574 | return Some("names credential material"); |
| 575 | } |
| 576 | None |
| 577 | } |
| 578 | |
| 579 | fn is_network_allow_path(path: &str) -> bool { |
| 580 | let mut segments = path.split('.').map(normalize_bundle_key).rev(); |
| 581 | matches!( |
| 582 | (segments.next().as_deref(), segments.next().as_deref()), |
| 583 | (Some("allow"), Some("network")) |
| 584 | ) |
| 585 | } |
| 586 | |
| 587 | /// Telemetry opt-out is safe to move between machines, but opt-in is durable |
| 588 | /// user consent coupled to SetupState. A portable bundle may tighten that |
| 589 | /// consent (`false`); it must never manufacture or transfer `true`. |
| 590 | fn nonportable_value_reason(path: &str, value: &toml::Value) -> Option<&'static str> { |
| 591 | let top_level_telemetry = !path.contains('.') && normalize_bundle_key(path) == "telemetry"; |
| 592 | if top_level_telemetry && matches!(value, toml::Value::Boolean(true)) { |
| 593 | return Some("would port telemetry opt-in consent between machines"); |
| 594 | } |
| 595 | if is_network_allow_path(path) |
| 596 | && let toml::Value::String(host) = value |
| 597 | && codewhale_net::guard::is_visibly_local_host(host) |
| 598 | { |
| 599 | return Some("network.allow entry would grant local-network authority"); |
| 600 | } |
| 601 | None |
| 602 | } |
| 603 | |
| 604 | // --------------------------------------------------------------------------- |
| 605 | // Import plan |
| 606 | // --------------------------------------------------------------------------- |
| 607 | |
| 608 | /// What applying the bundle would do, computed before anything is written. |
| 609 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 610 | pub struct ImportPlan { |
| 611 | pub added: Vec<String>, |
| 612 | pub changed: Vec<String>, |
| 613 | pub skipped: Vec<String>, |
| 614 | pub conflicting: Vec<String>, |
| 615 | pub rejected: Vec<RejectedEntry>, |
| 616 | } |
| 617 | |
| 618 | impl ImportPlan { |
| 619 | #[must_use] |
| 620 | pub fn is_no_op(&self) -> bool { |
| 621 | self.added.is_empty() && self.changed.is_empty() |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | /// Compute the deterministic import plan for `bundle` against `config`. |
| 626 | /// |
| 627 | /// `section` selects the target document mapping: bundle `project` entries |
| 628 | /// apply only to a project-scope document, `global` entries only to a |
| 629 | /// user-global one; `preferences`, `profiles`, and `plugins` apply to both. |
| 630 | /// Entries that would not touch the target document are `skipped`, so the |
| 631 | /// same bundle imports cleanly at either scope. |
| 632 | pub fn plan_import(bundle: &PortableBundle, config: &ConfigToml, scope: BundleScope) -> ImportPlan { |
| 633 | let mut plan = ImportPlan { |
| 634 | rejected: find_rejected_entries(bundle), |
| 635 | ..ImportPlan::default() |
| 636 | }; |
| 637 | let rejected_keys: std::collections::BTreeSet<&str> = plan |
| 638 | .rejected |
| 639 | .iter() |
| 640 | .map(|entry| entry.key.as_str()) |
| 641 | .collect(); |
| 642 | // Sections are presentation and scope labels over one flat ConfigToml |
| 643 | // keyspace. Two applicable sections naming the same key would otherwise |
| 644 | // make apply order decide which value wins. Detect that ambiguity before |
| 645 | // classifying or writing any entry. |
| 646 | let mut applicable_key_counts = std::collections::BTreeMap::<&str, usize>::new(); |
| 647 | for (section, table) in [ |
| 648 | ("preferences", &bundle.preferences), |
| 649 | ("profiles", &bundle.profiles), |
| 650 | ("plugins", &bundle.plugins), |
| 651 | ("project", &bundle.project), |
| 652 | ("global", &bundle.global), |
| 653 | ] { |
| 654 | if section_applies(section, scope) { |
| 655 | for key in table.entries.keys() { |
| 656 | *applicable_key_counts.entry(key.as_str()).or_default() += 1; |
| 657 | } |
| 658 | } |
| 659 | } |
| 660 | let colliding_keys: std::collections::BTreeSet<&str> = applicable_key_counts |
| 661 | .into_iter() |
| 662 | .filter_map(|(key, count)| (count > 1).then_some(key)) |
| 663 | .collect(); |
| 664 | |
| 665 | for (section, table) in [ |
| 666 | ("preferences", &bundle.preferences), |
| 667 | ("profiles", &bundle.profiles), |
| 668 | ("plugins", &bundle.plugins), |
| 669 | ("project", &bundle.project), |
| 670 | ("global", &bundle.global), |
| 671 | ] { |
| 672 | let dotted = |key: &str| format!("{section}.{key}"); |
| 673 | let applies = section_applies(section, scope); |
| 674 | for (key, value) in &table.entries { |
| 675 | let dotted = dotted(key); |
| 676 | if rejected_keys.contains(dotted.as_str()) |
| 677 | || (applies && colliding_keys.contains(key.as_str())) |
| 678 | { |
| 679 | plan.conflicting.push(dotted); |
| 680 | continue; |
| 681 | } |
| 682 | if !applies { |
| 683 | plan.skipped.push(dotted); |
| 684 | continue; |
| 685 | } |
| 686 | if config_value_matches(config, key, value) { |
| 687 | plan.skipped.push(dotted); |
| 688 | } else if config_has_value(config, key) { |
| 689 | plan.changed.push(dotted); |
| 690 | } else { |
| 691 | plan.added.push(dotted); |
| 692 | } |
| 693 | } |
| 694 | } |
| 695 | plan |
| 696 | } |
| 697 | |
| 698 | fn config_value_matches(config: &ConfigToml, key: &str, value: &toml::Value) -> bool { |
| 699 | let semantically_equal = (|| { |
| 700 | let current = config_document(config).ok()?; |
| 701 | let mut candidate = config.clone(); |
| 702 | apply_config_value(&mut candidate, key, value).ok()?; |
| 703 | Some(config_document(&candidate).ok()? == current) |
| 704 | })() |
| 705 | .unwrap_or(false); |
| 706 | semantically_equal |
| 707 | || config.get_value(key).is_some_and(|current| { |
| 708 | render_toml_value(value).ok().as_deref() == Some(current.as_str()) |
| 709 | }) |
| 710 | } |
| 711 | |
| 712 | fn config_has_value(config: &ConfigToml, key: &str) -> bool { |
| 713 | config_document(config) |
| 714 | .ok() |
| 715 | .is_some_and(|table| table.contains_key(key)) |
| 716 | || config.get_value(key).is_some() |
| 717 | } |
| 718 | |
| 719 | fn section_applies(section: &str, scope: BundleScope) -> bool { |
| 720 | match section { |
| 721 | "project" => scope == BundleScope::Project, |
| 722 | "global" => scope == BundleScope::Global, |
| 723 | _ => true, |
| 724 | } |
| 725 | } |
| 726 | |
| 727 | // --------------------------------------------------------------------------- |
| 728 | // Scope |
| 729 | // --------------------------------------------------------------------------- |
| 730 | |
| 731 | /// Which document an import/export targets. |
| 732 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 733 | pub enum BundleScope { |
| 734 | /// The user-global config (`~/.codewhale/config.toml` by default). |
| 735 | Global, |
| 736 | /// The workspace-scoped config (`<repo>/.codewhale/config.toml`). |
| 737 | Project, |
| 738 | } |
| 739 | |
| 740 | impl BundleScope { |
| 741 | #[must_use] |
| 742 | pub fn label(self) -> &'static str { |
| 743 | match self { |
| 744 | Self::Global => "global", |
| 745 | Self::Project => "project", |
| 746 | } |
| 747 | } |
| 748 | } |
| 749 | |
| 750 | fn validate_scope_target(scope: BundleScope, target: &Path) -> Result<()> { |
| 751 | let workspace_scoped = codewhale_config::config_path_is_workspace_scoped(target); |
| 752 | match (scope, workspace_scoped) { |
| 753 | (BundleScope::Project, false) => bail!( |
| 754 | "--project requires a workspace config ({} is the user-global document)", |
| 755 | target.display() |
| 756 | ), |
| 757 | (BundleScope::Global, true) => bail!( |
| 758 | "global bundle operations cannot target workspace config {}; rerun with --project or select the user-global config", |
| 759 | target.display() |
| 760 | ), |
| 761 | _ => {} |
| 762 | } |
| 763 | Ok(()) |
| 764 | } |
| 765 | |
| 766 | // --------------------------------------------------------------------------- |
| 767 | // Path safety |
| 768 | // --------------------------------------------------------------------------- |
| 769 | |
| 770 | /// Resolve `candidate` inside `base_dir`, refusing traversal and symlink |
| 771 | /// escapes. Returns the resolved path or an error naming the refusal — the |
| 772 | /// candidate string itself is safe to echo (it is config data, not a secret). |
| 773 | /// Resolve `candidate` inside `base_dir`, refusing traversal and symlink |
| 774 | /// escapes. Returns the joined path or an error naming the refusal. |
| 775 | /// Reserved for path-carrying bundle sections (none shipped yet); exercised |
| 776 | /// by the traversal tests so the contract cannot silently rot. |
| 777 | #[cfg(test)] |
| 778 | pub fn resolve_bounded_path(base_dir: &Path, candidate: &str) -> Result<PathBuf> { |
| 779 | if candidate.contains('\0') { |
| 780 | bail!("bundle path contains a NUL byte; refused"); |
| 781 | } |
| 782 | let candidate_path = Path::new(candidate); |
| 783 | if candidate_path.is_absolute() { |
| 784 | bail!( |
| 785 | "bundle path {candidate:?} is absolute; only paths inside the config directory are accepted" |
| 786 | ); |
| 787 | } |
| 788 | let canonical_base = base_dir |
| 789 | .canonicalize() |
| 790 | .with_context(|| format!("config directory {} is unavailable", base_dir.display()))?; |
| 791 | let joined = base_dir.join(candidate_path); |
| 792 | // Walk the joined path's ancestors from the deepest existing component up: |
| 793 | // every existing component must canonicalize inside the base, so a symlink |
| 794 | // pointing outside the config directory is refused even when the final |
| 795 | // target does not exist yet. |
| 796 | let deepest_existing = joined |
| 797 | .ancestors() |
| 798 | .find(|ancestor| ancestor.symlink_metadata().is_ok()) |
| 799 | .context("bundle path has no existing ancestor inside the config directory")?; |
| 800 | let resolved = deepest_existing.canonicalize().with_context(|| { |
| 801 | format!( |
| 802 | "could not resolve bundle path component {}", |
| 803 | deepest_existing.display() |
| 804 | ) |
| 805 | })?; |
| 806 | if !resolved.starts_with(&canonical_base) { |
| 807 | bail!("bundle path {candidate:?} escapes the config directory via a symlink; refused"); |
| 808 | } |
| 809 | Ok(joined) |
| 810 | } |
| 811 | |
| 812 | // --------------------------------------------------------------------------- |
| 813 | // Remote fetch |
| 814 | // --------------------------------------------------------------------------- |
| 815 | |
| 816 | /// Fetch a bundle over HTTPS (or plain http on loopback only) with a hard |
| 817 | /// size cap, a timeout, and bounded redirects. The first request and every |
| 818 | /// redirect go through the shared guarded download: the network policy |
| 819 | /// applies, the host is resolved and checked, and loopback, private, |
| 820 | /// link-local and cloud-metadata destinations are refused unless the person |
| 821 | /// listed a visibly local host in `network.allow`. A loopback host typed as |
| 822 | /// the URL itself is admitted without a listing. |
| 823 | pub fn fetch_bundle( |
| 824 | url: &str, |
| 825 | network: &codewhale_net::network_policy::NetworkPolicy, |
| 826 | ) -> Result<Vec<u8>> { |
| 827 | let initial_url = reqwest::Url::parse(url).map_err(|_| anyhow!("invalid bundle URL"))?; |
| 828 | validate_bundle_url(&initial_url)?; |
| 829 | let initial_scheme = initial_url.scheme().to_string(); |
| 830 | let initial_host = initial_url |
| 831 | .host_str() |
| 832 | .context("bundle URL must include a host")? |
| 833 | .to_string(); |
| 834 | |
| 835 | let mut policy = network.clone(); |
| 836 | if is_loopback_bundle_host(&initial_host) { |
| 837 | policy.add_allow(&initial_host); |
| 838 | } |
| 839 | let check = |
| 840 | move |next: &reqwest::Url| validate_bundle_redirect(&initial_scheme, &initial_host, next); |
| 841 | let request = codewhale_net::guard::GuardedGet::new( |
| 842 | url, |
| 843 | &policy, |
| 844 | "config_import", |
| 845 | codewhale_net::guard::PrivateTargets::TypedLocalHosts, |
| 846 | ) |
| 847 | .timeouts( |
| 848 | std::time::Duration::from_secs(FETCH_TIMEOUT_SECS), |
| 849 | std::time::Duration::from_secs(FETCH_TIMEOUT_SECS), |
| 850 | ) |
| 851 | .max_redirects(MAX_REDIRECTS) |
| 852 | .redirect_check(&check); |
| 853 | |
| 854 | run_blocking(async move { |
| 855 | let mut response = request.send().await?; |
| 856 | if !response.status().is_success() { |
| 857 | bail!( |
| 858 | "bundle fetch failed with HTTP status {}", |
| 859 | response.status().as_u16() |
| 860 | ); |
| 861 | } |
| 862 | if response |
| 863 | .content_length() |
| 864 | .is_some_and(|length| length > MAX_BUNDLE_BYTES) |
| 865 | { |
| 866 | bail!("remote bundle exceeds the {MAX_BUNDLE_BYTES} byte limit; refused"); |
| 867 | } |
| 868 | let mut buffer = Vec::new(); |
| 869 | while let Some(chunk) = response |
| 870 | .chunk() |
| 871 | .await |
| 872 | .map_err(|_| anyhow!("reading remote bundle failed"))? |
| 873 | { |
| 874 | if (buffer.len() + chunk.len()) as u64 > MAX_BUNDLE_BYTES { |
| 875 | bail!("remote bundle exceeds the {MAX_BUNDLE_BYTES} byte limit; refused"); |
| 876 | } |
| 877 | buffer.extend_from_slice(&chunk); |
| 878 | } |
| 879 | Ok(buffer) |
| 880 | }) |
| 881 | } |
| 882 | |
| 883 | fn run_blocking<T: Send>(future: impl std::future::Future<Output = Result<T>> + Send) -> Result<T> { |
| 884 | std::thread::scope(|scope| { |
| 885 | scope |
| 886 | .spawn(|| { |
| 887 | tokio::runtime::Builder::new_current_thread() |
| 888 | .enable_all() |
| 889 | .build() |
| 890 | .map_err(|_| anyhow!("building bundle fetch runtime failed"))? |
| 891 | .block_on(future) |
| 892 | }) |
| 893 | .join() |
| 894 | .map_err(|_| anyhow!("bundle fetch thread failed"))? |
| 895 | }) |
| 896 | } |
| 897 | |
| 898 | fn validate_bundle_url(url: &reqwest::Url) -> Result<()> { |
| 899 | if !matches!(url.scheme(), "http" | "https") { |
| 900 | bail!("unsupported bundle URL scheme; use https"); |
| 901 | } |
| 902 | if !url.username().is_empty() || url.password().is_some() { |
| 903 | bail!("bundle URLs may not include credentials"); |
| 904 | } |
| 905 | let host = url.host_str().context("bundle URL must include a host")?; |
| 906 | match url.scheme() { |
| 907 | "https" => Ok(()), |
| 908 | "http" if is_loopback_bundle_host(host) => Ok(()), |
| 909 | "http" => bail!("plain http is only allowed for loopback hosts; use https"), |
| 910 | _ => unreachable!("scheme was validated above"), |
| 911 | } |
| 912 | } |
| 913 | |
| 914 | fn validate_bundle_redirect( |
| 915 | initial_scheme: &str, |
| 916 | initial_host: &str, |
| 917 | next_url: &reqwest::Url, |
| 918 | ) -> Result<()> { |
| 919 | validate_bundle_url(next_url)?; |
| 920 | if next_url.scheme() != initial_scheme { |
| 921 | bail!("bundle redirects may not change URL scheme"); |
| 922 | } |
| 923 | let next_host = next_url |
| 924 | .host_str() |
| 925 | .context("bundle URL must include a host")?; |
| 926 | if codewhale_net::guard::is_visibly_local_host(next_host) |
| 927 | && !same_bundle_host(initial_host, next_host) |
| 928 | { |
| 929 | bail!("bundle redirects may not target a different local host"); |
| 930 | } |
| 931 | Ok(()) |
| 932 | } |
| 933 | |
| 934 | fn same_bundle_host(left: &str, right: &str) -> bool { |
| 935 | let normalize = |host: &str| host.trim().trim_end_matches('.').to_ascii_lowercase(); |
| 936 | normalize(left) == normalize(right) |
| 937 | } |
| 938 | |
| 939 | fn is_loopback_bundle_host(host: &str) -> bool { |
| 940 | let normalized = host |
| 941 | .strip_prefix('[') |
| 942 | .and_then(|value| value.strip_suffix(']')) |
| 943 | .unwrap_or(host) |
| 944 | .trim_end_matches('.'); |
| 945 | normalized.eq_ignore_ascii_case("localhost") |
| 946 | || normalized.to_ascii_lowercase().ends_with(".localhost") |
| 947 | || normalized |
| 948 | .parse::<std::net::IpAddr>() |
| 949 | .is_ok_and(|address| address.is_loopback()) |
| 950 | } |
| 951 | |
| 952 | // --------------------------------------------------------------------------- |
| 953 | // Export |
| 954 | // --------------------------------------------------------------------------- |
| 955 | |
| 956 | /// Build a deterministic, secret-free export from `config`. |
| 957 | /// |
| 958 | /// Keys are sorted, machine-specific absolute paths and credential fields are |
| 959 | /// dropped, and the same section mapping as import is used so an exported |
| 960 | /// bundle re-imports at the same scope. |
| 961 | pub fn export_bundle( |
| 962 | config: &ConfigToml, |
| 963 | scope: BundleScope, |
| 964 | metadata: BundleMetadata, |
| 965 | ) -> Result<PortableBundle> { |
| 966 | let mut preferences = BundleTable::default(); |
| 967 | let profiles = BundleTable::default(); |
| 968 | let mut global = BundleTable::default(); |
| 969 | let mut project = BundleTable::default(); |
| 970 | |
| 971 | let mut document = config_document(config)?; |
| 972 | if scope == BundleScope::Global { |
| 973 | // Root model aliases are route-relative on import; reconcile them with |
| 974 | // the canonical provider slots so the bundle never conflicts with |
| 975 | // itself, without reparsing unrelated preserved extras as `Config`. |
| 976 | codewhale_engine::route_preferences::scrub_root_model_aliases_for_export(&mut document)?; |
| 977 | } |
| 978 | for (key, value) in document { |
| 979 | if let Some(value) = sanitize_export_value(&key, &value) { |
| 980 | match export_section_for(&key, scope) { |
| 981 | ExportSection::Preferences => { |
| 982 | preferences.entries.insert(key, value); |
| 983 | } |
| 984 | ExportSection::Global => { |
| 985 | global.entries.insert(key, value); |
| 986 | } |
| 987 | ExportSection::Project => { |
| 988 | project.entries.insert(key, value); |
| 989 | } |
| 990 | ExportSection::Drop => {} |
| 991 | } |
| 992 | } |
| 993 | } |
| 994 | |
| 995 | let bundle = PortableBundle { |
| 996 | schema_version: BUNDLE_SCHEMA_VERSION, |
| 997 | kind: BUNDLE_KIND.to_string(), |
| 998 | metadata, |
| 999 | preferences, |
| 1000 | profiles, |
| 1001 | plugins: BundleTable::default(), |
| 1002 | project, |
| 1003 | global, |
| 1004 | }; |
| 1005 | let rejected = find_rejected_entries(&bundle); |
| 1006 | if !rejected.is_empty() { |
| 1007 | bail!( |
| 1008 | "portable export refused credential-bearing config paths: {}", |
| 1009 | rejected |
| 1010 | .iter() |
| 1011 | .map(|entry| entry.key.as_str()) |
| 1012 | .collect::<Vec<_>>() |
| 1013 | .join(", ") |
| 1014 | ); |
| 1015 | } |
| 1016 | Ok(bundle) |
| 1017 | } |
| 1018 | |
| 1019 | /// Serialize a bundle deterministically (sorted keys, TOML). |
| 1020 | pub fn serialize_bundle(bundle: &PortableBundle) -> Result<String> { |
| 1021 | toml::to_string_pretty(bundle).context("serializing portable bundle") |
| 1022 | } |
| 1023 | |
| 1024 | /// Config keys that name a machine-local location and must never be exported. |
| 1025 | const MACHINE_SPECIFIC_KEYS: [&str; 13] = [ |
| 1026 | "base_url", |
| 1027 | "bwrap_dev_roots", |
| 1028 | "bwrap_ro_roots", |
| 1029 | "hook_sinks.unix_socket_path", |
| 1030 | "mcp_config_path", |
| 1031 | "mcp_oauth_callback_port", |
| 1032 | "mcp_oauth_callback_url", |
| 1033 | "memory_path", |
| 1034 | "network.proxy", |
| 1035 | "sandbox_backend", |
| 1036 | "sandbox_url", |
| 1037 | "skills_dir", |
| 1038 | "telemetry_endpoint", |
| 1039 | ]; |
| 1040 | |
| 1041 | enum ExportSection { |
| 1042 | Preferences, |
| 1043 | Global, |
| 1044 | Project, |
| 1045 | Drop, |
| 1046 | } |
| 1047 | |
| 1048 | fn export_section_for(key: &str, scope: BundleScope) -> ExportSection { |
| 1049 | if key.starts_with("skills") || key.starts_with("tools") || key.starts_with("snapshots") { |
| 1050 | return ExportSection::Preferences; |
| 1051 | } |
| 1052 | if key.starts_with("auth.") { |
| 1053 | return ExportSection::Drop; |
| 1054 | } |
| 1055 | match scope { |
| 1056 | BundleScope::Global => ExportSection::Global, |
| 1057 | BundleScope::Project => ExportSection::Project, |
| 1058 | } |
| 1059 | } |
| 1060 | |
| 1061 | fn config_document(config: &ConfigToml) -> Result<toml::map::Map<String, toml::Value>> { |
| 1062 | // Serialize through TOML text before parsing to Value. Direct |
| 1063 | // `Value::try_from` double-encodes datetime values held inside flattened |
| 1064 | // `toml::Value` extras as the serializer's private marker table. |
| 1065 | let text = toml::to_string(config).context("serializing typed config for bundle")?; |
| 1066 | let value: toml::Value = |
| 1067 | toml::from_str(&text).map_err(|_| anyhow!("serialized typed config was not valid TOML"))?; |
| 1068 | let toml::Value::Table(mut table) = value else { |
| 1069 | bail!("typed config did not serialize to a TOML table"); |
| 1070 | }; |
| 1071 | // `selected_provider_id` is runtime parse state and is skipped by serde; |
| 1072 | // restore the exact named-provider identity that ConfigStore writes. |
| 1073 | table.insert( |
| 1074 | "provider".to_string(), |
| 1075 | toml::Value::String(config.provider_id().to_string()), |
| 1076 | ); |
| 1077 | Ok(table) |
| 1078 | } |
| 1079 | |
| 1080 | /// Return a recursively scrubbed export value. Secret-bearing leaves and |
| 1081 | /// machine-local paths are omitted rather than replaced with a placeholder, |
| 1082 | /// because a placeholder would become literal config on re-import. |
| 1083 | fn sanitize_export_value(path: &str, value: &toml::Value) -> Option<toml::Value> { |
| 1084 | sanitize_export_value_at(path, value, 0) |
| 1085 | } |
| 1086 | |
| 1087 | fn sanitize_export_value_at(path: &str, value: &toml::Value, depth: usize) -> Option<toml::Value> { |
| 1088 | if depth > MAX_EXPORT_WALK_DEPTH { |
| 1089 | return None; |
| 1090 | } |
| 1091 | if nonportable_path_reason(path).is_some() || nonportable_value_reason(path, value).is_some() { |
| 1092 | return None; |
| 1093 | } |
| 1094 | match value { |
| 1095 | toml::Value::String(text) if string_secret_reason(text).is_some() => None, |
| 1096 | toml::Value::Array(values) => Some(toml::Value::Array( |
| 1097 | values |
| 1098 | .iter() |
| 1099 | .filter_map(|value| sanitize_export_value_at(path, value, depth + 1)) |
| 1100 | .collect(), |
| 1101 | )), |
| 1102 | toml::Value::Table(table) => { |
| 1103 | let mut scrubbed = toml::map::Map::new(); |
| 1104 | for (key, value) in table { |
| 1105 | let child_path = format!("{path}.{key}"); |
| 1106 | if let Some(value) = sanitize_export_value_at(&child_path, value, depth + 1) { |
| 1107 | scrubbed.insert(key.clone(), value); |
| 1108 | } |
| 1109 | } |
| 1110 | Some(toml::Value::Table(scrubbed)) |
| 1111 | } |
| 1112 | _ => Some(value.clone()), |
| 1113 | } |
| 1114 | } |
| 1115 | |
| 1116 | // --------------------------------------------------------------------------- |
| 1117 | // Transactional apply |
| 1118 | // --------------------------------------------------------------------------- |
| 1119 | |
| 1120 | /// Outcome of a committed import. |
| 1121 | #[derive(Debug)] |
| 1122 | pub struct ImportReceipt { |
| 1123 | pub plan: ImportPlan, |
| 1124 | pub backup_path: Option<PathBuf>, |
| 1125 | pub target: PathBuf, |
| 1126 | } |
| 1127 | |
| 1128 | /// Apply a validated bundle to `store` transactionally. |
| 1129 | /// |
| 1130 | /// The current document is backed up to `<target>.bundle-backup-<timestamp>-<random>`, |
| 1131 | /// the prepared candidate is committed through one `ConfigStore::save`, and any failure |
| 1132 | /// restores the backup before returning the error. The receipt redacts by |
| 1133 | /// construction: it carries only key paths and counts, never values. |
| 1134 | #[cfg(test)] |
| 1135 | pub fn apply_bundle( |
| 1136 | bundle: &PortableBundle, |
| 1137 | store: &mut codewhale_config::ConfigStore, |
| 1138 | scope: BundleScope, |
| 1139 | _workspace: &Path, |
| 1140 | ) -> Result<ImportReceipt> { |
| 1141 | let prepared = prepare_import(bundle, store, scope)?; |
| 1142 | apply_prepared_bundle(prepared, store, save_candidate) |
| 1143 | } |
| 1144 | |
| 1145 | struct PreparedImport { |
| 1146 | plan: ImportPlan, |
| 1147 | candidate: ConfigToml, |
| 1148 | } |
| 1149 | |
| 1150 | fn apply_prepared_bundle<F>( |
| 1151 | prepared: PreparedImport, |
| 1152 | store: &mut codewhale_config::ConfigStore, |
| 1153 | apply: F, |
| 1154 | ) -> Result<ImportReceipt> |
| 1155 | where |
| 1156 | F: FnOnce(ConfigToml, &mut codewhale_config::ConfigStore, &mut bool) -> Result<()>, |
| 1157 | { |
| 1158 | let PreparedImport { plan, candidate } = prepared; |
| 1159 | if !plan.conflicting.is_empty() { |
| 1160 | bail!( |
| 1161 | "bundle contains conflicting or rejected entries: {}; remove duplicate keys or credential-shaped entries and re-export", |
| 1162 | plan.conflicting.join(", ") |
| 1163 | ); |
| 1164 | } |
| 1165 | if plan.is_no_op() { |
| 1166 | return Ok(ImportReceipt { |
| 1167 | plan, |
| 1168 | backup_path: None, |
| 1169 | target: store.path().to_path_buf(), |
| 1170 | }); |
| 1171 | } |
| 1172 | |
| 1173 | let target = store.path().to_path_buf(); |
| 1174 | let original_config = store.config.clone(); |
| 1175 | let backup_path = if target |
| 1176 | .try_exists() |
| 1177 | .with_context(|| format!("checking config target {}", target.display()))? |
| 1178 | { |
| 1179 | Some(create_collision_safe_backup(&target)?) |
| 1180 | } else { |
| 1181 | None |
| 1182 | }; |
| 1183 | |
| 1184 | let mut target_written = false; |
| 1185 | let apply_result = apply(candidate, store, &mut target_written); |
| 1186 | if let Err(error) = apply_result { |
| 1187 | store.config = original_config; |
| 1188 | let rollback = rollback_import_target(&target, backup_path.as_deref(), target_written) |
| 1189 | .and_then(|()| store.reload()); |
| 1190 | match rollback { |
| 1191 | Ok(()) => bail!("{error:#}; rolled back to the pre-import document"), |
| 1192 | Err(_) => bail!( |
| 1193 | "{error:#}; ROLLBACK FAILED — the pre-import document is preserved at {}", |
| 1194 | backup_path |
| 1195 | .as_deref() |
| 1196 | .map(Path::display) |
| 1197 | .map(|path| path.to_string()) |
| 1198 | .unwrap_or_else( |
| 1199 | || "<no prior file; remove the new target manually>".to_string() |
| 1200 | ) |
| 1201 | ), |
| 1202 | } |
| 1203 | } |
| 1204 | |
| 1205 | Ok(ImportReceipt { |
| 1206 | plan, |
| 1207 | backup_path, |
| 1208 | target, |
| 1209 | }) |
| 1210 | } |
| 1211 | |
| 1212 | fn rollback_import_target( |
| 1213 | target: &Path, |
| 1214 | backup_path: Option<&Path>, |
| 1215 | target_written: bool, |
| 1216 | ) -> Result<()> { |
| 1217 | // ConfigStore fails closed before replacing a stale target. If it did not |
| 1218 | // report a successful write, leave a concurrently-created or edited file |
| 1219 | // alone instead of mistaking somebody else's bytes for ours. |
| 1220 | if !target_written { |
| 1221 | return Ok(()); |
| 1222 | } |
| 1223 | if let Some(backup_path) = backup_path { |
| 1224 | let bytes = std::fs::read(backup_path) |
| 1225 | .with_context(|| format!("reading pre-import backup {}", backup_path.display()))?; |
| 1226 | // Replace the name by rename (owner-only), never write through a link |
| 1227 | // that has appeared at it since the import wrote the file. |
| 1228 | codewhale_config::persistence::atomic_write(target, &bytes) |
| 1229 | .with_context(|| format!("restoring pre-import config {}", target.display()))?; |
| 1230 | return Ok(()); |
| 1231 | } |
| 1232 | |
| 1233 | match std::fs::remove_file(target) { |
| 1234 | Ok(()) => Ok(()), |
| 1235 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), |
| 1236 | Err(error) => Err(error) |
| 1237 | .with_context(|| format!("removing newly-created config {}", target.display())), |
| 1238 | } |
| 1239 | } |
| 1240 | |
| 1241 | /// Build the exact candidate used for both preview and commit. Legacy route |
| 1242 | /// migration remains in memory until the existing ConfigStore CAS save. |
| 1243 | fn prepare_import( |
| 1244 | bundle: &PortableBundle, |
| 1245 | store: &codewhale_config::ConfigStore, |
| 1246 | scope: BundleScope, |
| 1247 | ) -> Result<PreparedImport> { |
| 1248 | match scope { |
| 1249 | BundleScope::Global if !bundle.project.entries.is_empty() => bail!( |
| 1250 | "bundle carries [project] entries; import it with --project from the workspace instead" |
| 1251 | ), |
| 1252 | BundleScope::Project if !bundle.global.entries.is_empty() => bail!( |
| 1253 | "bundle carries [global] entries; importing them into a project document would leak machine state" |
| 1254 | ), |
| 1255 | _ => {} |
| 1256 | } |
| 1257 | validate_scope_target(scope, store.path())?; |
| 1258 | let mut plan = plan_import(bundle, &store.config, scope); |
| 1259 | if !plan.conflicting.is_empty() || (plan.is_no_op() && plan.skipped.is_empty()) { |
| 1260 | return Ok(PreparedImport { |
| 1261 | plan, |
| 1262 | candidate: store.config.clone(), |
| 1263 | }); |
| 1264 | } |
| 1265 | let rendered; |
| 1266 | let original = if let Some(original) = store.original_body() { |
| 1267 | original |
| 1268 | } else { |
| 1269 | rendered = store.rendered_body()?; |
| 1270 | &rendered |
| 1271 | }; |
| 1272 | let mut document = |
| 1273 | codewhale_engine::route_preferences::prepare_document(store.path(), original)?; |
| 1274 | let mut candidate = config_from_document(&document.to_string())?; |
| 1275 | let mut model_edits = Vec::<(String, String, String)>::new(); |
| 1276 | let mut selected_provider = None; |
| 1277 | for (section, table) in [ |
| 1278 | ("preferences", &bundle.preferences), |
| 1279 | ("profiles", &bundle.profiles), |
| 1280 | ("plugins", &bundle.plugins), |
| 1281 | ("project", &bundle.project), |
| 1282 | ("global", &bundle.global), |
| 1283 | ] { |
| 1284 | if !section_applies(section, scope) { |
| 1285 | continue; |
| 1286 | } |
| 1287 | for (key, value) in &table.entries { |
| 1288 | let dotted = format!("{section}.{key}"); |
| 1289 | if nonportable_path_reason(key).is_some() |
| 1290 | || value_rejection_reason(key, value).is_some() |
| 1291 | { |
| 1292 | bail!("refusing to import non-portable config path {dotted}"); |
| 1293 | } |
| 1294 | if key == "provider" { |
| 1295 | selected_provider = Some( |
| 1296 | value |
| 1297 | .as_str() |
| 1298 | .ok_or_else(|| anyhow!("config entry {dotted:?} must be a string"))?, |
| 1299 | ); |
| 1300 | continue; |
| 1301 | } |
| 1302 | collect_model_edits(&dotted, key, value, &mut model_edits)?; |
| 1303 | if codewhale_engine::route_preferences::is_route_key(key) { |
| 1304 | continue; |
| 1305 | } |
| 1306 | apply_config_value(&mut candidate, key, value)?; |
| 1307 | } |
| 1308 | } |
| 1309 | document = toml::to_string(&toml::Value::Table(config_document(&candidate)?))? |
| 1310 | .parse() |
| 1311 | .map_err(|_| anyhow!("could not prepare imported configuration; contents omitted"))?; |
| 1312 | // Definitions precede the exact final selector. Root aliases then target |
| 1313 | // that selected route, so an old provider slot cannot mask an imported model. |
| 1314 | if let Some(provider) = selected_provider { |
| 1315 | codewhale_engine::route_preferences::set_document( |
| 1316 | store.path(), |
| 1317 | &mut document, |
| 1318 | "provider", |
| 1319 | provider, |
| 1320 | )?; |
| 1321 | } |
| 1322 | model_edits.sort_by_key(|(_, key, _)| !key.starts_with("providers.")); |
| 1323 | for (_, key, value) in &model_edits { |
| 1324 | codewhale_engine::route_preferences::set_document(store.path(), &mut document, key, value)?; |
| 1325 | } |
| 1326 | let final_value: toml::Value = toml::from_str(&document.to_string())?; |
| 1327 | for (dotted, key, value) in &model_edits { |
| 1328 | let mut replay = document.clone(); |
| 1329 | codewhale_engine::route_preferences::set_document(store.path(), &mut replay, key, value)?; |
| 1330 | if toml::from_str::<toml::Value>(&replay.to_string())? != final_value { |
| 1331 | plan.conflicting.push(dotted.clone()); |
| 1332 | } |
| 1333 | } |
| 1334 | candidate = config_from_document(&document.to_string())?; |
| 1335 | // Run the same validation/serialization as the final save before consent |
| 1336 | // or backup creation. This clone never writes or replaces the CAS snapshot. |
| 1337 | let mut validation_store = store.clone(); |
| 1338 | validation_store.config = candidate.clone(); |
| 1339 | validation_store.rendered_body()?; |
| 1340 | if config_document(&candidate)? == config_document(&store.config)? { |
| 1341 | plan.skipped.append(&mut plan.added); |
| 1342 | plan.skipped.append(&mut plan.changed); |
| 1343 | } else { |
| 1344 | // A raw root alias may already match while its canonical provider |
| 1345 | // slot differs. Such an import is a real change, not a skipped write. |
| 1346 | if plan.is_no_op() { |
| 1347 | for (dotted, _, _) in &model_edits { |
| 1348 | plan.skipped.retain(|key| key != dotted); |
| 1349 | plan.changed.push(dotted.clone()); |
| 1350 | } |
| 1351 | } |
| 1352 | let original_value: toml::Value = toml::from_str(original)?; |
| 1353 | if original_value.get("route_preferences_version").is_none() |
| 1354 | && final_value.get("route_preferences_version").is_some() |
| 1355 | { |
| 1356 | plan.added |
| 1357 | .push("global.route_preferences_version (local migration)".to_string()); |
| 1358 | } |
| 1359 | } |
| 1360 | for keys in [ |
| 1361 | &mut plan.added, |
| 1362 | &mut plan.changed, |
| 1363 | &mut plan.skipped, |
| 1364 | &mut plan.conflicting, |
| 1365 | ] { |
| 1366 | keys.sort(); |
| 1367 | keys.dedup(); |
| 1368 | } |
| 1369 | Ok(PreparedImport { plan, candidate }) |
| 1370 | } |
| 1371 | |
| 1372 | fn collect_model_edits( |
| 1373 | dotted: &str, |
| 1374 | key: &str, |
| 1375 | value: &toml::Value, |
| 1376 | edits: &mut Vec<(String, String, String)>, |
| 1377 | ) -> Result<()> { |
| 1378 | if key != "provider" && codewhale_engine::route_preferences::is_route_key(key) { |
| 1379 | let value = value |
| 1380 | .as_str() |
| 1381 | .ok_or_else(|| anyhow!("config entry {dotted:?} must be a string"))?; |
| 1382 | edits.push((dotted.to_string(), key.to_string(), value.to_string())); |
| 1383 | } else if (key == "providers" || key.starts_with("providers.")) |
| 1384 | && let Some(table) = value.as_table() |
| 1385 | { |
| 1386 | for (child, value) in table { |
| 1387 | collect_model_edits( |
| 1388 | &format!("{dotted}.{child}"), |
| 1389 | &format!("{key}.{child}"), |
| 1390 | value, |
| 1391 | edits, |
| 1392 | )?; |
| 1393 | } |
| 1394 | } |
| 1395 | Ok(()) |
| 1396 | } |
| 1397 | |
| 1398 | fn config_from_document(body: &str) -> Result<ConfigToml> { |
| 1399 | let mut config = codewhale_config::parse_config_toml(body).map_err(|_| { |
| 1400 | anyhow!("imported configuration has an invalid TOML type; contents omitted") |
| 1401 | })?; |
| 1402 | let document: toml::Value = toml::from_str(body)?; |
| 1403 | if let Some(provider) = document.get("provider").and_then(toml::Value::as_str) { |
| 1404 | config.bind_persisted_provider_id(provider)?; |
| 1405 | } |
| 1406 | Ok(config) |
| 1407 | } |
| 1408 | |
| 1409 | fn save_candidate( |
| 1410 | candidate: ConfigToml, |
| 1411 | store: &mut codewhale_config::ConfigStore, |
| 1412 | target_written: &mut bool, |
| 1413 | ) -> Result<()> { |
| 1414 | store.config = candidate; |
| 1415 | store.save().context("saving imported bundle")?; |
| 1416 | *target_written = true; |
| 1417 | Ok(()) |
| 1418 | } |
| 1419 | |
| 1420 | fn apply_config_value(config: &mut ConfigToml, key: &str, value: &toml::Value) -> Result<()> { |
| 1421 | if codewhale_config::config_toml_choices(key).is_some() |
| 1422 | || key == "auth.mode" |
| 1423 | || key == "hook_sinks.unix_socket_path" |
| 1424 | || key.starts_with("providers.") |
| 1425 | { |
| 1426 | return config.set_value(key, &render_toml_value(value)?); |
| 1427 | } |
| 1428 | |
| 1429 | let mut document = config_document(config)?; |
| 1430 | if let Some(current) = document.get_mut(key) { |
| 1431 | deep_merge_toml_value(current, value); |
| 1432 | } else { |
| 1433 | document.insert(key.to_string(), value.clone()); |
| 1434 | } |
| 1435 | // As in `config_document`, round-trip through TOML text so datetimes in |
| 1436 | // flattened extras stay TOML datetimes instead of serde-private marker |
| 1437 | // tables or strings. |
| 1438 | let text = toml::to_string(&toml::Value::Table(document)) |
| 1439 | .with_context(|| format!("config entry {key:?} could not be serialized"))?; |
| 1440 | *config = config_from_document(&text)?; |
| 1441 | Ok(()) |
| 1442 | } |
| 1443 | |
| 1444 | /// Merge a portable value into the target document without treating omitted |
| 1445 | /// table leaves as deletions. Tables recurse; arrays and scalars represent an |
| 1446 | /// explicit portable choice and replace the corresponding target value. |
| 1447 | fn deep_merge_toml_value(target: &mut toml::Value, incoming: &toml::Value) { |
| 1448 | match (target, incoming) { |
| 1449 | (toml::Value::Table(target), toml::Value::Table(incoming)) => { |
| 1450 | for (key, value) in incoming { |
| 1451 | if let Some(current) = target.get_mut(key) { |
| 1452 | deep_merge_toml_value(current, value); |
| 1453 | } else { |
| 1454 | target.insert(key.clone(), value.clone()); |
| 1455 | } |
| 1456 | } |
| 1457 | } |
| 1458 | (target, incoming) => *target = incoming.clone(), |
| 1459 | } |
| 1460 | } |
| 1461 | |
| 1462 | /// Render a TOML value into the scalar text `config set` accepts. |
| 1463 | fn render_toml_value(value: &toml::Value) -> Result<String> { |
| 1464 | Ok(match value { |
| 1465 | toml::Value::String(text) => text.clone(), |
| 1466 | toml::Value::Integer(number) => number.to_string(), |
| 1467 | toml::Value::Float(number) => number.to_string(), |
| 1468 | toml::Value::Boolean(flag) => flag.to_string(), |
| 1469 | toml::Value::Datetime(text) => text.to_string(), |
| 1470 | toml::Value::Array(_) | toml::Value::Table(_) => { |
| 1471 | toml::to_string(value)?.trim_end().to_string() |
| 1472 | } |
| 1473 | }) |
| 1474 | } |
| 1475 | |
| 1476 | fn create_collision_safe_backup(target: &Path) -> Result<PathBuf> { |
| 1477 | let timestamp = std::time::SystemTime::now() |
| 1478 | .duration_since(std::time::UNIX_EPOCH) |
| 1479 | .map(|since| since.as_secs()) |
| 1480 | .unwrap_or_default(); |
| 1481 | let file_name = target |
| 1482 | .file_name() |
| 1483 | .map(|name| name.to_string_lossy().into_owned()) |
| 1484 | .unwrap_or_else(|| "config.toml".to_string()); |
| 1485 | let parent = target.parent().unwrap_or_else(|| Path::new(".")); |
| 1486 | let prefix = format!("{file_name}.bundle-backup-{timestamp}-"); |
| 1487 | // NamedTempFile uses exclusive creation and restrictive initial |
| 1488 | // permissions, so concurrent same-second imports cannot clobber an older |
| 1489 | // receipt or expose config bytes before target permissions are applied. |
| 1490 | let mut backup = tempfile::Builder::new() |
| 1491 | .prefix(&prefix) |
| 1492 | .tempfile_in(parent) |
| 1493 | .with_context(|| { |
| 1494 | format!( |
| 1495 | "creating a collision-safe backup beside {}", |
| 1496 | target.display() |
| 1497 | ) |
| 1498 | })?; |
| 1499 | let mut source = std::fs::File::open(target) |
| 1500 | .with_context(|| format!("opening {} for bundle backup", target.display()))?; |
| 1501 | std::io::copy(&mut source, backup.as_file_mut()) |
| 1502 | .with_context(|| format!("copying {} into its bundle backup", target.display()))?; |
| 1503 | use std::io::Write as _; |
| 1504 | backup |
| 1505 | .as_file_mut() |
| 1506 | .flush() |
| 1507 | .context("flushing bundle backup")?; |
| 1508 | let permissions = source |
| 1509 | .metadata() |
| 1510 | .with_context(|| format!("reading permissions for {}", target.display()))? |
| 1511 | .permissions(); |
| 1512 | std::fs::set_permissions(backup.path(), permissions) |
| 1513 | .context("preserving config permissions on bundle backup")?; |
| 1514 | backup |
| 1515 | .as_file() |
| 1516 | .sync_all() |
| 1517 | .context("syncing bundle backup")?; |
| 1518 | let (_file, path) = backup |
| 1519 | .keep() |
| 1520 | .map_err(|error| error.error) |
| 1521 | .context("persisting bundle backup")?; |
| 1522 | Ok(path) |
| 1523 | } |
| 1524 | |
| 1525 | // --------------------------------------------------------------------------- |
| 1526 | // Consent |
| 1527 | // --------------------------------------------------------------------------- |
| 1528 | |
| 1529 | /// Require explicit consent before mutating: interactive sessions get a |
| 1530 | /// prompt; headless runs require `--yes`. |
| 1531 | pub fn require_import_consent(yes: bool, plan: &ImportPlan) -> Result<()> { |
| 1532 | if yes { |
| 1533 | return Ok(()); |
| 1534 | } |
| 1535 | if !std::io::stdin().is_terminal() { |
| 1536 | bail!( |
| 1537 | "import refused: non-interactive use requires explicit --yes after reviewing the plan" |
| 1538 | ); |
| 1539 | } |
| 1540 | print!( |
| 1541 | "Apply this bundle ({} added, {} changed)? Type 'yes': ", |
| 1542 | plan.added.len(), |
| 1543 | plan.changed.len() |
| 1544 | ); |
| 1545 | use std::io::Write; |
| 1546 | std::io::stdout().flush()?; |
| 1547 | let mut answer = String::new(); |
| 1548 | std::io::stdin() |
| 1549 | .read_line(&mut answer) |
| 1550 | .context("reading import consent")?; |
| 1551 | if answer.trim() != "yes" { |
| 1552 | bail!("import cancelled; no configuration was changed"); |
| 1553 | } |
| 1554 | Ok(()) |
| 1555 | } |
| 1556 | |
| 1557 | // --------------------------------------------------------------------------- |
| 1558 | // CLI surface |
| 1559 | // --------------------------------------------------------------------------- |
| 1560 | |
| 1561 | /// Arguments for `codewhale config import`. |
| 1562 | #[derive(Debug, clap::Args)] |
| 1563 | pub struct ImportArgs { |
| 1564 | /// Bundle source: a file path, an HTTPS URL, or `-` for stdin. |
| 1565 | pub source: String, |
| 1566 | /// Print the deterministic import plan without writing anything. |
| 1567 | #[arg(long, default_value_t = false)] |
| 1568 | dry_run: bool, |
| 1569 | /// Skip the interactive consent prompt (required for headless use). |
| 1570 | #[arg(long, default_value_t = false)] |
| 1571 | yes: bool, |
| 1572 | /// Target the project config instead of the user-global document. |
| 1573 | #[arg(long, default_value_t = false)] |
| 1574 | project: bool, |
| 1575 | } |
| 1576 | |
| 1577 | /// Arguments for `codewhale config export --portable`. |
| 1578 | #[derive(Debug, clap::Args)] |
| 1579 | pub struct ExportArgs { |
| 1580 | /// Emit a portable, secret-free bundle (required flag; plain `export` |
| 1581 | /// is reserved so a future non-portable format cannot silently change |
| 1582 | /// what the command writes). |
| 1583 | #[arg(long, default_value_t = false)] |
| 1584 | portable: bool, |
| 1585 | /// Export the project config instead of the user-global document. |
| 1586 | #[arg(long, default_value_t = false)] |
| 1587 | project: bool, |
| 1588 | /// Write to this path instead of stdout. |
| 1589 | #[arg(long, value_name = "FILE")] |
| 1590 | out: Option<PathBuf>, |
| 1591 | } |
| 1592 | |
| 1593 | /// Run `config import`. |
| 1594 | pub fn run_import( |
| 1595 | args: &ImportArgs, |
| 1596 | store: &mut codewhale_config::ConfigStore, |
| 1597 | _workspace: &Path, |
| 1598 | ) -> Result<()> { |
| 1599 | let scope = if args.project { |
| 1600 | BundleScope::Project |
| 1601 | } else { |
| 1602 | BundleScope::Global |
| 1603 | }; |
| 1604 | validate_scope_target(scope, store.path())?; |
| 1605 | let remote_source = args.source.starts_with("https://") || args.source.starts_with("http://"); |
| 1606 | let source_label = if args.source == "-" { |
| 1607 | "stdin" |
| 1608 | } else if remote_source { |
| 1609 | "remote bundle" |
| 1610 | } else { |
| 1611 | args.source.as_str() |
| 1612 | }; |
| 1613 | let raw = if args.source == "-" { |
| 1614 | let mut buffer = Vec::new(); |
| 1615 | std::io::stdin() |
| 1616 | .lock() |
| 1617 | .take(MAX_BUNDLE_BYTES + 1) |
| 1618 | .read_to_end(&mut buffer) |
| 1619 | .context("reading bundle from stdin")?; |
| 1620 | if buffer.len() as u64 > MAX_BUNDLE_BYTES { |
| 1621 | bail!("stdin bundle exceeds the {MAX_BUNDLE_BYTES} byte limit; refused"); |
| 1622 | } |
| 1623 | buffer |
| 1624 | } else if remote_source { |
| 1625 | let network = store |
| 1626 | .config |
| 1627 | .network |
| 1628 | .clone() |
| 1629 | .map(codewhale_net::network_policy::NetworkPolicy::from) |
| 1630 | .unwrap_or_default(); |
| 1631 | fetch_bundle(&args.source, &network)? |
| 1632 | } else { |
| 1633 | let path = PathBuf::from(&args.source); |
| 1634 | let metadata = std::fs::metadata(&path) |
| 1635 | .with_context(|| format!("reading bundle at {}", path.display()))?; |
| 1636 | if metadata.len() > MAX_BUNDLE_BYTES { |
| 1637 | bail!( |
| 1638 | "bundle at {} is {} bytes; the limit is {MAX_BUNDLE_BYTES} bytes", |
| 1639 | path.display(), |
| 1640 | metadata.len() |
| 1641 | ); |
| 1642 | } |
| 1643 | std::fs::read(&path).with_context(|| format!("reading bundle at {}", path.display()))? |
| 1644 | }; |
| 1645 | |
| 1646 | let bundle = parse_bundle_bytes(&raw, source_label)?; |
| 1647 | let prepared = prepare_import(&bundle, store, scope)?; |
| 1648 | let plan = &prepared.plan; |
| 1649 | |
| 1650 | println!("import plan ({} scope, {source_label}):", scope.label()); |
| 1651 | println!(" added: {}", plan.added.len()); |
| 1652 | println!(" changed: {}", plan.changed.len()); |
| 1653 | println!(" skipped: {}", plan.skipped.len()); |
| 1654 | println!(" conflicting: {}", plan.conflicting.len()); |
| 1655 | println!(" rejected: {}", plan.rejected.len()); |
| 1656 | for entry in &plan.added { |
| 1657 | println!(" + {entry}"); |
| 1658 | } |
| 1659 | for entry in &plan.changed { |
| 1660 | println!(" ~ {entry}"); |
| 1661 | } |
| 1662 | for entry in &plan.rejected { |
| 1663 | println!(" ! {} — {}", entry.key, entry.reason); |
| 1664 | } |
| 1665 | for entry in &plan.conflicting { |
| 1666 | println!(" x {entry}"); |
| 1667 | } |
| 1668 | |
| 1669 | if args.dry_run { |
| 1670 | println!("dry run: nothing was written"); |
| 1671 | return Ok(()); |
| 1672 | } |
| 1673 | |
| 1674 | require_import_consent(args.yes, plan)?; |
| 1675 | let receipt = apply_prepared_bundle(prepared, store, save_candidate)?; |
| 1676 | if receipt.plan.is_no_op() { |
| 1677 | println!("nothing to apply; config already matches the bundle (idempotent re-import)"); |
| 1678 | return Ok(()); |
| 1679 | } |
| 1680 | println!( |
| 1681 | "imported: {} added, {} changed into {}", |
| 1682 | receipt.plan.added.len(), |
| 1683 | receipt.plan.changed.len(), |
| 1684 | receipt.target.display() |
| 1685 | ); |
| 1686 | if let Some(backup) = &receipt.backup_path { |
| 1687 | println!("pre-import backup: {}", backup.display()); |
| 1688 | } |
| 1689 | Ok(()) |
| 1690 | } |
| 1691 | |
| 1692 | /// Run `config export --portable`. |
| 1693 | pub fn run_export(args: &ExportArgs, store: &codewhale_config::ConfigStore) -> Result<()> { |
| 1694 | if !args.portable { |
| 1695 | bail!("config export requires --portable; plain export is not defined yet"); |
| 1696 | } |
| 1697 | let scope = if args.project { |
| 1698 | BundleScope::Project |
| 1699 | } else { |
| 1700 | BundleScope::Global |
| 1701 | }; |
| 1702 | validate_scope_target(scope, store.path())?; |
| 1703 | let metadata = BundleMetadata { |
| 1704 | name: None, |
| 1705 | created_at: Some(chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)), |
| 1706 | generator: Some(format!("codewhale {}", env!("CARGO_PKG_VERSION"))), |
| 1707 | }; |
| 1708 | let bundle = export_bundle(&store.config, scope, metadata)?; |
| 1709 | let body = serialize_bundle(&bundle)?; |
| 1710 | match &args.out { |
| 1711 | Some(path) => { |
| 1712 | codewhale_config::persistence::atomic_write(path, body.as_bytes()) |
| 1713 | .with_context(|| format!("writing bundle to {}", path.display()))?; |
| 1714 | println!("wrote portable bundle to {}", path.display()); |
| 1715 | } |
| 1716 | None => { |
| 1717 | use std::io::Write; |
| 1718 | std::io::stdout().write_all(body.as_bytes())?; |
| 1719 | } |
| 1720 | } |
| 1721 | Ok(()) |
| 1722 | } |
| 1723 | |
| 1724 | // --------------------------------------------------------------------------- |
| 1725 | // Tests |
| 1726 | // --------------------------------------------------------------------------- |
| 1727 | |
| 1728 | #[cfg(test)] |
| 1729 | mod tests { |
| 1730 | use super::*; |
| 1731 | use codewhale_config::ConfigStore; |
| 1732 | use codewhale_net::network_policy::NetworkPolicy; |
| 1733 | use std::io::Write; |
| 1734 | use std::net::{Ipv4Addr, TcpListener}; |
| 1735 | |
| 1736 | const VALID_TOML: &str = r#" |
| 1737 | schema_version = 1 |
| 1738 | kind = "codewhale.portable-config" |
| 1739 | |
| 1740 | [metadata] |
| 1741 | name = "team-baseline" |
| 1742 | |
| 1743 | [preferences] |
| 1744 | verbosity = "concise" |
| 1745 | telemetry = false |
| 1746 | |
| 1747 | [global] |
| 1748 | log_level = "debug" |
| 1749 | "#; |
| 1750 | |
| 1751 | fn sample_bundle() -> PortableBundle { |
| 1752 | parse_bundle_str(VALID_TOML, "test.toml").expect("valid bundle") |
| 1753 | } |
| 1754 | |
| 1755 | #[test] |
| 1756 | fn valid_bundle_parses_and_validates() { |
| 1757 | let bundle = sample_bundle(); |
| 1758 | assert_eq!(bundle.schema_version, 1); |
| 1759 | assert_eq!(bundle.kind, "codewhale.portable-config"); |
| 1760 | assert_eq!(bundle.metadata.name.as_deref(), Some("team-baseline")); |
| 1761 | assert_eq!(bundle.preferences.entries.len(), 2); |
| 1762 | } |
| 1763 | |
| 1764 | #[test] |
| 1765 | fn unknown_envelope_fields_fail_the_parse() { |
| 1766 | let text = r#" |
| 1767 | schema_version = 1 |
| 1768 | kind = "codewhale.portable-config" |
| 1769 | sneaky_extra = true |
| 1770 | "#; |
| 1771 | let err = parse_bundle_str(text, "test.toml").expect_err("unknown field must fail"); |
| 1772 | let rendered = format!("{err:#}"); |
| 1773 | assert!(rendered.contains("unknown field"), "{rendered}"); |
| 1774 | } |
| 1775 | |
| 1776 | #[test] |
| 1777 | fn wrong_kind_or_schema_version_is_refused() { |
| 1778 | let bad_kind = "schema_version = 1 |
| 1779 | kind = \"something-else\"\n"; |
| 1780 | let err = parse_bundle_str(bad_kind, "t.toml").expect_err("kind must match"); |
| 1781 | assert!(err.to_string().contains("kind"), "{err:#}"); |
| 1782 | |
| 1783 | let bad_version = "schema_version = 99\nkind = \"codewhale.portable-config\"\n"; |
| 1784 | let err = parse_bundle_str(bad_version, "t.toml").expect_err("schema version must match"); |
| 1785 | assert!(err.to_string().contains("schema_version"), "{err:#}"); |
| 1786 | } |
| 1787 | |
| 1788 | #[test] |
| 1789 | fn json_bundles_parse_when_the_document_is_json() { |
| 1790 | let json = r#"{"schema_version": 1, "kind": "codewhale.portable-config", |
| 1791 | "preferences": {"verbosity": "quiet"}}"#; |
| 1792 | let bundle = parse_bundle_str(json, "bundle.json").expect("json bundle"); |
| 1793 | assert_eq!(bundle.preferences.entries.len(), 1); |
| 1794 | } |
| 1795 | |
| 1796 | #[test] |
| 1797 | fn oversize_input_is_refused_before_parse() { |
| 1798 | let big = vec![b'#'; (MAX_BUNDLE_BYTES + 1) as usize]; |
| 1799 | let err = parse_bundle_bytes(&big, "big.toml").expect_err("oversize must fail"); |
| 1800 | assert!(err.to_string().contains("limit"), "{err:#}"); |
| 1801 | } |
| 1802 | |
| 1803 | #[test] |
| 1804 | fn credential_keys_are_rejected_by_name() { |
| 1805 | let text = r#" |
| 1806 | schema_version = 1 |
| 1807 | kind = "codewhale.portable-config" |
| 1808 | |
| 1809 | [global] |
| 1810 | api_key = "value-is-never-echoed" |
| 1811 | |
| 1812 | [preferences] |
| 1813 | openai_api_key = "also-secret" |
| 1814 | "#; |
| 1815 | let bundle = parse_bundle_str(text, "t.toml").expect("parses"); |
| 1816 | let rejected = find_rejected_entries(&bundle); |
| 1817 | assert_eq!(rejected.len(), 2, "{rejected:?}"); |
| 1818 | assert!(rejected.iter().any(|r| r.key == "global.api_key")); |
| 1819 | assert!( |
| 1820 | rejected |
| 1821 | .iter() |
| 1822 | .all(|r| !r.reason.contains("value-is-never-echoed")) |
| 1823 | ); |
| 1824 | } |
| 1825 | |
| 1826 | #[test] |
| 1827 | fn credential_shaped_values_are_rejected_under_benign_names() { |
| 1828 | let text = r#" |
| 1829 | schema_version = 1 |
| 1830 | kind = "codewhale.portable-config" |
| 1831 | |
| 1832 | [preferences] |
| 1833 | note = "sk-abcdefghij0123456789" |
| 1834 | "#; |
| 1835 | let bundle = parse_bundle_str(text, "t.toml").expect("parses"); |
| 1836 | let rejected = find_rejected_entries(&bundle); |
| 1837 | assert_eq!(rejected.len(), 1, "{rejected:?}"); |
| 1838 | assert!(!rejected[0].reason.contains("sk-abcdefghij")); |
| 1839 | } |
| 1840 | |
| 1841 | #[test] |
| 1842 | fn nested_secret_keys_and_values_are_rejected_without_echoing_values() { |
| 1843 | let shaped_value = ["Bear", "er nested-token-must-not-leak"].concat(); |
| 1844 | let text = format!( |
| 1845 | r#" |
| 1846 | schema_version = 1 |
| 1847 | kind = "codewhale.portable-config" |
| 1848 | |
| 1849 | [preferences.with_key.nested] |
| 1850 | password = "nested-password-must-not-leak" |
| 1851 | |
| 1852 | [preferences.with_value.nested] |
| 1853 | note = "{shaped_value}" |
| 1854 | "# |
| 1855 | ); |
| 1856 | let bundle = parse_bundle_str(&text, "nested.toml").expect("bundle parses"); |
| 1857 | let rejected = find_rejected_entries(&bundle); |
| 1858 | assert_eq!(rejected.len(), 2, "{rejected:?}"); |
| 1859 | assert!( |
| 1860 | rejected |
| 1861 | .iter() |
| 1862 | .any(|entry| entry.key == "preferences.with_key") |
| 1863 | ); |
| 1864 | assert!( |
| 1865 | rejected |
| 1866 | .iter() |
| 1867 | .any(|entry| entry.key == "preferences.with_value") |
| 1868 | ); |
| 1869 | let rendered = format!("{rejected:?}"); |
| 1870 | assert!(!rendered.contains("nested-password-must-not-leak")); |
| 1871 | assert!(!rendered.contains("nested-token-must-not-leak")); |
| 1872 | } |
| 1873 | |
| 1874 | #[test] |
| 1875 | fn json_bundles_with_duplicate_keys_fail_before_parse() { |
| 1876 | let duplicate = r#"{"schema_version":1,"kind":"codewhale.portable-config","preferences":{"verbosity":"quiet","verbosity":"loud"}}"#; |
| 1877 | let error = parse_bundle_str(duplicate, "dup.json").expect_err("duplicate key must fail"); |
| 1878 | let rendered = format!("{error:#}"); |
| 1879 | assert!(rendered.contains("duplicate key"), "{rendered}"); |
| 1880 | assert!(rendered.contains("preferences.verbosity"), "{rendered}"); |
| 1881 | assert!(!rendered.contains("loud"), "{rendered}"); |
| 1882 | |
| 1883 | let nested_array = r#"{"schema_version":1,"kind":"codewhale.portable-config","preferences":{"list":[{"a":1,"a":2}]}}"#; |
| 1884 | let error = parse_bundle_str(nested_array, "dup-array.json") |
| 1885 | .expect_err("nested duplicate must fail"); |
| 1886 | assert!( |
| 1887 | format!("{error:#}").contains("preferences.list.[0].a"), |
| 1888 | "{error:#}" |
| 1889 | ); |
| 1890 | |
| 1891 | let clean = r#"{"schema_version":1,"kind":"codewhale.portable-config","preferences":{"verbosity":"quiet","profiles":{"verbosity":"loud"}}}"#; |
| 1892 | parse_bundle_str(clean, "clean.json").expect("same key under different parents is fine"); |
| 1893 | } |
| 1894 | |
| 1895 | #[test] |
| 1896 | fn network_proxy_routes_are_rejected_on_import_and_scrubbed_on_export() { |
| 1897 | let proxy_url = ["http://proxy-user:proxy-", "pass@proxy.internal:3128"].concat(); |
| 1898 | let text = format!( |
| 1899 | r#" |
| 1900 | schema_version = 1 |
| 1901 | kind = "codewhale.portable-config" |
| 1902 | |
| 1903 | [global.network] |
| 1904 | default = "prompt" |
| 1905 | allow = ["registry.example"] |
| 1906 | proxy = ["{proxy_url}"] |
| 1907 | "# |
| 1908 | ); |
| 1909 | let bundle = parse_bundle_str(&text, "network-proxy.toml").expect("bundle parses"); |
| 1910 | let rejected = find_rejected_entries(&bundle); |
| 1911 | assert_eq!(rejected.len(), 1, "{rejected:?}"); |
| 1912 | assert_eq!(rejected[0].key, "global.network"); |
| 1913 | let rendered = format!("{rejected:?}"); |
| 1914 | assert!(!rendered.contains("proxy-pass"), "{rendered}"); |
| 1915 | assert!(!rendered.contains("proxy.internal"), "{rendered}"); |
| 1916 | |
| 1917 | let config: ConfigToml = toml::from_str(&format!( |
| 1918 | r#" |
| 1919 | [network] |
| 1920 | default = "prompt" |
| 1921 | allow = ["registry.example"] |
| 1922 | proxy = ["{proxy_url}"] |
| 1923 | "# |
| 1924 | )) |
| 1925 | .expect("network config parses"); |
| 1926 | let exported = export_bundle(&config, BundleScope::Global, BundleMetadata::default()) |
| 1927 | .expect("network proxy is scrubbed"); |
| 1928 | let body = serialize_bundle(&exported).expect("serialize network export"); |
| 1929 | assert!(!body.contains("proxy-user"), "{body}"); |
| 1930 | assert!(!body.contains("proxy.internal"), "{body}"); |
| 1931 | let reparsed: toml::Value = toml::from_str(&body).expect("export reparses"); |
| 1932 | let network = reparsed |
| 1933 | .get("global") |
| 1934 | .and_then(|global| global.get("network")) |
| 1935 | .expect("portable network policy is kept"); |
| 1936 | assert!(network.get("proxy").is_none(), "{body}"); |
| 1937 | assert_eq!( |
| 1938 | network.get("default").and_then(toml::Value::as_str), |
| 1939 | Some("prompt") |
| 1940 | ); |
| 1941 | assert!(body.contains("registry.example"), "{body}"); |
| 1942 | } |
| 1943 | |
| 1944 | #[test] |
| 1945 | fn redaction_placeholders_are_rejected_on_import_and_export() { |
| 1946 | let placeholder = codewhale_config::persistence::REDACTED; |
| 1947 | let text = format!( |
| 1948 | r#" |
| 1949 | schema_version = 1 |
| 1950 | kind = "codewhale.portable-config" |
| 1951 | |
| 1952 | [preferences] |
| 1953 | verbosity = "quiet" |
| 1954 | note = "prefix {placeholder} suffix" |
| 1955 | "# |
| 1956 | ); |
| 1957 | let bundle = parse_bundle_str(&text, "placeholder.toml").expect("bundle parses"); |
| 1958 | let rejected = find_rejected_entries(&bundle); |
| 1959 | assert_eq!(rejected.len(), 1, "{rejected:?}"); |
| 1960 | assert_eq!(rejected[0].key, "preferences.note"); |
| 1961 | assert!( |
| 1962 | rejected[0].reason.contains("redaction placeholder"), |
| 1963 | "{rejected:?}" |
| 1964 | ); |
| 1965 | |
| 1966 | let config: ConfigToml = toml::from_str(&format!( |
| 1967 | "verbosity = \"quiet\"\nnote = \"prefix {placeholder} suffix\"\n" |
| 1968 | )) |
| 1969 | .expect("placeholder config parses"); |
| 1970 | let exported = export_bundle(&config, BundleScope::Global, BundleMetadata::default()) |
| 1971 | .expect("placeholder is scrubbed"); |
| 1972 | let body = serialize_bundle(&exported).expect("serialize placeholder export"); |
| 1973 | assert!(!body.contains(placeholder), "{body}"); |
| 1974 | assert!(body.contains("quiet"), "{body}"); |
| 1975 | } |
| 1976 | |
| 1977 | #[test] |
| 1978 | fn camel_case_and_dotted_secret_keys_avoid_token_count_false_positives() { |
| 1979 | for key in [ |
| 1980 | "accessToken", |
| 1981 | "refreshToken", |
| 1982 | "clientSecret", |
| 1983 | "apiKey", |
| 1984 | "api.key", |
| 1985 | "private.key", |
| 1986 | "accessKey", |
| 1987 | "aws_access_key", |
| 1988 | "awsSecretAccessKey", |
| 1989 | "Cookie", |
| 1990 | "Set-Cookie", |
| 1991 | "providers.xai.auth.command", |
| 1992 | "providers.xai.external_credentials", |
| 1993 | "providers.xai.oauth_credential_generation", |
| 1994 | "nested.service.accessToken", |
| 1995 | "nested.service.refreshToken", |
| 1996 | ] { |
| 1997 | assert!(is_sensitive_bundle_key(key), "must reject {key}"); |
| 1998 | } |
| 1999 | for key in [ |
| 2000 | "auth_mode", |
| 2001 | "maxTokens", |
| 2002 | "tokenizer", |
| 2003 | "tokenBudget", |
| 2004 | "max_tokens", |
| 2005 | ] { |
| 2006 | assert!(!is_sensitive_bundle_key(key), "must preserve {key}"); |
| 2007 | } |
| 2008 | } |
| 2009 | |
| 2010 | #[test] |
| 2011 | fn compound_and_access_keys_are_rejected_before_import_without_mutation() { |
| 2012 | let api_dot = ["api", ".key"].concat(); |
| 2013 | let private_dot = ["private", ".key"].concat(); |
| 2014 | let access_camel = ["access", "Key"].concat(); |
| 2015 | let aws_snake = ["aws", "_access_key"].concat(); |
| 2016 | let aws_camel = ["aws", "SecretAccessKey"].concat(); |
| 2017 | let cookie = ["Coo", "kie"].concat(); |
| 2018 | let set_cookie = ["Set-", "Cookie"].concat(); |
| 2019 | let text = format!( |
| 2020 | r#" |
| 2021 | schema_version = 1 |
| 2022 | kind = "codewhale.portable-config" |
| 2023 | |
| 2024 | [preferences] |
| 2025 | "{api_dot}" = "opaque-api-value" |
| 2026 | "{private_dot}" = "opaque-private-value" |
| 2027 | {access_camel} = "opaque-access-value" |
| 2028 | {aws_snake} = "opaque-aws-access-value" |
| 2029 | {aws_camel} = "opaque-aws-secret-access-value" |
| 2030 | maxTokens = 8192 |
| 2031 | tokenizer = "bpe" |
| 2032 | |
| 2033 | [preferences.http_headers] |
| 2034 | {cookie} = "opaque-cookie-import-value" |
| 2035 | {set_cookie} = "opaque-set-cookie-import-value" |
| 2036 | "# |
| 2037 | ); |
| 2038 | let bundle = |
| 2039 | parse_bundle_str(&text, "compound-secrets.toml").expect("compound-key bundle parses"); |
| 2040 | let rejected = find_rejected_entries(&bundle); |
| 2041 | assert_eq!(rejected.len(), 6, "{rejected:?}"); |
| 2042 | assert!( |
| 2043 | rejected |
| 2044 | .iter() |
| 2045 | .any(|entry| entry.key == "preferences.http_headers"), |
| 2046 | "{rejected:?}" |
| 2047 | ); |
| 2048 | assert!( |
| 2049 | rejected |
| 2050 | .iter() |
| 2051 | .all(|entry| !entry.key.contains("maxTokens") && !entry.key.contains("tokenizer")), |
| 2052 | "{rejected:?}" |
| 2053 | ); |
| 2054 | |
| 2055 | let dir = tempfile::tempdir().expect("config dir"); |
| 2056 | let path = dir.path().join("config.toml"); |
| 2057 | std::fs::write(&path, "verbosity = \"quiet\"\n").expect("seed config"); |
| 2058 | let before = std::fs::read(&path).expect("config before import"); |
| 2059 | let mut store = ConfigStore::load(Some(path.clone())).expect("store loads"); |
| 2060 | let error = apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()) |
| 2061 | .expect_err("credential keys must refuse the entire import"); |
| 2062 | let rendered = format!("{error:#}"); |
| 2063 | assert!(rendered.contains("conflicting or rejected"), "{rendered}"); |
| 2064 | for secret in [ |
| 2065 | "opaque-api-value", |
| 2066 | "opaque-private-value", |
| 2067 | "opaque-access-value", |
| 2068 | "opaque-aws-access-value", |
| 2069 | "opaque-aws-secret-access-value", |
| 2070 | "opaque-cookie-import-value", |
| 2071 | "opaque-set-cookie-import-value", |
| 2072 | ] { |
| 2073 | assert!( |
| 2074 | !rendered.contains(secret), |
| 2075 | "error leaked {secret}: {rendered}" |
| 2076 | ); |
| 2077 | } |
| 2078 | assert_eq!(std::fs::read(path).expect("config after refusal"), before); |
| 2079 | assert_eq!(store.config.verbosity.as_deref(), Some("quiet")); |
| 2080 | } |
| 2081 | |
| 2082 | #[test] |
| 2083 | fn plan_reports_added_changed_skipped_deterministically() { |
| 2084 | let store = isolated_store(); |
| 2085 | let bundle_text = r#" |
| 2086 | schema_version = 1 |
| 2087 | kind = "codewhale.portable-config" |
| 2088 | |
| 2089 | [preferences] |
| 2090 | verbosity = "concise" |
| 2091 | log_level = "debug" |
| 2092 | |
| 2093 | [global] |
| 2094 | telemetry = false |
| 2095 | "#; |
| 2096 | let bundle = parse_bundle_str(bundle_text, "t.toml").expect("bundle"); |
| 2097 | // verbosity already matches; log_level is new; telemetry is global-scope. |
| 2098 | let plan_global = plan_import(&bundle, &store.config, BundleScope::Global); |
| 2099 | assert!( |
| 2100 | plan_global |
| 2101 | .added |
| 2102 | .contains(&"preferences.log_level".to_string()) |
| 2103 | ); |
| 2104 | // `verbosity` resolves to a shipped default even when the file key is |
| 2105 | // unset, so an equal value reads as changed-or-skipped by resolution; |
| 2106 | // what matters for determinism is that every entry lands in exactly |
| 2107 | // one bucket and nothing is dropped silently. |
| 2108 | let all: std::collections::BTreeSet<&String> = plan_global |
| 2109 | .added |
| 2110 | .iter() |
| 2111 | .chain(plan_global.changed.iter()) |
| 2112 | .chain(plan_global.skipped.iter()) |
| 2113 | .collect(); |
| 2114 | assert_eq!(all.len(), 3, "{plan_global:?}"); |
| 2115 | // Project scope skips global-section entries. |
| 2116 | let plan_project = plan_import(&bundle, &store.config, BundleScope::Project); |
| 2117 | assert!( |
| 2118 | plan_project |
| 2119 | .skipped |
| 2120 | .contains(&"global.telemetry".to_string()) |
| 2121 | ); |
| 2122 | } |
| 2123 | |
| 2124 | #[test] |
| 2125 | fn rejected_entries_show_up_as_conflicting_in_the_plan() { |
| 2126 | let store = isolated_store(); |
| 2127 | let text = r#" |
| 2128 | schema_version = 1 |
| 2129 | kind = "codewhale.portable-config" |
| 2130 | |
| 2131 | [global] |
| 2132 | api_key = "never-echoed" |
| 2133 | "#; |
| 2134 | let bundle = parse_bundle_str(text, "t.toml").expect("bundle"); |
| 2135 | let plan = plan_import(&bundle, &store.config, BundleScope::Global); |
| 2136 | assert!(plan.conflicting.contains(&"global.api_key".to_string())); |
| 2137 | assert!(plan.added.is_empty()); |
| 2138 | } |
| 2139 | |
| 2140 | #[test] |
| 2141 | fn duplicate_flat_keys_across_applicable_sections_fail_before_apply() { |
| 2142 | let mut store = isolated_store(); |
| 2143 | let before = std::fs::read(store.path()).expect("config before import"); |
| 2144 | let text = r#" |
| 2145 | schema_version = 1 |
| 2146 | kind = "codewhale.portable-config" |
| 2147 | |
| 2148 | [preferences] |
| 2149 | verbosity = "concise" |
| 2150 | |
| 2151 | [global] |
| 2152 | verbosity = "normal" |
| 2153 | "#; |
| 2154 | let bundle = parse_bundle_str(text, "collision.toml").expect("bundle parses"); |
| 2155 | let plan = plan_import(&bundle, &store.config, BundleScope::Global); |
| 2156 | |
| 2157 | assert_eq!( |
| 2158 | plan.conflicting, |
| 2159 | ["preferences.verbosity", "global.verbosity"] |
| 2160 | ); |
| 2161 | assert!(plan.added.is_empty(), "{plan:?}"); |
| 2162 | assert!(plan.changed.is_empty(), "{plan:?}"); |
| 2163 | assert!(plan.skipped.is_empty(), "{plan:?}"); |
| 2164 | |
| 2165 | let workspace = tempfile::tempdir().expect("workspace"); |
| 2166 | let error = apply_bundle(&bundle, &mut store, BundleScope::Global, workspace.path()) |
| 2167 | .expect_err("ambiguous flat key must fail closed"); |
| 2168 | let rendered = error.to_string(); |
| 2169 | assert!(rendered.contains("conflicting"), "{error:#}"); |
| 2170 | assert!(!rendered.contains("concise"), "{error:#}"); |
| 2171 | assert!(!rendered.contains("normal"), "{error:#}"); |
| 2172 | assert_eq!( |
| 2173 | std::fs::read(store.path()).expect("config after refused import"), |
| 2174 | before, |
| 2175 | "collision must be refused before any write" |
| 2176 | ); |
| 2177 | } |
| 2178 | |
| 2179 | #[test] |
| 2180 | fn dry_run_semantics_plan_never_mutates() { |
| 2181 | let store = isolated_store(); |
| 2182 | let before = std::fs::read_to_string(store.path()).expect("read config"); |
| 2183 | let bundle = sample_bundle(); |
| 2184 | let _prepared = prepare_import(&bundle, &store, BundleScope::Global) |
| 2185 | .expect("prepare import without writing"); |
| 2186 | let after = std::fs::read_to_string(store.path()).expect("read config"); |
| 2187 | assert_eq!(before, after, "planning must not write"); |
| 2188 | } |
| 2189 | |
| 2190 | #[test] |
| 2191 | fn route_import_prepares_migration_once_and_overrides_a_masking_provider_slot() { |
| 2192 | use crate::tests::{ScopedEnvVar, env_lock}; |
| 2193 | let _env = env_lock(); |
| 2194 | let home = tempfile::tempdir().expect("isolated home"); |
| 2195 | let _home = ScopedEnvVar::set("CODEWHALE_HOME", &home.path().to_string_lossy()); |
| 2196 | let _config_override = ScopedEnvVar::remove("CODEWHALE_CONFIG_PATH"); |
| 2197 | let _legacy_override = ScopedEnvVar::remove("DEEPSEEK_CONFIG_PATH"); |
| 2198 | let path = home.path().join("config.toml"); |
| 2199 | let original = "provider = 'zai'\ndefault_text_model = 'GLM-5.3'\n[providers.zai]\nmodel = 'GLM-5.2'\n"; |
| 2200 | std::fs::write(&path, original).expect("seed config"); |
| 2201 | let settings_path = home.path().join("settings.toml"); |
| 2202 | let old_settings = "default_provider = 'deepseek'\n[provider_models]\ndeepseek = 'deepseek-v4-pro'\nzai = 'GLM-5.4'\n"; |
| 2203 | std::fs::write(&settings_path, old_settings).expect("seed legacy choices"); |
| 2204 | let bundle = parse_bundle_str( |
| 2205 | "schema_version = 1\nkind = 'codewhale.portable-config'\n[global]\nprovider = 'zai'\ndefault_text_model = 'GLM-5.3'\n", |
| 2206 | "route.toml", |
| 2207 | ).expect("route bundle"); |
| 2208 | let mut store = ConfigStore::load(Some(path.clone())).expect("store"); |
| 2209 | let prepared = prepare_import(&bundle, &store, BundleScope::Global).expect("preview"); |
| 2210 | assert!( |
| 2211 | prepared |
| 2212 | .plan |
| 2213 | .changed |
| 2214 | .iter() |
| 2215 | .any(|key| key == "global.default_text_model") |
| 2216 | ); |
| 2217 | assert!( |
| 2218 | !prepared.plan.is_no_op(), |
| 2219 | "the old slot still masks the root value" |
| 2220 | ); |
| 2221 | assert_eq!(std::fs::read_to_string(&path).unwrap(), original); |
| 2222 | assert_eq!( |
| 2223 | std::fs::read_to_string(&settings_path).unwrap(), |
| 2224 | old_settings |
| 2225 | ); |
| 2226 | |
| 2227 | // Consent commits exactly the preview even if the archived input moves. |
| 2228 | let later_settings = "default_provider = 'openai'\n"; |
| 2229 | std::fs::write(&settings_path, later_settings).unwrap(); |
| 2230 | apply_prepared_bundle(prepared, &mut store, save_candidate).expect("commit preview"); |
| 2231 | let saved: toml::Value = toml::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); |
| 2232 | assert_eq!(saved["provider"].as_str(), Some("zai")); |
| 2233 | assert_eq!(saved["providers"]["zai"]["model"].as_str(), Some("GLM-5.3")); |
| 2234 | assert_eq!( |
| 2235 | saved["providers"]["deepseek"]["model"].as_str(), |
| 2236 | Some("deepseek-v4-pro") |
| 2237 | ); |
| 2238 | assert_eq!(saved["route_preferences_version"].as_integer(), Some(1)); |
| 2239 | assert_eq!( |
| 2240 | std::fs::read_to_string(settings_path).unwrap(), |
| 2241 | later_settings |
| 2242 | ); |
| 2243 | assert_eq!( |
| 2244 | codewhale_engine::route_preferences::get(&path, "provider") |
| 2245 | .unwrap() |
| 2246 | .as_deref(), |
| 2247 | Some("zai") |
| 2248 | ); |
| 2249 | assert_eq!( |
| 2250 | codewhale_engine::route_preferences::get(&path, "model") |
| 2251 | .unwrap() |
| 2252 | .as_deref(), |
| 2253 | Some("GLM-5.3") |
| 2254 | ); |
| 2255 | let again = prepare_import(&bundle, &store, BundleScope::Global).expect("repeat preview"); |
| 2256 | assert!(again.plan.is_no_op(), "{:?}", again.plan); |
| 2257 | } |
| 2258 | |
| 2259 | #[test] |
| 2260 | fn conflicting_import_model_aliases_fail_before_any_write() { |
| 2261 | let dir = tempfile::tempdir().expect("config dir"); |
| 2262 | let path = dir.path().join("config.toml"); |
| 2263 | let original = "provider = 'zai'\n[providers.zai]\nmodel = 'GLM-5.2'\n"; |
| 2264 | std::fs::write(&path, original).unwrap(); |
| 2265 | let mut store = ConfigStore::load(Some(path.clone())).unwrap(); |
| 2266 | let bundle = parse_bundle_str( |
| 2267 | "schema_version = 1\nkind = 'codewhale.portable-config'\n[global]\ndefault_text_model = 'GLM-5.3'\n[global.providers.zai]\nmodel = 'GLM-5.4'\n", |
| 2268 | "conflict.toml", |
| 2269 | ).unwrap(); |
| 2270 | let prepared = prepare_import(&bundle, &store, BundleScope::Global).unwrap(); |
| 2271 | assert!( |
| 2272 | prepared |
| 2273 | .plan |
| 2274 | .conflicting |
| 2275 | .iter() |
| 2276 | .any(|key| key == "global.providers.zai.model") |
| 2277 | ); |
| 2278 | let error = apply_prepared_bundle(prepared, &mut store, save_candidate) |
| 2279 | .expect_err("conflicting aliases must be refused"); |
| 2280 | assert!(error.to_string().contains("conflicting")); |
| 2281 | assert!(!error.to_string().contains("GLM-5.4")); |
| 2282 | assert_eq!(std::fs::read_to_string(path).unwrap(), original); |
| 2283 | assert_eq!( |
| 2284 | std::fs::read_dir(dir.path()).unwrap().count(), |
| 2285 | 1, |
| 2286 | "no backup or staged write before validation" |
| 2287 | ); |
| 2288 | } |
| 2289 | |
| 2290 | #[test] |
| 2291 | fn prepared_import_keeps_configstore_cas_against_concurrent_edits() { |
| 2292 | let dir = tempfile::tempdir().expect("config dir"); |
| 2293 | let path = dir.path().join("config.toml"); |
| 2294 | std::fs::write(&path, "provider = 'deepseek'\n").unwrap(); |
| 2295 | let mut store = ConfigStore::load(Some(path.clone())).unwrap(); |
| 2296 | let prepared = prepare_import(&sample_bundle(), &store, BundleScope::Global).unwrap(); |
| 2297 | let concurrent = "provider = 'openai'\n# concurrent writer\n"; |
| 2298 | std::fs::write(&path, concurrent).unwrap(); |
| 2299 | apply_prepared_bundle(prepared, &mut store, save_candidate) |
| 2300 | .expect_err("stale preview must fail closed"); |
| 2301 | assert_eq!(std::fs::read_to_string(path).unwrap(), concurrent); |
| 2302 | } |
| 2303 | |
| 2304 | #[test] |
| 2305 | fn route_migration_receipts_are_local_and_not_portable() { |
| 2306 | let bundle = parse_bundle_str( |
| 2307 | "schema_version = 1\nkind = 'codewhale.portable-config'\n[global]\nroute_preferences_version = 1\n[global.route_preferences_migration]\nprevious_provider = 'zai'\n", |
| 2308 | "receipt.toml", |
| 2309 | ).unwrap(); |
| 2310 | assert_eq!(find_rejected_entries(&bundle).len(), 2); |
| 2311 | let config: ConfigToml = toml::from_str( |
| 2312 | "route_preferences_version = 1\n[route_preferences_migration]\nprevious_provider = 'zai'\n", |
| 2313 | ).unwrap(); |
| 2314 | let exported = |
| 2315 | export_bundle(&config, BundleScope::Global, BundleMetadata::default()).unwrap(); |
| 2316 | assert!( |
| 2317 | !exported |
| 2318 | .global |
| 2319 | .entries |
| 2320 | .contains_key("route_preferences_version") |
| 2321 | ); |
| 2322 | assert!( |
| 2323 | !exported |
| 2324 | .global |
| 2325 | .entries |
| 2326 | .contains_key("route_preferences_migration") |
| 2327 | ); |
| 2328 | } |
| 2329 | |
| 2330 | #[test] |
| 2331 | fn canonical_route_export_omits_shadowed_roots_and_round_trips_provider_slots() { |
| 2332 | let config: ConfigToml = toml::from_str( |
| 2333 | "provider = 'zai'\ndefault_text_model = 'deepseek-v4-pro'\nmodel = 'old-root-model'\n[providers.zai]\nmodel = 'GLM-5.3'\n[providers.deepseek]\nmodel = 'deepseek-v4-flash'\n[providers.openai]\nmodel = 'gpt-4.1'\n", |
| 2334 | ).unwrap(); |
| 2335 | let bundle = |
| 2336 | export_bundle(&config, BundleScope::Global, BundleMetadata::default()).unwrap(); |
| 2337 | assert!(!bundle.global.entries.contains_key("model")); |
| 2338 | assert!(!bundle.global.entries.contains_key("default_text_model")); |
| 2339 | let dir = tempfile::tempdir().expect("config dir"); |
| 2340 | let mut store = ConfigStore::load(Some(dir.path().join("config.toml"))).unwrap(); |
| 2341 | let receipt = apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()) |
| 2342 | .expect("canonical export must import without alias conflicts"); |
| 2343 | assert!(receipt.plan.conflicting.is_empty()); |
| 2344 | assert_eq!(store.config.provider_id(), "zai"); |
| 2345 | assert_eq!( |
| 2346 | store.config.get_value("providers.zai.model").as_deref(), |
| 2347 | Some("GLM-5.3") |
| 2348 | ); |
| 2349 | assert_eq!( |
| 2350 | store |
| 2351 | .config |
| 2352 | .get_value("providers.deepseek.model") |
| 2353 | .as_deref(), |
| 2354 | Some("deepseek-v4-flash") |
| 2355 | ); |
| 2356 | assert_eq!( |
| 2357 | store.config.get_value("providers.openai.model").as_deref(), |
| 2358 | Some("gpt-4.1") |
| 2359 | ); |
| 2360 | let again = export_bundle( |
| 2361 | &store.config, |
| 2362 | BundleScope::Global, |
| 2363 | BundleMetadata::default(), |
| 2364 | ) |
| 2365 | .unwrap(); |
| 2366 | assert_eq!( |
| 2367 | serialize_bundle(&again).unwrap(), |
| 2368 | serialize_bundle(&bundle).unwrap() |
| 2369 | ); |
| 2370 | |
| 2371 | let root_only: ConfigToml = |
| 2372 | toml::from_str("default_text_model = 'deepseek-v4-pro'\n").unwrap(); |
| 2373 | let legacy = |
| 2374 | export_bundle(&root_only, BundleScope::Global, BundleMetadata::default()).unwrap(); |
| 2375 | assert_eq!( |
| 2376 | legacy |
| 2377 | .global |
| 2378 | .entries |
| 2379 | .get("default_text_model") |
| 2380 | .and_then(toml::Value::as_str), |
| 2381 | Some("deepseek-v4-pro") |
| 2382 | ); |
| 2383 | let literal_custom = config_from_document( |
| 2384 | "provider = 'custom'\nbase_url = 'https://literal.example.test/v1'\ndefault_text_model = 'LiteralRootModel'\n", |
| 2385 | ).unwrap(); |
| 2386 | let literal_export = export_bundle( |
| 2387 | &literal_custom, |
| 2388 | BundleScope::Global, |
| 2389 | BundleMetadata::default(), |
| 2390 | ) |
| 2391 | .unwrap(); |
| 2392 | // The literal route's top-level fields became `[providers.custom]` |
| 2393 | // when parsed (#6394); its model survives the export. |
| 2394 | assert!( |
| 2395 | serialize_bundle(&literal_export) |
| 2396 | .unwrap() |
| 2397 | .contains("LiteralRootModel"), |
| 2398 | "{literal_export:#?}" |
| 2399 | ); |
| 2400 | } |
| 2401 | |
| 2402 | #[test] |
| 2403 | fn export_reconciles_a_legacy_root_default_model_with_the_deepseek_slot() { |
| 2404 | // Migration writes the canonical slot but never removes a legacy root |
| 2405 | // `default_model`; on import that alias also targets the DeepSeek slot, |
| 2406 | // so a raw export would conflict with itself. |
| 2407 | let config: ConfigToml = toml::from_str( |
| 2408 | "provider = 'deepseek'\ndefault_model = 'deepseek-v4-flash'\n[providers.deepseek]\nmodel = 'deepseek-v4-pro'\n", |
| 2409 | ) |
| 2410 | .unwrap(); |
| 2411 | let bundle = |
| 2412 | export_bundle(&config, BundleScope::Global, BundleMetadata::default()).unwrap(); |
| 2413 | assert!(!bundle.global.entries.contains_key("default_model")); |
| 2414 | let providers = bundle |
| 2415 | .global |
| 2416 | .entries |
| 2417 | .get("providers") |
| 2418 | .and_then(toml::Value::as_table) |
| 2419 | .expect("providers table"); |
| 2420 | assert_eq!( |
| 2421 | providers["deepseek"]["model"].as_str(), |
| 2422 | Some("deepseek-v4-pro") |
| 2423 | ); |
| 2424 | |
| 2425 | let dir = tempfile::tempdir().expect("config dir"); |
| 2426 | let mut store = ConfigStore::load(Some(dir.path().join("config.toml"))).unwrap(); |
| 2427 | let receipt = apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()) |
| 2428 | .expect("export must import without alias conflicts"); |
| 2429 | assert!(receipt.plan.conflicting.is_empty(), "{:?}", receipt.plan); |
| 2430 | assert_eq!( |
| 2431 | store |
| 2432 | .config |
| 2433 | .get_value("providers.deepseek.model") |
| 2434 | .as_deref(), |
| 2435 | Some("deepseek-v4-pro") |
| 2436 | ); |
| 2437 | |
| 2438 | // Without a canonical slot the root alias folds into the DeepSeek slot. |
| 2439 | let config: ConfigToml = toml::from_str( |
| 2440 | "provider = 'zai'\ndefault_model = 'deepseek-v4-flash'\n[providers.zai]\nmodel = 'GLM-5.3'\n", |
| 2441 | ) |
| 2442 | .unwrap(); |
| 2443 | let bundle = |
| 2444 | export_bundle(&config, BundleScope::Global, BundleMetadata::default()).unwrap(); |
| 2445 | assert!(!bundle.global.entries.contains_key("default_model")); |
| 2446 | let providers = bundle |
| 2447 | .global |
| 2448 | .entries |
| 2449 | .get("providers") |
| 2450 | .and_then(toml::Value::as_table) |
| 2451 | .expect("providers table"); |
| 2452 | assert_eq!( |
| 2453 | providers["deepseek"]["model"].as_str(), |
| 2454 | Some("deepseek-v4-flash") |
| 2455 | ); |
| 2456 | assert_eq!(providers["zai"]["model"].as_str(), Some("GLM-5.3")); |
| 2457 | } |
| 2458 | |
| 2459 | #[test] |
| 2460 | fn export_preserves_the_deepseek_root_fallback_when_another_route_is_active() { |
| 2461 | // With Z.ai active, a DeepSeek-id root `default_text_model` is |
| 2462 | // DeepSeek's saved fallback, not shadowed state; the active route's |
| 2463 | // canonical slot must not cause it to be dropped. |
| 2464 | let config: ConfigToml = toml::from_str( |
| 2465 | "provider = 'zai'\ndefault_text_model = 'deepseek-v4-flash'\n[providers.zai]\nmodel = 'GLM-5.3'\n", |
| 2466 | ) |
| 2467 | .unwrap(); |
| 2468 | let bundle = |
| 2469 | export_bundle(&config, BundleScope::Global, BundleMetadata::default()).unwrap(); |
| 2470 | assert!(!bundle.global.entries.contains_key("default_text_model")); |
| 2471 | let providers = bundle |
| 2472 | .global |
| 2473 | .entries |
| 2474 | .get("providers") |
| 2475 | .and_then(toml::Value::as_table) |
| 2476 | .expect("providers table"); |
| 2477 | assert_eq!( |
| 2478 | providers["deepseek"]["model"].as_str(), |
| 2479 | Some("deepseek-v4-flash") |
| 2480 | ); |
| 2481 | assert_eq!(providers["zai"]["model"].as_str(), Some("GLM-5.3")); |
| 2482 | |
| 2483 | let dir = tempfile::tempdir().expect("config dir"); |
| 2484 | let mut store = ConfigStore::load(Some(dir.path().join("config.toml"))).unwrap(); |
| 2485 | let receipt = apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()) |
| 2486 | .expect("export must import without alias conflicts"); |
| 2487 | assert!(receipt.plan.conflicting.is_empty(), "{:?}", receipt.plan); |
| 2488 | assert_eq!( |
| 2489 | store |
| 2490 | .config |
| 2491 | .get_value("providers.deepseek.model") |
| 2492 | .as_deref(), |
| 2493 | Some("deepseek-v4-flash") |
| 2494 | ); |
| 2495 | |
| 2496 | // A root alias the active route still consumes stays shadowed state and |
| 2497 | // is dropped; a canonical DeepSeek leaf wins over a duplicate root |
| 2498 | // fallback. |
| 2499 | let config: ConfigToml = toml::from_str( |
| 2500 | "provider = 'zai'\ndefault_text_model = 'deepseek-v4-pro'\nmodel = 'GLM-5.1'\n[providers.zai]\nmodel = 'GLM-5.3'\n[providers.deepseek]\nmodel = 'deepseek-v4-flash'\n", |
| 2501 | ) |
| 2502 | .unwrap(); |
| 2503 | let bundle = |
| 2504 | export_bundle(&config, BundleScope::Global, BundleMetadata::default()).unwrap(); |
| 2505 | assert!(!bundle.global.entries.contains_key("model")); |
| 2506 | assert!(!bundle.global.entries.contains_key("default_text_model")); |
| 2507 | let providers = bundle |
| 2508 | .global |
| 2509 | .entries |
| 2510 | .get("providers") |
| 2511 | .and_then(toml::Value::as_table) |
| 2512 | .expect("providers table"); |
| 2513 | assert_eq!( |
| 2514 | providers["deepseek"]["model"].as_str(), |
| 2515 | Some("deepseek-v4-flash") |
| 2516 | ); |
| 2517 | } |
| 2518 | |
| 2519 | #[test] |
| 2520 | fn imports_preserve_exact_builtin_shadowing_custom_provider_identity() { |
| 2521 | let dir = tempfile::tempdir().expect("config dir"); |
| 2522 | let path = dir.path().join("config.toml"); |
| 2523 | std::fs::write( |
| 2524 | &path, |
| 2525 | "provider = 'OpenAI'\n[providers.OpenAI]\nkind = 'openai-compatible'\nbase_url = 'https://custom.example.test/v1'\nmodel = 'LiteralOldModel'\n[providers.openai]\nmodel = 'gpt-4.1'\n", |
| 2526 | ).unwrap(); |
| 2527 | let mut store = ConfigStore::load(Some(path.clone())).unwrap(); |
| 2528 | for (entries, expected_model) in [ |
| 2529 | ("verbosity = 'concise'\n", "LiteralOldModel"), |
| 2530 | ( |
| 2531 | "provider = 'OpenAI'\nmodel = 'LiteralNewModel'\nlog_level = 'debug'\n", |
| 2532 | "LiteralNewModel", |
| 2533 | ), |
| 2534 | ] { |
| 2535 | let bundle = parse_bundle_str( |
| 2536 | &format!( |
| 2537 | "schema_version = 1\nkind = 'codewhale.portable-config'\n[global]\n{entries}" |
| 2538 | ), |
| 2539 | "custom.toml", |
| 2540 | ) |
| 2541 | .unwrap(); |
| 2542 | apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()).unwrap(); |
| 2543 | let saved: toml::Value = |
| 2544 | toml::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); |
| 2545 | assert_eq!(saved["provider"].as_str(), Some("OpenAI")); |
| 2546 | assert_eq!( |
| 2547 | saved["providers"]["OpenAI"]["model"].as_str(), |
| 2548 | Some(expected_model) |
| 2549 | ); |
| 2550 | assert_eq!( |
| 2551 | saved["providers"]["OpenAI"]["base_url"].as_str(), |
| 2552 | Some("https://custom.example.test/v1") |
| 2553 | ); |
| 2554 | assert_eq!( |
| 2555 | saved["providers"]["openai"]["model"].as_str(), |
| 2556 | Some("gpt-4.1") |
| 2557 | ); |
| 2558 | store.reload().unwrap(); |
| 2559 | assert_eq!( |
| 2560 | store.config.provider, |
| 2561 | codewhale_config::ProviderKind::Custom |
| 2562 | ); |
| 2563 | assert_eq!(store.config.provider_id(), "OpenAI"); |
| 2564 | assert_eq!( |
| 2565 | codewhale_engine::route_preferences::get(&path, "provider") |
| 2566 | .unwrap() |
| 2567 | .as_deref(), |
| 2568 | Some("OpenAI") |
| 2569 | ); |
| 2570 | } |
| 2571 | } |
| 2572 | |
| 2573 | #[test] |
| 2574 | fn imports_preserve_regional_selector_and_canonical_model_slot() { |
| 2575 | let dir = tempfile::tempdir().expect("config dir"); |
| 2576 | let path = dir.path().join("config.toml"); |
| 2577 | std::fs::write( |
| 2578 | &path, |
| 2579 | "provider = 'deepseek-cn'\n[providers.deepseek_cn]\nmodel = 'deepseek-v4-pro'\n[providers.deepseek]\nmodel = 'deepseek-v4-pro'\n", |
| 2580 | ).unwrap(); |
| 2581 | let mut store = ConfigStore::load(Some(path.clone())).unwrap(); |
| 2582 | for (entries, expected_model) in [ |
| 2583 | ("verbosity = 'concise'\n", "deepseek-v4-pro"), |
| 2584 | ( |
| 2585 | "'providers.deepseek_cn.model' = 'deepseek-v4-flash'\n", |
| 2586 | "deepseek-v4-flash", |
| 2587 | ), |
| 2588 | ] { |
| 2589 | let bundle = parse_bundle_str( |
| 2590 | &format!( |
| 2591 | "schema_version = 1\nkind = 'codewhale.portable-config'\n[global]\n{entries}" |
| 2592 | ), |
| 2593 | "regional.toml", |
| 2594 | ) |
| 2595 | .unwrap(); |
| 2596 | apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()).unwrap(); |
| 2597 | let saved: toml::Value = |
| 2598 | toml::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); |
| 2599 | assert_eq!(saved["provider"].as_str(), Some("deepseek-cn")); |
| 2600 | assert_eq!( |
| 2601 | saved["providers"]["deepseek_cn"]["model"].as_str(), |
| 2602 | Some(expected_model) |
| 2603 | ); |
| 2604 | assert_eq!( |
| 2605 | saved["providers"]["deepseek"]["model"].as_str(), |
| 2606 | Some("deepseek-v4-pro") |
| 2607 | ); |
| 2608 | store.reload().unwrap(); |
| 2609 | assert_eq!(store.config.provider_id(), "deepseek-cn"); |
| 2610 | assert_eq!( |
| 2611 | codewhale_engine::route_preferences::get(&path, "model") |
| 2612 | .unwrap() |
| 2613 | .as_deref(), |
| 2614 | Some(expected_model) |
| 2615 | ); |
| 2616 | let mut export_config = store.config.clone(); |
| 2617 | export_config.default_text_model = Some("stale-regional-root".to_string()); |
| 2618 | let exported = export_bundle( |
| 2619 | &export_config, |
| 2620 | BundleScope::Global, |
| 2621 | BundleMetadata::default(), |
| 2622 | ) |
| 2623 | .unwrap(); |
| 2624 | assert!(!exported.global.entries.contains_key("default_text_model")); |
| 2625 | assert_eq!( |
| 2626 | exported |
| 2627 | .global |
| 2628 | .entries |
| 2629 | .get("provider") |
| 2630 | .and_then(toml::Value::as_str), |
| 2631 | Some("deepseek-cn") |
| 2632 | ); |
| 2633 | } |
| 2634 | } |
| 2635 | |
| 2636 | #[test] |
| 2637 | fn apply_is_idempotent_on_reimport() { |
| 2638 | let mut store = isolated_store(); |
| 2639 | let workspace = tempfile::tempdir().expect("workspace"); |
| 2640 | let bundle = sample_bundle(); |
| 2641 | |
| 2642 | let first = apply_bundle(&bundle, &mut store, BundleScope::Global, workspace.path()) |
| 2643 | .expect("first import"); |
| 2644 | assert!(first.plan.added.len() + first.plan.changed.len() > 0); |
| 2645 | |
| 2646 | let second = apply_bundle(&bundle, &mut store, BundleScope::Global, workspace.path()) |
| 2647 | .expect("second import"); |
| 2648 | assert!( |
| 2649 | second.plan.is_no_op(), |
| 2650 | "re-import must be a no-op: {:?}", |
| 2651 | second.plan |
| 2652 | ); |
| 2653 | assert!(second.backup_path.is_none()); |
| 2654 | } |
| 2655 | |
| 2656 | #[test] |
| 2657 | fn immediate_mutating_imports_create_distinct_no_clobber_backups() { |
| 2658 | let dir = tempfile::tempdir().expect("config dir"); |
| 2659 | let path = dir.path().join("config.toml"); |
| 2660 | let original = b"verbosity = \"concise\"\n"; |
| 2661 | std::fs::write(&path, original).expect("seed config"); |
| 2662 | #[cfg(unix)] |
| 2663 | { |
| 2664 | use std::os::unix::fs::PermissionsExt as _; |
| 2665 | std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)) |
| 2666 | .expect("restrict target permissions"); |
| 2667 | } |
| 2668 | let mut store = ConfigStore::load(Some(path.clone())).expect("store loads"); |
| 2669 | let first_bundle = parse_bundle_str( |
| 2670 | r#" |
| 2671 | schema_version = 1 |
| 2672 | kind = "codewhale.portable-config" |
| 2673 | |
| 2674 | [global] |
| 2675 | verbosity = "normal" |
| 2676 | "#, |
| 2677 | "first.toml", |
| 2678 | ) |
| 2679 | .expect("first bundle parses"); |
| 2680 | let first = apply_bundle(&first_bundle, &mut store, BundleScope::Global, dir.path()) |
| 2681 | .expect("first import"); |
| 2682 | let first_backup = first.backup_path.expect("first backup receipt"); |
| 2683 | assert_eq!( |
| 2684 | std::fs::read(&first_backup).expect("first backup"), |
| 2685 | original |
| 2686 | ); |
| 2687 | let after_first = std::fs::read(&path).expect("target after first import"); |
| 2688 | |
| 2689 | let second_bundle = parse_bundle_str( |
| 2690 | r#" |
| 2691 | schema_version = 1 |
| 2692 | kind = "codewhale.portable-config" |
| 2693 | |
| 2694 | [global] |
| 2695 | log_level = "trace" |
| 2696 | "#, |
| 2697 | "second.toml", |
| 2698 | ) |
| 2699 | .expect("second bundle parses"); |
| 2700 | let second = apply_bundle(&second_bundle, &mut store, BundleScope::Global, dir.path()) |
| 2701 | .expect("second import"); |
| 2702 | let second_backup = second.backup_path.expect("second backup receipt"); |
| 2703 | assert_ne!(first_backup, second_backup, "backups must never collide"); |
| 2704 | assert_eq!( |
| 2705 | std::fs::read(&second_backup).expect("second backup"), |
| 2706 | after_first, |
| 2707 | "second receipt must preserve its exact pre-import document" |
| 2708 | ); |
| 2709 | assert_eq!( |
| 2710 | std::fs::read(&first_backup).expect("first backup remains"), |
| 2711 | original, |
| 2712 | "second import must not overwrite the first receipt" |
| 2713 | ); |
| 2714 | for backup in [&first_backup, &second_backup] { |
| 2715 | assert!( |
| 2716 | backup |
| 2717 | .file_name() |
| 2718 | .and_then(|name| name.to_str()) |
| 2719 | .is_some_and(|name| name.contains(".bundle-backup-")), |
| 2720 | "unexpected backup name: {}", |
| 2721 | backup.display() |
| 2722 | ); |
| 2723 | #[cfg(unix)] |
| 2724 | { |
| 2725 | use std::os::unix::fs::PermissionsExt as _; |
| 2726 | assert_eq!( |
| 2727 | std::fs::metadata(backup) |
| 2728 | .expect("backup metadata") |
| 2729 | .permissions() |
| 2730 | .mode() |
| 2731 | & 0o777, |
| 2732 | 0o600, |
| 2733 | "backup must preserve restrictive target permissions" |
| 2734 | ); |
| 2735 | } |
| 2736 | } |
| 2737 | } |
| 2738 | |
| 2739 | #[test] |
| 2740 | fn closed_choice_imports_refuse_before_backup_or_write() { |
| 2741 | for key in ["approval_policy", "sandbox_mode", "verbosity"] { |
| 2742 | for value in [ |
| 2743 | toml::Value::String("misspelled-choice".into()), |
| 2744 | toml::Value::Boolean(true), |
| 2745 | ] { |
| 2746 | for existing in [false, true] { |
| 2747 | let dir = tempfile::tempdir().unwrap(); |
| 2748 | let path = dir.path().join("config.toml"); |
| 2749 | let original = b"# Preserve this document exactly\nverbosity = 'normal'\n"; |
| 2750 | if existing { |
| 2751 | std::fs::write(&path, original).unwrap(); |
| 2752 | } |
| 2753 | let mut store = ConfigStore::load(Some(path.clone())).unwrap(); |
| 2754 | let before = toml::to_string(&store.config).unwrap(); |
| 2755 | let mut bundle = sample_bundle(); |
| 2756 | bundle.preferences.entries.clear(); |
| 2757 | bundle.global.entries.clear(); |
| 2758 | bundle.preferences.entries.insert(key.into(), value.clone()); |
| 2759 | // Even an earlier valid candidate edit must not reach the store. |
| 2760 | bundle |
| 2761 | .preferences |
| 2762 | .entries |
| 2763 | .insert("log_level".into(), toml::Value::String("info".into())); |
| 2764 | let error = apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()) |
| 2765 | .expect_err("closed choice must fail before the transaction"); |
| 2766 | assert!(error.to_string().contains(key), "{error:#}"); |
| 2767 | assert_eq!(toml::to_string(&store.config).unwrap(), before); |
| 2768 | assert_eq!(path.exists(), existing); |
| 2769 | if existing { |
| 2770 | assert_eq!(std::fs::read(&path).unwrap(), original); |
| 2771 | } |
| 2772 | assert!( |
| 2773 | std::fs::read_dir(dir.path()) |
| 2774 | .unwrap() |
| 2775 | .all(|entry| { entry.unwrap().path() == path }), |
| 2776 | "refusal must not create a backup or another file" |
| 2777 | ); |
| 2778 | } |
| 2779 | } |
| 2780 | } |
| 2781 | } |
| 2782 | |
| 2783 | #[test] |
| 2784 | fn closed_choice_imports_accept_reader_values_without_revalidating_old_fields() { |
| 2785 | // Trust posture is intentionally machine-bound and rejected by the |
| 2786 | // bundle boundary even when its value is otherwise valid. Exercise |
| 2787 | // the portable closed choice here; authority rejection has its own |
| 2788 | // no-write and export-scrubbing regressions below. |
| 2789 | for value in [" CONCISE ", "normal"] { |
| 2790 | let key = "verbosity"; |
| 2791 | let dir = tempfile::tempdir().unwrap(); |
| 2792 | let path = dir.path().join("config.toml"); |
| 2793 | // Loading and unrelated round trips still preserve legacy text; only |
| 2794 | // the value being written gets the shared closed-choice validation. |
| 2795 | let original = |
| 2796 | "# Preserve old fields\napproval_policy = 'legacy-unknown'\nverbosity = 'quiet'\n"; |
| 2797 | std::fs::write(&path, original).unwrap(); |
| 2798 | let mut store = ConfigStore::load(Some(path.clone())).unwrap(); |
| 2799 | assert_eq!(std::fs::read_to_string(&path).unwrap(), original); |
| 2800 | let mut bundle = sample_bundle(); |
| 2801 | bundle.preferences.entries.clear(); |
| 2802 | bundle.global.entries.clear(); |
| 2803 | bundle |
| 2804 | .preferences |
| 2805 | .entries |
| 2806 | .insert(key.into(), toml::Value::String(value.into())); |
| 2807 | let receipt = |
| 2808 | apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()).unwrap(); |
| 2809 | assert_eq!( |
| 2810 | std::fs::read_to_string(receipt.backup_path.unwrap()).unwrap(), |
| 2811 | original |
| 2812 | ); |
| 2813 | let reloaded = ConfigStore::load(Some(path)).unwrap(); |
| 2814 | assert_eq!(reloaded.config.get_value(key).as_deref(), Some(value)); |
| 2815 | assert_eq!( |
| 2816 | reloaded.config.approval_policy.as_deref(), |
| 2817 | Some("legacy-unknown") |
| 2818 | ); |
| 2819 | } |
| 2820 | } |
| 2821 | |
| 2822 | #[test] |
| 2823 | fn non_no_op_import_creates_a_missing_config_without_a_backup() { |
| 2824 | let dir = tempfile::tempdir().expect("config dir"); |
| 2825 | let path = dir.path().join("config.toml"); |
| 2826 | let mut store = ConfigStore::load(Some(path.clone())).expect("missing config loads"); |
| 2827 | assert!(!path.exists(), "load must not create the config"); |
| 2828 | |
| 2829 | let receipt = apply_bundle( |
| 2830 | &sample_bundle(), |
| 2831 | &mut store, |
| 2832 | BundleScope::Global, |
| 2833 | dir.path(), |
| 2834 | ) |
| 2835 | .expect("import creates config"); |
| 2836 | |
| 2837 | assert!(path.is_file(), "non-no-op import must create the config"); |
| 2838 | assert!( |
| 2839 | receipt.backup_path.is_none(), |
| 2840 | "no prior file means no backup" |
| 2841 | ); |
| 2842 | let reloaded = ConfigStore::load(Some(path)).expect("created config reloads"); |
| 2843 | assert_eq!(reloaded.config.verbosity.as_deref(), Some("concise")); |
| 2844 | assert_eq!(reloaded.config.log_level.as_deref(), Some("debug")); |
| 2845 | } |
| 2846 | |
| 2847 | #[test] |
| 2848 | fn failed_import_removes_a_config_created_during_the_transaction() { |
| 2849 | let dir = tempfile::tempdir().expect("config dir"); |
| 2850 | let path = dir.path().join("config.toml"); |
| 2851 | let mut store = ConfigStore::load(Some(path.clone())).expect("missing config loads"); |
| 2852 | |
| 2853 | let prepared = |
| 2854 | prepare_import(&sample_bundle(), &store, BundleScope::Global).expect("prepare import"); |
| 2855 | let error = |
| 2856 | apply_prepared_bundle(prepared, &mut store, |candidate, store, target_written| { |
| 2857 | save_candidate(candidate, store, target_written)?; |
| 2858 | bail!("forced failure after the new document was saved") |
| 2859 | }) |
| 2860 | .expect_err("forced post-save failure must roll back"); |
| 2861 | |
| 2862 | assert!(error.to_string().contains("rolled back"), "{error:#}"); |
| 2863 | assert!( |
| 2864 | !path.exists(), |
| 2865 | "rollback must remove the newly-created file" |
| 2866 | ); |
| 2867 | assert_eq!( |
| 2868 | store.config.verbosity, None, |
| 2869 | "in-memory state also rolls back" |
| 2870 | ); |
| 2871 | } |
| 2872 | |
| 2873 | #[test] |
| 2874 | fn project_scope_never_touches_the_global_document() { |
| 2875 | let mut store = isolated_store(); |
| 2876 | let global_before = std::fs::read_to_string(store.path()).expect("global doc"); |
| 2877 | |
| 2878 | let text = r#" |
| 2879 | schema_version = 1 |
| 2880 | kind = "codewhale.portable-config" |
| 2881 | |
| 2882 | [project] |
| 2883 | verbosity = "quiet" |
| 2884 | "#; |
| 2885 | let bundle = parse_bundle_str(text, "t.toml").expect("bundle"); |
| 2886 | assert!(find_rejected_entries(&bundle).is_empty()); |
| 2887 | let ws = tempfile::tempdir().expect("ws"); |
| 2888 | apply_bundle(&bundle, &mut store, BundleScope::Project, ws.path()) |
| 2889 | .expect_err("project entries cannot land in a global-scoped store"); |
| 2890 | let global_after = std::fs::read_to_string(store.path()).expect("global doc"); |
| 2891 | assert_eq!(global_before, global_after); |
| 2892 | } |
| 2893 | |
| 2894 | #[cfg(unix)] |
| 2895 | #[test] |
| 2896 | fn failed_apply_rolls_back_to_the_prior_document() { |
| 2897 | let mut store = isolated_store(); |
| 2898 | let original = std::fs::read_to_string(store.path()).expect("config"); |
| 2899 | |
| 2900 | // A bundle whose entry fails mid-apply: `providers.deepseek.wire` is a |
| 2901 | // real key path but an invalid value for it, so set_value errors after |
| 2902 | // earlier entries were applied. |
| 2903 | let text = r#" |
| 2904 | schema_version = 1 |
| 2905 | kind = "codewhale.portable-config" |
| 2906 | |
| 2907 | [preferences] |
| 2908 | log_level = "debug" |
| 2909 | |
| 2910 | [global] |
| 2911 | providers_deepseek_wire = "not-a-real-key-so-this-errors" |
| 2912 | "#; |
| 2913 | let _ = text; |
| 2914 | // Simpler deterministic failure: make the target file read-only. |
| 2915 | let text_ok = r#" |
| 2916 | schema_version = 1 |
| 2917 | kind = "codewhale.portable-config" |
| 2918 | |
| 2919 | [preferences] |
| 2920 | log_level = "debug" |
| 2921 | "#; |
| 2922 | let bundle = parse_bundle_str(text_ok, "t.toml").expect("bundle"); |
| 2923 | let path = store.path().to_path_buf(); |
| 2924 | // Atomic saves replace the file via rename, so the *directory* must |
| 2925 | // be made unwritable to force the write failure. |
| 2926 | use std::os::unix::fs::PermissionsExt; |
| 2927 | let dir = path.parent().expect("config dir").to_path_buf(); |
| 2928 | let mut perms = std::fs::metadata(&dir).expect("dir meta").permissions(); |
| 2929 | perms.set_mode(0o555); |
| 2930 | std::fs::set_permissions(&dir, perms).expect("chmod dir"); |
| 2931 | |
| 2932 | let result = apply_bundle(&bundle, &mut store, BundleScope::Global, Path::new(".")); |
| 2933 | // Restore permissions so the tempdir can be cleaned up. |
| 2934 | let mut perms = std::fs::metadata(&dir).expect("dir meta").permissions(); |
| 2935 | perms.set_mode(0o755); |
| 2936 | std::fs::set_permissions(&dir, perms).expect("chmod restore"); |
| 2937 | |
| 2938 | assert!(result.is_err(), "apply must fail on a read-only document"); |
| 2939 | let restored = std::fs::read_to_string(&path).expect("config after rollback"); |
| 2940 | assert_eq!(restored, original, "rollback must preserve the prior bytes"); |
| 2941 | } |
| 2942 | |
| 2943 | #[test] |
| 2944 | fn export_is_deterministic_and_secret_free() { |
| 2945 | let mut store = isolated_store(); |
| 2946 | store |
| 2947 | .config |
| 2948 | .set_value("verbosity", "concise") |
| 2949 | .expect("set verbosity"); |
| 2950 | store |
| 2951 | .config |
| 2952 | .set_value("default_text_model", "deepseek-v4-pro") |
| 2953 | .expect("set model"); |
| 2954 | store.save().expect("save"); |
| 2955 | |
| 2956 | let metadata = BundleMetadata::default(); |
| 2957 | let one = export_bundle(&store.config, BundleScope::Global, metadata.clone()) |
| 2958 | .and_then(|b| serialize_bundle(&b)) |
| 2959 | .expect("export one"); |
| 2960 | let two = export_bundle(&store.config, BundleScope::Global, metadata) |
| 2961 | .and_then(|b| serialize_bundle(&b)) |
| 2962 | .expect("export two"); |
| 2963 | assert_eq!(one, two, "export must be deterministic"); |
| 2964 | |
| 2965 | // No machine-specific absolute paths in the body. |
| 2966 | assert!(!one.contains("/Users/"), "{one}"); |
| 2967 | assert!(!one.contains("/home/"), "{one}"); |
| 2968 | } |
| 2969 | |
| 2970 | #[test] |
| 2971 | fn export_preserves_typed_structured_config_and_toml_value_kinds() { |
| 2972 | let config: ConfigToml = toml::from_str( |
| 2973 | r#" |
| 2974 | provider = "deepseek" |
| 2975 | telemetry = false |
| 2976 | retry_count = 3 |
| 2977 | ratio = 1.25 |
| 2978 | started_at = 1979-05-27T07:32:00Z |
| 2979 | labels = ["alpha", "beta"] |
| 2980 | |
| 2981 | [skills] |
| 2982 | registry_url = "https://registry.example/skills.json" |
| 2983 | max_install_size_bytes = 12345 |
| 2984 | |
| 2985 | [snapshots] |
| 2986 | enabled = false |
| 2987 | max_age_days = 11 |
| 2988 | |
| 2989 | [portable_table] |
| 2990 | enabled = true |
| 2991 | count = 4 |
| 2992 | "#, |
| 2993 | ) |
| 2994 | .expect("typed config parses"); |
| 2995 | |
| 2996 | let bundle = export_bundle(&config, BundleScope::Global, BundleMetadata::default()) |
| 2997 | .expect("typed export"); |
| 2998 | assert!(matches!( |
| 2999 | bundle.preferences.entries.get("skills"), |
| 3000 | Some(toml::Value::Table(_)) |
| 3001 | )); |
| 3002 | assert!(matches!( |
| 3003 | bundle.preferences.entries.get("snapshots"), |
| 3004 | Some(toml::Value::Table(_)) |
| 3005 | )); |
| 3006 | assert!(matches!( |
| 3007 | bundle.global.entries.get("telemetry"), |
| 3008 | Some(toml::Value::Boolean(false)) |
| 3009 | )); |
| 3010 | assert!(matches!( |
| 3011 | bundle.global.entries.get("retry_count"), |
| 3012 | Some(toml::Value::Integer(3)) |
| 3013 | )); |
| 3014 | assert!(matches!( |
| 3015 | bundle.global.entries.get("ratio"), |
| 3016 | Some(toml::Value::Float(value)) if *value == 1.25 |
| 3017 | )); |
| 3018 | assert!( |
| 3019 | matches!( |
| 3020 | bundle.global.entries.get("started_at"), |
| 3021 | Some(toml::Value::Datetime(_)) |
| 3022 | ), |
| 3023 | "{bundle:#?}" |
| 3024 | ); |
| 3025 | |
| 3026 | let dir = tempfile::tempdir().expect("round-trip dir"); |
| 3027 | let path = dir.path().join("config.toml"); |
| 3028 | let mut store = ConfigStore::load(Some(path.clone())).expect("fresh store"); |
| 3029 | apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()) |
| 3030 | .expect("typed bundle imports"); |
| 3031 | let reloaded = ConfigStore::load(Some(path)).expect("typed config reloads"); |
| 3032 | let reexported = export_bundle( |
| 3033 | &reloaded.config, |
| 3034 | BundleScope::Global, |
| 3035 | BundleMetadata::default(), |
| 3036 | ) |
| 3037 | .expect("round-trip export"); |
| 3038 | assert_eq!( |
| 3039 | serialize_bundle(&reexported).expect("serialize round trip"), |
| 3040 | serialize_bundle(&bundle).expect("serialize original"), |
| 3041 | "typed portable config must round-trip without stringification or loss" |
| 3042 | ); |
| 3043 | let plan = plan_import(&bundle, &reloaded.config, BundleScope::Global); |
| 3044 | assert!( |
| 3045 | plan.is_no_op(), |
| 3046 | "typed re-import must be idempotent: {plan:?}" |
| 3047 | ); |
| 3048 | } |
| 3049 | |
| 3050 | #[test] |
| 3051 | fn typed_reimport_normalizes_omitted_serde_defaults_before_comparison() { |
| 3052 | let bundle = parse_bundle_str( |
| 3053 | r#" |
| 3054 | schema_version = 1 |
| 3055 | kind = "codewhale.portable-config" |
| 3056 | |
| 3057 | [preferences.snapshots] |
| 3058 | enabled = false |
| 3059 | "#, |
| 3060 | "defaults.toml", |
| 3061 | ) |
| 3062 | .expect("bundle with omitted typed default"); |
| 3063 | let dir = tempfile::tempdir().expect("config dir"); |
| 3064 | let path = dir.path().join("config.toml"); |
| 3065 | let mut store = ConfigStore::load(Some(path)).expect("fresh store"); |
| 3066 | apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()) |
| 3067 | .expect("first typed import"); |
| 3068 | |
| 3069 | assert_eq!( |
| 3070 | store |
| 3071 | .config |
| 3072 | .snapshots |
| 3073 | .as_ref() |
| 3074 | .expect("snapshots configured") |
| 3075 | .max_age_days, |
| 3076 | 7, |
| 3077 | "serde default must be materialized" |
| 3078 | ); |
| 3079 | let plan = plan_import(&bundle, &store.config, BundleScope::Global); |
| 3080 | assert!( |
| 3081 | plan.is_no_op(), |
| 3082 | "normalized re-import must be a no-op: {plan:?}" |
| 3083 | ); |
| 3084 | } |
| 3085 | |
| 3086 | #[test] |
| 3087 | fn telemetry_opt_out_round_trips_but_opt_in_consent_never_does() { |
| 3088 | let opted_in = ConfigToml { |
| 3089 | telemetry: Some(true), |
| 3090 | ..ConfigToml::default() |
| 3091 | }; |
| 3092 | let exported = export_bundle(&opted_in, BundleScope::Global, BundleMetadata::default()) |
| 3093 | .expect("opt-in export is safely omitted"); |
| 3094 | assert!( |
| 3095 | !exported.global.entries.contains_key("telemetry"), |
| 3096 | "opt-in consent must not be portable: {exported:?}" |
| 3097 | ); |
| 3098 | |
| 3099 | let opt_in_bundle = parse_bundle_str( |
| 3100 | r#" |
| 3101 | schema_version = 1 |
| 3102 | kind = "codewhale.portable-config" |
| 3103 | |
| 3104 | [global] |
| 3105 | telemetry = true |
| 3106 | "#, |
| 3107 | "telemetry-opt-in.toml", |
| 3108 | ) |
| 3109 | .expect("opt-in bundle parses before policy validation"); |
| 3110 | let rejected = find_rejected_entries(&opt_in_bundle); |
| 3111 | assert_eq!(rejected.len(), 1, "{rejected:?}"); |
| 3112 | assert!( |
| 3113 | rejected[0].reason.contains("opt-in consent"), |
| 3114 | "{rejected:?}" |
| 3115 | ); |
| 3116 | |
| 3117 | let dir = tempfile::tempdir().expect("config dir"); |
| 3118 | let path = dir.path().join("config.toml"); |
| 3119 | std::fs::write(&path, "verbosity = \"concise\"\n").expect("seed config"); |
| 3120 | let before = std::fs::read(&path).expect("config before refusal"); |
| 3121 | let mut store = ConfigStore::load(Some(path.clone())).expect("store loads"); |
| 3122 | apply_bundle(&opt_in_bundle, &mut store, BundleScope::Global, dir.path()) |
| 3123 | .expect_err("portable opt-in consent must be refused"); |
| 3124 | assert_eq!(std::fs::read(&path).expect("config after refusal"), before); |
| 3125 | assert_eq!(store.config.telemetry, None); |
| 3126 | |
| 3127 | let opt_out_bundle = parse_bundle_str( |
| 3128 | r#" |
| 3129 | schema_version = 1 |
| 3130 | kind = "codewhale.portable-config" |
| 3131 | |
| 3132 | [global] |
| 3133 | telemetry = false |
| 3134 | "#, |
| 3135 | "telemetry-opt-out.toml", |
| 3136 | ) |
| 3137 | .expect("opt-out bundle parses"); |
| 3138 | assert!(find_rejected_entries(&opt_out_bundle).is_empty()); |
| 3139 | apply_bundle(&opt_out_bundle, &mut store, BundleScope::Global, dir.path()) |
| 3140 | .expect("portable opt-out applies"); |
| 3141 | assert_eq!(store.config.telemetry, Some(false)); |
| 3142 | let reloaded = ConfigStore::load(Some(path)).expect("opt-out config reloads"); |
| 3143 | let plan = plan_import(&opt_out_bundle, &reloaded.config, BundleScope::Global); |
| 3144 | assert!( |
| 3145 | plan.is_no_op(), |
| 3146 | "opt-out re-import must be idempotent: {plan:?}" |
| 3147 | ); |
| 3148 | let reexported = export_bundle( |
| 3149 | &reloaded.config, |
| 3150 | BundleScope::Global, |
| 3151 | BundleMetadata::default(), |
| 3152 | ) |
| 3153 | .expect("opt-out re-exports"); |
| 3154 | assert_eq!( |
| 3155 | reexported.global.entries.get("telemetry"), |
| 3156 | Some(&toml::Value::Boolean(false)) |
| 3157 | ); |
| 3158 | } |
| 3159 | |
| 3160 | #[test] |
| 3161 | fn structured_import_deep_merges_without_erasing_local_authority() { |
| 3162 | let dir = tempfile::tempdir().expect("config dir"); |
| 3163 | let path = dir.path().join("config.toml"); |
| 3164 | let api_key_name = ["api", "_key"].concat(); |
| 3165 | let api_key_env_name = ["api", "_key_env"].concat(); |
| 3166 | let target = format!( |
| 3167 | r#" |
| 3168 | provider = "acme_gateway" |
| 3169 | |
| 3170 | [providers.acme_gateway] |
| 3171 | kind = "openai-compatible" |
| 3172 | base_url = "https://local-only.invalid/v1" |
| 3173 | model = "old-model" |
| 3174 | {api_key_name} = "opaque-local-api-value" |
| 3175 | {api_key_env_name} = "LOCAL_ACME_GATEWAY_KEY" |
| 3176 | |
| 3177 | [providers.acme_gateway.auth] |
| 3178 | source = "command" |
| 3179 | command = ["/synthetic/local-credential-helper"] |
| 3180 | |
| 3181 | [lsp] |
| 3182 | enabled = true |
| 3183 | include_warnings = false |
| 3184 | |
| 3185 | [lsp.servers] |
| 3186 | rust = ["/synthetic/local-rust-analyzer", "--stdio"] |
| 3187 | |
| 3188 | [lsp.custom.foo] |
| 3189 | language_id = "foo-language" |
| 3190 | command = "/synthetic/local-foo-lsp" |
| 3191 | args = ["--stdio"] |
| 3192 | |
| 3193 | [hook_sinks] |
| 3194 | unix_socket_path = "/synthetic/local-codewhale.sock" |
| 3195 | "# |
| 3196 | ); |
| 3197 | std::fs::write(&path, target).expect("seed local-authority config"); |
| 3198 | let mut store = ConfigStore::load(Some(path.clone())).expect("target config loads"); |
| 3199 | let bundle = parse_bundle_str( |
| 3200 | r#" |
| 3201 | schema_version = 1 |
| 3202 | kind = "codewhale.portable-config" |
| 3203 | |
| 3204 | [global] |
| 3205 | provider = "acme_gateway" |
| 3206 | |
| 3207 | [global.providers.acme_gateway] |
| 3208 | kind = "openai-compatible" |
| 3209 | model = "new-portable-model" |
| 3210 | |
| 3211 | [global.lsp] |
| 3212 | enabled = false |
| 3213 | include_warnings = true |
| 3214 | "#, |
| 3215 | "deep-merge.toml", |
| 3216 | ) |
| 3217 | .expect("portable update parses"); |
| 3218 | assert!(find_rejected_entries(&bundle).is_empty(), "{bundle:?}"); |
| 3219 | |
| 3220 | let receipt = apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()) |
| 3221 | .expect("portable values merge into target"); |
| 3222 | assert_eq!( |
| 3223 | receipt.plan.changed, |
| 3224 | ["global.lsp", "global.providers"], |
| 3225 | "{:?}", |
| 3226 | receipt.plan |
| 3227 | ); |
| 3228 | assert_eq!( |
| 3229 | receipt.plan.skipped, |
| 3230 | ["global.provider"], |
| 3231 | "{:?}", |
| 3232 | receipt.plan |
| 3233 | ); |
| 3234 | assert_eq!(store.config.provider_id(), "acme_gateway"); |
| 3235 | let document = config_document(&store.config).expect("merged typed document"); |
| 3236 | let acme = document |
| 3237 | .get("providers") |
| 3238 | .and_then(toml::Value::as_table) |
| 3239 | .and_then(|providers| providers.get("acme_gateway")) |
| 3240 | .and_then(toml::Value::as_table) |
| 3241 | .expect("custom provider survives"); |
| 3242 | assert_eq!( |
| 3243 | acme.get("model").and_then(toml::Value::as_str), |
| 3244 | Some("new-portable-model") |
| 3245 | ); |
| 3246 | assert_eq!( |
| 3247 | acme.get("base_url").and_then(toml::Value::as_str), |
| 3248 | Some("https://local-only.invalid/v1") |
| 3249 | ); |
| 3250 | assert_eq!( |
| 3251 | acme.get("api_key").and_then(toml::Value::as_str), |
| 3252 | Some("opaque-local-api-value") |
| 3253 | ); |
| 3254 | assert_eq!( |
| 3255 | acme.get("api_key_env").and_then(toml::Value::as_str), |
| 3256 | Some("LOCAL_ACME_GATEWAY_KEY") |
| 3257 | ); |
| 3258 | assert_eq!( |
| 3259 | acme.get("auth") |
| 3260 | .and_then(toml::Value::as_table) |
| 3261 | .and_then(|auth| auth.get("command")) |
| 3262 | .and_then(toml::Value::as_array) |
| 3263 | .and_then(|command| command.first()) |
| 3264 | .and_then(toml::Value::as_str), |
| 3265 | Some("/synthetic/local-credential-helper") |
| 3266 | ); |
| 3267 | let lsp = store.config.lsp.as_ref().expect("LSP config survives"); |
| 3268 | assert_eq!(lsp.enabled, Some(false)); |
| 3269 | assert_eq!(lsp.include_warnings, Some(true)); |
| 3270 | assert!(lsp.servers.as_ref().is_some_and(|servers| { |
| 3271 | servers |
| 3272 | .get("rust") |
| 3273 | .is_some_and(|command| command.first().is_some_and(|part| part.contains("rust"))) |
| 3274 | })); |
| 3275 | assert!( |
| 3276 | lsp.custom |
| 3277 | .as_ref() |
| 3278 | .is_some_and(|custom| custom.contains_key("foo")) |
| 3279 | ); |
| 3280 | assert_eq!( |
| 3281 | store |
| 3282 | .config |
| 3283 | .hook_sinks |
| 3284 | .as_ref() |
| 3285 | .and_then(|sinks| sinks.unix_socket_path.as_deref()), |
| 3286 | Some(Path::new("/synthetic/local-codewhale.sock")) |
| 3287 | ); |
| 3288 | |
| 3289 | let reloaded = ConfigStore::load(Some(path)).expect("merged config reloads"); |
| 3290 | assert_eq!(reloaded.config.provider_id(), "acme_gateway"); |
| 3291 | let plan = plan_import(&bundle, &reloaded.config, BundleScope::Global); |
| 3292 | assert!( |
| 3293 | plan.is_no_op(), |
| 3294 | "deep-merged re-import must be idempotent: {plan:?}" |
| 3295 | ); |
| 3296 | } |
| 3297 | |
| 3298 | #[test] |
| 3299 | fn export_recursively_drops_nested_secrets_but_keeps_safe_typed_siblings() { |
| 3300 | let provider_prefix = ["s", "k-"].concat(); |
| 3301 | let bearer_prefix = ["Bear", "er "].concat(); |
| 3302 | let access_key = ["access", "Token"].concat(); |
| 3303 | let dotted_refresh_key = ["service.refresh", "Token"].concat(); |
| 3304 | let refresh_key = ["refresh", "Token"].concat(); |
| 3305 | let fixture = format!( |
| 3306 | r#" |
| 3307 | [tools] |
| 3308 | always_load = ["read_file", "{provider_prefix}nested-tool-value-must-not-leak", "write_file"] |
| 3309 | |
| 3310 | [portable] |
| 3311 | safe_count = 7 |
| 3312 | note = "{bearer_prefix}nested-export-value-must-not-leak" |
| 3313 | values = ["plain", "{provider_prefix}nested-array-value-must-not-leak"] |
| 3314 | |
| 3315 | [portable.nested] |
| 3316 | {access_key} = "nested-export-key-must-not-leak" |
| 3317 | "{dotted_refresh_key}" = "nested-dotted-value-must-not-leak" |
| 3318 | label = "keep-me" |
| 3319 | |
| 3320 | [[portable.records]] |
| 3321 | {refresh_key} = "nested-record-value-must-not-leak" |
| 3322 | count = 2 |
| 3323 | |
| 3324 | [[portable.records]] |
| 3325 | label = "safe-record" |
| 3326 | "# |
| 3327 | ); |
| 3328 | let config: ConfigToml = toml::from_str(&fixture).expect("secret-bearing config parses"); |
| 3329 | let bundle = export_bundle(&config, BundleScope::Global, BundleMetadata::default()) |
| 3330 | .expect("safe export"); |
| 3331 | let body = serialize_bundle(&bundle).expect("serialize export"); |
| 3332 | for secret in [ |
| 3333 | "nested-export-value-must-not-leak", |
| 3334 | "nested-array-value-must-not-leak", |
| 3335 | "nested-tool-value-must-not-leak", |
| 3336 | "nested-export-key-must-not-leak", |
| 3337 | "nested-dotted-value-must-not-leak", |
| 3338 | "nested-record-value-must-not-leak", |
| 3339 | ] { |
| 3340 | assert!(!body.contains(secret), "export leaked {secret}: {body}"); |
| 3341 | } |
| 3342 | assert!(body.contains("safe_count = 7"), "{body}"); |
| 3343 | assert!(body.contains("label = \"keep-me\""), "{body}"); |
| 3344 | assert!(body.contains("label = \"safe-record\""), "{body}"); |
| 3345 | assert!(body.contains("values = [\"plain\"]"), "{body}"); |
| 3346 | assert!(find_rejected_entries(&bundle).is_empty(), "{bundle:?}"); |
| 3347 | |
| 3348 | let dir = tempfile::tempdir().expect("sanitized import dir"); |
| 3349 | let path = dir.path().join("config.toml"); |
| 3350 | let mut store = ConfigStore::load(Some(path)).expect("fresh store"); |
| 3351 | apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()) |
| 3352 | .expect("sanitized typed arrays re-import"); |
| 3353 | assert_eq!( |
| 3354 | store |
| 3355 | .config |
| 3356 | .tools |
| 3357 | .as_ref() |
| 3358 | .expect("tools preserved") |
| 3359 | .always_load |
| 3360 | .as_slice(), |
| 3361 | ["read_file", "write_file"], |
| 3362 | "dropping a secret array element must preserve a valid typed array" |
| 3363 | ); |
| 3364 | let plan = plan_import(&bundle, &store.config, BundleScope::Global); |
| 3365 | assert!( |
| 3366 | plan.is_no_op(), |
| 3367 | "sanitized re-import must be idempotent: {plan:?}" |
| 3368 | ); |
| 3369 | } |
| 3370 | |
| 3371 | #[test] |
| 3372 | fn compound_access_and_cookie_fields_are_scrubbed_on_export() { |
| 3373 | let cookie = ["Coo", "kie"].concat(); |
| 3374 | let set_cookie = ["Set-", "Cookie"].concat(); |
| 3375 | let api_dot = ["api", ".key"].concat(); |
| 3376 | let private_dot = ["private", ".key"].concat(); |
| 3377 | let access_camel = ["access", "Key"].concat(); |
| 3378 | let aws_snake = ["aws", "_access_key"].concat(); |
| 3379 | let aws_camel = ["aws", "SecretAccessKey"].concat(); |
| 3380 | let fixture = format!( |
| 3381 | r#" |
| 3382 | [http_headers] |
| 3383 | {cookie} = "opaque-cookie-value" |
| 3384 | {set_cookie} = "opaque-set-cookie-value" |
| 3385 | X-Safe = "portable-header" |
| 3386 | |
| 3387 | [portable] |
| 3388 | "{api_dot}" = "opaque-api-value" |
| 3389 | "{private_dot}" = "opaque-private-value" |
| 3390 | {access_camel} = "opaque-access-value" |
| 3391 | {aws_snake} = "opaque-aws-access-value" |
| 3392 | {aws_camel} = "opaque-aws-secret-access-value" |
| 3393 | maxTokens = 8192 |
| 3394 | tokenizer = "bpe" |
| 3395 | "# |
| 3396 | ); |
| 3397 | let config: ConfigToml = toml::from_str(&fixture).expect("credential-key config parses"); |
| 3398 | let bundle = export_bundle(&config, BundleScope::Global, BundleMetadata::default()) |
| 3399 | .expect("credential fields are scrubbed"); |
| 3400 | let body = serialize_bundle(&bundle).expect("serialize scrubbed export"); |
| 3401 | for forbidden in [ |
| 3402 | "opaque-cookie-value", |
| 3403 | "opaque-set-cookie-value", |
| 3404 | "opaque-api-value", |
| 3405 | "opaque-private-value", |
| 3406 | "opaque-access-value", |
| 3407 | "opaque-aws-access-value", |
| 3408 | "opaque-aws-secret-access-value", |
| 3409 | "api.key", |
| 3410 | "private.key", |
| 3411 | "accessKey", |
| 3412 | "aws_access_key", |
| 3413 | "awsSecretAccessKey", |
| 3414 | "Cookie", |
| 3415 | "Set-Cookie", |
| 3416 | ] { |
| 3417 | assert!( |
| 3418 | !body.contains(forbidden), |
| 3419 | "export retained {forbidden}: {body}" |
| 3420 | ); |
| 3421 | } |
| 3422 | assert!(body.contains("X-Safe = \"portable-header\""), "{body}"); |
| 3423 | assert!(body.contains("maxTokens = 8192"), "{body}"); |
| 3424 | assert!(body.contains("tokenizer = \"bpe\""), "{body}"); |
| 3425 | assert!(find_rejected_entries(&bundle).is_empty(), "{bundle:?}"); |
| 3426 | } |
| 3427 | |
| 3428 | #[test] |
| 3429 | fn provider_credential_authority_is_rejected_on_import_and_scrubbed_on_export() { |
| 3430 | let dir = tempfile::tempdir().expect("config dir"); |
| 3431 | let path = dir.path().join("config.toml"); |
| 3432 | std::fs::write(&path, "verbosity = \"quiet\"\n").expect("seed config"); |
| 3433 | let before = std::fs::read(&path).expect("config before imports"); |
| 3434 | let mut store = ConfigStore::load(Some(path.clone())).expect("store loads"); |
| 3435 | let api_key_env_name = ["api", "_key_env"].concat(); |
| 3436 | |
| 3437 | for (name, body) in [ |
| 3438 | ( |
| 3439 | "auth", |
| 3440 | r#" |
| 3441 | [global.providers.xai.auth] |
| 3442 | source = "command" |
| 3443 | command = ["synthetic-credential-helper"] |
| 3444 | "# |
| 3445 | .to_string(), |
| 3446 | ), |
| 3447 | ( |
| 3448 | "external", |
| 3449 | r#" |
| 3450 | [global.providers.xai.external_credentials] |
| 3451 | access = "read_only" |
| 3452 | provider = "xai" |
| 3453 | source = "grok_cli" |
| 3454 | path = "/synthetic/external/auth.json" |
| 3455 | consent_version = 1 |
| 3456 | "# |
| 3457 | .to_string(), |
| 3458 | ), |
| 3459 | ( |
| 3460 | "oauth-generation", |
| 3461 | r#" |
| 3462 | [global.providers.xai] |
| 3463 | oauth_credential_generation = "synthetic-owned-generation.toml" |
| 3464 | "# |
| 3465 | .to_string(), |
| 3466 | ), |
| 3467 | ( |
| 3468 | "api-key-env", |
| 3469 | format!( |
| 3470 | r#" |
| 3471 | [global.providers.xai] |
| 3472 | {api_key_env_name} = "SYNTHETIC_RANDOM_PROVIDER_KEY" |
| 3473 | "# |
| 3474 | ), |
| 3475 | ), |
| 3476 | ] { |
| 3477 | let text = format!("schema_version = 1\nkind = \"codewhale.portable-config\"\n{body}"); |
| 3478 | let bundle = parse_bundle_str(&text, name).expect("authority bundle parses"); |
| 3479 | assert_eq!(find_rejected_entries(&bundle).len(), 1, "{name}"); |
| 3480 | let error = apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()) |
| 3481 | .expect_err("authority-bearing import must fail"); |
| 3482 | assert!( |
| 3483 | error.to_string().contains("conflicting or rejected"), |
| 3484 | "{name}: {error:#}" |
| 3485 | ); |
| 3486 | assert_eq!(std::fs::read(&path).expect("config after refusal"), before); |
| 3487 | assert_eq!(store.config.verbosity.as_deref(), Some("quiet")); |
| 3488 | } |
| 3489 | |
| 3490 | let fixture = format!( |
| 3491 | r#" |
| 3492 | provider = "xai" |
| 3493 | |
| 3494 | [providers.xai] |
| 3495 | model = "grok-safe-model" |
| 3496 | oauth_credential_generation = "synthetic-owned-generation.toml" |
| 3497 | {api_key_env_name} = "SYNTHETIC_RANDOM_PROVIDER_KEY" |
| 3498 | |
| 3499 | [providers.xai.auth] |
| 3500 | source = "command" |
| 3501 | command = ["synthetic-credential-helper"] |
| 3502 | |
| 3503 | [providers.xai.external_credentials] |
| 3504 | access = "read_only" |
| 3505 | provider = "xai" |
| 3506 | source = "grok_cli" |
| 3507 | path = "/synthetic/external/auth.json" |
| 3508 | consent_version = 1 |
| 3509 | "# |
| 3510 | ); |
| 3511 | let config: ConfigToml = |
| 3512 | toml::from_str(&fixture).expect("provider authority config parses"); |
| 3513 | let exported = export_bundle(&config, BundleScope::Global, BundleMetadata::default()) |
| 3514 | .expect("provider authority is scrubbed"); |
| 3515 | let body = serialize_bundle(&exported).expect("serialize provider export"); |
| 3516 | for forbidden in [ |
| 3517 | "external_credentials", |
| 3518 | "oauth_credential_generation", |
| 3519 | "synthetic-credential-helper", |
| 3520 | "synthetic-owned-generation.toml", |
| 3521 | "SYNTHETIC_RANDOM_PROVIDER_KEY", |
| 3522 | api_key_env_name.as_str(), |
| 3523 | "/synthetic/external/auth.json", |
| 3524 | ] { |
| 3525 | assert!( |
| 3526 | !body.contains(forbidden), |
| 3527 | "export retained {forbidden}: {body}" |
| 3528 | ); |
| 3529 | } |
| 3530 | assert!(body.contains("model = \"grok-safe-model\""), "{body}"); |
| 3531 | assert!(find_rejected_entries(&exported).is_empty(), "{exported:?}"); |
| 3532 | } |
| 3533 | |
| 3534 | #[test] |
| 3535 | fn machine_local_route_and_path_fields_are_rejected_and_scrubbed_symmetrically() { |
| 3536 | let bundle = parse_bundle_str( |
| 3537 | r#" |
| 3538 | schema_version = 1 |
| 3539 | kind = "codewhale.portable-config" |
| 3540 | |
| 3541 | [global] |
| 3542 | telemetry_endpoint = "https://synthetic.invalid/telemetry" |
| 3543 | mcpConfigPath = "/synthetic/import-mcp.json" |
| 3544 | |
| 3545 | [global.providers.deepseek] |
| 3546 | baseUrl = "https://synthetic.invalid/provider/v1" |
| 3547 | model = "safe-model" |
| 3548 | |
| 3549 | [global.hook_sinks] |
| 3550 | unix_socket_path = "/synthetic/import-codewhale.sock" |
| 3551 | "#, |
| 3552 | "machine-local-paths.toml", |
| 3553 | ) |
| 3554 | .expect("machine-local bundle parses"); |
| 3555 | let rejected = find_rejected_entries(&bundle); |
| 3556 | assert_eq!(rejected.len(), 4, "{rejected:?}"); |
| 3557 | for key in [ |
| 3558 | "global.telemetry_endpoint", |
| 3559 | "global.mcpConfigPath", |
| 3560 | "global.providers", |
| 3561 | "global.hook_sinks", |
| 3562 | ] { |
| 3563 | assert!( |
| 3564 | rejected.iter().any(|entry| entry.key == key), |
| 3565 | "{rejected:?}" |
| 3566 | ); |
| 3567 | } |
| 3568 | |
| 3569 | let dir = tempfile::tempdir().expect("config dir"); |
| 3570 | let path = dir.path().join("config.toml"); |
| 3571 | std::fs::write(&path, "verbosity = \"quiet\"\n").expect("seed config"); |
| 3572 | let before = std::fs::read(&path).expect("config before import"); |
| 3573 | let mut store = ConfigStore::load(Some(path.clone())).expect("store loads"); |
| 3574 | let error = apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()) |
| 3575 | .expect_err("machine-local paths must refuse the entire import"); |
| 3576 | assert!( |
| 3577 | error.to_string().contains("conflicting or rejected"), |
| 3578 | "{error:#}" |
| 3579 | ); |
| 3580 | assert_eq!(std::fs::read(&path).expect("config after refusal"), before); |
| 3581 | assert_eq!(store.config.verbosity.as_deref(), Some("quiet")); |
| 3582 | |
| 3583 | let config: ConfigToml = toml::from_str( |
| 3584 | r#" |
| 3585 | telemetry_endpoint = "https://synthetic.invalid/telemetry" |
| 3586 | mcp_config_path = "/synthetic/export-mcp.json" |
| 3587 | |
| 3588 | [providers.deepseek] |
| 3589 | base_url = "https://synthetic.invalid/provider/v1" |
| 3590 | model = "safe-model" |
| 3591 | |
| 3592 | [hook_sinks] |
| 3593 | unix_socket_path = "/synthetic/export-codewhale.sock" |
| 3594 | "#, |
| 3595 | ) |
| 3596 | .expect("machine-local config parses"); |
| 3597 | let exported = export_bundle(&config, BundleScope::Global, BundleMetadata::default()) |
| 3598 | .expect("machine-local paths are scrubbed"); |
| 3599 | let body = serialize_bundle(&exported).expect("serialize machine-local export"); |
| 3600 | for forbidden in [ |
| 3601 | "synthetic.invalid", |
| 3602 | "/synthetic/export-mcp.json", |
| 3603 | "/synthetic/export-codewhale.sock", |
| 3604 | "telemetry_endpoint", |
| 3605 | "mcp_config_path", |
| 3606 | "unix_socket_path", |
| 3607 | "base_url", |
| 3608 | ] { |
| 3609 | assert!( |
| 3610 | !body.contains(forbidden), |
| 3611 | "export retained {forbidden}: {body}" |
| 3612 | ); |
| 3613 | } |
| 3614 | assert!(body.contains("model = \"safe-model\""), "{body}"); |
| 3615 | assert!(find_rejected_entries(&exported).is_empty(), "{exported:?}"); |
| 3616 | } |
| 3617 | |
| 3618 | #[test] |
| 3619 | fn remaining_local_authority_is_rejected_while_safe_policy_stays_portable() { |
| 3620 | for safe in [ |
| 3621 | "databaseUrl", |
| 3622 | "baseUrlTemplate", |
| 3623 | "memoryPathology", |
| 3624 | "sandboxUrlTemplate", |
| 3625 | "skills.registry_url", |
| 3626 | "network.allow", |
| 3627 | "workflow.automatic", |
| 3628 | "fleet.exec.allowed_tools", |
| 3629 | ] { |
| 3630 | assert_eq!(nonportable_path_reason(safe), None, "must preserve {safe}"); |
| 3631 | } |
| 3632 | |
| 3633 | let bundle = parse_bundle_str( |
| 3634 | r#" |
| 3635 | schema_version = 1 |
| 3636 | kind = "codewhale.portable-config" |
| 3637 | |
| 3638 | [global] |
| 3639 | instructions = "/synthetic/import-instructions.md" |
| 3640 | project_instruction_imports = "all" |
| 3641 | projectInstructionImports = "all" |
| 3642 | sandbox_backend = "synthetic-local-backend" |
| 3643 | sandboxUrl = "http://127.0.0.1:47891" |
| 3644 | bwrapRoRoots = ["/synthetic/import-ro"] |
| 3645 | bwrap_dev_roots = ["/synthetic/import-dev"] |
| 3646 | skills_dir = "/synthetic/import-skills" |
| 3647 | memoryPath = "/synthetic/import-memory.md" |
| 3648 | mcpOauthCallbackUrl = "http://127.0.0.1:47892/callback" |
| 3649 | mcp_oauth_callback_port = 47892 |
| 3650 | |
| 3651 | [global.runtime_api] |
| 3652 | bind = "127.0.0.1:47893" |
| 3653 | |
| 3654 | [global.auto_review] |
| 3655 | allow = ["synthetic-shell-action"] |
| 3656 | |
| 3657 | [global.tools] |
| 3658 | always_load = ["read_file"] |
| 3659 | plugin_dir = "/synthetic/import-plugins" |
| 3660 | |
| 3661 | [global.tools.overrides.shell] |
| 3662 | command = "/synthetic/import-tool-override" |
| 3663 | |
| 3664 | [global.update] |
| 3665 | channel = "stable" |
| 3666 | update_uri = "file:///synthetic/import-update" |
| 3667 | |
| 3668 | [global.notifications] |
| 3669 | enabled = true |
| 3670 | sound_file = "/synthetic/import-sound.wav" |
| 3671 | |
| 3672 | [global.speech] |
| 3673 | enabled = true |
| 3674 | output_dir = "/synthetic/import-speech" |
| 3675 | |
| 3676 | [global.skills] |
| 3677 | registry_url = "https://registry.example/skills.json" |
| 3678 | |
| 3679 | [global.network] |
| 3680 | default = "prompt" |
| 3681 | allow = ["registry.example"] |
| 3682 | |
| 3683 | [global.workflow] |
| 3684 | automatic = false |
| 3685 | |
| 3686 | [global.fleet.exec] |
| 3687 | allowed_tools = ["read_file"] |
| 3688 | "#, |
| 3689 | "remaining-local-authority.toml", |
| 3690 | ) |
| 3691 | .expect("remaining authority bundle parses"); |
| 3692 | let rejected = find_rejected_entries(&bundle); |
| 3693 | assert_eq!(rejected.len(), 17, "{rejected:?}"); |
| 3694 | for safe in [ |
| 3695 | "global.skills", |
| 3696 | "global.network", |
| 3697 | "global.workflow", |
| 3698 | "global.fleet", |
| 3699 | ] { |
| 3700 | assert!( |
| 3701 | rejected.iter().all(|entry| entry.key != safe), |
| 3702 | "safe entry {safe} was rejected: {rejected:?}" |
| 3703 | ); |
| 3704 | } |
| 3705 | |
| 3706 | let dir = tempfile::tempdir().expect("config dir"); |
| 3707 | let path = dir.path().join("config.toml"); |
| 3708 | std::fs::write(&path, "verbosity = \"concise\"\n").expect("seed config"); |
| 3709 | let before = std::fs::read(&path).expect("config before import"); |
| 3710 | let mut store = ConfigStore::load(Some(path.clone())).expect("store loads"); |
| 3711 | apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()) |
| 3712 | .expect_err("remaining local authority import must fail"); |
| 3713 | assert_eq!(std::fs::read(&path).expect("config after refusal"), before); |
| 3714 | assert_eq!(store.config.verbosity.as_deref(), Some("concise")); |
| 3715 | |
| 3716 | let config: ConfigToml = toml::from_str( |
| 3717 | r#" |
| 3718 | instructions = "/synthetic/export-instructions.md" |
| 3719 | project_instruction_imports = "all" |
| 3720 | projectInstructionImports = "all" |
| 3721 | sandbox_backend = "synthetic-local-backend" |
| 3722 | sandboxUrl = "http://127.0.0.1:47894" |
| 3723 | bwrapRoRoots = ["/synthetic/export-ro"] |
| 3724 | bwrap_dev_roots = ["/synthetic/export-dev"] |
| 3725 | skills_dir = "/synthetic/export-skills" |
| 3726 | memoryPath = "/synthetic/export-memory.md" |
| 3727 | mcpOauthCallbackUrl = "http://127.0.0.1:47895/callback" |
| 3728 | mcp_oauth_callback_port = 47895 |
| 3729 | |
| 3730 | [runtime_api] |
| 3731 | bind = "127.0.0.1:47896" |
| 3732 | |
| 3733 | [auto_review] |
| 3734 | allow = ["synthetic-shell-action"] |
| 3735 | |
| 3736 | [tools] |
| 3737 | always_load = ["read_file"] |
| 3738 | plugin_dir = "/synthetic/export-plugins" |
| 3739 | |
| 3740 | [tools.overrides.shell] |
| 3741 | command = "/synthetic/export-tool-override" |
| 3742 | |
| 3743 | [update] |
| 3744 | channel = "stable" |
| 3745 | update_uri = "file:///synthetic/export-update" |
| 3746 | |
| 3747 | [notifications] |
| 3748 | enabled = true |
| 3749 | sound_file = "/synthetic/export-sound.wav" |
| 3750 | |
| 3751 | [speech] |
| 3752 | enabled = true |
| 3753 | output_dir = "/synthetic/export-speech" |
| 3754 | |
| 3755 | [skills] |
| 3756 | registry_url = "https://registry.example/skills.json" |
| 3757 | max_install_size_bytes = 12345 |
| 3758 | |
| 3759 | [network] |
| 3760 | default = "prompt" |
| 3761 | allow = ["registry.example"] |
| 3762 | |
| 3763 | [workflow] |
| 3764 | automatic = false |
| 3765 | |
| 3766 | [fleet.exec] |
| 3767 | allowed_tools = ["read_file"] |
| 3768 | "#, |
| 3769 | ) |
| 3770 | .expect("remaining authority config parses"); |
| 3771 | let exported = export_bundle(&config, BundleScope::Global, BundleMetadata::default()) |
| 3772 | .expect("remaining authority is scrubbed"); |
| 3773 | for key in [ |
| 3774 | "instructions", |
| 3775 | "project_instruction_imports", |
| 3776 | "projectInstructionImports", |
| 3777 | "sandbox_backend", |
| 3778 | "sandboxUrl", |
| 3779 | "bwrapRoRoots", |
| 3780 | "bwrap_dev_roots", |
| 3781 | "skills_dir", |
| 3782 | "memoryPath", |
| 3783 | "mcpOauthCallbackUrl", |
| 3784 | "mcp_oauth_callback_port", |
| 3785 | "runtime_api", |
| 3786 | "auto_review", |
| 3787 | ] { |
| 3788 | assert!(!exported.global.entries.contains_key(key), "retained {key}"); |
| 3789 | } |
| 3790 | let body = serialize_bundle(&exported).expect("serialize safe policy export"); |
| 3791 | for forbidden in [ |
| 3792 | "/synthetic/export-instructions.md", |
| 3793 | "/synthetic/export-ro", |
| 3794 | "/synthetic/export-dev", |
| 3795 | "/synthetic/export-skills", |
| 3796 | "/synthetic/export-memory.md", |
| 3797 | "/synthetic/export-sound.wav", |
| 3798 | "/synthetic/export-speech", |
| 3799 | "file:///synthetic/export-update", |
| 3800 | "127.0.0.1:47896", |
| 3801 | ] { |
| 3802 | assert!( |
| 3803 | !body.contains(forbidden), |
| 3804 | "export retained {forbidden}: {body}" |
| 3805 | ); |
| 3806 | } |
| 3807 | for safe in [ |
| 3808 | "https://registry.example/skills.json", |
| 3809 | "registry.example", |
| 3810 | "automatic = false", |
| 3811 | "allowed_tools = [\"read_file\"]", |
| 3812 | "channel = \"stable\"", |
| 3813 | "enabled = true", |
| 3814 | ] { |
| 3815 | assert!(body.contains(safe), "export lost {safe}: {body}"); |
| 3816 | } |
| 3817 | |
| 3818 | // ToolsToml currently ignores these legacy fields while parsing, so |
| 3819 | // exercise the recursive export sanitizer directly as defense in depth. |
| 3820 | let raw: toml::Value = toml::from_str( |
| 3821 | r#" |
| 3822 | [tools] |
| 3823 | always_load = ["read_file"] |
| 3824 | plugin_dir = "/synthetic/direct-plugin-dir" |
| 3825 | |
| 3826 | [tools.overrides.shell] |
| 3827 | command = "/synthetic/direct-tool-override" |
| 3828 | "#, |
| 3829 | ) |
| 3830 | .expect("raw tools table parses"); |
| 3831 | let scrubbed = |
| 3832 | sanitize_export_value("tools", raw.get("tools").expect("raw tools table exists")) |
| 3833 | .expect("safe tools sibling remains"); |
| 3834 | let scrubbed = scrubbed.to_string(); |
| 3835 | assert!(scrubbed.contains("read_file"), "{scrubbed}"); |
| 3836 | assert!(!scrubbed.contains("plugin_dir"), "{scrubbed}"); |
| 3837 | assert!(!scrubbed.contains("overrides"), "{scrubbed}"); |
| 3838 | assert!(find_rejected_entries(&exported).is_empty(), "{exported:?}"); |
| 3839 | } |
| 3840 | |
| 3841 | #[test] |
| 3842 | fn deep_nesting_fails_closed_for_rejection_and_sanitize() { |
| 3843 | fn deep_toml(depth: usize) -> toml::Value { |
| 3844 | let mut value = toml::Value::String("leaf".to_string()); |
| 3845 | for _ in 0..depth { |
| 3846 | let mut map = toml::map::Map::new(); |
| 3847 | map.insert("t".to_string(), value); |
| 3848 | value = toml::Value::Table(map); |
| 3849 | } |
| 3850 | value |
| 3851 | } |
| 3852 | |
| 3853 | let deep = deep_toml(70); |
| 3854 | let reason = value_rejection_reason("t", &deep).expect("over-deep value must be rejected"); |
| 3855 | assert!(reason.contains("levels deep"), "{reason}"); |
| 3856 | assert!( |
| 3857 | sanitize_export_value("t", &deep) |
| 3858 | .is_some_and(|scrubbed| !scrubbed.to_string().contains("leaf")), |
| 3859 | "over-deep branch must be omitted, not exported" |
| 3860 | ); |
| 3861 | } |
| 3862 | |
| 3863 | #[test] |
| 3864 | fn lsp_executable_authority_is_rejected_while_inert_settings_remain_portable() { |
| 3865 | let config: ConfigToml = toml::from_str( |
| 3866 | r#" |
| 3867 | [lsp] |
| 3868 | enabled = true |
| 3869 | poll_after_edit_ms = 250 |
| 3870 | max_diagnostics_per_file = 12 |
| 3871 | include_warnings = true |
| 3872 | |
| 3873 | [lsp.servers] |
| 3874 | rust = ["/synthetic/rust-analyzer", "--stdio"] |
| 3875 | |
| 3876 | [lsp.custom.foo] |
| 3877 | language_id = "foo-language" |
| 3878 | command = "/synthetic/foo-language-server" |
| 3879 | args = ["--stdio", "--synthetic"] |
| 3880 | "#, |
| 3881 | ) |
| 3882 | .expect("LSP config parses"); |
| 3883 | let exported = export_bundle(&config, BundleScope::Global, BundleMetadata::default()) |
| 3884 | .expect("LSP executable authority is scrubbed"); |
| 3885 | let body = serialize_bundle(&exported).expect("serialize LSP export"); |
| 3886 | for forbidden in [ |
| 3887 | "/synthetic/rust-analyzer", |
| 3888 | "/synthetic/foo-language-server", |
| 3889 | "foo-language", |
| 3890 | "--stdio", |
| 3891 | "--synthetic", |
| 3892 | ] { |
| 3893 | assert!( |
| 3894 | !body.contains(forbidden), |
| 3895 | "export retained {forbidden}: {body}" |
| 3896 | ); |
| 3897 | } |
| 3898 | for inert in [ |
| 3899 | "enabled = true", |
| 3900 | "poll_after_edit_ms = 250", |
| 3901 | "max_diagnostics_per_file = 12", |
| 3902 | "include_warnings = true", |
| 3903 | ] { |
| 3904 | assert!(body.contains(inert), "export lost {inert}: {body}"); |
| 3905 | } |
| 3906 | assert!(find_rejected_entries(&exported).is_empty(), "{exported:?}"); |
| 3907 | |
| 3908 | let dir = tempfile::tempdir().expect("config dir"); |
| 3909 | let path = dir.path().join("config.toml"); |
| 3910 | std::fs::write(&path, "verbosity = \"concise\"\n").expect("seed config"); |
| 3911 | let before = std::fs::read(&path).expect("config before imports"); |
| 3912 | let mut store = ConfigStore::load(Some(path.clone())).expect("store loads"); |
| 3913 | for (name, body) in [ |
| 3914 | ( |
| 3915 | "servers", |
| 3916 | r#" |
| 3917 | [global.lsp] |
| 3918 | enabled = true |
| 3919 | |
| 3920 | [global.lsp.servers] |
| 3921 | rust = ["/synthetic/import-rust-analyzer", "--stdio"] |
| 3922 | "#, |
| 3923 | ), |
| 3924 | ( |
| 3925 | "custom", |
| 3926 | r#" |
| 3927 | [global.lsp] |
| 3928 | include_warnings = true |
| 3929 | |
| 3930 | [global.lsp.custom.foo] |
| 3931 | language_id = "foo-language" |
| 3932 | command = "/synthetic/import-foo-server" |
| 3933 | args = ["--stdio"] |
| 3934 | "#, |
| 3935 | ), |
| 3936 | ] { |
| 3937 | let text = format!("schema_version = 1\nkind = \"codewhale.portable-config\"\n{body}"); |
| 3938 | let bundle = parse_bundle_str(&text, name).expect("LSP bundle parses"); |
| 3939 | assert_eq!(find_rejected_entries(&bundle).len(), 1, "{name}"); |
| 3940 | apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()) |
| 3941 | .expect_err("LSP executable authority import must fail"); |
| 3942 | assert_eq!(std::fs::read(&path).expect("config after refusal"), before); |
| 3943 | assert_eq!(store.config.verbosity.as_deref(), Some("concise")); |
| 3944 | } |
| 3945 | } |
| 3946 | |
| 3947 | #[test] |
| 3948 | fn trust_posture_and_local_endpoint_keys_are_rejected_on_import() { |
| 3949 | let bundle = parse_bundle_str( |
| 3950 | r#" |
| 3951 | schema_version = 1 |
| 3952 | kind = "codewhale.portable-config" |
| 3953 | |
| 3954 | [preferences] |
| 3955 | yolo = true |
| 3956 | allow_shell = true |
| 3957 | sandbox_mode = "danger-full-access" |
| 3958 | approval_policy = "never" |
| 3959 | sandboxNetworkAccess = true |
| 3960 | log_level = "debug" |
| 3961 | |
| 3962 | [preferences.lifecycle_outbox] |
| 3963 | webhook_url = "https://collector.example/collect" |
| 3964 | |
| 3965 | [preferences.extension_host] |
| 3966 | node = "/bin/echo" |
| 3967 | |
| 3968 | [preferences.control_socket] |
| 3969 | enabled = true |
| 3970 | |
| 3971 | [global] |
| 3972 | sandbox_read_denylist_exempt = ["/synthetic/exempt"] |
| 3973 | "#, |
| 3974 | "posture.toml", |
| 3975 | ) |
| 3976 | .expect("posture bundle parses"); |
| 3977 | let rejected = find_rejected_entries(&bundle); |
| 3978 | let keys: Vec<&str> = rejected.iter().map(|entry| entry.key.as_str()).collect(); |
| 3979 | assert_eq!(rejected.len(), 9, "{rejected:?}"); |
| 3980 | assert!(!keys.contains(&"preferences.log_level"), "{keys:?}"); |
| 3981 | let rendered = format!("{rejected:?}"); |
| 3982 | assert!(!rendered.contains("collector.example"), "{rendered}"); |
| 3983 | assert!(!rendered.contains("/bin/echo"), "{rendered}"); |
| 3984 | |
| 3985 | let dir = tempfile::tempdir().expect("config dir"); |
| 3986 | let path = dir.path().join("config.toml"); |
| 3987 | std::fs::write(&path, "verbosity = \"quiet\"\n").expect("seed config"); |
| 3988 | let before = std::fs::read(&path).expect("config before import"); |
| 3989 | let mut store = ConfigStore::load(Some(path.clone())).expect("store loads"); |
| 3990 | apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()) |
| 3991 | .expect_err("trust posture import must fail"); |
| 3992 | assert_eq!(std::fs::read(&path).expect("config after refusal"), before); |
| 3993 | } |
| 3994 | |
| 3995 | #[test] |
| 3996 | fn portable_export_drops_webhooks_local_executables_and_denylist_paths() { |
| 3997 | let config: ConfigToml = toml::from_str( |
| 3998 | r#" |
| 3999 | model = "safe-model" |
| 4000 | approval_policy = "never" |
| 4001 | sandbox_mode = "danger-full-access" |
| 4002 | yolo = true |
| 4003 | sandbox_denied_read_paths = ["/synthetic/private"] |
| 4004 | sandbox_read_denylist_exempt = ["/synthetic/exempt"] |
| 4005 | |
| 4006 | [lifecycle_outbox] |
| 4007 | path = "/synthetic/outbox.jsonl" |
| 4008 | webhook_url = "https://hooks.slack.com/services/T0SYNTH/B0SYNTH/synthetichookvalue" |
| 4009 | |
| 4010 | [extension_host] |
| 4011 | node = "/synthetic/bin/node" |
| 4012 | |
| 4013 | [control_socket] |
| 4014 | enabled = true |
| 4015 | "#, |
| 4016 | ) |
| 4017 | .expect("config parses"); |
| 4018 | let exported = export_bundle(&config, BundleScope::Global, BundleMetadata::default()) |
| 4019 | .expect("export scrubs posture"); |
| 4020 | let body = serialize_bundle(&exported).expect("serialize"); |
| 4021 | for forbidden in [ |
| 4022 | "hooks.slack.com", |
| 4023 | "synthetichookvalue", |
| 4024 | "/synthetic/outbox.jsonl", |
| 4025 | "/synthetic/bin/node", |
| 4026 | "/synthetic/private", |
| 4027 | "/synthetic/exempt", |
| 4028 | "danger-full-access", |
| 4029 | "approval_policy", |
| 4030 | "yolo", |
| 4031 | "control_socket", |
| 4032 | ] { |
| 4033 | assert!( |
| 4034 | !body.contains(forbidden), |
| 4035 | "export retained {forbidden}: {body}" |
| 4036 | ); |
| 4037 | } |
| 4038 | assert!(body.contains("model = \"safe-model\""), "{body}"); |
| 4039 | } |
| 4040 | |
| 4041 | #[test] |
| 4042 | fn urls_carrying_credentials_are_credential_shaped() { |
| 4043 | for url in [ |
| 4044 | "https://user:pass@registry.example/index.json", |
| 4045 | "https://registry.example/index.json?token=synthetic", |
| 4046 | "https://registry.example/index.json?access_token=synthetic", |
| 4047 | "https://hooks.slack.com/services/T0SYNTH/B0SYNTH/synthetic", |
| 4048 | "https://discord.com/api/webhooks/1/synthetic", |
| 4049 | "https://tenant.webhook.office.com/webhookb2/synthetic", |
| 4050 | ] { |
| 4051 | assert!(string_secret_reason(url).is_some(), "must reject {url}"); |
| 4052 | } |
| 4053 | for url in [ |
| 4054 | "https://registry.example/skills.json", |
| 4055 | "https://registry.example/search?q=codewhale&page=2", |
| 4056 | "https://registry.example/search?q=a+b%20c", |
| 4057 | "https://hooks.slack.com/", |
| 4058 | ] { |
| 4059 | assert_eq!(string_secret_reason(url), None, "must preserve {url}"); |
| 4060 | } |
| 4061 | } |
| 4062 | |
| 4063 | #[test] |
| 4064 | fn machine_bound_authority_subtrees_are_rejected_and_never_exported() { |
| 4065 | let config: ConfigToml = toml::from_str( |
| 4066 | r#" |
| 4067 | managed_config_path = "/synthetic/managed-config.toml" |
| 4068 | requirements_path = "/synthetic/requirements.md" |
| 4069 | |
| 4070 | [workspace] |
| 4071 | root = "/synthetic/workspace-root" |
| 4072 | trust = "trusted" |
| 4073 | allow_shell = true |
| 4074 | |
| 4075 | [projects."/synthetic/project-root"] |
| 4076 | trust = "trusted" |
| 4077 | allow_shell = true |
| 4078 | |
| 4079 | [hooks.session_start] |
| 4080 | command = "/synthetic/session-start" |
| 4081 | |
| 4082 | [portable.workspace] |
| 4083 | label = "safe-nested-workspace-label" |
| 4084 | |
| 4085 | [portable.projects] |
| 4086 | label = "safe-nested-projects-label" |
| 4087 | |
| 4088 | [portable.hooks] |
| 4089 | label = "safe-nested-hooks-label" |
| 4090 | "#, |
| 4091 | ) |
| 4092 | .expect("machine-bound authority config parses"); |
| 4093 | let exported = export_bundle(&config, BundleScope::Global, BundleMetadata::default()) |
| 4094 | .expect("machine-bound authority is scrubbed"); |
| 4095 | assert!(!exported.global.entries.contains_key("workspace")); |
| 4096 | assert!(!exported.global.entries.contains_key("projects")); |
| 4097 | assert!(!exported.global.entries.contains_key("hooks")); |
| 4098 | assert!(!exported.global.entries.contains_key("managed_config_path")); |
| 4099 | assert!(!exported.global.entries.contains_key("requirements_path")); |
| 4100 | let body = serialize_bundle(&exported).expect("serialize machine-bound export"); |
| 4101 | for path in [ |
| 4102 | "/synthetic/workspace-root", |
| 4103 | "/synthetic/project-root", |
| 4104 | "/synthetic/session-start", |
| 4105 | "/synthetic/managed-config.toml", |
| 4106 | "/synthetic/requirements.md", |
| 4107 | ] { |
| 4108 | assert!(!body.contains(path), "export retained {path}: {body}"); |
| 4109 | } |
| 4110 | assert!(body.contains("safe-nested-workspace-label"), "{body}"); |
| 4111 | assert!(body.contains("safe-nested-projects-label"), "{body}"); |
| 4112 | assert!(body.contains("safe-nested-hooks-label"), "{body}"); |
| 4113 | |
| 4114 | let bundle = parse_bundle_str( |
| 4115 | r#" |
| 4116 | schema_version = 1 |
| 4117 | kind = "codewhale.portable-config" |
| 4118 | |
| 4119 | [global] |
| 4120 | managed_config_path = "/synthetic/import-managed-config.toml" |
| 4121 | requirements_path = "/synthetic/import-requirements.md" |
| 4122 | |
| 4123 | [global.workspace] |
| 4124 | root = "/synthetic/import-workspace" |
| 4125 | trust = "trusted" |
| 4126 | allow_shell = true |
| 4127 | |
| 4128 | [global.projects."/synthetic/import-project"] |
| 4129 | trust = "trusted" |
| 4130 | allow_shell = true |
| 4131 | |
| 4132 | [global.hooks.session_start] |
| 4133 | command = "/synthetic/import-session-start" |
| 4134 | |
| 4135 | [global.portable.workspace] |
| 4136 | label = "safe-nested-workspace-label" |
| 4137 | "#, |
| 4138 | "machine-bound-authority.toml", |
| 4139 | ) |
| 4140 | .expect("machine-bound authority bundle parses"); |
| 4141 | let rejected = find_rejected_entries(&bundle); |
| 4142 | assert_eq!(rejected.len(), 5, "{rejected:?}"); |
| 4143 | assert!(rejected.iter().any(|entry| entry.key == "global.workspace")); |
| 4144 | assert!(rejected.iter().any(|entry| entry.key == "global.projects")); |
| 4145 | assert!(rejected.iter().any(|entry| entry.key == "global.hooks")); |
| 4146 | assert!( |
| 4147 | rejected |
| 4148 | .iter() |
| 4149 | .any(|entry| entry.key == "global.managed_config_path") |
| 4150 | ); |
| 4151 | assert!( |
| 4152 | rejected |
| 4153 | .iter() |
| 4154 | .any(|entry| entry.key == "global.requirements_path") |
| 4155 | ); |
| 4156 | |
| 4157 | let dir = tempfile::tempdir().expect("config dir"); |
| 4158 | let path = dir.path().join("config.toml"); |
| 4159 | std::fs::write(&path, "verbosity = \"concise\"\n").expect("seed config"); |
| 4160 | let before = std::fs::read(&path).expect("config before import"); |
| 4161 | let mut store = ConfigStore::load(Some(path.clone())).expect("store loads"); |
| 4162 | apply_bundle(&bundle, &mut store, BundleScope::Global, dir.path()) |
| 4163 | .expect_err("machine-bound authority import must fail"); |
| 4164 | assert_eq!(std::fs::read(path).expect("config after refusal"), before); |
| 4165 | assert_eq!(store.config.verbosity.as_deref(), Some("concise")); |
| 4166 | } |
| 4167 | |
| 4168 | #[test] |
| 4169 | fn bundle_scope_must_match_the_target_for_import_and_export() { |
| 4170 | let dir = tempfile::tempdir().expect("config dir"); |
| 4171 | let global_path = dir.path().join("config.toml"); |
| 4172 | let error = validate_scope_target(BundleScope::Project, &global_path) |
| 4173 | .expect_err("global path cannot masquerade as project scope"); |
| 4174 | assert!(error.to_string().contains("workspace config"), "{error:#}"); |
| 4175 | validate_scope_target(BundleScope::Global, &global_path) |
| 4176 | .expect("global config accepts global scope"); |
| 4177 | |
| 4178 | let project_path = dir.path().join(".codewhale").join("config.toml"); |
| 4179 | std::fs::create_dir(dir.path().join(".git")).expect("checkout marker"); |
| 4180 | validate_scope_target(BundleScope::Project, &project_path) |
| 4181 | .expect("workspace config accepts project scope"); |
| 4182 | let error = validate_scope_target(BundleScope::Global, &project_path) |
| 4183 | .expect_err("workspace path cannot masquerade as global scope"); |
| 4184 | assert!(error.to_string().contains("--project"), "{error:#}"); |
| 4185 | |
| 4186 | let mut store = ConfigStore::load(Some(project_path)).expect("workspace store loads"); |
| 4187 | let import = ImportArgs { |
| 4188 | source: dir |
| 4189 | .path() |
| 4190 | .join("must-not-be-read.toml") |
| 4191 | .display() |
| 4192 | .to_string(), |
| 4193 | dry_run: true, |
| 4194 | yes: true, |
| 4195 | project: false, |
| 4196 | }; |
| 4197 | let error = run_import(&import, &mut store, dir.path()) |
| 4198 | .expect_err("global import must refuse a workspace config before reading input"); |
| 4199 | assert!(error.to_string().contains("--project"), "{error:#}"); |
| 4200 | |
| 4201 | let output = dir.path().join("must-not-be-written.toml"); |
| 4202 | let export = ExportArgs { |
| 4203 | portable: true, |
| 4204 | project: false, |
| 4205 | out: Some(output.clone()), |
| 4206 | }; |
| 4207 | let error = run_export(&export, &store) |
| 4208 | .expect_err("global export must refuse a workspace config before writing output"); |
| 4209 | assert!(error.to_string().contains("--project"), "{error:#}"); |
| 4210 | assert!(!output.exists(), "refused export must not create an output"); |
| 4211 | } |
| 4212 | |
| 4213 | #[test] |
| 4214 | fn exported_bundle_reimports_cleanly() { |
| 4215 | let mut store = isolated_store(); |
| 4216 | store.config.set_value("verbosity", "concise").expect("set"); |
| 4217 | store.save().expect("save"); |
| 4218 | |
| 4219 | let bundle = export_bundle( |
| 4220 | &store.config, |
| 4221 | BundleScope::Global, |
| 4222 | BundleMetadata::default(), |
| 4223 | ) |
| 4224 | .expect("export"); |
| 4225 | let rejected = find_rejected_entries(&bundle); |
| 4226 | assert!( |
| 4227 | rejected.is_empty(), |
| 4228 | "export must be secret-free: {rejected:?}" |
| 4229 | ); |
| 4230 | |
| 4231 | let plan = plan_import(&bundle, &store.config, BundleScope::Global); |
| 4232 | assert!( |
| 4233 | plan.rejected.is_empty() && plan.conflicting.is_empty(), |
| 4234 | "own export must not trip rejection: {plan:?}" |
| 4235 | ); |
| 4236 | } |
| 4237 | |
| 4238 | #[test] |
| 4239 | fn http_non_loopback_fetch_is_refused_without_network_access() { |
| 4240 | let err = fetch_bundle("http://example.com/bundle.toml", &NetworkPolicy::default()) |
| 4241 | .expect_err("plain http to a public host must be refused"); |
| 4242 | assert!(err.to_string().contains("loopback"), "{err:#}"); |
| 4243 | assert!(!err.to_string().contains("example.com"), "{err:#}"); |
| 4244 | } |
| 4245 | |
| 4246 | #[test] |
| 4247 | fn redirect_to_non_loopback_http_is_refused_without_leaking_location() { |
| 4248 | let secret = "location-secret-must-not-leak"; |
| 4249 | let location = format!("http://example.com/internal?token={secret}"); |
| 4250 | let response = http_response("302 Found", &[("Location", location.as_str())], b""); |
| 4251 | let (url, server) = spawn_bundle_http_server(vec![response]); |
| 4252 | |
| 4253 | let error = fetch_bundle(&url, &NetworkPolicy::default()) |
| 4254 | .expect_err("redirect target must be revalidated"); |
| 4255 | let rendered = format!("{error:#}"); |
| 4256 | assert!(rendered.contains("loopback"), "{rendered}"); |
| 4257 | assert!(!rendered.contains("example.com"), "{rendered}"); |
| 4258 | assert!(!rendered.contains(secret), "{rendered}"); |
| 4259 | assert_eq!(server.join().expect("server joins"), 1); |
| 4260 | } |
| 4261 | |
| 4262 | #[test] |
| 4263 | fn visibly_local_network_allow_entries_are_rejected_while_public_hosts_import() { |
| 4264 | let local_bundle = parse_bundle_str( |
| 4265 | r#" |
| 4266 | schema_version = 1 |
| 4267 | kind = "codewhale.portable-config" |
| 4268 | |
| 4269 | [global.network] |
| 4270 | default = "prompt" |
| 4271 | allow = ["docs.example.com", "localhost", "10.0.0.5"] |
| 4272 | "#, |
| 4273 | "local-allow.toml", |
| 4274 | ) |
| 4275 | .expect("local allow bundle parses"); |
| 4276 | let rejected = find_rejected_entries(&local_bundle); |
| 4277 | assert_eq!(rejected.len(), 1, "{rejected:?}"); |
| 4278 | assert_eq!(rejected[0].key, "global.network"); |
| 4279 | assert!(rejected[0].reason.contains("network.allow"), "{rejected:?}"); |
| 4280 | assert!(!rejected[0].reason.contains("localhost"), "{rejected:?}"); |
| 4281 | assert!(!rejected[0].reason.contains("10.0.0.5"), "{rejected:?}"); |
| 4282 | |
| 4283 | let mut store = isolated_store(); |
| 4284 | let before = std::fs::read(store.path()).expect("config before import"); |
| 4285 | let dir = store.path().parent().expect("config dir").to_path_buf(); |
| 4286 | apply_bundle(&local_bundle, &mut store, BundleScope::Global, &dir) |
| 4287 | .expect_err("bundle adding visibly local network.allow entries must fail"); |
| 4288 | assert_eq!( |
| 4289 | std::fs::read(store.path()).expect("config after rejected import"), |
| 4290 | before |
| 4291 | ); |
| 4292 | |
| 4293 | let public_bundle = parse_bundle_str( |
| 4294 | r#" |
| 4295 | schema_version = 1 |
| 4296 | kind = "codewhale.portable-config" |
| 4297 | |
| 4298 | [global.network] |
| 4299 | default = "prompt" |
| 4300 | allow = ["docs.example.com"] |
| 4301 | "#, |
| 4302 | "public-allow.toml", |
| 4303 | ) |
| 4304 | .expect("public allow bundle parses"); |
| 4305 | assert!(find_rejected_entries(&public_bundle).is_empty()); |
| 4306 | let receipt = apply_bundle(&public_bundle, &mut store, BundleScope::Global, &dir) |
| 4307 | .expect("public network.allow entry must import"); |
| 4308 | assert!(receipt.plan.rejected.is_empty()); |
| 4309 | assert_eq!( |
| 4310 | store |
| 4311 | .config |
| 4312 | .network |
| 4313 | .as_ref() |
| 4314 | .map(|network| network.allow.as_slice()), |
| 4315 | Some(&["docs.example.com".to_string()][..]) |
| 4316 | ); |
| 4317 | } |
| 4318 | |
| 4319 | #[test] |
| 4320 | fn localdomain_and_localhost_wildcard_network_allow_entries_are_rejected_and_scrubbed() { |
| 4321 | for (section, entry) in [ |
| 4322 | ("global", ".localdomain"), |
| 4323 | ("global", "*.localdomain"), |
| 4324 | ("global", ".localhost"), |
| 4325 | ("global", "*.localhost"), |
| 4326 | ("global", "*.dev.localhost"), |
| 4327 | ("project", "*.localdomain"), |
| 4328 | ] { |
| 4329 | let bundle_text = format!( |
| 4330 | r#" |
| 4331 | schema_version = 1 |
| 4332 | kind = "codewhale.portable-config" |
| 4333 | |
| 4334 | [{section}.network] |
| 4335 | default = "prompt" |
| 4336 | allow = ["docs.example.com", "{entry}"] |
| 4337 | "# |
| 4338 | ); |
| 4339 | let bundle = parse_bundle_str(&bundle_text, "wildcard-local-allow.toml") |
| 4340 | .expect("wildcard allow bundle parses"); |
| 4341 | let rejected = find_rejected_entries(&bundle); |
| 4342 | assert_eq!(rejected.len(), 1, "{section} {entry}: {rejected:?}"); |
| 4343 | assert_eq!(rejected[0].key, format!("{section}.network")); |
| 4344 | assert!(rejected[0].reason.contains("network.allow"), "{rejected:?}"); |
| 4345 | assert!(!rejected[0].reason.contains(entry), "{rejected:?}"); |
| 4346 | } |
| 4347 | |
| 4348 | let combined = parse_bundle_str( |
| 4349 | r#" |
| 4350 | schema_version = 1 |
| 4351 | kind = "codewhale.portable-config" |
| 4352 | |
| 4353 | [global.network] |
| 4354 | default = "prompt" |
| 4355 | allow = [".localdomain", "*.localdomain", "*.localhost"] |
| 4356 | "#, |
| 4357 | "combined-wildcard-local-allow.toml", |
| 4358 | ) |
| 4359 | .expect("combined wildcard bundle parses"); |
| 4360 | let mut store = isolated_store(); |
| 4361 | let before = std::fs::read(store.path()).expect("config before import"); |
| 4362 | let dir = store.path().parent().expect("config dir").to_path_buf(); |
| 4363 | apply_bundle(&combined, &mut store, BundleScope::Global, &dir) |
| 4364 | .expect_err("bundle adding local-domain wildcard network.allow entries must fail"); |
| 4365 | assert_eq!( |
| 4366 | std::fs::read(store.path()).expect("config after rejected import"), |
| 4367 | before |
| 4368 | ); |
| 4369 | |
| 4370 | let config: ConfigToml = toml::from_str( |
| 4371 | r#" |
| 4372 | [network] |
| 4373 | default = "prompt" |
| 4374 | allow = ["docs.example.com", ".localdomain", "*.localdomain", ".localhost", "*.localhost", "localhost", "10.0.0.5"] |
| 4375 | "#, |
| 4376 | ) |
| 4377 | .expect("config with local network.allow entries parses"); |
| 4378 | let exported = export_bundle(&config, BundleScope::Global, BundleMetadata::default()) |
| 4379 | .expect("local network.allow entries are scrubbed on export"); |
| 4380 | let body = serialize_bundle(&exported).expect("serialize scrubbed export"); |
| 4381 | for forbidden in [ |
| 4382 | ".localdomain", |
| 4383 | "*.localdomain", |
| 4384 | ".localhost", |
| 4385 | "*.localhost", |
| 4386 | "\"localhost\"", |
| 4387 | "10.0.0.5", |
| 4388 | ] { |
| 4389 | assert!( |
| 4390 | !body.contains(forbidden), |
| 4391 | "export retained {forbidden}: {body}" |
| 4392 | ); |
| 4393 | } |
| 4394 | assert!(body.contains("docs.example.com"), "{body}"); |
| 4395 | assert!(find_rejected_entries(&exported).is_empty(), "{exported:?}"); |
| 4396 | } |
| 4397 | |
| 4398 | #[test] |
| 4399 | fn https_redirect_cannot_downgrade_to_loopback_http() { |
| 4400 | let secret = "downgrade-secret-must-not-leak"; |
| 4401 | let target = reqwest::Url::parse(&format!("http://127.0.0.1/internal?token={secret}")) |
| 4402 | .expect("test target URL"); |
| 4403 | |
| 4404 | let error = validate_bundle_redirect("https", "example.com", &target) |
| 4405 | .expect_err("HTTPS redirect must not downgrade to loopback HTTP"); |
| 4406 | let rendered = format!("{error:#}"); |
| 4407 | assert!(rendered.contains("scheme"), "{rendered}"); |
| 4408 | assert!(!rendered.contains(secret), "{rendered}"); |
| 4409 | assert!(!rendered.contains("127.0.0.1"), "{rendered}"); |
| 4410 | } |
| 4411 | |
| 4412 | fn spawn_counting_server( |
| 4413 | response: Vec<u8>, |
| 4414 | ) -> (u16, std::sync::Arc<std::sync::atomic::AtomicUsize>) { |
| 4415 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 4416 | let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind counting fixture"); |
| 4417 | let port = listener.local_addr().expect("fixture address").port(); |
| 4418 | let hits = std::sync::Arc::new(AtomicUsize::new(0)); |
| 4419 | let counter = std::sync::Arc::clone(&hits); |
| 4420 | std::thread::spawn(move || { |
| 4421 | for stream in listener.incoming() { |
| 4422 | let Ok(mut stream) = stream else { return }; |
| 4423 | counter.fetch_add(1, Ordering::SeqCst); |
| 4424 | let mut chunk = [0_u8; 1024]; |
| 4425 | let _ = stream.read(&mut chunk); |
| 4426 | let _ = stream.write_all(&response); |
| 4427 | } |
| 4428 | }); |
| 4429 | (port, hits) |
| 4430 | } |
| 4431 | |
| 4432 | #[test] |
| 4433 | fn redirect_to_another_local_host_is_refused() { |
| 4434 | use std::sync::atomic::Ordering; |
| 4435 | let (port, hits) = spawn_counting_server(http_response( |
| 4436 | "200 OK", |
| 4437 | &[("Content-Type", "text/plain")], |
| 4438 | VALID_TOML.as_bytes(), |
| 4439 | )); |
| 4440 | let location = format!("http://localhost:{port}/bundle.toml"); |
| 4441 | let redirect = http_response("302 Found", &[("Location", location.as_str())], b""); |
| 4442 | let (url, entry_server) = spawn_bundle_http_server(vec![redirect.clone()]); |
| 4443 | |
| 4444 | let error = fetch_bundle(&url, &NetworkPolicy::default()) |
| 4445 | .expect_err("a hop to another local host must be refused"); |
| 4446 | assert!(!format!("{error:#}").contains("bundle.toml"), "{error:#}"); |
| 4447 | assert_eq!(entry_server.join().expect("entry joins"), 1); |
| 4448 | assert_eq!(hits.load(Ordering::SeqCst), 0); |
| 4449 | |
| 4450 | let (listed_url, listed_entry_server) = spawn_bundle_http_server(vec![redirect]); |
| 4451 | let listed_policy = NetworkPolicy { |
| 4452 | allow: vec!["localhost".to_string()], |
| 4453 | ..NetworkPolicy::default() |
| 4454 | }; |
| 4455 | let listed_error = fetch_bundle(&listed_url, &listed_policy) |
| 4456 | .expect_err("even a listed local host must be refused on redirect from another host"); |
| 4457 | assert!( |
| 4458 | !format!("{listed_error:#}").contains("bundle.toml"), |
| 4459 | "{listed_error:#}" |
| 4460 | ); |
| 4461 | assert_eq!(listed_entry_server.join().expect("listed entry joins"), 1); |
| 4462 | assert_eq!(hits.load(Ordering::SeqCst), 0); |
| 4463 | } |
| 4464 | |
| 4465 | #[test] |
| 4466 | fn relative_loopback_redirect_fetches_bundle() { |
| 4467 | let redirect = http_response("302 Found", &[("Location", "/bundle.toml")], b""); |
| 4468 | let body = VALID_TOML.as_bytes(); |
| 4469 | let success = http_response("200 OK", &[("Content-Type", "text/plain")], body); |
| 4470 | let (url, server) = spawn_bundle_http_server(vec![redirect, success]); |
| 4471 | |
| 4472 | let fetched = fetch_bundle(&url, &NetworkPolicy::default()) |
| 4473 | .expect("relative redirect remains allowed"); |
| 4474 | assert_eq!(fetched, body); |
| 4475 | assert_eq!(server.join().expect("server joins"), 2); |
| 4476 | } |
| 4477 | |
| 4478 | #[test] |
| 4479 | fn redirect_limit_is_enforced_before_a_sixth_hop() { |
| 4480 | let responses = (0..=MAX_REDIRECTS) |
| 4481 | .map(|hop| { |
| 4482 | let location = format!("/hop-{}", hop + 1); |
| 4483 | http_response("302 Found", &[("Location", location.as_str())], b"") |
| 4484 | }) |
| 4485 | .collect(); |
| 4486 | let (url, server) = spawn_bundle_http_server(responses); |
| 4487 | |
| 4488 | let error = fetch_bundle(&url, &NetworkPolicy::default()) |
| 4489 | .expect_err("sixth redirect must be refused"); |
| 4490 | assert!( |
| 4491 | error.to_string().contains("too many redirects"), |
| 4492 | "{error:#}" |
| 4493 | ); |
| 4494 | assert_eq!(server.join().expect("server joins"), MAX_REDIRECTS + 1); |
| 4495 | } |
| 4496 | |
| 4497 | #[test] |
| 4498 | fn bundle_url_credentials_are_rejected_without_echoing_them() { |
| 4499 | let secret = "credential-secret-must-not-leak"; |
| 4500 | let error = fetch_bundle( |
| 4501 | &format!("https://user:{secret}@example.com/bundle.toml"), |
| 4502 | &NetworkPolicy::default(), |
| 4503 | ) |
| 4504 | .expect_err("URL userinfo must be refused"); |
| 4505 | let rendered = format!("{error:#}"); |
| 4506 | assert!(rendered.contains("credentials"), "{rendered}"); |
| 4507 | assert!(!rendered.contains(secret), "{rendered}"); |
| 4508 | assert!(!rendered.contains("example.com"), "{rendered}"); |
| 4509 | } |
| 4510 | |
| 4511 | #[test] |
| 4512 | fn unsupported_schemes_are_refused() { |
| 4513 | let err = fetch_bundle("file:///etc/passwd", &NetworkPolicy::default()) |
| 4514 | .expect_err("file scheme refused"); |
| 4515 | assert!(err.to_string().contains("scheme"), "{err:#}"); |
| 4516 | } |
| 4517 | |
| 4518 | #[test] |
| 4519 | fn headless_import_requires_yes() { |
| 4520 | let plan = ImportPlan { |
| 4521 | added: vec!["preferences.x".to_string()], |
| 4522 | ..ImportPlan::default() |
| 4523 | }; |
| 4524 | // The test harness runs headless (no tty), so consent without --yes |
| 4525 | // must refuse before any prompt. |
| 4526 | let err = require_import_consent(false, &plan).expect_err("headless needs --yes"); |
| 4527 | assert!(err.to_string().contains("--yes"), "{err:#}"); |
| 4528 | require_import_consent(true, &plan).expect("--yes short-circuits consent"); |
| 4529 | } |
| 4530 | |
| 4531 | #[test] |
| 4532 | fn bounded_paths_refuse_traversal_and_absolute_escapes() { |
| 4533 | let base = tempfile::tempdir().expect("base"); |
| 4534 | let err = |
| 4535 | resolve_bounded_path(base.path(), "../escape.toml").expect_err("traversal refused"); |
| 4536 | assert!( |
| 4537 | err.to_string().contains("escapes") || err.to_string().contains("absolute"), |
| 4538 | "{err:#}" |
| 4539 | ); |
| 4540 | let absolute = base.path().join("absolute.toml"); |
| 4541 | let err = resolve_bounded_path(base.path(), absolute.to_string_lossy().as_ref()) |
| 4542 | .expect_err("absolute refused"); |
| 4543 | assert!(err.to_string().contains("absolute"), "{err:#}"); |
| 4544 | let ok = resolve_bounded_path(base.path(), "nested/thing.toml").expect("inside ok"); |
| 4545 | assert!(ok.starts_with(base.path())); |
| 4546 | } |
| 4547 | |
| 4548 | // -- helpers ------------------------------------------------------------ |
| 4549 | |
| 4550 | fn http_response(status: &str, headers: &[(&str, &str)], body: &[u8]) -> Vec<u8> { |
| 4551 | let mut response = format!( |
| 4552 | "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n", |
| 4553 | body.len() |
| 4554 | ) |
| 4555 | .into_bytes(); |
| 4556 | for (name, value) in headers { |
| 4557 | response.extend_from_slice(format!("{name}: {value}\r\n").as_bytes()); |
| 4558 | } |
| 4559 | response.extend_from_slice(b"\r\n"); |
| 4560 | response.extend_from_slice(body); |
| 4561 | response |
| 4562 | } |
| 4563 | |
| 4564 | fn spawn_bundle_http_server( |
| 4565 | responses: Vec<Vec<u8>>, |
| 4566 | ) -> (String, std::thread::JoinHandle<usize>) { |
| 4567 | let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind HTTP fixture"); |
| 4568 | let address = listener.local_addr().expect("fixture address"); |
| 4569 | let handle = std::thread::spawn(move || { |
| 4570 | let mut served = 0usize; |
| 4571 | for response in responses { |
| 4572 | let (mut stream, _) = listener.accept().expect("accept fixture request"); |
| 4573 | stream |
| 4574 | .set_read_timeout(Some(std::time::Duration::from_secs(5))) |
| 4575 | .expect("fixture read timeout"); |
| 4576 | let mut request = Vec::new(); |
| 4577 | let mut chunk = [0_u8; 1024]; |
| 4578 | while !request.windows(4).any(|window| window == b"\r\n\r\n") { |
| 4579 | let read = stream.read(&mut chunk).expect("read fixture request"); |
| 4580 | if read == 0 { |
| 4581 | break; |
| 4582 | } |
| 4583 | request.extend_from_slice(&chunk[..read]); |
| 4584 | } |
| 4585 | stream.write_all(&response).expect("write fixture response"); |
| 4586 | served += 1; |
| 4587 | } |
| 4588 | served |
| 4589 | }); |
| 4590 | (format!("http://{address}/start"), handle) |
| 4591 | } |
| 4592 | |
| 4593 | /// A store over a config file that outlives the helper: the tempdir is |
| 4594 | /// leaked deliberately (tests are short-lived; explicit cleanup would need |
| 4595 | /// to thread the guard through every call site). |
| 4596 | fn isolated_store() -> ConfigStore { |
| 4597 | // Serialize with every other env-mutating test in this crate: a private |
| 4598 | // lock here would still race `ScopedEnvVar` users (observed as a flaky |
| 4599 | // credentials-dir failure in `api_key_config_failure_restores_*`). |
| 4600 | let _guard = crate::tests::env_lock(); |
| 4601 | |
| 4602 | let dir = { |
| 4603 | // TempDir::keep() is the non-deprecated ownership transfer. |
| 4604 | let temp = tempfile::TempDir::new().expect("tempdir"); |
| 4605 | temp.keep() |
| 4606 | }; |
| 4607 | let unique = dir.join("home").join(std::process::id().to_string()); |
| 4608 | std::fs::create_dir_all(&unique).expect("unique home"); |
| 4609 | // SAFETY: test-only env mutation, serialized by the lock above. |
| 4610 | unsafe { std::env::set_var("CODEWHALE_HOME", &unique) }; |
| 4611 | let path = unique.join("config.toml"); |
| 4612 | std::fs::write(&path, "# test config\n").expect("seed config file"); |
| 4613 | ConfigStore::load(Some(path)).expect("store loads") |
| 4614 | } |
| 4615 | } |
| 4616 |