返回 CodeWhale
redaction.rs
根目录 / crates / config / src / redaction.rs
1 //! Model-bound redaction opt-out (`[redaction] model_bound`).
2 //!
3 //! Codewhale masks credential-looking values in tool output before it is sent
4 //! to an upstream model (the "model boundary"). That masking is a security
5 //! backstop: a file read by a tool can contain a configured API key, a bare
6 //! provider token, or a credential-shaped opaque string, and the model must
7 //! never see those bytes.
8 //!
9 //! This module adds a deliberate, documented way to turn that masking off for
10 //! users who must edit files that contain real credentials. Because it lowers
11 //! a security boundary, it is not a plain boolean:
12 //!
13 //! * Setting `[redaction] model_bound = "disabled"` in `config.toml` only
14 //! records a *request*.
15 //! * The request takes effect only after a restart of the interactive TUI and
16 //! an explicit confirmation on the startup gate screen, which persists a
17 //! receipt next to the config file actually loaded by that launch.
18 //! * Non-interactive entry points (`codewhale exec`, hooks, automation) never
19 //! confirm anything; as long as no confirmation receipt exists they resolve
20 //! to the safe default (`Enabled`), whatever the config file says.
21 //! * Dismissing the gate (choosing "keep masking on") leaves the config field
22 //! and the receipt untouched, so the next launch asks again until the user
23 //! confirms or edits the field back to `"enabled"`.
24 //!
25 //! A confirmation receipt is bound to the loaded config file, including an
26 //! explicit `--config` or `CODEWHALE_CONFIG_PATH`. Different config filenames
27 //! have independent receipts. A receipt is honored only while the canonical
28 //! path, contents and modification time still match and the config requests
29 //! `"disabled"`.
30 //! Editing the field back to `"enabled"` - or changing `config.toml` in any
31 //! way - and later re-requesting `"disabled"` always asks for a fresh
32 //! confirmation, even when no process ran in between.
33
34 use serde::{Deserialize, Serialize};
35 use sha2::{Digest, Sha256};
36 use std::fs;
37 use std::io;
38 use std::path::{Path, PathBuf};
39
40 /// Name of the confirmation-receipt file, stored next to `config.toml` in the
41 /// Codewhale home directory.
42 pub const MODEL_BOUND_STATE_FILE_NAME: &str = "redaction-state.json";
43
44 /// Whether credential-shaped values are masked at the model boundary.
45 ///
46 /// Parsing is deliberately forgiving on the way in — the config value is a
47 /// security switch and users reach for boolean spellings — so `true`/`false`,
48 /// `"on"`/`"off"`, and `"enabled"`/`"disabled"` (any casing) all resolve to
49 /// the same two states. Serialization always writes the canonical
50 /// `"enabled"` / `"disabled"` words.
51 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
52 #[serde(rename_all = "kebab-case")]
53 pub enum ModelBoundMasking {
54 /// Mask credential-shaped tool output before it reaches the model (default).
55 #[default]
56 Enabled,
57 /// Let the model see the raw bytes of tool output, credentials included.
58 /// Only effective after an explicit startup confirmation (see the module
59 /// docs); until then it resolves to [`ModelBoundMasking::Enabled`].
60 Disabled,
61 }
62
63 impl ModelBoundMasking {
64 pub fn is_disabled(self) -> bool {
65 self == Self::Disabled
66 }
67 }
68
69 impl<'de> serde::Deserialize<'de> for ModelBoundMasking {
70 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
71 where
72 D: serde::Deserializer<'de>,
73 {
74 #[derive(serde::Deserialize)]
75 #[serde(untagged)]
76 enum Raw {
77 Flag(bool),
78 Word(String),
79 }
80 match Raw::deserialize(deserializer)? {
81 Raw::Flag(true) => Ok(ModelBoundMasking::Enabled),
82 Raw::Flag(false) => Ok(ModelBoundMasking::Disabled),
83 Raw::Word(word) => match word.to_ascii_lowercase().as_str() {
84 "enabled" | "on" | "true" => Ok(ModelBoundMasking::Enabled),
85 "disabled" | "off" | "false" => Ok(ModelBoundMasking::Disabled),
86 other => Err(serde::de::Error::unknown_variant(
87 other,
88 &["enabled", "disabled", "on", "off", "true", "false"],
89 )),
90 },
91 }
92 }
93 }
94
95 /// The `[redaction]` table of `config.toml`.
96 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
97 #[serde(default)]
98 pub struct RedactionToml {
99 /// Model-bound masking policy: `"enabled"` (default) or `"disabled"`.
100 /// Boolean spellings are also accepted: `false` / `"off"` mean the same
101 /// as `"disabled"`, and `true` / `"on"` mean `"enabled"`.
102 ///
103 /// A `"disabled"` request is honored only after a TUI restart and a one-time
104 /// confirmation on the startup gate; see the module documentation.
105 #[serde(skip_serializing_if = "Option::is_none")]
106 pub model_bound: Option<ModelBoundMasking>,
107 }
108
109 impl RedactionToml {
110 /// The requested masking mode, defaulting to [`ModelBoundMasking::Enabled`].
111 pub fn model_bound_masking(&self) -> ModelBoundMasking {
112 self.model_bound.unwrap_or_default()
113 }
114 }
115
116 /// Receipt belonging to this exact config file. Keep the established name
117 /// for config.toml; other filenames get independent receipts even when they
118 /// live in the same directory and contain identical configuration.
119 pub fn model_bound_state_path(config_path: &Path) -> PathBuf {
120 // --config and environment resolution may spell the same file through
121 // different symlinks (for example /var and /private/var on macOS).
122 let resolved = config_path.canonicalize().ok();
123 let config_path = resolved.as_deref().unwrap_or(config_path);
124 if config_path.file_name() == Some(std::ffi::OsStr::new(crate::CONFIG_FILE_NAME)) {
125 config_path.with_file_name(MODEL_BOUND_STATE_FILE_NAME)
126 } else {
127 let identity: String = Sha256::digest(config_path.as_os_str().as_encoded_bytes())
128 .iter()
129 .map(|byte| format!("{byte:02x}"))
130 .collect();
131 config_path.with_file_name(format!("redaction-state-{identity}.json"))
132 }
133 }
134
135 /// Clear only this config's confirmation. A stale receipt is rejected even
136 /// when filesystem errors prevent this best-effort sweep.
137 pub fn clear_model_bound_disabled_confirmation(config_path: &Path) -> io::Result<()> {
138 let path = model_bound_state_path(config_path);
139 for attempt in 0..6 {
140 match write_state(&path, config_path, false) {
141 Ok(()) => {
142 let _ = fs::remove_file(&path);
143 return Ok(());
144 }
145 Err(_) if attempt < 5 => {
146 std::thread::sleep(std::time::Duration::from_millis(100));
147 }
148 Err(err) => return Err(err),
149 }
150 }
151 unreachable!()
152 }
153
154 /// Persist consent for the config that was actually loaded by the caller.
155 /// Never infer that source from the receipt directory or the process home.
156 pub fn record_model_bound_disabled_confirmation(config_path: &Path) -> io::Result<PathBuf> {
157 let path = model_bound_state_path(config_path);
158 write_state(&path, config_path, true)?;
159 Ok(path)
160 }
161
162 pub fn confirmation_required(desired: ModelBoundMasking, config_path: Option<&Path>) -> bool {
163 desired.is_disabled() && !confirmed_for_current_request(desired, config_path)
164 }
165
166 /// Unloaded, unreadable, changed and unconfirmed requests remain masked.
167 pub fn effective_masking(
168 desired: ModelBoundMasking,
169 config_path: Option<&Path>,
170 ) -> ModelBoundMasking {
171 if confirmed_for_current_request(desired, config_path) {
172 ModelBoundMasking::Disabled
173 } else {
174 ModelBoundMasking::Enabled
175 }
176 }
177
178 fn confirmed_for_current_request(desired: ModelBoundMasking, config_path: Option<&Path>) -> bool {
179 let Some(config_path) = config_path else {
180 return false;
181 };
182 let receipt = read_state(&model_bound_state_path(config_path));
183 if !receipt.model_bound_disabled_confirmed {
184 return false;
185 }
186 let current = config_binding(config_path).ok();
187 if !desired.is_disabled() || current.is_none() || current != receipt.config_binding {
188 let _ = clear_model_bound_disabled_confirmation(config_path);
189 return false;
190 }
191 true
192 }
193
194 // === State-file plumbing (path-parameterized so tests stay hermetic) ===
195
196 #[derive(Debug, Default, Serialize, Deserialize)]
197 #[serde(default)]
198 struct StateFile {
199 model_bound_disabled_confirmed: bool,
200 config_binding: Option<ConfigBinding>,
201 }
202
203 #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
204 struct ConfigBinding {
205 config_path: PathBuf,
206 sha256: [u8; 32],
207 modified: std::time::SystemTime,
208 }
209
210 fn config_binding(config_path: &Path) -> io::Result<ConfigBinding> {
211 let config_path = config_path.canonicalize()?;
212 let file = fs::File::open(&config_path)?;
213 let modified = file.metadata()?.modified()?;
214 let body = crate::path_io::read_bounded_file_to_string(
215 &file,
216 &config_path,
217 crate::path_io::MAX_CONFIG_FILE_BYTES,
218 "config file",
219 )?;
220 let config: crate::ConfigToml = toml::from_str(&body)
221 .map_err(|_| io::Error::other("cannot confirm an unreadable redaction config"))?;
222 if !config.redaction_model_bound_masking().is_disabled() {
223 return Err(io::Error::other(
224 "config does not request disabling model-bound masking",
225 ));
226 }
227 Ok(ConfigBinding {
228 config_path,
229 sha256: Sha256::digest(body.as_bytes()).into(),
230 modified,
231 })
232 }
233
234 fn read_state(path: &std::path::Path) -> StateFile {
235 // A receipt is something this process wrote. A link in its place is never
236 // read through, so it cannot vouch for an opt-out; unconfirmed is the
237 // safe answer.
238 if fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_symlink()) {
239 return StateFile::default();
240 }
241 fs::read_to_string(path)
242 .ok()
243 .and_then(|body| serde_json::from_str(&body).ok())
244 .unwrap_or_default()
245 }
246
247 fn write_state(path: &Path, config_path: &Path, confirmed: bool) -> io::Result<()> {
248 let body = serde_json::to_string_pretty(&StateFile {
249 model_bound_disabled_confirmed: confirmed,
250 config_binding: if confirmed {
251 Some(config_binding(config_path)?)
252 } else {
253 None
254 },
255 })
256 .map_err(io::Error::other)?;
257 // Owner-only (0600 on Unix) through a temporary file renamed into place:
258 // the receipt's own name is replaced, never written through, so a link
259 // planted there cannot redirect the write.
260 crate::persistence::atomic_write(path, body.as_bytes())
261 .map_err(|error| io::Error::other(format!("{error:#}")))
262 }
263
264 #[cfg(test)]
265 mod tests {
266 use super::*;
267 use std::path::Path;
268
269 fn state_path(tmp: &Path) -> PathBuf {
270 tmp.join(MODEL_BOUND_STATE_FILE_NAME)
271 }
272
273 #[test]
274 fn absent_state_is_not_confirmed() {
275 let tmp = tempfile::tempdir().expect("tempdir");
276 assert!(!read_state(&state_path(tmp.path())).model_bound_disabled_confirmed);
277 }
278
279 /// The receipt is written owner-only, never through a link planted at its
280 /// name, and carries a path, a digest and a timestamp, not config text.
281 #[test]
282 fn receipt_is_private_never_written_through_a_link_and_holds_no_config_text() {
283 let tmp = tempfile::tempdir().expect("tempdir");
284 let config_path = tmp.path().join(crate::CONFIG_FILE_NAME);
285 let secret = "sk-redaction-receipt-marker-0123456789abcdef";
286 fs::write(
287 &config_path,
288 format!("api_key = \"{secret}\"\n[redaction]\nmodel_bound = \"disabled\"\n"),
289 )
290 .expect("write config");
291
292 // Plant a link where the receipt will go.
293 #[cfg(unix)]
294 let victim = {
295 let victim = tmp.path().join("victim.txt");
296 fs::write(&victim, "keep me").expect("victim");
297 std::os::unix::fs::symlink(&victim, model_bound_state_path(&config_path))
298 .expect("plant link");
299 assert!(
300 !read_state(&model_bound_state_path(&config_path)).model_bound_disabled_confirmed
301 );
302 victim
303 };
304
305 let receipt = record_model_bound_disabled_confirmation(&config_path).expect("record");
306 let body = fs::read_to_string(&receipt).expect("receipt");
307 assert!(body.contains("\"sha256\""), "{body}");
308 assert!(
309 !body.contains(secret),
310 "a receipt never carries config text"
311 );
312 assert!(
313 !body.contains("api_key"),
314 "a receipt never carries config text"
315 );
316 assert!(read_state(&receipt).model_bound_disabled_confirmed);
317
318 #[cfg(unix)]
319 {
320 use std::os::unix::fs::PermissionsExt;
321 assert_eq!(fs::read_to_string(&victim).unwrap(), "keep me");
322 let metadata = fs::symlink_metadata(&receipt).unwrap();
323 assert!(!metadata.file_type().is_symlink(), "the link was replaced");
324 assert_eq!(metadata.permissions().mode() & 0o777, 0o600);
325 }
326 }
327
328 #[test]
329 fn confirmation_round_trips_through_the_state_file() {
330 let tmp = tempfile::tempdir().expect("tempdir");
331 let path = state_path(tmp.path());
332 fs::write(
333 tmp.path().join(crate::CONFIG_FILE_NAME),
334 "[redaction]\nmodel_bound = \"disabled\"\n",
335 )
336 .expect("write config");
337 write_state(&path, &tmp.path().join(crate::CONFIG_FILE_NAME), true).expect("write state");
338 assert!(read_state(&path).model_bound_disabled_confirmed);
339 }
340
341 /// The disable-and-confirm lifecycle belongs to one explicit config.
342 #[test]
343 fn loaded_path_lifecycle_requires_confirmation_before_disabling() {
344 let tmp = tempfile::tempdir().expect("tempdir");
345 let config_path = tmp.path().join(crate::CONFIG_FILE_NAME);
346 assert!(!confirmed_for_current_request(
347 ModelBoundMasking::Disabled,
348 Some(&config_path)
349 ));
350
351 let desired = ModelBoundMasking::Disabled;
352 assert!(confirmation_required(desired, Some(&config_path)));
353 assert_eq!(
354 effective_masking(desired, Some(&config_path)),
355 ModelBoundMasking::Enabled
356 );
357
358 assert!(
359 record_model_bound_disabled_confirmation(&config_path).is_err(),
360 "missing config cannot authorize an opt-out"
361 );
362 let config_path = tmp.path().join(crate::CONFIG_FILE_NAME);
363 let disabled_config = "[redaction]\nmodel_bound = \"disabled\"\n";
364 fs::write(&config_path, disabled_config).expect("write disabled config");
365 let written = record_model_bound_disabled_confirmation(&config_path).expect("record");
366 assert_eq!(
367 written,
368 tmp.path()
369 .canonicalize()
370 .unwrap()
371 .join(MODEL_BOUND_STATE_FILE_NAME)
372 );
373 assert!(confirmed_for_current_request(
374 ModelBoundMasking::Disabled,
375 Some(&config_path)
376 ));
377 assert!(!confirmation_required(desired, Some(&config_path)));
378 assert_eq!(
379 effective_masking(desired, Some(&config_path)),
380 ModelBoundMasking::Disabled
381 );
382
383 // Windows real-time AV scanning can hold a short exclusive lock on a
384 // file we just wrote; the confirm -> re-enable sweep below rewrites
385 // that same file back-to-back, which is exactly the lock window. The
386 // product flow never does this (record and sweep happen on different
387 // launches), so back off briefly here to keep the test deterministic
388 // on Defender-equipped machines.
389 std::thread::sleep(std::time::Duration::from_millis(300));
390
391 // An enabled request never disables, even with a receipt on disk -
392 // and going back to enabled invalidates the receipt, so the next
393 // disabled request must be confirmed again.
394 let enabled = ModelBoundMasking::Enabled;
395 assert!(!confirmation_required(enabled, Some(&config_path)));
396 assert_eq!(
397 effective_masking(enabled, Some(&config_path)),
398 ModelBoundMasking::Enabled
399 );
400 clear_model_bound_disabled_confirmation(&config_path)
401 .expect("explicit clear must succeed after re-enabling");
402 assert!(
403 !confirmed_for_current_request(ModelBoundMasking::Disabled, Some(&config_path)),
404 "returning to enabled must clear the confirmation receipt"
405 );
406
407 // Re-disabling after an enabled period asks again from scratch.
408 assert!(confirmation_required(desired, Some(&config_path)));
409 assert_eq!(
410 effective_masking(desired, Some(&config_path)),
411 ModelBoundMasking::Enabled
412 );
413
414 // The receipt is bound to the config it was made against: rewriting
415 // config.toml after a fresh confirmation (an enabled -> disabled
416 // round trip with zero processes in between) must invalidate it too.
417 record_model_bound_disabled_confirmation(&config_path).expect("record again");
418 assert!(!confirmation_required(desired, Some(&config_path)));
419 // Ensure config.toml is strictly newer than the receipt before the
420 // rewrite check runs.
421 std::thread::sleep(std::time::Duration::from_millis(30));
422 std::fs::write(
423 tmp.path().join(crate::CONFIG_FILE_NAME),
424 "[redaction]\nmodel_bound = \"disabled\"\n",
425 )
426 .expect("touch config after receipt");
427 assert!(
428 confirmation_required(desired, Some(&config_path)),
429 "a config rewritten after the receipt must force a fresh confirmation"
430 );
431 assert_eq!(
432 effective_masking(desired, Some(&config_path)),
433 ModelBoundMasking::Enabled
434 );
435
436 record_model_bound_disabled_confirmation(&config_path).expect("confirm readable config");
437 let original_mtime = fs::metadata(&config_path).unwrap().modified().unwrap();
438 fs::write(&config_path, format!("{disabled_config}# changed\n")).unwrap();
439 fs::File::options()
440 .write(true)
441 .open(&config_path)
442 .unwrap()
443 .set_times(fs::FileTimes::new().set_modified(original_mtime))
444 .unwrap();
445 assert_eq!(
446 effective_masking(desired, Some(&config_path)),
447 ModelBoundMasking::Enabled,
448 "changed bytes with preserved timestamps must invalidate confirmation"
449 );
450
451 record_model_bound_disabled_confirmation(&config_path).expect("confirm updated config");
452 fs::remove_file(&config_path).unwrap();
453 assert_eq!(
454 effective_masking(desired, Some(&config_path)),
455 ModelBoundMasking::Enabled,
456 "missing config metadata must fail closed"
457 );
458 fs::write(&config_path, disabled_config).unwrap();
459 fs::write(&written, r#"{"model_bound_disabled_confirmed":true}"#).unwrap();
460 assert_eq!(
461 effective_masking(desired, Some(&config_path)),
462 ModelBoundMasking::Enabled,
463 "legacy receipts without a config binding cannot authorize the opt-out"
464 );
465 fs::write(&config_path, "[redaction]\nmodel_bound = \"enabled\"\n").unwrap();
466 assert!(
467 record_model_bound_disabled_confirmation(&config_path).is_err(),
468 "a loaded disabled request cannot confirm an enabled file on disk"
469 );
470 }
471
472 #[test]
473 fn custom_configs_cannot_borrow_or_erase_each_others_confirmation() {
474 let temp = tempfile::tempdir().unwrap();
475 let default = temp.path().join("config.toml");
476 let custom = temp.path().join("work.toml");
477 let other = temp.path().join("personal.toml");
478 for path in [&default, &custom, &other] {
479 fs::write(path, "[redaction]\nmodel_bound = \"disabled\"\n").unwrap();
480 }
481 let desired = ModelBoundMasking::Disabled;
482 record_model_bound_disabled_confirmation(&default).unwrap();
483 assert!(confirmation_required(desired, Some(&custom)));
484 record_model_bound_disabled_confirmation(&custom).unwrap();
485 assert!(!confirmation_required(desired, Some(&custom)));
486 assert!(confirmation_required(desired, Some(&other)));
487 assert_ne!(
488 model_bound_state_path(&custom),
489 model_bound_state_path(&other)
490 );
491 assert_ne!(
492 model_bound_state_path(&custom),
493 model_bound_state_path(&default)
494 );
495
496 // Re-enabling one config must not revoke either of the other files.
497 record_model_bound_disabled_confirmation(&other).unwrap();
498 assert_eq!(
499 effective_masking(ModelBoundMasking::Enabled, Some(&custom)),
500 ModelBoundMasking::Enabled
501 );
502 assert!(confirmation_required(desired, Some(&custom)));
503 assert!(!confirmation_required(desired, Some(&default)));
504 assert!(!confirmation_required(desired, Some(&other)));
505 assert!(confirmation_required(desired, None));
506 assert_eq!(effective_masking(desired, None), ModelBoundMasking::Enabled);
507 }
508
509 #[test]
510 fn copied_receipt_cannot_confirm_identical_file_with_identical_timestamp() {
511 let temp = tempfile::tempdir().unwrap();
512 let source = temp.path().join("first.toml");
513 let destination = temp.path().join("second.toml");
514 fs::write(&source, "[redaction]\nmodel_bound = \"disabled\"\n").unwrap();
515 fs::copy(&source, &destination).unwrap();
516 let modified = fs::metadata(&source).unwrap().modified().unwrap();
517 fs::File::options()
518 .write(true)
519 .open(&destination)
520 .unwrap()
521 .set_times(fs::FileTimes::new().set_modified(modified))
522 .unwrap();
523 let receipt = record_model_bound_disabled_confirmation(&source).unwrap();
524 fs::copy(receipt, model_bound_state_path(&destination)).unwrap();
525 assert!(confirmation_required(
526 ModelBoundMasking::Disabled,
527 Some(&destination)
528 ));
529 assert!(!confirmation_required(
530 ModelBoundMasking::Disabled,
531 Some(&source)
532 ));
533 }
534
535 #[test]
536 fn custom_confirmation_reads_loaded_file_instead_of_sibling_config_toml() {
537 let temp = tempfile::tempdir().unwrap();
538 let custom = temp.path().join("selected.toml");
539 let default = temp.path().join("config.toml");
540 fs::write(&default, "[redaction]\nmodel_bound = \"disabled\"\n").unwrap();
541 assert!(record_model_bound_disabled_confirmation(&custom).is_err());
542 fs::write(&custom, "[redaction]\nmodel_bound = \"enabled\"\n").unwrap();
543 assert!(record_model_bound_disabled_confirmation(&custom).is_err());
544 fs::write(&custom, "[redaction]\nmodel_bound = \"disabled\"\n").unwrap();
545 fs::write(&default, "[redaction]\nmodel_bound = \"enabled\"\n").unwrap();
546 record_model_bound_disabled_confirmation(&custom).unwrap();
547 assert!(!confirmation_required(
548 ModelBoundMasking::Disabled,
549 Some(&custom)
550 ));
551 assert!(!model_bound_state_path(&default).exists());
552 }
553
554 #[test]
555 fn corrupt_state_reads_as_unconfirmed() {
556 let tmp = tempfile::tempdir().expect("tempdir");
557 let path = state_path(tmp.path());
558 std::fs::write(&path, "not json at all").expect("write corrupt state");
559 assert!(!read_state(&path).model_bound_disabled_confirmed);
560 }
561
562 #[test]
563 fn toml_table_parses_and_round_trips() {
564 let parsed: crate::ConfigToml =
565 toml::from_str("[redaction]\nmodel_bound = \"disabled\"\n").expect("parse");
566 assert_eq!(
567 parsed
568 .redaction
569 .as_ref()
570 .expect("redaction table")
571 .model_bound_masking(),
572 ModelBoundMasking::Disabled
573 );
574
575 let absent: crate::ConfigToml = toml::from_str("").expect("parse empty");
576 assert_eq!(
577 absent.redaction_model_bound_masking(),
578 ModelBoundMasking::Enabled
579 );
580
581 let serialized = toml::to_string(&parsed).expect("serialize");
582 assert!(
583 serialized.contains("model_bound = \"disabled\""),
584 "{serialized}"
585 );
586 }
587
588 /// The switch reads like a boolean to most people (`model_bound = false`
589 /// is the natural way to ask "don't mask"). Accept boolean and on/off
590 /// spellings so a plain `false` cannot hard-fail config parsing.
591 #[test]
592 fn boolean_and_on_off_spellings_parse_to_the_same_states() {
593 for (body, expected) in [
594 ("model_bound = false", ModelBoundMasking::Disabled),
595 ("model_bound = true", ModelBoundMasking::Enabled),
596 ("model_bound = \"false\"", ModelBoundMasking::Disabled),
597 ("model_bound = \"off\"", ModelBoundMasking::Disabled),
598 ("model_bound = \"OFF\"", ModelBoundMasking::Disabled),
599 ("model_bound = \"on\"", ModelBoundMasking::Enabled),
600 ("model_bound = \"disabled\"", ModelBoundMasking::Disabled),
601 ("model_bound = \"ENABLED\"", ModelBoundMasking::Enabled),
602 ] {
603 let parsed: crate::ConfigToml =
604 toml::from_str(&format!("[redaction]\n{body}\n")).expect("parse");
605 assert_eq!(parsed.redaction_model_bound_masking(), expected, "{body}");
606 }
607
608 // Garbage stays a hard error with a useful message, not a silent default.
609 let err = toml::from_str::<crate::ConfigToml>("[redaction]\nmodel_bound = \"maybe\"\n")
610 .expect_err("unknown variant must fail");
611 assert!(err.to_string().contains("enabled"), "{err}");
612 }
613
614 #[test]
615 fn config_binding_rejects_oversized_config_before_parse() {
616 let tmp = tempfile::tempdir().expect("tempdir");
617 let config_path = tmp.path().join(crate::CONFIG_FILE_NAME);
618 let mut body = String::from("[redaction]\nmodel_bound = \"disabled\"\n# ");
619 body.push_str(&"x".repeat(crate::path_io::MAX_CONFIG_FILE_BYTES as usize + 64));
620 body.push('\n');
621 fs::write(&config_path, &body).expect("write oversized config");
622
623 let err = config_binding(&config_path).expect_err("oversized config must be rejected");
624 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
625 assert!(err.to_string().contains("1 MiB"), "{err}");
626 assert!(record_model_bound_disabled_confirmation(&config_path).is_err());
627 assert_eq!(
628 effective_masking(ModelBoundMasking::Disabled, Some(&config_path)),
629 ModelBoundMasking::Enabled
630 );
631 }
632 }
633
633 lines RUST