astrid-capsule 0.5.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
//! Host function implementation for plugin-level approval requests.
//!
//! Called by WASM guests via the `astrid_request_approval` FFI 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::host::util;
use crate::engine::wasm::host_state::HostState;
use astrid_approval::action::SensitiveAction;
use astrid_approval::{Allowance, AllowanceId, AllowancePattern, AllowanceStore};
use astrid_core::types::Timestamp;
use astrid_crypto::KeyPair;
use astrid_events::AstridEvent;
use astrid_events::ipc::{IpcMessage, IpcPayload};
use extism::{CurrentPlugin, Error, UserData, Val};
use serde::Deserialize;
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;

/// Maximum length for risk-level labels from WASM guests.
///
/// Risk levels are short classification labels ("low", "high", "critical").
/// 64 characters is generous for any reasonable label.
const MAX_RISK_LEVEL_LEN: usize = 64;

/// The wire format sent by the SDK's `approval::request` function.
#[derive(Deserialize)]
struct GuestApprovalRequest {
    action: String,
    resource: String,
    risk_level: String,
}

/// 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.
fn check_allowance(
    store: &AllowanceStore,
    resource: &str,
    workspace_root: Option<&std::path::Path>,
) -> bool {
    let action = SensitiveAction::ExecuteCommand {
        command: resource.to_owned(),
        args: vec![],
    };
    store
        .find_matching_and_consume(&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.
///
/// Unlike [`sanitize_action_for_pattern`], this is a general-purpose sanitizer
/// for fields that flow into IPC payloads and logs but do not participate in
/// glob pattern matching.
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.
    // Use byte-length comparison for O(1) detection; compute char counts only
    // inside the warning branch to avoid an O(N) scan on the full input.
    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. All printable characters are preserved - shell operators and
/// glob wildcards are handled by downstream layers.
///
/// Logs a warning if control characters were stripped or the string was
/// truncated, identifying the plugin for audit purposes. Does NOT warn
/// for whitespace trimming alone (that is normal, not suspicious).
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();

    // Only warn for control-char stripping or truncation, not whitespace trim.
    // Compare char counts (not byte lengths) so the log fields correlate with
    // MAX_ACTION_LEN which is a char-count limit.
    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. Layer 1
/// ([`sanitize_action_for_pattern`]) strips control characters and enforces
/// length. Layer 3 ([`contains_shell_operators`] in `pattern.rs`) rejects
/// shell injection at match time.
fn escape_glob_metacharacters(action: &str) -> String {
    // Worst case: every char is a glob metacharacter needing a `\` prefix.
    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.
///
/// For `approve_session`, creates a `CommandPattern` with a subcommand-level
/// glob (e.g. "git push" becomes "git push *"). For `approve_always`, uses
/// the same pattern but with `session_only: false`.
fn create_allowance_from_decision(
    store: &AllowanceStore,
    action: &str,
    decision: &str,
    workspace_root: Option<std::path::PathBuf>,
    capsule_id: &str,
) {
    let session_only = match decision {
        "approve_session" => true,
        // FIXME(#382): `approve_always` sets `session_only: false` but the
        // signing key is ephemeral. Treat as session-scoped until the kernel
        // runtime key is threaded through HostState for proper signatures.
        "approve_always" => false,
        // "approve" (once) intentionally creates no allowance. The next
        // identical call will re-prompt. Only "approve_session" and
        // "approve_always" persist across calls.
        _ => return,
    };

    // Layer 1: strip control characters, enforce length cap.
    let sanitized_action = sanitize_action_for_pattern(action, capsule_id);
    // Empty action after sanitization produces pattern " *" which is
    // meaningless. Skip allowance creation rather than storing a useless entry.
    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} *"),
    };

    // Generate an ephemeral keypair for signing. Session allowances are
    // ephemeral by nature; persistent allowances will get proper runtime
    // key signing when the capability persistence layer is wired.
    let keypair = KeyPair::generate();
    let allowance = Allowance {
        id: AllowanceId::new(),
        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}");
    }
}

/// Host function: `astrid_request_approval(request_json) -> response_json`
///
/// Blocks the WASM thread until the frontend user approves or denies, or
/// the request times out. If an allowance already exists, returns immediately.
#[expect(clippy::needless_pass_by_value)]
pub(crate) fn astrid_request_approval_impl(
    capsule: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostState>,
) -> Result<(), Error> {
    let request_bytes = util::get_safe_bytes(capsule, &inputs[0], util::MAX_GUEST_PAYLOAD_LEN)?;
    let mut guest_req: GuestApprovalRequest = serde_json::from_slice(&request_bytes)
        .map_err(|e| Error::msg(format!("invalid approval request JSON: {e}")))?;

    let ud = user_data.get()?;

    // Extract what we need from HostState, then drop the lock before blocking.
    // Extracted early so capsule_id is available for sanitization logging.
    let (
        allowance_store,
        event_bus,
        runtime_handle,
        capsule_id,
        cancel_token,
        host_semaphore,
        workspace_root,
    ) = {
        let state = ud
            .lock()
            .map_err(|e| Error::msg(format!("host state lock poisoned: {e}")))?;

        let store = state.allowance_store.clone();
        let event_bus = state.event_bus.clone();
        let runtime_handle = state.runtime_handle.clone();
        let capsule_id = state.capsule_id.to_string();
        let cancel_token = state.cancel_token.clone();
        let host_semaphore = state.host_semaphore.clone();
        let workspace = state.workspace_root.clone();

        (
            store,
            event_bus,
            runtime_handle,
            capsule_id,
            cancel_token,
            host_semaphore,
            workspace,
        )
    };

    // Validate and sanitize all guest-supplied strings at the entry point.
    // This ensures IPC payloads and log messages contain clean values.
    let action_char_count = guest_req.action.chars().count();
    if action_char_count > MAX_ACTION_LEN {
        return Err(Error::msg(format!(
            "approval request action exceeds maximum length ({action_char_count} > {MAX_ACTION_LEN})",
        )));
    }
    // Single source of truth: sanitize_action_for_pattern strips control
    // chars, trims whitespace, and enforces length. Applied here so the
    // cleaned value flows through to IPC payloads and logs.
    guest_req.action = sanitize_action_for_pattern(&guest_req.action, &capsule_id);
    // Sanitize resource and risk_level: trim whitespace, strip control
    // characters, and enforce length caps. These are guest-controlled and
    // flow into IPC payloads, tracing logs, and terminal-rendered approval
    // prompts. Without length caps, a 10 MB resource string (the upstream
    // MAX_GUEST_PAYLOAD_LEN limit) would DoS IPC consumers and log sinks.
    sanitize_guest_field(
        &mut guest_req.resource,
        MAX_RESOURCE_LEN,
        "resource",
        &capsule_id,
    );
    sanitize_guest_field(
        &mut guest_req.risk_level,
        MAX_RISK_LEVEL_LEN,
        "risk_level",
        &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, &guest_req.resource, ws_path)
    {
        let response = serde_json::to_vec(&serde_json::json!({
            "approved": true,
            "decision": "allowance",
        }))
        .map_err(|e| Error::msg(format!("failed to serialize response: {e}")))?;

        tracing::debug!(
            plugin = %capsule_id,
            action = %guest_req.action,
            resource = %guest_req.resource,
            "Approval auto-granted via existing allowance"
        );

        let mem = capsule.memory_new(&response)?;
        outputs[0] = capsule.memory_to_val(mem);
        return Ok(());
    }

    // 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: guest_req.action.clone(),
        resource: guest_req.resource.clone(),
        reason: format!("Capsule '{capsule_id}' requests approval"),
        risk_level: guest_req.risk_level.clone(),
    };
    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 = %guest_req.action,
        resource = %guest_req.resource,
        risk_level = %guest_req.risk_level,
        %request_id,
        "Published approval request, waiting for response"
    );

    // Block until response, timeout, or cancellation. Routed through the host
    // semaphore to bound concurrent blocking operations across all plugins.
    let event = util::bounded_block_on_cancellable(
        &runtime_handle,
        &host_semaphore,
        &cancel_token,
        async {
            tokio::time::timeout(
                std::time::Duration::from_millis(MAX_APPROVAL_TIMEOUT_MS),
                receiver.recv(),
            )
            .await
            .ok()
            .flatten()
        },
    )
    .flatten();

    let response_json = match event {
        Some(event) => {
            if let AstridEvent::Ipc { message, .. } = &*event {
                match &message.payload {
                    IpcPayload::ApprovalResponse {
                        decision, reason, ..
                    } => {
                        let approved = matches!(
                            decision.as_str(),
                            "approve" | "approve_session" | "approve_always"
                        );

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

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

                        serde_json::to_vec(&serde_json::json!({
                            "approved": approved,
                            "decision": decision,
                        }))
                        .map_err(|e| Error::msg(format!("failed to serialize response: {e}")))?
                    },
                    _ => {
                        return Err(Error::msg(
                            "unexpected IPC payload type in approval response",
                        ));
                    },
                }
            } else {
                return Err(Error::msg("unexpected event type in approval response"));
            }
        },
        None => {
            tracing::warn!(
                plugin = %capsule_id,
                action = %guest_req.action,
                "Approval request timed out or was cancelled"
            );
            // Timeout/cancellation = deny
            serde_json::to_vec(&serde_json::json!({
                "approved": false,
                "decision": "deny",
            }))
            .map_err(|e| Error::msg(format!("failed to serialize response: {e}")))?
        },
    };

    let mem = capsule.memory_new(&response_json)?;
    outputs[0] = capsule.memory_to_val(mem);
    Ok(())
}

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

    #[test]
    fn guest_approval_request_deserializes() {
        let json = r#"{"action":"git push","resource":"git push origin main","risk_level":"high"}"#;
        let req: GuestApprovalRequest = serde_json::from_str(json).unwrap();
        assert_eq!(req.action, "git push");
        assert_eq!(req.resource, "git push origin main");
        assert_eq!(req.risk_level, "high");
    }

    #[test]
    fn check_allowance_matches_command_pattern() {
        let store = AllowanceStore::new();
        let keypair = KeyPair::generate();
        let allowance = Allowance {
            id: AllowanceId::new(),
            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, "git push origin main", None));
        assert!(!check_allowance(&store, "git status", None));
    }

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

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

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

    #[test]
    fn create_allowance_simple_approve_does_nothing() {
        let store = AllowanceStore::new();
        create_allowance_from_decision(&store, "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, "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, "git push", "garbage", None, "test");
        assert_eq!(store.count(), 0);
        create_allowance_from_decision(&store, "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(),
            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();

        // Semicolon-injected command should NOT match "git push *"
        assert!(!check_allowance(&store, "git status; rm -rf /", None));
        // Normal match still works
        assert!(check_allowance(
            &store,
            "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();
        // A malicious plugin sends action = "*" hoping to get pattern "* *"
        // After escaping, pattern becomes "\* *" which won't match normal commands.
        create_allowance_from_decision(&store, "*", "approve_session", None, "test");
        assert_eq!(store.count(), 1);
        assert!(!check_allowance(&store, "git push origin main", None));
    }

    #[test]
    fn create_allowance_empty_action() {
        // Empty action after sanitization produces no allowance - the pattern
        // would be " *" which is meaningless.
        let store = AllowanceStore::new();
        create_allowance_from_decision(&store, "", "approve_session", None, "test");
        assert_eq!(store.count(), 0);
        assert!(!check_allowance(&store, "git push", None));
    }

    #[test]
    fn approve_once_does_not_create_allowance() {
        // "approve" (one-time) should NOT create an allowance. The next
        // identical call will re-prompt the user.
        let store = AllowanceStore::new();
        create_allowance_from_decision(&store, "git push", "approve", None, "test");
        assert_eq!(store.count(), 0);
        assert!(!check_allowance(&store, "git push origin main", None));
    }

    // --- sanitize_action_for_pattern tests ---

    #[test]
    fn sanitize_action_preserves_shell_fragments() {
        // Legitimate commands with shell-like characters must pass through
        // unchanged - they are handled by escape (layer 2) and
        // contains_shell_operators (layer 3), not this layer.
        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() {
        // Glob metacharacters are printable and pass through this layer.
        // They are neutralized by escape_glob_metacharacters (layer 2).
        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() {
        // Exactly MAX_ACTION_LEN printable chars should pass through unchanged.
        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() {
        // 200 ASCII + 100 x U+0100 ("Ä€", 2 bytes each) = 300 chars.
        // Truncation should produce exactly 256 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() {
        // Whitespace-padded action should flow through both layers and
        // produce a working session allowance.
        let store = AllowanceStore::new();
        create_allowance_from_decision(&store, "  git push  ", "approve_session", None, "test");
        assert_eq!(store.count(), 1);
        // After trim: "git push", pattern: "git push *"
        assert!(check_allowance(&store, "git push origin main", None));
        assert!(!check_allowance(&store, "git status", None));
    }

    #[test]
    fn create_allowance_combined_attack() {
        // A malicious plugin sends action with control chars + glob wildcards.
        // Layer 1 strips control chars, layer 2 escapes glob chars.
        // The resulting pattern must NOT match unintended commands.
        let store = AllowanceStore::new();
        let attack = "git\0 *\x1b[31m";
        create_allowance_from_decision(&store, attack, "approve_session", None, "test");
        assert_eq!(store.count(), 1);
        // After sanitization: "git *[31m" (control chars stripped)
        // After escaping: "git \*\[31m" (glob chars escaped)
        // Pattern: "git \*\[31m *"
        // This should NOT match normal git commands.
        assert!(!check_allowance(&store, "git push origin main", None));
        assert!(!check_allowance(&store, "git status", None));
    }

    #[test]
    fn create_allowance_null_byte_attack() {
        // Null bytes stripped, pattern still safe.
        let store = AllowanceStore::new();
        create_allowance_from_decision(&store, "git\0push", "approve_session", None, "test");
        assert_eq!(store.count(), 1);
        // After sanitization: "gitpush", pattern: "gitpush *"
        // Does not match "git push" (different string).
        assert!(!check_allowance(&store, "git push origin main", None));
        // Matches only literal "gitpush ..." which is not a real command.
        assert!(check_allowance(&store, "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_risk_level() {
        let mut s = "x".repeat(200);
        sanitize_guest_field(&mut s, MAX_RISK_LEVEL_LEN, "risk_level", "test");
        assert_eq!(s.chars().count(), MAX_RISK_LEVEL_LEN);
    }

    #[test]
    fn sanitize_guest_field_preserves_normal_risk_levels() {
        for level in &["low", "medium", "high", "critical"] {
            let mut s = level.to_string();
            sanitize_guest_field(&mut s, MAX_RISK_LEVEL_LEN, "risk_level", "test");
            assert_eq!(s, *level);
        }
    }

    #[test]
    fn sanitize_guest_field_truncates_multibyte() {
        // 500 ASCII + 600 x U+0100 (2-byte) = 1100 chars, truncated to 1024.
        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() {
        // 2000 chars with embedded control chars and ANSI escapes.
        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());
    }
}