mxc-sdk 1.0.1

Importable library for starting MXC sandboxes in-process, with streaming stdio.
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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! TraceLogging ETW event emission for MXC telemetry.
//!
//! Event-specific data types and emission functions. The actual ETW
//! write is delegated to the `mxc_telemetry` crate, which adds
//! common fields automatically.

/// Bounded set of failure categories for error classification.
/// Prevents free-form strings that could contain PII.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FailureReason {
    ConfigError,
    PolicyError,
    ProcessError,
    Timeout,
    InitError,
    /// An MXC-internal defect (e.g. a panic caught by the global panic hook),
    /// as opposed to an expected operational failure of a sandboxed run.
    InternalError,
    /// Execution was interrupted by the operator (Ctrl-C, console close, or a
    /// system shutdown/logoff) via the console control handler.
    Cancelled,
    Unknown,
}

impl FailureReason {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::ConfigError => "config_error",
            Self::PolicyError => "policy_error",
            Self::ProcessError => "process_error",
            Self::Timeout => "timeout",
            Self::InitError => "init_error",
            Self::InternalError => "internal_error",
            Self::Cancelled => "cancelled",
            Self::Unknown => "unknown",
        }
    }
}

impl std::fmt::Display for FailureReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Attribution shared by every telemetry event emitted for one dispatch: the
/// containment `backend`, the state-aware lifecycle `phase` (empty for one-shot),
/// and the `correlation_vector` MS-CV span (empty for one-shot). Grouped into one
/// struct so the three `&str`s can't be swapped positionally as they thread
/// through the emit helpers.
#[derive(Debug, Clone, Copy)]
pub struct TelemetryContext<'a> {
    pub backend: &'a str,
    /// State-aware lifecycle phase — one of `provision|start|exec|stop|
    /// deprovision`, or `""` for one-shot (non-state-aware) executions.
    pub phase: &'a str,
    /// Microsoft Correlation Vector (MS-CV) span for this event, emitted under
    /// `__TlgCV__` (see [`crate::mxc_common::telemetry::correlation_vector`]), or `""` for
    /// one-shot executions.
    pub correlation_vector: &'a str,
}

/// Data for an Execution ETW event.
pub struct ExecutionEvent<'a> {
    pub backend: &'a str,
    /// Containment kind requested by the caller before host-specific resolution.
    pub sandbox_kind: &'a str,
    pub exit_code: i32,
    pub outcome: &'a str,
    pub duration_ms: u64,
    pub failure_reason: Option<FailureReason>,
    /// State-aware lifecycle phase that produced this event — one of
    /// `provision|start|exec|stop|deprovision`. Empty (`""`) for one-shot
    /// (non-state-aware) executions, which have no lifecycle phase.
    pub phase: &'a str,
    /// Microsoft Correlation Vector (MS-CV) span for this event — seeded at
    /// `provision` and spun per phase so events from the separate per-phase
    /// `wxc-exec` processes share a base prefix and can be joined (see
    /// [`crate::mxc_common::telemetry::correlation_vector`]). Carries no `sandbox_id` / UPN.
    /// Empty (`""`) for one-shot executions.
    pub correlation_vector: &'a str,
}

/// One independently parseable chunk of a Learning Mode verbose document.
#[derive(Debug, Clone, Copy)]
pub struct VerboseEvent<'a> {
    pub backend: &'a str,
    pub sandbox_kind: &'a str,
    pub phase: &'a str,
    pub correlation_vector: &'a str,
    pub document_id: &'a str,
    pub document_version: u32,
    pub chunk_index: u32,
    pub chunk_count: u32,
    pub document_bytes: u64,
    pub document_sha256: &'a str,
    /// Compact JSON array of complete `VerboseLoggingAggregate` objects.
    pub content: &'a str,
    /// Compact JSON `VerboseLoggingDocumentSummary` object.
    pub summary: &'a str,
}

/// Log an Execution ETW event.
///
/// Delegates to the `mxc_telemetry` provider which adds common fields
/// (Version, Channel, IsDebugging, UTCReplace_AppSessionGuid).
pub fn log_execution(event: &ExecutionEvent<'_>) {
    let failure_str = event.failure_reason.map(|r| r.as_str()).unwrap_or("");

    crate::mxc_telemetry::log_execution(
        event.backend,
        event.sandbox_kind,
        event.exit_code,
        event.outcome,
        event.duration_ms,
        failure_str,
        event.phase,
        event.correlation_vector,
    );

    #[cfg(test)]
    test_sink::record_execution(event);
}

/// Log an Error ETW event.
///
/// To avoid leaking PII (paths, usernames, credentials embedded in error
/// strings), MXC deliberately does **not** emit the free-form error message.
/// The event carries only the bounded `error_type` category, the process
/// `exit_code`, the caller-requested `sandbox_kind`, and the
/// [`TelemetryContext`] attribution (backend, lifecycle phase, and correlation
/// vector — the latter two empty for one-shot).
pub fn log_error(
    ctx: TelemetryContext<'_>,
    sandbox_kind: &str,
    error_type: FailureReason,
    exit_code: i32,
) {
    crate::mxc_telemetry::log_error(
        ctx.backend,
        sandbox_kind,
        error_type.as_str(),
        exit_code,
        ctx.phase,
        ctx.correlation_vector,
    );

    #[cfg(test)]
    test_sink::record_error(ctx, sandbox_kind, error_type, exit_code);
}

/// Log one `MXC.VerboseDenials` ETW event.
pub fn log_verbose(event: &VerboseEvent<'_>) -> u32 {
    let status = crate::mxc_telemetry::log_verbose(
        event.backend,
        event.sandbox_kind,
        event.phase,
        event.correlation_vector,
        event.document_id,
        event.document_version,
        event.chunk_index,
        event.chunk_count,
        event.document_bytes,
        event.document_sha256,
        event.content,
        event.summary,
    );

    #[cfg(test)]
    test_sink::record_verbose(event);

    status
}

/// Emit a process lifecycle event required by the Windows diagnostics
/// contract. The event kind and payload are coupled in a single enum
/// to make mismatches unrepresentable at compile time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessEvent<'a> {
    Exited(i32),
    TimedOut(u64),
    /// Kill method attempted, plus the numeric OS error code returned by the
    /// failed termination call (e.g. `error.code().0` on Windows), so ETW
    /// consumers can see *why* the kill failed, not just what was attempted.
    KillFailed(&'a str, i32),
}

fn requirement_emission_allowed() -> bool {
    super::process_can_emit()
}

pub fn log_process_event(identity: &str, process_id: u32, event: ProcessEvent<'_>) {
    if !requirement_emission_allowed() {
        return;
    }

    match event {
        ProcessEvent::Exited(exit_code) => {
            crate::mxc_telemetry::log_process_exited(identity, process_id, exit_code);
        }
        ProcessEvent::TimedOut(timeout_ms) => {
            crate::mxc_telemetry::log_process_timed_out(identity, process_id, timeout_ms);
        }
        ProcessEvent::KillFailed(error_type, error_code) => {
            crate::mxc_telemetry::log_process_kill_failed(
                identity, process_id, error_type, error_code,
            );
        }
    }

    #[cfg(test)]
    test_sink::record_process(identity, process_id, event);
}

pub fn log_enforcement_degraded(
    identity: &str,
    tier: &str,
    needs_dacl_augmentation: bool,
    degradation_reasons: &str,
    effective_enforcement_level: &str,
) {
    if !requirement_emission_allowed() {
        return;
    }

    crate::mxc_telemetry::log_enforcement_degraded(
        identity,
        tier,
        needs_dacl_augmentation,
        degradation_reasons,
        effective_enforcement_level,
    );
    #[cfg(test)]
    test_sink::record_requirement(
        "MXC.EnforcementDegraded",
        vec![
            ("identity".to_owned(), identity.to_owned()),
            ("tier".to_owned(), tier.to_owned()),
            (
                "needs_dacl_augmentation".to_owned(),
                needs_dacl_augmentation.to_string(),
            ),
            (
                "degradation_reasons".to_owned(),
                degradation_reasons.to_owned(),
            ),
            (
                "effective_enforcement_level".to_owned(),
                effective_enforcement_level.to_owned(),
            ),
        ],
    );
}

pub fn log_policy_hash(identity: &str, policy_hash: &str, config_schema_version: &str) {
    if !requirement_emission_allowed() {
        return;
    }

    crate::mxc_telemetry::log_policy_hash(identity, policy_hash, config_schema_version);
    #[cfg(test)]
    test_sink::record_requirement(
        "MXC.PolicyHash",
        vec![
            ("identity".to_owned(), identity.to_owned()),
            ("policy_hash".to_owned(), policy_hash.to_owned()),
            (
                "config_schema_version".to_owned(),
                config_schema_version.to_owned(),
            ),
        ],
    );
}

pub fn log_network_policy_applied(
    identity: &str,
    enforcement_mode: &str,
    default_policy: &str,
    proxy_port: u64,
) {
    if !requirement_emission_allowed() {
        return;
    }

    crate::mxc_telemetry::log_network_policy_applied(
        identity,
        enforcement_mode,
        default_policy,
        proxy_port,
    );
    #[cfg(test)]
    test_sink::record_requirement(
        "MXC.SandboxNetworkPolicyApplied",
        vec![
            ("identity".to_owned(), identity.to_owned()),
            ("enforcement_mode".to_owned(), enforcement_mode.to_owned()),
            ("default_policy".to_owned(), default_policy.to_owned()),
            ("proxy_port".to_owned(), proxy_port.to_string()),
        ],
    );
}

pub fn log_sandbox_torn_down(identity: &str, status: &str, released_resources: &str) {
    if !requirement_emission_allowed() {
        return;
    }

    crate::mxc_telemetry::log_sandbox_torn_down(identity, status, released_resources);
    #[cfg(test)]
    test_sink::record_requirement(
        "MXC.SandboxTornDown",
        vec![
            ("identity".to_owned(), identity.to_owned()),
            ("status".to_owned(), status.to_owned()),
            (
                "released_resources".to_owned(),
                released_resources.to_owned(),
            ),
        ],
    );
}

pub fn log_config_rejected(
    correlation_id: &str,
    backend: &str,
    reason: &str,
    offending_field: &str,
    phase: &str,
) {
    if !requirement_emission_allowed() {
        return;
    }

    crate::mxc_telemetry::log_config_rejected(
        correlation_id,
        backend,
        reason,
        offending_field,
        phase,
    );
    #[cfg(test)]
    test_sink::record_requirement(
        "MXC.ConfigRejected",
        vec![
            ("correlation_id".to_owned(), correlation_id.to_owned()),
            ("backend".to_owned(), backend.to_owned()),
            ("reason".to_owned(), reason.to_owned()),
            ("offending_field".to_owned(), offending_field.to_owned()),
            ("phase".to_owned(), phase.to_owned()),
        ],
    );
}

/// In-memory capture sink for the two ETW emit calls, so tests can assert the
/// records that the real emit glue (`emit_panic` / `emit_cancellation` /
/// `emit_state_aware`) produces without an ETW consumer. Inert unless a test
/// explicitly installs it; the production path above always makes the direct
/// `mxc_telemetry` call regardless.
#[cfg(test)]
pub(super) mod test_sink {
    use super::{ExecutionEvent, FailureReason, ProcessEvent, TelemetryContext, VerboseEvent};
    use std::cell::Cell;
    use std::sync::Mutex;

    /// Serializes any test that installs/clears this capture sink or drives
    /// the emit glue in `telemetry::tests`, since `EXECUTIONS`/`ERRORS`/
    /// `REQUIREMENTS` below (and the process-global emit-slot state in the
    /// parent module) are shared regardless of which thread `cargo test`
    /// happens to run a given test on. Every test that touches this module,
    /// directly or via the parent module's emit helpers, must hold this lock
    /// for its capture window.
    pub(crate) static TEST_LOCK: Mutex<()> = Mutex::new(());

    /// Owned copy of an `Execution` record as captured for a test.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub struct CapturedExecution {
        pub backend: String,
        pub sandbox_kind: String,
        pub exit_code: i32,
        pub outcome: String,
        pub duration_ms: u64,
        pub failure_reason: Option<FailureReason>,
        pub phase: String,
        pub correlation_vector: String,
    }

    /// Owned copy of an `Error` record as captured for a test.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub struct CapturedError {
        pub backend: String,
        pub sandbox_kind: String,
        pub error_type: FailureReason,
        pub exit_code: i32,
        pub phase: String,
        pub correlation_vector: String,
    }

    /// Owned copy of an `MXC.VerboseDenials` record as captured for a test.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub struct CapturedVerbose {
        pub backend: String,
        pub sandbox_kind: String,
        pub phase: String,
        pub correlation_vector: String,
        pub document_id: String,
        pub document_version: u32,
        pub chunk_index: u32,
        pub chunk_count: u32,
        pub document_bytes: u64,
        pub document_sha256: String,
        pub content: String,
        pub summary: String,
    }

    #[derive(Debug, Clone, PartialEq, Eq)]
    pub struct CapturedRequirement {
        pub name: String,
        pub fields: Vec<(String, String)>,
    }

    thread_local! {
        /// Per-thread capture flag. Thread-local (not a global `AtomicBool`) so a
        /// stray emit on another thread — e.g. a concurrent `#[should_panic]`
        /// test tripping the global panic hook — can never leak a record into a
        /// telemetry test's capture buffer. Only emits on the installing thread
        /// are recorded, and telemetry tests drive the emit glue synchronously.
        static INSTALLED: Cell<bool> = const { Cell::new(false) };
    }

    static EXECUTIONS: Mutex<Vec<CapturedExecution>> = Mutex::new(Vec::new());
    static ERRORS: Mutex<Vec<CapturedError>> = Mutex::new(Vec::new());
    static VERBOSE: Mutex<Vec<CapturedVerbose>> = Mutex::new(Vec::new());
    static REQUIREMENTS: Mutex<Vec<CapturedRequirement>> = Mutex::new(Vec::new());

    /// Start capturing emitted records into the sink (and clear any leftovers).
    /// The caller must hold the telemetry `TEST_LOCK` for the capture window.
    pub fn install() {
        clear();
        INSTALLED.with(|f| f.set(true));
    }

    /// Stop capturing and drop any buffered records.
    pub fn clear() {
        INSTALLED.with(|f| f.set(false));
        EXECUTIONS.lock().unwrap_or_else(|e| e.into_inner()).clear();
        ERRORS.lock().unwrap_or_else(|e| e.into_inner()).clear();
        VERBOSE.lock().unwrap_or_else(|e| e.into_inner()).clear();
        REQUIREMENTS
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clear();
    }

    /// Drain and return the captured `Execution` records.
    pub fn take_executions() -> Vec<CapturedExecution> {
        std::mem::take(&mut *EXECUTIONS.lock().unwrap_or_else(|e| e.into_inner()))
    }

    /// Drain and return the captured `Error` records.
    pub fn take_errors() -> Vec<CapturedError> {
        std::mem::take(&mut *ERRORS.lock().unwrap_or_else(|e| e.into_inner()))
    }

    /// Drain and return the captured `MXC.VerboseDenials` records.
    pub fn take_verbose() -> Vec<CapturedVerbose> {
        std::mem::take(&mut *VERBOSE.lock().unwrap_or_else(|e| e.into_inner()))
    }

    pub fn take_requirements() -> Vec<CapturedRequirement> {
        std::mem::take(&mut *REQUIREMENTS.lock().unwrap_or_else(|e| e.into_inner()))
    }

    pub(super) fn record_requirement(name: &str, fields: Vec<(String, String)>) {
        if INSTALLED.with(|f| f.get()) {
            REQUIREMENTS
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .push(CapturedRequirement {
                    name: name.to_owned(),
                    fields,
                });
        }
    }

    pub(super) fn record_process(identity: &str, process_id: u32, event: ProcessEvent<'_>) {
        let (name, fields) = match event {
            ProcessEvent::Exited(exit_code) => (
                "MXC.ProcessExited",
                vec![
                    ("identity".to_owned(), identity.to_owned()),
                    ("process_id".to_owned(), process_id.to_string()),
                    ("ExitCode".to_owned(), exit_code.to_string()),
                ],
            ),
            ProcessEvent::TimedOut(timeout_ms) => (
                "MXC.ProcessTimedOut",
                vec![
                    ("identity".to_owned(), identity.to_owned()),
                    ("process_id".to_owned(), process_id.to_string()),
                    ("TimeoutMs".to_owned(), timeout_ms.to_string()),
                ],
            ),
            ProcessEvent::KillFailed(error_type, error_code) => (
                "MXC.ProcessKillFailed",
                vec![
                    ("identity".to_owned(), identity.to_owned()),
                    ("process_id".to_owned(), process_id.to_string()),
                    ("mxc.error_type".to_owned(), error_type.to_owned()),
                    ("mxc.error_code".to_owned(), error_code.to_string()),
                ],
            ),
        };

        if INSTALLED.with(|f| f.get()) {
            REQUIREMENTS
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .push(CapturedRequirement {
                    name: name.to_owned(),
                    fields,
                });
        }
    }

    pub(super) fn record_execution(event: &ExecutionEvent<'_>) {
        if !INSTALLED.with(|f| f.get()) {
            return;
        }
        EXECUTIONS
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .push(CapturedExecution {
                backend: event.backend.to_owned(),
                sandbox_kind: event.sandbox_kind.to_owned(),
                exit_code: event.exit_code,
                outcome: event.outcome.to_owned(),
                duration_ms: event.duration_ms,
                failure_reason: event.failure_reason,
                phase: event.phase.to_owned(),
                correlation_vector: event.correlation_vector.to_owned(),
            });
    }

    pub(super) fn record_error(
        ctx: TelemetryContext<'_>,
        sandbox_kind: &str,
        error_type: FailureReason,
        exit_code: i32,
    ) {
        if !INSTALLED.with(|f| f.get()) {
            return;
        }
        ERRORS
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .push(CapturedError {
                backend: ctx.backend.to_owned(),
                sandbox_kind: sandbox_kind.to_owned(),
                error_type,
                exit_code,
                phase: ctx.phase.to_owned(),
                correlation_vector: ctx.correlation_vector.to_owned(),
            });
    }

    pub(super) fn record_verbose(event: &VerboseEvent<'_>) {
        if !INSTALLED.with(|f| f.get()) {
            return;
        }
        VERBOSE
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .push(CapturedVerbose {
                backend: event.backend.to_owned(),
                sandbox_kind: event.sandbox_kind.to_owned(),
                phase: event.phase.to_owned(),
                correlation_vector: event.correlation_vector.to_owned(),
                document_id: event.document_id.to_owned(),
                document_version: event.document_version,
                chunk_index: event.chunk_index,
                chunk_count: event.chunk_count,
                document_bytes: event.document_bytes,
                document_sha256: event.document_sha256.to_owned(),
                content: event.content.to_owned(),
                summary: event.summary.to_owned(),
            });
    }
}

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

    #[test]
    fn failure_reason_as_str() {
        assert_eq!(FailureReason::ConfigError.as_str(), "config_error");
        assert_eq!(FailureReason::PolicyError.as_str(), "policy_error");
        assert_eq!(FailureReason::ProcessError.as_str(), "process_error");
        assert_eq!(FailureReason::Timeout.as_str(), "timeout");
        assert_eq!(FailureReason::InitError.as_str(), "init_error");
        assert_eq!(FailureReason::InternalError.as_str(), "internal_error");
        assert_eq!(FailureReason::Cancelled.as_str(), "cancelled");
        assert_eq!(FailureReason::Unknown.as_str(), "unknown");
    }

    #[test]
    fn verbose_event_is_captured_with_parseable_json_fields() {
        let _lock = test_sink::TEST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        test_sink::install();
        log_verbose(&VerboseEvent {
            backend: "processcontainer",
            sandbox_kind: "process",
            phase: "",
            correlation_vector: "",
            document_id: "0123456789abcdef0123456789abcdef",
            document_version: 2,
            chunk_index: 0,
            chunk_count: 1,
            document_bytes: 64,
            document_sha256: "abc",
            content: "[]",
            summary: r#"{"totalOccurrences":0}"#,
        });

        let captured = test_sink::take_verbose();
        test_sink::clear();
        assert_eq!(captured.len(), 1);
        assert_eq!(
            serde_json::from_str::<serde_json::Value>(&captured[0].content).unwrap(),
            serde_json::json!([])
        );
        assert!(serde_json::from_str::<serde_json::Value>(&captured[0].summary).is_ok());
    }

    #[test]
    fn requirement_events_use_bounded_event_names() {
        let _lock = test_sink::TEST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        super::super::reset_for_test();
        super::super::TEST_FORCE_ACTIVE.with(|value| value.set(true));
        super::super::TEST_AUTHORIZATION_OVERRIDE.with(|value| value.set(Some(true)));
        test_sink::install();
        log_process_event("opaque", 42, ProcessEvent::Exited(0));
        log_process_event("opaque", 42, ProcessEvent::TimedOut(1000));
        log_process_event("opaque", 42, ProcessEvent::KillFailed("terminate", 5));
        log_enforcement_degraded("opaque", "base_container", true, "reason", "dacl_augmented");
        log_policy_hash("opaque", "sha256:abc", "0.9.0-alpha");
        log_network_policy_applied("opaque", "proxy", "deny", 8080);
        log_sandbox_torn_down("opaque", "success", "released");
        log_config_rejected(
            "corr",
            "process_container",
            "invalid",
            "process.commandLine",
            "validate",
        );
        let events = test_sink::take_requirements();
        super::super::reset_for_test();

        // Validate ProcessExited payload
        let process_exited = events
            .iter()
            .find(|e| {
                e.name == "MXC.ProcessExited"
                    && e.fields
                        .iter()
                        .any(|(n, v)| n == "identity" && v == "opaque")
            })
            .expect("MXC.ProcessExited with opaque identity");
        assert!(process_exited
            .fields
            .iter()
            .any(|(n, v)| n == "process_id" && v == "42"));
        assert!(
            process_exited
                .fields
                .iter()
                .any(|(n, v)| n == "ExitCode" && v == "0"),
            "ProcessExited must include ExitCode field with value 0"
        );

        // Validate ProcessTimedOut payload
        let process_timedout = events
            .iter()
            .find(|e| e.name == "MXC.ProcessTimedOut")
            .expect("MXC.ProcessTimedOut");
        assert!(process_timedout
            .fields
            .iter()
            .any(|(n, v)| n == "identity" && v == "opaque"));
        assert!(process_timedout
            .fields
            .iter()
            .any(|(n, v)| n == "process_id" && v == "42"));
        assert!(
            process_timedout
                .fields
                .iter()
                .any(|(n, v)| n == "TimeoutMs" && v == "1000"),
            "ProcessTimedOut must include TimeoutMs field with value 1000"
        );

        // Validate ProcessKillFailed payload
        let process_killfailed = events
            .iter()
            .find(|e| e.name == "MXC.ProcessKillFailed")
            .expect("MXC.ProcessKillFailed");
        assert!(process_killfailed
            .fields
            .iter()
            .any(|(n, v)| n == "identity" && v == "opaque"));
        assert!(process_killfailed
            .fields
            .iter()
            .any(|(n, v)| n == "process_id" && v == "42"));
        assert!(
            process_killfailed
                .fields
                .iter()
                .any(|(n, v)| n == "mxc.error_type" && v == "terminate"),
            "ProcessKillFailed must include mxc.error_type field"
        );
        assert!(
            process_killfailed
                .fields
                .iter()
                .any(|(n, v)| n == "mxc.error_code" && v == "5"),
            "ProcessKillFailed must include mxc.error_code field"
        );

        // Validate EnforcementDegraded payload
        let enforcement = events
            .iter()
            .find(|e| e.name == "MXC.EnforcementDegraded")
            .expect("enforcement event");
        assert!(enforcement
            .fields
            .iter()
            .any(|(n, v)| n == "identity" && v == "opaque"));
        assert!(
            enforcement
                .fields
                .iter()
                .any(|(n, v)| n == "tier" && v == "base_container"),
            "EnforcementDegraded must include tier field with correct value"
        );
        assert!(enforcement
            .fields
            .contains(&("needs_dacl_augmentation".to_owned(), "true".to_owned())));
        assert!(
            enforcement
                .fields
                .iter()
                .any(|(n, v)| !n.starts_with("degradation_reasons") || !v.is_empty()),
            "EnforcementDegraded must include non-empty degradation_reasons"
        );
        assert!(
            enforcement
                .fields
                .iter()
                .any(|(n, v)| !n.starts_with("effective_enforcement_level") || !v.is_empty()),
            "EnforcementDegraded must include non-empty effective_enforcement_level"
        );

        // Validate PolicyHash payload
        let policy_hash = events
            .iter()
            .find(|e| e.name == "MXC.PolicyHash")
            .expect("policy hash event");
        assert!(policy_hash
            .fields
            .contains(&("identity".to_owned(), "opaque".to_owned())));
        assert!(policy_hash
            .fields
            .contains(&("policy_hash".to_owned(), "sha256:abc".to_owned())));
        assert!(policy_hash
            .fields
            .contains(&("config_schema_version".to_owned(), "0.9.0-alpha".to_owned())));

        // Validate SandboxNetworkPolicyApplied payload
        let network = events
            .iter()
            .find(|e| e.name == "MXC.SandboxNetworkPolicyApplied")
            .expect("network event");
        assert!(network
            .fields
            .iter()
            .any(|(n, v)| n == "identity" && v == "opaque"));
        assert!(network
            .fields
            .iter()
            .any(|(n, v)| n == "enforcement_mode" && v == "proxy"));
        assert!(network
            .fields
            .iter()
            .any(|(n, v)| n == "default_policy" && v == "deny"));
        assert!(network
            .fields
            .contains(&("proxy_port".to_owned(), "8080".to_owned())));

        // Validate SandboxTornDown payload
        let teardown = events
            .iter()
            .find(|e| e.name == "MXC.SandboxTornDown")
            .expect("teardown event");
        assert!(teardown
            .fields
            .iter()
            .any(|(n, v)| n == "identity" && v == "opaque"));
        assert!(teardown
            .fields
            .iter()
            .any(|(n, v)| n == "status" && v == "success"));
        assert!(teardown
            .fields
            .contains(&("released_resources".to_owned(), "released".to_owned())));

        // Validate ConfigRejected payload
        let rejected = events
            .iter()
            .find(|e| e.name == "MXC.ConfigRejected")
            .expect("config rejection event");
        assert!(rejected
            .fields
            .iter()
            .any(|(n, v)| n == "correlation_id" && v == "corr"));
        assert!(rejected
            .fields
            .iter()
            .any(|(n, v)| n == "backend" && v == "process_container"));
        assert!(rejected
            .fields
            .iter()
            .any(|(n, v)| n == "reason" && v == "invalid"));
        assert!(rejected.fields.contains(&(
            "offending_field".to_owned(),
            "process.commandLine".to_owned()
        )));
        assert!(rejected
            .fields
            .contains(&("phase".to_owned(), "validate".to_owned())));
    }

    #[test]
    fn requirement_events_respect_live_authorization() {
        let _lock = test_sink::TEST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        super::super::reset_for_test();
        super::super::TEST_FORCE_ACTIVE.with(|value| value.set(true));
        super::super::TEST_AUTHORIZATION_OVERRIDE.with(|value| value.set(Some(false)));
        test_sink::install();

        log_process_event("opaque", 42, ProcessEvent::Exited(0));
        log_enforcement_degraded("opaque", "base_container", true, "reason", "dacl_augmented");
        log_policy_hash("opaque", "sha256:abc", "0.9.0-alpha");
        log_network_policy_applied("opaque", "proxy", "deny", 8080);
        log_sandbox_torn_down("opaque", "success", "released");
        log_config_rejected(
            "corr",
            "process_container",
            "invalid",
            "process.commandLine",
            "validate",
        );

        assert!(test_sink::take_requirements().is_empty());
        super::super::reset_for_test();
    }
}