astrid-capsule 0.8.0

Core runtime management for User-Space Capsules in Astrid OS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
//! Host function implementation for plugin-level approval requests.
//!
//! Called by WASM guests via the `request_approval` trait method when a plugin
//! needs human consent for a sensitive action. Checks the shared
//! [`AllowanceStore`] first (instant path), then publishes an
//! [`ApprovalRequired`] IPC event and blocks until the frontend responds.

use crate::engine::wasm::bindings::astrid::approval::host::{
    self as approval, ApprovalDecision, ApprovalRequest, ApprovalResponse, ErrorCode,
};
use crate::engine::wasm::host::util;
use crate::engine::wasm::host_state::HostState;
use astrid_approval::action::SensitiveAction;
use astrid_approval::{Allowance, AllowanceId, AllowancePattern, AllowanceStore};
use astrid_core::principal::PrincipalId;
use astrid_core::types::Timestamp;
use astrid_crypto::KeyPair;
use astrid_events::AstridEvent;
use astrid_events::ipc::{IpcMessage, IpcPayload};
use uuid::Uuid;

/// Maximum timeout for approval requests (60 seconds).
const MAX_APPROVAL_TIMEOUT_MS: u64 = 60_000;

/// Maximum length for action strings from WASM guests.
///
/// Actions longer than this are rejected at the entry point and truncated
/// in the sanitization layer. Prevents DoS via oversized glob pattern
/// compilation.
const MAX_ACTION_LEN: usize = 256;

/// Maximum length for resource strings from WASM guests.
///
/// Resources contain full command strings with arguments, so the limit is
/// higher than [`MAX_ACTION_LEN`]. Strings exceeding this are truncated
/// (not rejected) since resource is a display/audit field that does not
/// drive glob pattern compilation.
const MAX_RESOURCE_LEN: usize = 1024;

/// Check the allowance store for a matching pattern, consuming limited-use
/// allowances.
///
/// Builds a `SensitiveAction::ExecuteCommand` from the full resource string
/// so that `CommandPattern` glob matching works against the complete command.
/// Uses `find_matching_and_consume` to correctly decrement `uses_remaining`
/// on limited-use allowances. Scoped to the invoking `principal` — Agent A's
/// approval never matches Agent B's action (Layer 4, issue #668).
fn check_allowance(
    store: &AllowanceStore,
    principal: &PrincipalId,
    resource: &str,
    workspace_root: Option<&std::path::Path>,
) -> bool {
    let action = SensitiveAction::ExecuteCommand {
        command: resource.to_owned(),
        args: vec![],
    };
    store
        .find_matching_and_consume(principal, &action, workspace_root)
        .is_some()
}

/// Sanitize a guest-supplied display field in place.
///
/// Trims whitespace, strips control characters, and enforces a character-count
/// length cap. Logs a warning (with plugin ID and field name) when control
/// characters were stripped or the string was truncated.
fn sanitize_guest_field(s: &mut String, max_len: usize, field_name: &str, capsule_id: &str) {
    let trimmed = s.trim();
    let sanitized: String = trimmed
        .chars()
        .filter(|c| !c.is_control())
        .take(max_len)
        .collect();

    // Only warn for control-char stripping or truncation, not whitespace trim.
    if sanitized.len() != trimmed.len() {
        let original_chars = trimmed.chars().count();
        let sanitized_chars = sanitized.chars().count();
        tracing::warn!(
            plugin = %capsule_id,
            field = field_name,
            original_chars,
            sanitized_chars,
            "{field_name} sanitized: control characters stripped or length truncated"
        );
    }

    *s = sanitized;
}

/// Sanitize a guest-supplied action string for safe use in glob patterns.
///
/// Defense layer 1: strips control characters and enforces a length cap.
/// Runs BEFORE [`escape_glob_metacharacters`] (layer 2). Together they
/// guarantee that no guest input can produce a dangerous or oversized glob
/// pattern.
fn sanitize_action_for_pattern(action: &str, capsule_id: &str) -> String {
    let trimmed = action.trim();
    let sanitized: String = trimmed
        .chars()
        .filter(|c| !c.is_control())
        .take(MAX_ACTION_LEN)
        .collect();

    let trimmed_chars = trimmed.chars().count();
    let sanitized_chars = sanitized.chars().count();
    if sanitized_chars != trimmed_chars {
        tracing::warn!(
            plugin = %capsule_id,
            original_chars = trimmed_chars,
            sanitized_chars = sanitized_chars,
            "Action string sanitized: control characters stripped or length truncated"
        );
    }

    sanitized
}

/// Escape glob metacharacters in a guest-supplied action string.
///
/// Defense layer 2: escapes glob wildcards so they are matched literally.
fn escape_glob_metacharacters(action: &str) -> String {
    let mut escaped = String::with_capacity(action.len() * 2);
    for c in action.chars() {
        if matches!(c, '*' | '?' | '[' | ']' | '{' | '}' | '\\') {
            escaped.push('\\');
        }
        escaped.push(c);
    }
    escaped
}

/// Create a session-scoped allowance from an approval decision.
fn create_allowance_from_decision(
    store: &AllowanceStore,
    principal: &PrincipalId,
    action: &str,
    decision: &str,
    workspace_root: Option<std::path::PathBuf>,
    capsule_id: &str,
) {
    let session_only = match decision {
        "approve_session" => true,
        "approve_always" => false,
        _ => return,
    };

    // Layer 1: strip control characters, enforce length cap.
    let sanitized_action = sanitize_action_for_pattern(action, capsule_id);
    if sanitized_action.is_empty() {
        return;
    }
    // Layer 2: escape glob metacharacters so wildcards match literally.
    let escaped_action = escape_glob_metacharacters(&sanitized_action);
    let pattern = AllowancePattern::CommandPattern {
        command: format!("{escaped_action} *"),
    };

    let keypair = KeyPair::generate();
    let allowance = Allowance {
        id: AllowanceId::new(),
        principal: principal.clone(),
        action_pattern: pattern,
        created_at: Timestamp::now(),
        expires_at: None,
        max_uses: None,
        uses_remaining: None,
        session_only,
        workspace_root,
        signature: keypair.sign(b"plugin-approval"),
    };

    if let Err(e) = store.add_allowance(allowance) {
        tracing::warn!("Failed to add approval allowance: {e}");
    }
}

/// Map the JSON-string decision in `IpcPayload::ApprovalResponse` to the
/// typed [`ApprovalDecision`] returned to the WASM guest.
fn decision_from_str(decision: &str) -> ApprovalDecision {
    match decision {
        "approve" => ApprovalDecision::Approved,
        "approve_session" => ApprovalDecision::ApprovedSession,
        "approve_always" => ApprovalDecision::ApprovedAlways,
        // Anything else — including explicit denies, unknown strings, or
        // empty — is treated as a deny.
        _ => ApprovalDecision::Denied,
    }
}

impl approval::Host for HostState {
    /// Host function: `request_approval(request) -> ApprovalResponse`
    ///
    /// Blocks the WASM thread until the frontend user approves or denies, or
    /// the request times out. If an allowance already exists, returns immediately
    /// with `ApprovalDecision::Allowance` so the capsule UI can communicate
    /// WHY consent was granted.
    fn request_approval(
        &mut self,
        mut request: ApprovalRequest,
    ) -> Result<ApprovalResponse, ErrorCode> {
        let allowance_store = self.allowance_store.clone();
        let event_bus = self.event_bus.clone();
        let runtime_handle = self.runtime_handle.clone();
        let capsule_id = self.capsule_id.to_string();
        let cancel_token = self.cancel_token.clone();
        let blocking_semaphore = self.blocking_semaphore.clone();
        let workspace_root = self.workspace_root.clone();
        // Layer 4 (#668): the invoking principal scopes allowance lookups.
        // Falls back to the capsule owner for load-time / tests / daemons.
        let principal = self.effective_principal();

        // Validate and sanitize all guest-supplied strings at the entry point.
        let action_char_count = request.action.chars().count();
        if action_char_count > MAX_ACTION_LEN {
            return Err(ErrorCode::InvalidInput);
        }
        request.action = sanitize_action_for_pattern(&request.action, &capsule_id);
        sanitize_guest_field(
            &mut request.target_resource,
            MAX_RESOURCE_LEN,
            "resource",
            &capsule_id,
        );

        let ws_path = Some(workspace_root.as_path());

        // Fast path: check existing allowances.
        if let Some(ref store) = allowance_store
            && check_allowance(store, &principal, &request.target_resource, ws_path)
        {
            tracing::debug!(
                plugin = %capsule_id,
                action = %request.action,
                resource = %request.target_resource,
                "Approval auto-granted via existing allowance"
            );

            return Ok(ApprovalResponse {
                decision: ApprovalDecision::Allowance,
            });
        }

        // Slow path: publish ApprovalRequired and wait for response.
        let request_id = Uuid::new_v4().to_string();
        let response_topic = format!("astrid.v1.approval.response.{request_id}");

        // Subscribe BEFORE publishing to prevent a race.
        let mut receiver = event_bus.subscribe_topic(&response_topic);

        let request_payload = IpcPayload::ApprovalRequired {
            request_id: request_id.clone(),
            action: request.action.clone(),
            resource: request.target_resource.clone(),
            reason: format!("Capsule '{capsule_id}' requests approval"),
        };
        let message = IpcMessage::new(
            "astrid.v1.approval",
            request_payload,
            Uuid::nil(), // Kernel-originated
        );
        event_bus.publish(AstridEvent::Ipc {
            message,
            metadata: astrid_events::EventMetadata::default(),
        });

        tracing::debug!(
            plugin = %capsule_id,
            action = %request.action,
            resource = %request.target_resource,
            %request_id,
            "Published approval request, waiting for response"
        );

        // Block until response, timeout, or cancellation.
        let event = util::bounded_block_on_cancellable(
            &runtime_handle,
            &blocking_semaphore,
            &cancel_token,
            async {
                tokio::time::timeout(
                    std::time::Duration::from_millis(MAX_APPROVAL_TIMEOUT_MS),
                    receiver.recv(),
                )
                .await
                .ok()
                .flatten()
            },
        )
        .flatten();

        match event {
            Some(event) => {
                if let AstridEvent::Ipc { message, .. } = &*event {
                    match &message.payload {
                        IpcPayload::ApprovalResponse {
                            decision, reason, ..
                        } => {
                            let typed = decision_from_str(decision);
                            let approved = matches!(
                                typed,
                                ApprovalDecision::Approved
                                    | ApprovalDecision::ApprovedSession
                                    | ApprovalDecision::ApprovedAlways
                            );

                            // Create allowance for session/always decisions.
                            if approved && let Some(ref store) = allowance_store {
                                create_allowance_from_decision(
                                    store,
                                    &principal,
                                    &request.action,
                                    decision,
                                    Some(workspace_root.clone()),
                                    &capsule_id,
                                );
                            }

                            tracing::info!(
                                plugin = %capsule_id,
                                action = %request.action,
                                %decision,
                                reason = reason.as_deref().unwrap_or("none"),
                                "Approval response received"
                            );

                            Ok(ApprovalResponse { decision: typed })
                        },
                        _ => Err(ErrorCode::Unknown(
                            "unexpected IPC payload type in approval response".to_string(),
                        )),
                    }
                } else {
                    Err(ErrorCode::Unknown(
                        "unexpected event type in approval response".to_string(),
                    ))
                }
            },
            None => {
                tracing::warn!(
                    plugin = %capsule_id,
                    action = %request.action,
                    "Approval request timed out or was cancelled"
                );
                // Per WIT: timeout returns the typed `timeout` ErrorCode arm.
                Err(ErrorCode::Timeout)
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn check_allowance_matches_command_pattern() {
        let store = AllowanceStore::new();
        let keypair = KeyPair::generate();
        let allowance = Allowance {
            id: AllowanceId::new(),
            principal: PrincipalId::default(),
            action_pattern: AllowancePattern::CommandPattern {
                command: "git push *".into(),
            },
            created_at: Timestamp::now(),
            expires_at: None,
            max_uses: None,
            uses_remaining: None,
            session_only: true,
            workspace_root: None,
            signature: keypair.sign(b"test"),
        };
        store.add_allowance(allowance).unwrap();

        assert!(check_allowance(
            &store,
            &PrincipalId::default(),
            "git push origin main",
            None
        ));
        assert!(!check_allowance(
            &store,
            &PrincipalId::default(),
            "git status",
            None
        ));
    }

    #[test]
    fn check_allowance_returns_false_on_empty_store() {
        let store = AllowanceStore::new();
        assert!(!check_allowance(
            &store,
            &PrincipalId::default(),
            "git push origin main",
            None
        ));
    }

    #[test]
    fn create_allowance_approve_session() {
        let store = AllowanceStore::new();
        create_allowance_from_decision(
            &store,
            &PrincipalId::default(),
            "git push",
            "approve_session",
            None,
            "test",
        );
        assert_eq!(store.count(), 1);
        assert!(check_allowance(
            &store,
            &PrincipalId::default(),
            "git push origin main",
            None
        ));
    }

    #[test]
    fn create_allowance_approve_always() {
        let store = AllowanceStore::new();
        create_allowance_from_decision(
            &store,
            &PrincipalId::default(),
            "docker run",
            "approve_always",
            None,
            "test",
        );
        assert_eq!(store.count(), 1);
        assert!(check_allowance(
            &store,
            &PrincipalId::default(),
            "docker run my-image",
            None
        ));
    }

    #[test]
    fn create_allowance_simple_approve_does_nothing() {
        let store = AllowanceStore::new();
        create_allowance_from_decision(
            &store,
            &PrincipalId::default(),
            "git push",
            "approve",
            None,
            "test",
        );
        assert_eq!(store.count(), 0);
    }

    #[test]
    fn create_allowance_deny_does_nothing() {
        let store = AllowanceStore::new();
        create_allowance_from_decision(
            &store,
            &PrincipalId::default(),
            "git push",
            "deny",
            None,
            "test",
        );
        assert_eq!(store.count(), 0);
    }

    #[test]
    fn create_allowance_garbage_decision_does_nothing() {
        let store = AllowanceStore::new();
        create_allowance_from_decision(
            &store,
            &PrincipalId::default(),
            "git push",
            "garbage",
            None,
            "test",
        );
        assert_eq!(store.count(), 0);
        create_allowance_from_decision(
            &store,
            &PrincipalId::default(),
            "git push",
            "",
            None,
            "test",
        );
        assert_eq!(store.count(), 0);
    }

    #[test]
    fn check_allowance_with_special_characters() {
        let store = AllowanceStore::new();
        let keypair = KeyPair::generate();
        let allowance = Allowance {
            id: AllowanceId::new(),
            principal: PrincipalId::default(),
            action_pattern: AllowancePattern::CommandPattern {
                command: "git push *".into(),
            },
            created_at: Timestamp::now(),
            expires_at: None,
            max_uses: None,
            uses_remaining: None,
            session_only: true,
            workspace_root: None,
            signature: keypair.sign(b"test"),
        };
        store.add_allowance(allowance).unwrap();

        assert!(!check_allowance(
            &store,
            &PrincipalId::default(),
            "git status; rm -rf /",
            None
        ));
        assert!(check_allowance(
            &store,
            &PrincipalId::default(),
            "git push --force origin main",
            None
        ));
    }

    #[test]
    fn escape_glob_metacharacters_preserves_normal_chars() {
        assert_eq!(escape_glob_metacharacters("git push"), "git push");
        assert_eq!(
            escape_glob_metacharacters("npm install @types/react"),
            "npm install @types/react"
        );
        assert_eq!(escape_glob_metacharacters("my-tool_v2.0"), "my-tool_v2.0");
    }

    #[test]
    fn escape_glob_metacharacters_escapes_wildcards() {
        assert_eq!(escape_glob_metacharacters("*"), "\\*");
        assert_eq!(escape_glob_metacharacters("git *"), "git \\*");
        assert_eq!(escape_glob_metacharacters("git[status]"), "git\\[status\\]");
        assert_eq!(escape_glob_metacharacters("cmd?"), "cmd\\?");
    }

    #[test]
    fn create_allowance_with_wildcard_in_action_is_not_overly_broad() {
        let store = AllowanceStore::new();
        create_allowance_from_decision(
            &store,
            &PrincipalId::default(),
            "*",
            "approve_session",
            None,
            "test",
        );
        assert_eq!(store.count(), 1);
        assert!(!check_allowance(
            &store,
            &PrincipalId::default(),
            "git push origin main",
            None
        ));
    }

    #[test]
    fn create_allowance_empty_action() {
        let store = AllowanceStore::new();
        create_allowance_from_decision(
            &store,
            &PrincipalId::default(),
            "",
            "approve_session",
            None,
            "test",
        );
        assert_eq!(store.count(), 0);
        assert!(!check_allowance(
            &store,
            &PrincipalId::default(),
            "git push",
            None
        ));
    }

    #[test]
    fn approve_once_does_not_create_allowance() {
        let store = AllowanceStore::new();
        create_allowance_from_decision(
            &store,
            &PrincipalId::default(),
            "git push",
            "approve",
            None,
            "test",
        );
        assert_eq!(store.count(), 0);
        assert!(!check_allowance(
            &store,
            &PrincipalId::default(),
            "git push origin main",
            None
        ));
    }

    // --- sanitize_action_for_pattern tests ---

    #[test]
    fn sanitize_action_preserves_shell_fragments() {
        assert_eq!(
            sanitize_action_for_pattern("python -c 'print(\"hello\")'", "test"),
            "python -c 'print(\"hello\")'"
        );
        assert_eq!(
            sanitize_action_for_pattern("awk '{print $1}' file.txt", "test"),
            "awk '{print $1}' file.txt"
        );
        assert_eq!(
            sanitize_action_for_pattern("bash -c 'echo $HOME'", "test"),
            "bash -c 'echo $HOME'"
        );
        assert_eq!(
            sanitize_action_for_pattern("g++ main.cpp", "test"),
            "g++ main.cpp"
        );
        assert_eq!(
            sanitize_action_for_pattern("npm install @types/react", "test"),
            "npm install @types/react"
        );
        assert_eq!(
            sanitize_action_for_pattern("docker run ubuntu:latest", "test"),
            "docker run ubuntu:latest"
        );
    }

    #[test]
    fn sanitize_action_preserves_glob_chars_for_escaping() {
        assert_eq!(sanitize_action_for_pattern("*", "test"), "*");
        assert_eq!(sanitize_action_for_pattern("git *", "test"), "git *");
        assert_eq!(sanitize_action_for_pattern("cmd?", "test"), "cmd?");
        assert_eq!(
            sanitize_action_for_pattern("git[status]", "test"),
            "git[status]"
        );
    }

    #[test]
    fn sanitize_action_strips_control_characters() {
        assert_eq!(sanitize_action_for_pattern("git\0push", "test"), "gitpush");
        assert_eq!(sanitize_action_for_pattern("git\rpush", "test"), "gitpush");
        assert_eq!(
            sanitize_action_for_pattern("git\x1b[31mpush", "test"),
            "git[31mpush"
        );
        assert_eq!(sanitize_action_for_pattern("git\tpush", "test"), "gitpush");
        assert_eq!(sanitize_action_for_pattern("git\npush", "test"), "gitpush");
    }

    #[test]
    fn sanitize_action_truncates_long_strings() {
        let long_action = "a".repeat(500);
        let sanitized = sanitize_action_for_pattern(&long_action, "test");
        assert_eq!(sanitized.chars().count(), MAX_ACTION_LEN);
    }

    #[test]
    fn sanitize_action_exact_limit_no_change() {
        let action = "a".repeat(MAX_ACTION_LEN);
        let sanitized = sanitize_action_for_pattern(&action, "test");
        assert_eq!(sanitized, action);
        assert_eq!(sanitized.chars().count(), MAX_ACTION_LEN);
    }

    #[test]
    fn sanitize_action_truncates_multibyte_chars() {
        let action = "a".repeat(200) + &"\u{0100}".repeat(100);
        assert_eq!(action.chars().count(), 300);
        let sanitized = sanitize_action_for_pattern(&action, "test");
        assert_eq!(sanitized.chars().count(), MAX_ACTION_LEN);
        assert!(sanitized.starts_with(&"a".repeat(200)));
    }

    #[test]
    fn sanitize_action_trims_whitespace() {
        assert_eq!(
            sanitize_action_for_pattern("  git push  ", "test"),
            "git push"
        );
    }

    #[test]
    fn create_allowance_whitespace_padded_action() {
        let store = AllowanceStore::new();
        create_allowance_from_decision(
            &store,
            &PrincipalId::default(),
            "  git push  ",
            "approve_session",
            None,
            "test",
        );
        assert_eq!(store.count(), 1);
        assert!(check_allowance(
            &store,
            &PrincipalId::default(),
            "git push origin main",
            None
        ));
        assert!(!check_allowance(
            &store,
            &PrincipalId::default(),
            "git status",
            None
        ));
    }

    #[test]
    fn create_allowance_combined_attack() {
        let store = AllowanceStore::new();
        let attack = "git\0 *\x1b[31m";
        create_allowance_from_decision(
            &store,
            &PrincipalId::default(),
            attack,
            "approve_session",
            None,
            "test",
        );
        assert_eq!(store.count(), 1);
        assert!(!check_allowance(
            &store,
            &PrincipalId::default(),
            "git push origin main",
            None
        ));
        assert!(!check_allowance(
            &store,
            &PrincipalId::default(),
            "git status",
            None
        ));
    }

    #[test]
    fn create_allowance_null_byte_attack() {
        let store = AllowanceStore::new();
        create_allowance_from_decision(
            &store,
            &PrincipalId::default(),
            "git\0push",
            "approve_session",
            None,
            "test",
        );
        assert_eq!(store.count(), 1);
        assert!(!check_allowance(
            &store,
            &PrincipalId::default(),
            "git push origin main",
            None
        ));
        assert!(check_allowance(
            &store,
            &PrincipalId::default(),
            "gitpush something",
            None
        ));
    }

    // --- sanitize_guest_field tests ---

    #[test]
    fn sanitize_guest_field_strips_control_chars() {
        let mut s = "git push\x1b[31m origin".to_string();
        sanitize_guest_field(&mut s, MAX_RESOURCE_LEN, "resource", "test");
        assert_eq!(s, "git push[31m origin");
    }

    #[test]
    fn sanitize_guest_field_truncates_resource() {
        let mut s = "a".repeat(2000);
        sanitize_guest_field(&mut s, MAX_RESOURCE_LEN, "resource", "test");
        assert_eq!(s.chars().count(), MAX_RESOURCE_LEN);
    }

    #[test]
    fn sanitize_guest_field_resource_exact_limit() {
        let original = "a".repeat(MAX_RESOURCE_LEN);
        let mut s = original.clone();
        sanitize_guest_field(&mut s, MAX_RESOURCE_LEN, "resource", "test");
        assert_eq!(s, original);
    }

    #[test]
    fn sanitize_guest_field_truncates_multibyte() {
        let mut s = "a".repeat(500) + &"\u{0100}".repeat(600);
        assert_eq!(s.chars().count(), 1100);
        sanitize_guest_field(&mut s, MAX_RESOURCE_LEN, "resource", "test");
        assert_eq!(s.chars().count(), MAX_RESOURCE_LEN);
        assert!(s.starts_with(&"a".repeat(500)));
    }

    #[test]
    fn sanitize_guest_field_trims_whitespace() {
        let mut s = "  git push origin  ".to_string();
        sanitize_guest_field(&mut s, MAX_RESOURCE_LEN, "resource", "test");
        assert_eq!(s, "git push origin");
    }

    #[test]
    fn sanitize_guest_field_combined_attack() {
        let mut s = format!("{}\x1b[31m{}", "A".repeat(1000), "B".repeat(1000));
        sanitize_guest_field(&mut s, MAX_RESOURCE_LEN, "resource", "test");
        assert_eq!(s.chars().count(), MAX_RESOURCE_LEN);
        assert!(s.chars().all(|c| !c.is_control()));
    }

    #[test]
    fn sanitize_guest_field_empty_string() {
        let mut s = String::new();
        sanitize_guest_field(&mut s, MAX_RESOURCE_LEN, "resource", "test");
        assert!(s.is_empty());
    }
}