1use serde::{Serialize, Serializer};
23
24const MAX_IDENTIFIER_LEN: usize = 64;
27const MAX_PHRASE_LEN: usize = 80;
29const MAX_ERROR_LEN: usize = 200;
31const OPAQUE_RUN_LEN: usize = 20;
34const FINGERPRINT_HEX_LEN: usize = 12;
36
37#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct SafeLabel {
45 text: String,
46 redacted: bool,
47}
48
49impl SafeLabel {
50 pub fn identifier(raw: &str) -> Self {
54 let trimmed = raw.trim();
55 if identifier_is_allowlisted(trimmed) {
56 Self {
57 text: trimmed.to_string(),
58 redacted: false,
59 }
60 } else {
61 Self::fingerprint(raw)
62 }
63 }
64
65 pub fn catalog_model(raw: &str) -> Self {
70 let trimmed = raw.trim();
71 if !trimmed.contains('/') {
72 return Self::identifier(raw);
73 }
74 if catalog_model_identifier_is_allowlisted(trimmed) {
75 Self {
76 text: trimmed.to_string(),
77 redacted: false,
78 }
79 } else {
80 Self::fingerprint(raw)
81 }
82 }
83
84 pub fn phrase(raw: &str) -> Self {
87 let trimmed = raw.trim();
88 if phrase_is_allowlisted(trimmed) {
89 Self {
90 text: trimmed.to_string(),
91 redacted: false,
92 }
93 } else {
94 Self::fingerprint(raw)
95 }
96 }
97
98 fn fingerprint(raw: &str) -> Self {
100 let digest = crate::hashing::sha256_hex(raw.as_bytes());
101 Self {
102 text: format!("sha256:{}", &digest[..FINGERPRINT_HEX_LEN]),
103 redacted: true,
104 }
105 }
106
107 pub fn as_str(&self) -> &str {
108 &self.text
109 }
110
111 #[cfg(any(test, feature = "test-support"))]
114 pub fn is_redacted(&self) -> bool {
115 self.redacted
116 }
117}
118
119impl std::fmt::Display for SafeLabel {
120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121 f.write_str(&self.text)
122 }
123}
124
125impl Serialize for SafeLabel {
126 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
127 serializer.serialize_str(&self.text)
128 }
129}
130
131fn identifier_is_allowlisted(value: &str) -> bool {
132 if value.is_empty() || value.len() > MAX_IDENTIFIER_LEN {
133 return false;
134 }
135 if value.starts_with('/') || value.starts_with('~') || value.starts_with('.') {
136 return false;
137 }
138 if value.contains("//") || value.contains("..") || value.contains(':') && value.contains('/') {
139 return false;
140 }
141 if !value.chars().all(is_identifier_char) {
142 return false;
143 }
144 if value.contains('/') {
145 return false;
146 }
147 !looks_opaque(value)
148}
149
150fn catalog_model_identifier_is_allowlisted(value: &str) -> bool {
151 if value.is_empty()
152 || value.len() > MAX_IDENTIFIER_LEN
153 || value.starts_with('/')
154 || value.starts_with('~')
155 || value.starts_with('.')
156 || value.contains("//")
157 || value.contains("..")
158 || value.contains(':')
159 || !value.chars().all(is_identifier_char)
160 || looks_opaque(value)
161 {
162 return false;
163 }
164 codewhale_config::catalog::reviewed::public_model_identifier(value)
165}
166
167fn phrase_is_allowlisted(value: &str) -> bool {
168 if value.is_empty() || value.len() > MAX_PHRASE_LEN {
169 return false;
170 }
171 if value.contains('/') || value.contains('\\') || value.contains('~') {
172 return false;
173 }
174 if !value
175 .chars()
176 .all(|ch| is_identifier_char(ch) || matches!(ch, ' ' | '(' | ')' | ','))
177 {
178 return false;
179 }
180 !looks_opaque(value)
181}
182
183fn is_identifier_char(ch: char) -> bool {
184 ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-' | '+' | '@' | ':' | '/')
185}
186
187fn looks_opaque(value: &str) -> bool {
192 let lower = value.to_ascii_lowercase();
193 for marker in ["sk-", "api_key", "apikey", "secret", "password", "bearer"] {
194 if lower.contains(marker) {
195 return true;
196 }
197 }
198 let mut run = 0usize;
199 for ch in value.chars() {
200 if ch.is_ascii_alphanumeric() {
203 run += 1;
204 if run >= OPAQUE_RUN_LEN {
205 return true;
206 }
207 } else {
208 run = 0;
209 }
210 }
211 false
212}
213
214const MAX_ERROR_WORD_LEN: usize = 40;
216const MAX_SCHEME_LEN: usize = 16;
218const MAX_HOST_LEN: usize = 80;
220const REDACTED_WORD: &str = "<redacted>";
222const REDACTED_PATH: &str = "<path-redacted>";
224
225pub fn safe_error_text(raw: &str) -> String {
251 let redacted = codewhale_config::persistence::redact_secrets(raw);
252 let mut out = String::with_capacity(redacted.len().min(MAX_ERROR_LEN));
253 let mut last_was_redacted = false;
254 for token in redacted.split_whitespace() {
255 let safe = safe_error_token(token);
256 if safe.is_empty() {
257 continue;
258 }
259 let is_redacted = safe == REDACTED_WORD;
262 if is_redacted && last_was_redacted {
263 continue;
264 }
265 last_was_redacted = is_redacted;
266 if !out.is_empty() {
267 out.push(' ');
268 }
269 out.push_str(&safe);
270 }
271 if out.is_empty() {
272 out.push_str("<unavailable>");
273 }
274 if out.len() > MAX_ERROR_LEN {
275 out.truncate(
276 (0..=MAX_ERROR_LEN)
277 .rev()
278 .find(|index| out.is_char_boundary(*index))
279 .unwrap_or(0),
280 );
281 out.push('…');
282 }
283 out
284}
285
286fn safe_error_token(token: &str) -> String {
287 if token.chars().any(char::is_control) {
288 return REDACTED_WORD.to_string();
289 }
290 if let Some(scheme_end) = token.find("://") {
293 return safe_url_token(token, scheme_end);
294 }
295 let looks_like_path = token.starts_with('/')
298 || token.starts_with("~/")
299 || token.contains('\\')
300 || (token.len() > 2 && token.as_bytes()[1] == b':' && token.contains('\\'));
301 if looks_like_path {
302 return REDACTED_PATH.to_string();
303 }
304 if token.contains(['"', '\'', '`']) {
307 return REDACTED_WORD.to_string();
308 }
309
310 let (lead, core, trail) = split_sentence_punctuation(token);
311 if core.is_empty() {
312 return format!("{lead}{trail}");
315 }
316 if error_word_is_allowlisted(core) {
317 format!("{lead}{core}{trail}")
318 } else {
319 REDACTED_WORD.to_string()
320 }
321}
322
323fn safe_url_token(token: &str, scheme_end: usize) -> String {
329 let scheme = &token[..scheme_end];
330 let rest = &token[scheme_end + 3..];
331 let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
332 let host = rest[..authority_end].rsplit('@').next().unwrap_or("");
333
334 let scheme_ok = !scheme.is_empty()
335 && scheme.len() <= MAX_SCHEME_LEN
336 && scheme
337 .chars()
338 .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '+' | '-' | '.'));
339 let host_ok = !host.is_empty()
340 && host.len() <= MAX_HOST_LEN
341 && host
342 .chars()
343 .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '-' | ':'))
344 && !looks_opaque(host);
345 if scheme_ok && host_ok {
346 format!("{scheme}://{host}/{REDACTED_PATH}")
347 } else {
348 REDACTED_WORD.to_string()
349 }
350}
351
352fn is_edge_punctuation(ch: char) -> bool {
355 matches!(ch, '.' | ',' | ';' | ':' | '!' | '?' | '(' | ')')
356}
357
358fn split_sentence_punctuation(token: &str) -> (&str, &str, &str) {
363 let start = token
364 .char_indices()
365 .find(|(_, ch)| !is_edge_punctuation(*ch))
366 .map_or(token.len(), |(index, _)| index);
367 let end = token
368 .char_indices()
369 .rev()
370 .find(|(_, ch)| !is_edge_punctuation(*ch))
371 .map_or(start, |(index, ch)| index + ch.len_utf8());
372 (
373 &token[..start],
374 &token[start..end.max(start)],
375 &token[end.max(start)..],
376 )
377}
378
379fn error_word_is_allowlisted(word: &str) -> bool {
381 if word.is_empty() || word.len() > MAX_ERROR_WORD_LEN {
382 return false;
383 }
384 if word.contains("..") {
385 return false;
386 }
387 if !word
388 .chars()
389 .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.'))
390 {
391 return false;
392 }
393 !looks_opaque(word)
394}
395
396const MAX_RECEIPT_FIELD_CHARS: usize = 96;
397
398pub fn safe_receipt_field(raw: &str) -> String {
399 let sanitized = sanitize_persisted_route_label(raw);
400 let mut out = String::with_capacity(raw.len().min(MAX_RECEIPT_FIELD_CHARS));
401 let mut previous_separator = false;
402 for ch in sanitized.chars() {
403 if out.chars().count() >= MAX_RECEIPT_FIELD_CHARS {
404 break;
405 }
406 let safe = if ch.is_alphanumeric() || matches!(ch, '.' | '_' | '-' | '/' | ':' | '+') {
407 ch
408 } else {
409 '_'
410 };
411 let separator = safe == '_';
412 if separator && previous_separator {
413 continue;
414 }
415 out.push(safe);
416 previous_separator = separator;
417 }
418 if out.is_empty() { "-".to_string() } else { out }
419}
420
421pub fn sanitize_persisted_route_label(raw: &str) -> String {
422 const MAX_PERSISTED_ROUTE_LABEL_CHARS: usize = 256;
423 let value = raw.trim();
424 let lower = value.to_ascii_lowercase();
425
426 if value.is_empty() {
427 return "-".to_string();
428 }
429
430 if value.contains("://") {
434 return "redacted-url".to_string();
435 }
436
437 let authorization_value = ["bearer ", "basic ", "digest ", "token ", "apikey "]
438 .iter()
439 .any(|scheme| lower.starts_with(scheme))
440 || lower.contains("authorization:")
441 || lower.contains("proxy-authorization:");
442 if authorization_value {
443 return "redacted-credential".to_string();
444 }
445
446 for (index, ch) in value.char_indices() {
449 if !matches!(ch, '=' | ':') {
450 continue;
451 }
452 let name = lower[..index]
453 .trim()
454 .trim_matches(|ch: char| matches!(ch, '"' | '\'' | '{' | '[' | ','));
455 let name = name.rsplit([' ', ',', ';']).next().unwrap_or(name);
456 let normalized = name.replace('-', "_");
457 if normalized.ends_with("api_key")
458 || normalized.ends_with("token")
459 || normalized.ends_with("secret")
460 || normalized.ends_with("password")
461 || normalized.ends_with("passwd")
462 {
463 return "redacted-credential".to_string();
464 }
465 }
466
467 let credential_prefix = lower
470 .split(|ch: char| ch.is_whitespace() || matches!(ch, '=' | ':' | ',' | ';' | '"' | '\''))
471 .filter(|part| !part.is_empty())
472 .any(|part| {
473 [
474 "sk-",
475 "sk_",
476 "rk-",
477 "pk-",
478 "ghp_",
479 "gho_",
480 "ghu_",
481 "ghs_",
482 "github_pat_",
483 "hf_",
484 "glpat-",
485 "xoxb-",
486 "xoxp-",
487 "xoxa-",
488 "akia",
489 "aiza",
490 "eyj",
491 ]
492 .iter()
493 .any(|prefix| part.starts_with(prefix))
494 });
495 if credential_prefix {
496 return "redacted-credential".to_string();
497 }
498
499 let windows_absolute = value.as_bytes().get(1) == Some(&b':')
500 && value
501 .as_bytes()
502 .get(2)
503 .is_some_and(|separator| matches!(separator, b'/' | b'\\'));
504 let contains_local_root = [
505 "/users/",
506 "/volumes/",
507 "/home/",
508 "/private/",
509 "\\users\\",
510 "file://",
511 "/.ssh/",
512 "\\.ssh\\",
513 ]
514 .iter()
515 .any(|needle| lower.contains(needle));
516 let looks_like_relative_path = value.contains('\\')
517 || lower.starts_with(".ssh/")
518 || lower.starts_with(".ssh\\")
519 || lower.split('/').any(|segment| {
520 matches!(
521 segment,
522 "." | ".."
523 | ".ssh"
524 | ".config"
525 | "secrets"
526 | "secret"
527 | "credentials"
528 | "credential"
529 | "relative"
530 | "workspace"
531 | "tmp"
532 )
533 });
534 if std::path::Path::new(value).is_absolute()
535 || windows_absolute
536 || value.starts_with("~/")
537 || value.starts_with("./")
538 || value.starts_with("../")
539 || contains_local_root
540 || looks_like_relative_path
541 {
542 return "redacted-local-path".to_string();
543 }
544 let bounded: String = value
545 .chars()
546 .filter(|ch| !ch.is_control())
547 .take(MAX_PERSISTED_ROUTE_LABEL_CHARS)
548 .collect();
549 if bounded.is_empty() {
550 "-".to_string()
551 } else {
552 bounded
553 }
554}
555
556#[cfg(test)]
557mod tests {
558 use super::*;
559
560 #[test]
561 fn ordinary_identifiers_pass_through_verbatim() {
562 for value in [
563 "deepseek-chat",
564 "claude-sonnet-4-5",
565 "gpt-5-codex",
566 "MiniMax-M3",
567 "my-gateway",
568 "kimi-k2-0905-preview",
569 ] {
570 let label = SafeLabel::identifier(value);
571 assert_eq!(label.as_str(), value, "{value} must publish verbatim");
572 assert!(!label.is_redacted(), "{value}");
573 }
574 }
575
576 #[test]
577 fn hostile_route_and_model_identifiers_never_reach_a_surface() {
578 let hostile = [
579 "/Users/someone/models/private-weights.gguf".to_string(),
580 "~/.codewhale/config.toml".to_string(),
581 "https://internal.example.com/v1/deployments/prod".to_string(),
582 "C:\\Users\\someone\\models\\weights.bin".to_string(),
583 ["sk", "-fixture-not-a-real-key-00000000"].concat(),
584 "deployments/9f8e7d6c5b4a39281706abcdef012345".to_string(),
585 "../../etc/passwd".to_string(),
586 "model with spaces and a /path/inside".to_string(),
587 ["api_key=sk", "-live-1234567890"].concat(),
588 "src/lib.rs".to_string(),
589 "config/prod".to_string(),
590 "models/weights.gguf".to_string(),
591 "foo/bar-baz".to_string(),
592 ];
593 for value in hostile {
594 let label = SafeLabel::identifier(&value);
595 assert!(label.is_redacted(), "`{value}` must not publish verbatim");
596 assert!(label.as_str().starts_with("sha256:"), "{}", label.as_str());
597 assert!(!label.as_str().contains('/'), "{}", label.as_str());
598 assert!(!label.as_str().contains(' '), "{}", label.as_str());
599 }
600 }
601
602 #[test]
603 fn generic_identifiers_reject_all_slashes_and_catalog_models_require_exact_ids() {
604 for path in [
605 "src/lib.rs",
606 "docs/PREVIEW_REQUEST.md",
607 "config/prod",
608 "models/llama-3.gguf",
609 "foo/bar-baz",
610 ] {
611 assert!(
612 SafeLabel::identifier(path).is_redacted(),
613 "relative path `{path}` must not be published"
614 );
615 }
616
617 let known = "qwen/qwen3.6-flash";
618 assert!(SafeLabel::identifier(known).is_redacted());
619 assert_eq!(SafeLabel::catalog_model(known).as_str(), known);
620 for hostile in ["openai/secrets/config", "qwen/src/lib.rs"] {
621 assert!(SafeLabel::identifier(hostile).is_redacted());
622 assert!(SafeLabel::catalog_model(hostile).is_redacted());
623 }
624 }
625
626 #[test]
627 fn fingerprints_are_stable_and_distinguishing() {
628 let first = SafeLabel::identifier("/models/a.gguf");
629 let second = SafeLabel::identifier("/models/a.gguf");
630 let other = SafeLabel::identifier("/models/b.gguf");
631 assert_eq!(first, second);
632 assert_ne!(first, other);
633 }
634
635 #[test]
636 fn phrases_allow_spaces_but_not_paths() {
637 assert_eq!(
638 SafeLabel::phrase("Codex OAuth quota").as_str(),
639 "Codex OAuth quota"
640 );
641 assert!(SafeLabel::phrase("/opt/quota/plan").is_redacted());
642 }
643
644 #[test]
645 fn error_text_is_path_and_url_path_safe() {
646 let raw = "MCP server 'x' failed: cannot spawn /Users/someone/work/repo/bin/server \
647 while calling https://gateway.internal.example.com/v1/secret-deployment/messages";
648 let safe = safe_error_text(raw);
649 assert!(!safe.contains("/Users/someone"), "{safe}");
650 assert!(!safe.contains("/v1/secret-deployment"), "{safe}");
651 assert!(safe.contains("<path-redacted>"), "{safe}");
652 assert!(
653 safe.contains("https://gateway.internal.example.com/<path-redacted>"),
654 "{safe}"
655 );
656 }
657
658 #[test]
662 fn hostile_error_text_never_publishes_the_hostile_part() {
663 let home = std::env::var("HOME").unwrap_or_else(|_| "/root".to_string());
664 let hostile: Vec<String> = vec![
665 "route 'prod-key-8f2a' rejected key sk-live-abcdef0123456789abcdef".to_string(),
666 "cannot read C:\\Users\\someone\\.codewhale\\config.toml".to_string(),
667 format!("cannot read {home}/.codewhale/config.toml"),
668 "GET https://gw.example.com/v1/deployments/prod-key-8f2a?api_key=sk-1234567890abcdef failed".to_string(),
669 "server \"my secret server\" refused: password=hunter2".to_string(),
670 "model /Users/someone/models/private.gguf is unavailable".to_string(),
671 "authorization: Bearer eyJhbGciFAKEFIXTUREnotasecret".to_string(),
672 "endpoint http://10.0.0.5:8443/internal/deploy-9f8e7d6c5b4a3928 timed out".to_string(),
673 format!("crash{}oops", '\u{7}'),
674 ];
675 for raw in &hostile {
676 let safe = safe_error_text(raw);
677 for forbidden in [
678 "prod-key-8f2a",
679 "sk-live-",
680 "sk-1234567890",
681 "/Users/someone",
682 "C:\\Users",
683 ".codewhale",
684 "api_key=",
685 "hunter2",
686 "password=",
687 "eyJhbGci",
688 "/v1/deployments",
689 "/internal/deploy",
690 "private.gguf",
691 "my secret server",
692 ] {
693 assert!(
694 !safe.contains(forbidden),
695 "`{forbidden}` leaked from `{raw}`:\n{safe}"
696 );
697 }
698 assert!(!safe.contains(&home), "home leaked from `{raw}`:\n{safe}");
699 assert!(!safe.contains('"'), "{safe}");
700 assert!(!safe.contains('\''), "{safe}");
701 assert!(!safe.contains('`'), "{safe}");
702 assert!(!safe.chars().any(char::is_control), "{safe}");
703 }
704 }
705
706 #[test]
707 fn ordinary_error_words_survive_so_the_message_stays_useful() {
708 let safe = safe_error_text("the shared route planner could not resolve this turn.");
709 assert_eq!(
710 safe, "the shared route planner could not resolve this turn.",
711 "an allowlisted sentence must survive intact"
712 );
713 }
714
715 #[test]
716 fn a_url_with_a_hostile_authority_is_dropped_rather_than_half_published() {
717 let safe = safe_error_text("calling https://9f8e7d6c5b4a39281706abcdef012345.example/x");
720 assert!(!safe.contains("9f8e7d6c5b4a3928"), "{safe}");
721 assert!(safe.contains("<redacted>"), "{safe}");
722 }
723
724 #[test]
725 fn error_text_is_bounded_and_single_line() {
726 let raw = format!("failure {}", "x".repeat(4_000));
727 let safe = safe_error_text(&raw);
728 assert!(safe.chars().count() <= MAX_ERROR_LEN + 1, "{}", safe.len());
729 assert!(!safe.contains('\n'));
730 }
731}