返回 CodeWhale
payload.rs
根目录 / crates / notify / src / payload.rs
1 //! Typed, bounded, redaction-aware desktop notification payloads (#4834).
2 //!
3 //! Before this module every desktop notification was a single free-form
4 //! `String` assembled at the call site and handed straight to the OS.
5 //! Notification Center on macOS (and the equivalent surface behind OSC 9 /
6 //! OSC 99 / OSC 777) is lock-screen capable: whatever happened to be in
7 //! that string — a pasted API key, an absolute path that names the user
8 //! and their client, the full shell command awaiting approval — was
9 //! rendered verbatim to anyone looking at the machine.
10 //!
11 //! [`NotificationPayload`] replaces the string with a closed set of event
12 //! kinds and three bounded fields:
13 //!
14 //! | field | max chars | contents |
15 //! |------------|-----------|-------------------------------------------|
16 //! | `headline` | 80 | localized event label (+ elapsed/cost) |
17 //! | `detail` | 120 | short, event-specific identifier |
18 //! | `preview` | 200 | assistant text — two kinds only |
19 //!
20 //! Every field passes through [`sanitize_field`], which strips control
21 //! bytes, collapses newlines and whitespace runs, and redacts credentials,
22 //! absolute local paths, and structured tool input. There is no
23 //! constructor that bypasses it, and `preview` is gated by
24 //! [`NotificationKind::allows_preview`] rather than by the caller.
25 //!
26 //! ## What each kind is allowed to show
27 //!
28 //! - [`NotificationKind::TurnComplete`] — the localized "Turn complete"
29 //! headline (plus elapsed/cost when `include_summary` is on) and a
30 //! preview of the assistant's own reply. Unchanged in spirit from the
31 //! previous behavior; now bounded and redacted.
32 //! - [`NotificationKind::SubagentTerminal`] — localized status headline,
33 //! the sub-agent's display name as detail, and a preview of the child's summary
34 //! line.
35 //! - [`NotificationKind::BackgroundTerminal`] — shell/task or mixed batch
36 //! headline and labels only. Commands, task prompts and errors stay in the UI;
37 //! this kind never carries a preview, even if an agent is in the batch.
38 //! - [`NotificationKind::ApprovalNeeded`] — headline plus the *tool name*.
39 //! Never the tool description or arguments: an approval prompt fires
40 //! precisely when those arguments are untrusted, and the previous code
41 //! put the full description on the lock screen.
42 //! - [`NotificationKind::InputNeeded`] — headline only. The question text
43 //! stays in the terminal.
44 //! - [`NotificationKind::ElevationNeeded`] — headline plus tool name and
45 //! the sandbox denial reason. The reason is engine-authored but not a
46 //! closed vocabulary, so it is sanitized like everything else.
47 //! - [`NotificationKind::ModelNotify`] — the model-callable `notify` tool.
48 //! Title and body are model-authored, so they are the least trusted
49 //! input here and carry no preview on top.
50
51 use std::sync::OnceLock;
52
53 use regex::Regex;
54
55 /// Maximum characters in the headline (the macOS subtitle line).
56 pub const HEADLINE_MAX_CHARS: usize = 80;
57 /// Maximum characters in the detail line.
58 pub const DETAIL_MAX_CHARS: usize = 120;
59 /// Maximum characters in the assistant preview.
60 pub const PREVIEW_MAX_CHARS: usize = 200;
61
62 /// Separator between the detail and preview segments of a rendered body.
63 const BODY_SEPARATOR: &str = " — ";
64
65 /// Placeholder substituted for anything that must never reach a
66 /// lock-screen-capable surface.
67 pub const REDACTED: &str = "[redacted]";
68 /// Placeholder substituted for structured tool input/output.
69 pub const HIDDEN_DETAILS: &str = "[details hidden]";
70
71 /// Fallback headline when sanitization leaves nothing behind.
72 const FALLBACK_HEADLINE: &str = "codewhale";
73
74 /// The closed set of events that can produce a desktop notification.
75 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
76 pub enum NotificationKind {
77 /// An agent turn finished successfully.
78 TurnComplete,
79 /// A sub-agent reached a terminal status (complete/failed/cancelled/…).
80 SubagentTerminal,
81 /// Shell/task completion, possibly batched with agents; no raw previews.
82 BackgroundTerminal,
83 /// A tool call is blocked waiting for the user to approve it.
84 ApprovalNeeded,
85 /// The agent asked the user a question and is blocked on the answer.
86 InputNeeded,
87 /// The sandbox denied an operation and the user must elevate.
88 ElevationNeeded,
89 /// The model called the `notify` tool.
90 ModelNotify,
91 }
92
93 impl NotificationKind {
94 /// Whether this kind may carry assistant preview text at all.
95 ///
96 /// Interactive prompts (approval/input/elevation) never do: the whole
97 /// point of the prompt is that the pending content is not yet trusted.
98 /// `ModelNotify` does not either — its body *is* model-authored text
99 /// and already occupies the body budget.
100 #[must_use]
101 pub const fn allows_preview(self) -> bool {
102 matches!(self, Self::TurnComplete | Self::SubagentTerminal)
103 }
104 }
105
106 /// A bounded, sanitized notification ready to hand to the OS.
107 ///
108 /// Construct via the per-kind constructors; every one of them sanitizes
109 /// and truncates. There is no way to smuggle raw text through.
110 #[derive(Debug, Clone, PartialEq, Eq)]
111 pub struct NotificationPayload {
112 kind: NotificationKind,
113 headline: String,
114 detail: Option<String>,
115 preview: Option<String>,
116 }
117
118 impl NotificationPayload {
119 fn new(kind: NotificationKind, headline: &str, detail: Option<&str>) -> Self {
120 let headline = bounded(headline, HEADLINE_MAX_CHARS);
121 Self {
122 kind,
123 headline: if headline.is_empty() {
124 FALLBACK_HEADLINE.to_string()
125 } else {
126 headline
127 },
128 detail: detail
129 .map(|d| bounded(d, DETAIL_MAX_CHARS))
130 .filter(|d| !d.is_empty()),
131 preview: None,
132 }
133 }
134
135 /// Turn finished. `headline` is the already-localized status line
136 /// (optionally carrying elapsed/cost when `include_summary` is on).
137 #[must_use]
138 pub fn turn_complete(headline: &str) -> Self {
139 Self::new(NotificationKind::TurnComplete, headline, None)
140 }
141
142 /// Sub-agent reached a terminal status. `detail` is the agent's display
143 /// name, the one every other surface shows.
144 #[must_use]
145 pub fn subagent_terminal(headline: &str, agent_name: &str) -> Self {
146 Self::new(
147 NotificationKind::SubagentTerminal,
148 headline,
149 Some(agent_name),
150 )
151 }
152
153 /// Finished background work. Callers supply only display labels, never
154 /// commands or task prompts; output and errors remain in the terminal.
155 #[must_use]
156 pub fn background_terminal(headline: &str, labels: &str) -> Self {
157 Self::new(NotificationKind::BackgroundTerminal, headline, Some(labels))
158 }
159
160 /// A tool call needs approval. Only the tool *name* is disclosed —
161 /// never the description or the arguments.
162 #[must_use]
163 pub fn approval_needed(headline: &str, tool_name: &str) -> Self {
164 Self::new(NotificationKind::ApprovalNeeded, headline, Some(tool_name))
165 }
166
167 /// The agent is blocked on a user answer. The question stays in the
168 /// terminal; the banner only says "come back".
169 #[must_use]
170 pub fn input_needed(headline: &str) -> Self {
171 Self::new(NotificationKind::InputNeeded, headline, None)
172 }
173
174 /// The sandbox denied an operation and the user must decide whether
175 /// to elevate.
176 #[must_use]
177 pub fn elevation_needed(headline: &str, tool_name: &str, reason: &str) -> Self {
178 let detail = if reason.trim().is_empty() {
179 tool_name.to_string()
180 } else {
181 format!("{tool_name}{BODY_SEPARATOR}{reason}")
182 };
183 Self::new(NotificationKind::ElevationNeeded, headline, Some(&detail))
184 }
185
186 /// The model-callable `notify` tool. Both fields are model-authored
187 /// and therefore fully sanitized like everything else.
188 #[must_use]
189 pub fn model_notify(title: &str, body: Option<&str>) -> Self {
190 Self::new(NotificationKind::ModelNotify, title, body)
191 }
192
193 /// Attach assistant preview text.
194 ///
195 /// A no-op unless the kind permits a preview. Callers cannot override
196 /// the kind policy — routing every preview through this method is
197 /// what makes "approval banners never show the command" a type-level
198 /// property instead of a call-site convention.
199 #[must_use]
200 pub fn with_preview(mut self, preview: Option<&str>) -> Self {
201 if !self.kind.allows_preview() {
202 return self;
203 }
204 self.preview = preview
205 .map(|p| bounded(p, PREVIEW_MAX_CHARS))
206 .filter(|p| !p.is_empty());
207 self
208 }
209
210 /// The event kind.
211 #[must_use]
212 pub const fn kind(&self) -> NotificationKind {
213 self.kind
214 }
215
216 /// Bounded, sanitized headline. Never empty.
217 #[must_use]
218 pub fn headline(&self) -> &str {
219 &self.headline
220 }
221
222 /// Bounded, sanitized detail line, if the kind carries one.
223 #[must_use]
224 pub fn detail(&self) -> Option<&str> {
225 self.detail.as_deref()
226 }
227
228 /// Bounded, sanitized assistant preview. `None` unless the kind
229 /// allows one and the caller supplied non-empty text.
230 #[must_use]
231 pub fn preview(&self) -> Option<&str> {
232 self.preview.as_deref()
233 }
234
235 /// The body lines below the headline, joined for surfaces that take a
236 /// single body string (macOS Notification Center).
237 #[must_use]
238 pub fn body(&self) -> String {
239 let mut parts: Vec<&str> = Vec::with_capacity(2);
240 if let Some(detail) = self.detail() {
241 parts.push(detail);
242 }
243 if let Some(preview) = self.preview() {
244 parts.push(preview);
245 }
246 parts.join(BODY_SEPARATOR)
247 }
248
249 /// Single-line rendering for terminal escape protocols (OSC 9 / 99 /
250 /// 777), which cannot express a title/subtitle/body hierarchy.
251 #[must_use]
252 pub fn render_inline(&self) -> String {
253 let body = self.body();
254 if body.is_empty() {
255 self.headline.clone()
256 } else {
257 format!("{}: {body}", self.headline)
258 }
259 }
260 }
261
262 /// Sanitize then truncate to `max_chars`, appending an ellipsis when the
263 /// input was longer. Character-based, not byte-based, so multi-byte text
264 /// is never sliced mid-scalar.
265 fn bounded(text: &str, max_chars: usize) -> String {
266 truncate_chars(&sanitize_field(text), max_chars)
267 }
268
269 /// Truncate to `max_chars` characters *inclusive* of the `...` marker, so
270 /// the result never exceeds the declared bound.
271 fn truncate_chars(text: &str, max_chars: usize) -> String {
272 if text.chars().count() <= max_chars {
273 return text.to_string();
274 }
275 let take = max_chars.saturating_sub(3);
276 let mut out: String = text.chars().take(take).collect();
277 out.push_str("...");
278 out
279 }
280
281 /// Strip control bytes and redact anything that must not reach a
282 /// lock-screen-capable surface.
283 ///
284 /// Redaction runs per line so a credential cannot be hidden by wrapping,
285 /// then the lines are joined into one bounded field.
286 #[must_use]
287 pub fn sanitize_field(text: &str) -> String {
288 // Strip whole escape sequences *before* `sanitize_stream_chunk`, which
289 // drops the ESC byte but leaves the parameter tail behind — good
290 // enough for a terminal that will never re-interpret it, wrong for a
291 // notification banner that would render a literal `[31m`.
292 codewhale_sanitize::sanitize::sanitize_text(&strip_escape_sequences(text))
293 .lines()
294 .map(|line| {
295 let redacted = redact_structured(line.trim());
296 let redacted = redact_credentials(&redacted);
297 let redacted = redact_absolute_paths(&redacted);
298 // Collapse whitespace runs so a bounded field cannot be
299 // padded out with invisible filler.
300 redacted.split_whitespace().collect::<Vec<_>>().join(" ")
301 })
302 .filter(|line| !line.is_empty())
303 .collect::<Vec<_>>()
304 .join(" ")
305 }
306
307 fn regex_cache<const N: usize>(
308 cell: &'static OnceLock<Vec<Regex>>,
309 patterns: [&str; N],
310 ) -> &'static [Regex] {
311 cell.get_or_init(|| {
312 patterns
313 .iter()
314 .map(|p| Regex::new(p).expect("static notification redaction pattern must compile"))
315 .collect()
316 })
317 }
318
319 /// Remove complete ANSI escape sequences (CSI, OSC, and single-character
320 /// escapes) so neither the sequence nor its parameter tail survives into a
321 /// notification field.
322 fn strip_escape_sequences(text: &str) -> String {
323 static PATTERNS: OnceLock<Vec<Regex>> = OnceLock::new();
324 let res = regex_cache(
325 &PATTERNS,
326 [
327 // OSC: ESC ] … terminated by BEL or ST.
328 r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?",
329 // CSI: ESC [ params intermediates final.
330 r"\x1b\[[0-9;?<>=]*[ -/]*[@-~]?",
331 // Any remaining two-character escape.
332 r"\x1b.",
333 ],
334 );
335 let mut out = text.to_string();
336 for re in res {
337 out = re.replace_all(&out, "").into_owned();
338 }
339 out
340 }
341
342 /// Replace structured tool input/output (JSON objects and arrays) with a
343 /// placeholder. Raw tool arguments are the single most likely place for a
344 /// credential or a private path to appear verbatim.
345 fn redact_structured(text: &str) -> String {
346 static PATTERNS: OnceLock<Vec<Regex>> = OnceLock::new();
347 let res = regex_cache(
348 &PATTERNS,
349 [
350 // A JSON-ish object: braces containing a `"key":` pair.
351 r#"\{[^{}]*"[^"]*"\s*:[^{}]*\}"#,
352 // A JSON-ish array of objects or quoted strings.
353 r#"\[\s*(?:\{[^\[\]]*\}|"[^"]*"(?:\s*,\s*"[^"]*")*)\s*\]"#,
354 ],
355 );
356 let mut out = text.to_string();
357 for re in res {
358 out = re.replace_all(&out, HIDDEN_DETAILS).into_owned();
359 }
360 // A field that is *entirely* a structured blob (possibly nested, so
361 // the brace-matching patterns above may not have fired) is dropped
362 // whole rather than partially rewritten.
363 let trimmed = out.trim();
364 if (trimmed.starts_with('{') || trimmed.starts_with('[')) && trimmed.contains('"') {
365 return HIDDEN_DETAILS.to_string();
366 }
367 out
368 }
369
370 /// Replace credential-shaped substrings with [`REDACTED`].
371 ///
372 /// This is deliberately over-eager: a notification banner is a glance
373 /// surface, so losing a long opaque identifier costs almost nothing while
374 /// leaking one is unrecoverable.
375 fn redact_credentials(text: &str) -> String {
376 static PATTERNS: OnceLock<Vec<Regex>> = OnceLock::new();
377 let res = regex_cache(
378 &PATTERNS,
379 [
380 // PEM private key headers.
381 r"-----BEGIN[A-Z ]*PRIVATE KEY-----",
382 // Provider-prefixed keys: OpenAI/Anthropic/DeepSeek style
383 // `sk-…`, GitHub `ghp_/gho_/ghu_/ghs_/ghr_`, AWS `AKIA…`,
384 // Slack `xoxb-…`, Google `AIza…`.
385 r"(?i)\bsk-[A-Za-z0-9_\-]{8,}",
386 r"\bgh[pousr]_[A-Za-z0-9]{16,}",
387 r"\bAKIA[0-9A-Z]{12,}",
388 r"(?i)\bxox[baprse]-[A-Za-z0-9\-]{8,}",
389 r"\bAIza[0-9A-Za-z_\-]{20,}",
390 // `Bearer <token>` / `Basic <token>` authorization values.
391 r"(?i)\b(?:bearer|basic)\s+[A-Za-z0-9_\-\.=+/]{8,}",
392 // `NAME=value` / `name: value` where the name says secret.
393 r"(?i)\b[A-Za-z0-9_\-]*(?:api[_\-]?key|secret|token|password|passwd|credential)[A-Za-z0-9_\-]*\s*[:=]\s*\S+",
394 // Long opaque blobs with no word structure.
395 r"\b[A-Za-z0-9_\-]{40,}\b",
396 ],
397 );
398 let mut out = text.to_string();
399 for re in res {
400 out = re.replace_all(&out, REDACTED).into_owned();
401 }
402 out
403 }
404
405 /// Replace absolute local filesystem paths with `…/<basename>`.
406 ///
407 /// The identifying information in `/Users/jane/clients/acme/contract.md`
408 /// is the prefix, not the leaf: it names the account, the machine layout,
409 /// and often the customer. Keeping only the basename preserves the "which
410 /// file?" utility of the banner while the identifying prefix never
411 /// reaches the lock screen.
412 ///
413 /// URLs are left alone — the POSIX pattern only fires when the slash run
414 /// is not preceded by `:` or another `/`.
415 fn redact_absolute_paths(text: &str) -> String {
416 static PATTERNS: OnceLock<Vec<Regex>> = OnceLock::new();
417 let res = regex_cache(
418 &PATTERNS,
419 [
420 // Windows UNC and extended paths reveal server/share names.
421 r"(^|[^A-Za-z0-9_\\])(\\\\(?:\?\\)?[^\\/\s]+\\[^\\/\s]+(?:\\[^\\/\s]*)*)",
422 // Leave the double slash after a URL scheme alone.
423 r"(^|[^A-Za-z0-9_:/])(//[^/\s]+/[^/\s]+(?:/[^/\s]*)*)",
424 // POSIX: at least two components so a bare `/tmp` or a lone
425 // slash in prose is not mangled.
426 r"(^|[^A-Za-z0-9_:/\\])((?:/[A-Za-z0-9._~%+@\-]+){2,}/?)",
427 // Windows drive-letter paths.
428 r"(^|[^A-Za-z0-9_])([A-Za-z]:[\\/](?:[^\\/:*?<>|\s]+[\\/]?)+)",
429 ],
430 );
431 let mut out = text.to_string();
432 for re in res {
433 out = re
434 .replace_all(&out, |caps: &regex::Captures<'_>| {
435 let lead = caps.get(1).map_or("", |m| m.as_str());
436 let path = caps.get(2).map_or("", |m| m.as_str());
437 let basename = path
438 .trim_end_matches(['/', '\\'])
439 .rsplit(['/', '\\'])
440 .next()
441 .unwrap_or_default();
442 if basename.is_empty() {
443 format!("{lead}…")
444 } else {
445 format!("{lead}…/{basename}")
446 }
447 })
448 .into_owned();
449 }
450 out
451 }
452
453 #[cfg(test)]
454 mod tests {
455 use super::*;
456
457 /// One payload of every kind, fed pathological input. This is the
458 /// enumeration test the issue asks for: if a new kind is added
459 /// without a bound, this array stops compiling or the assertion
460 /// fires.
461 fn every_kind(text: &str) -> Vec<NotificationPayload> {
462 vec![
463 NotificationPayload::turn_complete(text).with_preview(Some(text)),
464 NotificationPayload::subagent_terminal(text, text).with_preview(Some(text)),
465 NotificationPayload::background_terminal(text, text).with_preview(Some(text)),
466 NotificationPayload::approval_needed(text, text),
467 NotificationPayload::input_needed(text),
468 NotificationPayload::elevation_needed(text, text, text),
469 NotificationPayload::model_notify(text, Some(text)),
470 ]
471 }
472
473 #[test]
474 fn every_kind_renders_within_declared_bounds() {
475 for payload in every_kind(&"word ".repeat(400)) {
476 assert!(
477 payload.headline().chars().count() <= HEADLINE_MAX_CHARS,
478 "{:?} headline unbounded: {}",
479 payload.kind(),
480 payload.headline()
481 );
482 assert!(
483 payload
484 .detail()
485 .is_none_or(|d| d.chars().count() <= DETAIL_MAX_CHARS),
486 "{:?} detail unbounded",
487 payload.kind()
488 );
489 assert!(
490 payload
491 .preview()
492 .is_none_or(|p| p.chars().count() <= PREVIEW_MAX_CHARS),
493 "{:?} preview unbounded",
494 payload.kind()
495 );
496 assert!(!payload.headline().is_empty());
497 }
498 }
499
500 /// The redaction guarantee, asserted for *every* event kind rather
501 /// than one convenient constructor: a payload carrying an API key, an
502 /// absolute local path, and raw tool JSON must leak none of them.
503 #[test]
504 fn no_kind_leaks_credentials_paths_or_raw_tool_input() {
505 let hostile = concat!(
506 "sk-proj-abc123DEF456ghi789jkl012 ",
507 "wrote /Users/jane/clients/acme/contract.md ",
508 r#"input {"command":"curl -H 'Authorization: Bearer abcdef123456'","cwd":"/Users/jane"}"#,
509 );
510
511 for payload in every_kind(hostile) {
512 let rendered = payload.render_inline();
513 for leak in [
514 "sk-proj-abc123DEF456ghi789jkl012",
515 "/Users/jane",
516 "clients/acme",
517 "Bearer abcdef123456",
518 "\"command\"",
519 ] {
520 assert!(
521 !rendered.contains(leak),
522 "{:?} leaked {leak:?}: {rendered}",
523 payload.kind()
524 );
525 }
526 }
527 }
528
529 #[test]
530 fn bounds_are_char_based_not_byte_based() {
531 let payload = NotificationPayload::turn_complete(&"日".repeat(200));
532 assert_eq!(payload.headline().chars().count(), HEADLINE_MAX_CHARS);
533 assert!(payload.headline().ends_with("..."));
534 }
535
536 #[test]
537 fn preview_is_kind_gated_not_caller_gated() {
538 let on = NotificationPayload::turn_complete("Turn complete")
539 .with_preview(Some("assistant said something"));
540 assert_eq!(on.preview(), Some("assistant said something"));
541
542 // Prompt kinds refuse a preview no matter what the caller does.
543 for payload in [
544 NotificationPayload::background_terminal("Shell failed", "shell"),
545 NotificationPayload::approval_needed("Approval needed", "bash"),
546 NotificationPayload::input_needed("Input needed"),
547 NotificationPayload::elevation_needed("Elevation needed", "bash", "network blocked"),
548 NotificationPayload::model_notify("Build done", None),
549 ] {
550 let kind = payload.kind();
551 assert_eq!(
552 payload.with_preview(Some("leaky")).preview(),
553 None,
554 "{kind:?} must never carry assistant preview"
555 );
556 }
557 }
558
559 /// #4834: the approval banner used to render
560 /// `Approval needed: {tool} - {description}`, where the description
561 /// is the pending shell command. Only the tool name survives.
562 #[test]
563 fn approval_payload_carries_only_the_tool_name() {
564 let payload = NotificationPayload::approval_needed("Approval needed", "bash");
565 assert_eq!(payload.detail(), Some("bash"));
566 assert_eq!(payload.render_inline(), "Approval needed: bash");
567 }
568
569 #[test]
570 fn input_needed_body_is_empty() {
571 let payload = NotificationPayload::input_needed("Input needed");
572 assert_eq!(payload.detail(), None);
573 assert_eq!(payload.body(), "");
574 assert_eq!(payload.render_inline(), "Input needed");
575 }
576
577 #[test]
578 fn api_keys_are_redacted() {
579 let cases = [
580 "here is the key sk-proj-abc123DEF456ghi789jkl012",
581 "token ghp_0123456789abcdefghijABCDEFGHIJ0123",
582 "aws AKIAIOSFODNN7EXAMPLE",
583 "slack xoxb-1234567890-abcdefghij",
584 "google AIzaSyA1234567890abcdefghijklmnopqrstu",
585 // Deliberately NOT a JWT-shaped literal. The obvious fixture here
586 // is the textbook base64 JWT header, but that is exactly what
587 // secret scanners match: it fired a bearer-token incident on the
588 // first push of this branch and trains people to ignore the
589 // scanner. What this case actually exercises is the
590 // `Bearer <value>` authorization rule, which does not care about
591 // the value's shape.
592 "Authorization: Bearer not-a-real-token-0123456789abcdef",
593 "DEEPSEEK_API_KEY=sk-livekeyvalue1234567890",
594 "password: hunter2correctbattery",
595 "-----BEGIN RSA PRIVATE KEY-----",
596 ];
597 for case in cases {
598 let payload = NotificationPayload::model_notify("Heads up", Some(case));
599 let body = payload.body();
600 assert!(
601 body.contains(REDACTED),
602 "expected redaction marker for {case:?}, got {body:?}"
603 );
604 for leak in [
605 "sk-proj-abc123DEF456ghi789jkl012",
606 "ghp_0123456789abcdefghijABCDEFGHIJ0123",
607 "AKIAIOSFODNN7EXAMPLE",
608 "xoxb-1234567890-abcdefghij",
609 "AIzaSyA1234567890abcdefghijklmnopqrstu",
610 "not-a-real-token-0123456789abcdef",
611 "sk-livekeyvalue1234567890",
612 "hunter2correctbattery",
613 "PRIVATE KEY",
614 ] {
615 assert!(
616 !body.contains(leak),
617 "leaked {leak:?} from {case:?}: {body:?}"
618 );
619 }
620 }
621 }
622
623 /// Deliberate over-eagerness, pinned so it is a decision and not a
624 /// surprise: an unbroken 40+ character run has no word structure, so
625 /// it is treated as credential-shaped even when it is not.
626 #[test]
627 fn long_opaque_runs_are_treated_as_credential_shaped() {
628 let payload = NotificationPayload::turn_complete("Turn complete")
629 .with_preview(Some(&"a".repeat(500)));
630 assert_eq!(payload.preview(), Some(REDACTED));
631 }
632
633 #[test]
634 fn absolute_paths_are_reduced_to_basename() {
635 let payload = NotificationPayload::turn_complete("Turn complete").with_preview(Some(
636 "wrote /Users/jane/clients/acme/contract.md and C:\\Users\\jane\\secret\\plan.docx",
637 ));
638 let preview = payload.preview().expect("preview should survive");
639 assert!(!preview.contains("/Users/jane"), "{preview}");
640 assert!(!preview.contains("clients/acme"), "{preview}");
641 assert!(!preview.contains("C:\\Users"), "{preview}");
642 assert!(preview.contains("…/contract.md"), "{preview}");
643 assert!(preview.contains("…/plan.docx"), "{preview}");
644 }
645
646 #[test]
647 fn urls_survive_path_redaction() {
648 let payload = NotificationPayload::model_notify(
649 "Deployed",
650 Some("live at https://app.example.com/status/ok"),
651 );
652 assert!(
653 payload.body().contains("https://app.example.com/status/ok"),
654 "{}",
655 payload.body()
656 );
657 }
658
659 #[test]
660 fn raw_tool_input_json_is_hidden() {
661 let raw =
662 r#"{"command":"curl -H 'Authorization: Bearer abc' https://x","cwd":"/Users/jane"}"#;
663 let payload = NotificationPayload::model_notify("Ran tool", Some(raw));
664 let body = payload.body();
665 assert_eq!(body, HIDDEN_DETAILS, "{body}");
666 }
667
668 #[test]
669 fn embedded_tool_json_is_hidden_inline() {
670 let payload = NotificationPayload::turn_complete("Turn complete").with_preview(Some(
671 r#"called write with {"path":"/etc/passwd"} then stopped"#,
672 ));
673 let preview = payload.preview().expect("preview should survive");
674 assert!(preview.contains(HIDDEN_DETAILS), "{preview}");
675 assert!(!preview.contains("/etc/passwd"), "{preview}");
676 }
677
678 #[test]
679 fn control_bytes_and_newlines_are_collapsed() {
680 let payload = NotificationPayload::turn_complete("Turn\x1b[31m complete\n\nsecond line");
681 assert_eq!(payload.headline(), "Turn complete second line");
682 }
683
684 #[test]
685 fn empty_input_still_yields_a_headline() {
686 let payload = NotificationPayload::turn_complete(" \n ");
687 assert_eq!(payload.headline(), FALLBACK_HEADLINE);
688 }
689 #[test]
690 fn notification_payload_masks_unc_server_share_and_directories() {
691 for path in [
692 r"\\fileserver\share\clients\case.txt",
693 r"\\?\C:\Users\fixture\clients\case.txt",
694 "//fileserver/share/clients/case.txt",
695 ] {
696 let payload =
697 NotificationPayload::turn_complete("Turn complete").with_preview(Some(path));
698 let preview = payload.preview().expect("preview");
699 assert_eq!(preview, "…/case.txt");
700 assert!(!preview.contains("fileserver"));
701 assert!(!preview.contains("clients"));
702 }
703 let payload = NotificationPayload::turn_complete("Turn complete")
704 .with_preview(Some("see https://example.com/docs/page"));
705 assert_eq!(payload.preview(), Some("see https://example.com/docs/page"));
706 }
707 }
708
708 lines RUST