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
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Typed error model for the IsolationSession backend and the conversions to
//! `ScriptResponse` (one-shot) and `MxcError` (state-aware dispatch).
//!
//! Failures raised by the IsolationSession API are carried **structurally**
//! — operation, HRESULT, message and remediation stay separate fields all the
//! way to the wire, so a caller can react to them without parsing prose. The
//! one-shot path has no structured envelope, so [`IsolationSessionError`]'s
//! `Display` folds the same components back into one human-readable string.

use crate::mxc_common::models::ScriptResponse;
use crate::mxc_common::mxc_error::{ApiFailure, MxcError, MxcErrorCode};

use crate::isolation_session_bindings::bindings::{IsoSessionError, IsoSessionResult};

/// Interface-qualified names of the API operations this backend invokes.
///
/// These are the values that reach the wire as `error.operation`. They are
/// deliberately constants rather than formatted strings: the field must stay
/// low-cardinality and free of call parameters so it can be grouped in
/// telemetry.
pub(super) mod op {
    pub(crate) const CO_INCREMENT_MTA_USAGE: &str = "Com.CoIncrementMTAUsage";

    pub(crate) const ACTIVATE: &str = "IsoSessionOps.ActivateInstance";
    pub(crate) const ADD_USER: &str = "IsoSessionOps.AddUserAsync2";
    pub(crate) const ADD_USER_LEGACY: &str = "IsoSessionOps.AddUserAsync";
    pub(crate) const ADD_USER_DEDUCED: &str = "IsoSessionOps.AddUserAsync3";
    pub(crate) const START_SESSION: &str = "IsoSessionOps.StartSessionAsync";
    pub(crate) const START_SESSION_DEDUCED: &str = "IsoSessionOps.StartSessionAsync2";
    pub(crate) const RUN_PROCESS: &str = "IsoSessionOps.RunProcessWithOptionsAsync";
    pub(crate) const STOP_SESSION: &str = "IsoSessionOps.StopSessionAsync";
    pub(crate) const REMOVE_USER: &str = "IsoSessionOps.RemoveUserAsync";

    pub(crate) const OPTIONS_NEW: &str = "IsoSessionProcessOptions.new";
    pub(crate) const OPTIONS_TIMEOUT: &str = "IsoSessionProcessOptions.SetTimeoutMilliseconds";
    pub(crate) const OPTIONS_WORKING_DIR: &str = "IsoSessionProcessOptions.SetWorkingDirectory";
    pub(crate) const OPTIONS_INTERACTIVE: &str = "IsoSessionProcessOptions.SetInteractiveConsole";
    pub(crate) const OPTIONS_REDIRECT_STDIN: &str =
        "IsoSessionProcessOptions.SetRedirectStandardInput";
    pub(crate) const OPTIONS_REDIRECT_STDOUT: &str =
        "IsoSessionProcessOptions.SetRedirectStandardOutput";
    pub(crate) const OPTIONS_REDIRECT_STDERR: &str =
        "IsoSessionProcessOptions.SetRedirectStandardError";
    pub(crate) const OPTIONS_ENVIRONMENT: &str = "IsoSessionProcessOptions.Environment";
}

/// `HRESULT_FROM_WIN32(ERROR_NOT_FOUND)`. Every non-provision lifecycle op
/// (start / exec / stop / deprovision) surfaces this HRESULT when the
/// agent user is unknown to the OS API; we promote it to `Stale` so a
/// deprovisioned `sandbox_id` reads as `MxcError::StaleId` at the dispatch
/// boundary, not a generic backend error.
const ERROR_NOT_FOUND_HRESULT: u32 = 0x80070490;

/// `CLASS_E_CLASSNOTAVAILABLE` — the runtime class is known but cannot be
/// activated on this OS build.
const CLASS_E_CLASSNOTAVAILABLE_HRESULT: u32 = 0x80040111;

/// `REGDB_E_CLASSNOTREG` — the runtime class is not registered at all.
const REGDB_E_CLASSNOTREG_HRESULT: u32 = 0x80040154;

/// Renders an HRESULT for the wire `nativeCode` field.
fn format_native_code(code: u32) -> String {
    format!("{code:#010x}")
}

/// Substituted when the API reports a failure but supplies no message text.
///
/// `message` is a required field on the wire envelope. Before the components
/// were split out it was always non-empty because it embedded the operation
/// and HRESULT; now that those have their own fields, nothing backfills it, so
/// a failed or empty `Message()` getter would otherwise surface as
/// `"message": ""`.
const NO_API_MESSAGE: &str = "the IsolationSession API reported a failure without a message";

/// The components of a failure raised by the IsolationSession API, kept
/// separate rather than pre-formatted.
///
/// `operation` is always present — this type only describes failures where an
/// API call was in flight. `code` is absent only when the status could not be
/// read; `remediation` only when the API supplied one. `message` is likewise
/// never empty — see [`IsoApiFailure::new`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct IsoApiFailure {
    /// Interface-qualified operation, e.g. `IsoSessionOps.AddUserAsync`.
    pub operation: String,
    /// The underlying HRESULT, when it could be read.
    pub code: Option<u32>,
    /// The bare human-readable message — no operation prefix, no HRESULT, no
    /// remediation folded in. Never empty.
    pub message: String,
    /// The API-supplied "how to fix it" hint, when it provided one.
    pub remediation: Option<String>,
}

impl IsoApiFailure {
    /// Builds a failure, normalising the two best-effort text fields.
    ///
    /// `Message()` and `Remediation()` are fallible getters that the API may
    /// also answer with an empty string, so both arrive as `Option`. An absent
    /// or empty `message` is replaced with [`NO_API_MESSAGE`] — the wire
    /// requires the field, and no other field backfills it. An absent or empty
    /// `remediation` stays absent, since that field is optional on the wire.
    ///
    /// Normalising here rather than at each call site is what keeps the
    /// guarantee from having to be re-stated (and re-remembered) per branch.
    fn new(
        operation: &str,
        code: Option<u32>,
        message: Option<String>,
        remediation: Option<String>,
    ) -> Self {
        Self {
            operation: operation.to_string(),
            code,
            message: message
                .filter(|m| !m.is_empty())
                .unwrap_or_else(|| NO_API_MESSAGE.to_string()),
            remediation: remediation.filter(|r| !r.is_empty()),
        }
    }

    /// Folds the components back into one human-readable string.
    ///
    /// Only the one-shot path consumes this: it has no structured error
    /// envelope, so the string is the sole carrier of the detail. The
    /// state-aware path reads the fields directly and must not use this.
    fn describe(&self) -> String {
        let mut out = format!("{}: {}", self.operation, self.message);
        if let Some(code) = self.code {
            out.push_str(&format!(" (HRESULT: {})", format_native_code(code)));
        }
        if let Some(remediation) = &self.remediation {
            out.push_str(&format!(" -- remediation: {remediation}"));
        }
        out
    }

    /// Builds the wire error, attaching the structured components.
    fn into_mxc_error(self, code: MxcErrorCode) -> MxcError {
        let mut failure = ApiFailure::new(self.operation);
        if let Some(hresult) = self.code {
            failure = failure.with_native_code(format_native_code(hresult));
        }
        let mut error = MxcError::new(code, self.message).with_api_failure(failure);
        if let Some(remediation) = self.remediation {
            error = error.with_remediation(remediation);
        }
        error
    }
}

/// A lifecycle step failed. The arms exist so that a failure MXC raises itself
/// *cannot* carry an API operation: there was no API call in flight, so there
/// is nothing to name.
#[derive(Debug)]
pub(super) enum LifecycleFailure {
    /// An IsolationSession API call failed.
    Api(IsoApiFailure),
    /// MXC's own machinery failed (thread creation, console handles, and
    /// other work that is not an API call). Message-only by construction.
    Internal(String),
    /// MXC declined to proceed and can say what the caller should do instead.
    /// The remediation is required — a refusal with no way forward is
    /// [`LifecycleFailure::Internal`].
    Refused {
        message: String,
        remediation: String,
    },
}

/// Categorised errors from the IsolationSession backend.
#[derive(Debug)]
pub(super) enum IsolationSessionError {
    /// Caller-supplied container policy carries a field this backend does
    /// not support (filesystem rules, network rules, proxy). Raised by MXC
    /// before any API call, so it carries no structured components.
    Policy(String),
    /// The in-proc IsolationSession runtime API is not available on this
    /// host (not registered, or the OS feature gate is off). This is a real
    /// COM activation failure, so it does carry the operation and the
    /// HRESULT.
    ServiceUnavailable(IsoApiFailure),
    /// A lifecycle step (provision / start / exec / stop / deprovision)
    /// failed.
    Lifecycle(LifecycleFailure),
    /// The OS API could not find the agent user — the sandbox has been
    /// deprovisioned (or never existed in this user's session). Surfaces
    /// as `MxcError::StaleId` at the dispatch boundary.
    Stale(IsoApiFailure),
}

impl IsolationSessionError {
    /// Appends context to the message this carries, keeping the variant and
    /// every structured field.
    ///
    /// Rebuilding the error as a message-only variant instead would drop the
    /// failing API call, its status and its remediation, and would demote a
    /// stale-id failure to a generic backend error.
    pub(super) fn with_context(mut self, context: &str) -> Self {
        let message = match &mut self {
            Self::Policy(message) => message,
            Self::ServiceUnavailable(failure) | Self::Stale(failure) => &mut failure.message,
            Self::Lifecycle(LifecycleFailure::Api(failure)) => &mut failure.message,
            Self::Lifecycle(LifecycleFailure::Internal(message)) => message,
            Self::Lifecycle(LifecycleFailure::Refused { message, .. }) => message,
        };
        message.push_str(context);
        self
    }
}

impl std::fmt::Display for IsolationSessionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Policy(msg) => write!(f, "Isolation Session policy error: {}", msg),
            Self::ServiceUnavailable(failure) => {
                write!(
                    f,
                    "Isolation Session service unavailable: {}",
                    failure.describe()
                )
            }
            Self::Lifecycle(LifecycleFailure::Api(failure)) => {
                write!(
                    f,
                    "Isolation Session lifecycle error: {}",
                    failure.describe()
                )
            }
            Self::Lifecycle(LifecycleFailure::Internal(msg)) => {
                write!(f, "Isolation Session lifecycle error: {}", msg)
            }
            Self::Lifecycle(LifecycleFailure::Refused {
                message,
                remediation,
            }) => {
                write!(
                    f,
                    "Isolation Session lifecycle error: {message} -- remediation: {remediation}"
                )
            }
            Self::Stale(failure) => {
                write!(f, "Isolation Session stale id: {}", failure.describe())
            }
        }
    }
}

impl From<IsolationSessionError> for ScriptResponse {
    fn from(err: IsolationSessionError) -> Self {
        ScriptResponse::error(&err.to_string())
    }
}

/// An MXC-side lifecycle failure, with no API operation in flight.
pub(super) fn lifecycle_err(msg: impl Into<String>) -> IsolationSessionError {
    IsolationSessionError::Lifecycle(LifecycleFailure::Internal(msg.into()))
}

/// A transport failure: the API call itself could not be completed (the
/// channel dropped, the object is gone, a property could not be read).
///
/// `step` names the sub-operation within `operation` — the operation stays
/// the lifecycle call in flight so a consumer has a stable value to branch
/// on, while the finer detail rides in the message.
pub(super) fn transport_err(
    operation: &str,
    step: &str,
    err: &windows_core::Error,
) -> IsolationSessionError {
    IsolationSessionError::Lifecycle(LifecycleFailure::Api(IsoApiFailure::new(
        operation,
        Some(err.code().0 as u32),
        Some(compose_transport_message(step, &err.message())),
        None,
    )))
}

/// Joins `step` with the platform's text, tolerating an absent text.
///
/// `windows_core::Error::message()` answers with an empty string for an
/// HRESULT that has no entry in the OS message table (`0xDEADBEEF`, and any
/// custom facility code a service invents). Formatting unconditionally would
/// then yield a dangling `"wait failed: "` — non-empty, so it sails past the
/// empty-message guard in [`IsoApiFailure::new`] and reaches the caller as a
/// trailing colon with no explanation. Fall back to the step alone instead.
fn compose_transport_message(step: &str, platform_message: &str) -> String {
    if platform_message.is_empty() {
        step.to_string()
    } else {
        format!("{step}: {platform_message}")
    }
}

/// Maps an activation failure of the in-proc IsolationSession runtime API to
/// `ServiceUnavailable`.
///
/// Pure over the HRESULT: activation itself depends on whether the host
/// supports isolation sessions, but this mapping does not, so it stays
/// testable on any machine.
pub(super) fn activation_error(code: u32, detail: &str) -> IsolationSessionError {
    let message =
        if code == CLASS_E_CLASSNOTAVAILABLE_HRESULT || code == REGDB_E_CLASSNOTREG_HRESULT {
            "the in-proc IsolationSession runtime API is not available on this OS build. Ensure \
         the OS feature gate is enabled and the platform supports isolation sessions."
                .to_string()
        } else {
            format!("IsolationSession runtime API activation failed: {detail}")
        };
    IsolationSessionError::ServiceUnavailable(IsoApiFailure::new(
        op::ACTIVATE,
        Some(code),
        Some(message),
        None,
    ))
}

/// The refusal for a caller whose impersonation token cannot be carried onto
/// the thread that makes the call.
pub(super) fn identity_refusal(err: windows_core::Error) -> IsolationSessionError {
    IsolationSessionError::Lifecycle(LifecycleFailure::Refused {
        message: format!(
            "the calling thread's impersonation token could not be carried onto the thread that \
             makes the call: {err}"
        ),
        remediation: "Call without impersonating, or with an impersonation token this process can \
                      duplicate at SecurityImpersonation level."
            .to_string(),
    })
}

/// Whether an `ERROR_NOT_FOUND` from this operation means "the sandbox is
/// gone".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum StalePromotion {
    /// Non-provision operations address an existing agent user, so
    /// `ERROR_NOT_FOUND` means that user is gone.
    Eligible,
    /// Provision *mints* the agent user. There is no `sandboxId` yet, so
    /// reporting `stale_id` — whose remediation is "re-provision; treat the
    /// id as dead" — would be incoherent.
    NotEligible,
}

/// Classifies an API failure whose components have already been extracted.
///
/// Pure, and deliberately separate from [`format_iso_error`]: `IsoSessionError`
/// is a WinRT interface obtained by activation and cannot be constructed in a
/// unit test, so the classification rules would otherwise be untestable.
///
/// The `ERROR_NOT_FOUND` promotion is **semantic-path only** by design. The
/// in-proc client maps its internal codes to standard HRESULTs when it builds
/// the `IsoSessionError`, and that mapping is what gives `0x80070490` the
/// meaning "agent user not provisioned". A transport-path HRESULT of the same
/// value has no such provenance — it could be any "not found" from activation
/// or RPC — so promoting it would emit a false `stale_id` and tell the caller
/// to destroy a healthy sandbox. Do not "fix" the asymmetry.
pub(super) fn classify_api_failure(
    failure: IsoApiFailure,
    promotion: StalePromotion,
) -> IsolationSessionError {
    if failure.code == Some(ERROR_NOT_FOUND_HRESULT) && promotion == StalePromotion::Eligible {
        IsolationSessionError::Stale(failure)
    } else {
        IsolationSessionError::Lifecycle(LifecycleFailure::Api(failure))
    }
}

/// Reads an `IsoSessionError`'s components and classifies them.
///
/// Thin by design — the rules live in [`classify_api_failure`] and
/// [`unreadable_code_failure`]; this only crosses the WinRT boundary.
pub(super) fn format_iso_error(
    operation: &str,
    err: &IsoSessionError,
    promotion: StalePromotion,
) -> IsolationSessionError {
    // Both getters are best-effort and may also answer with an empty string,
    // so both collapse to `None` here and `IsoApiFailure::new` decides what an
    // absent value means for each field.
    let message = err
        .Message()
        .map(|h| h.to_string())
        .ok()
        .filter(|m| !m.is_empty());
    let remediation = err.Remediation().map(|h| h.to_string()).ok();

    // `Code()` is the classification-critical field: it drives the `Stale`
    // promotion, so fabricating 0 when the getter fails would silently
    // downgrade a stale sandbox to a generic lifecycle error. Report the
    // read failure instead and leave the code unknown, which also keeps
    // `nativeCode` off the wire rather than carrying the getter's own
    // HRESULT — that would describe reading the field, not the operation.
    match err.Code() {
        Ok(code) => classify_api_failure(
            IsoApiFailure::new(operation, Some(code.0 as u32), message, remediation),
            promotion,
        ),
        Err(read_err) => {
            unreadable_code_failure(operation, message, remediation, &read_err.to_string())
        }
    }
}

/// Builds the failure for the case where the status getter itself failed.
///
/// Pure, and split out of [`format_iso_error`] for the same reason
/// [`classify_api_failure`] is: that function takes an `IsoSessionError`, a
/// WinRT interface obtained by activation, so nothing inside it can be reached
/// from a unit test.
///
/// With no usable status there is nothing to classify on, so this never
/// promotes to `Stale` — the note is the only signal that classification is
/// degraded, which is why it is folded into the message rather than dropped.
fn unreadable_code_failure(
    operation: &str,
    message: Option<String>,
    remediation: Option<String>,
    read_err: &str,
) -> IsolationSessionError {
    let note = format!("could not read HRESULT code: {read_err}");
    let message = Some(match message {
        Some(m) => format!("{m} ({note})"),
        None => note,
    });
    IsolationSessionError::Lifecycle(LifecycleFailure::Api(IsoApiFailure::new(
        operation,
        None,
        message,
        remediation,
    )))
}

/// Checks the `Error` property of an `IsoSessionResult`. `Ok(())` on no
/// error; lifecycle (or stale) error with structured details otherwise.
pub(super) fn check_result(
    result: &IsoSessionResult,
    operation: &str,
    promotion: StalePromotion,
) -> Result<(), IsolationSessionError> {
    let err = result
        .Error()
        .map_err(|e| transport_err(operation, "get Error failed", &e))?;
    let is_error = err
        .IsError()
        .map_err(|e| transport_err(operation, "get IsError failed", &e))?;
    if is_error {
        Err(format_iso_error(operation, &err, promotion))
    } else {
        Ok(())
    }
}

pub(super) fn map_lifecycle_error(err: IsolationSessionError) -> MxcError {
    match err {
        IsolationSessionError::Policy(msg) => MxcError::policy_validation(msg),
        IsolationSessionError::ServiceUnavailable(failure) => {
            failure.into_mxc_error(MxcErrorCode::BackendUnavailable)
        }
        IsolationSessionError::Lifecycle(LifecycleFailure::Internal(msg)) => {
            MxcError::backend_error(msg)
        }
        IsolationSessionError::Lifecycle(LifecycleFailure::Refused {
            message,
            remediation,
        }) => MxcError::backend_error(message).with_remediation(remediation),
        IsolationSessionError::Lifecycle(LifecycleFailure::Api(failure)) => {
            failure.into_mxc_error(MxcErrorCode::BackendError)
        }
        IsolationSessionError::Stale(failure) => failure.into_mxc_error(MxcErrorCode::StaleId),
    }
}

/// Constructors for tests in sibling modules, which cannot reach the private
/// failure types directly.
#[cfg(test)]
pub(crate) mod test_support {
    use super::{classify_api_failure, IsoApiFailure, IsolationSessionError, StalePromotion};

    /// A stale-id failure carrying an operation, a status and a remediation —
    /// the shape that has the most to lose if an error is rebuilt.
    pub(crate) fn stale_failure() -> IsolationSessionError {
        classify_api_failure(
            IsoApiFailure::new(
                super::op::STOP_SESSION,
                Some(super::ERROR_NOT_FOUND_HRESULT),
                Some("agent user not found".to_string()),
                Some("Re-provision the sandbox.".to_string()),
            ),
            StalePromotion::Eligible,
        )
    }
}

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

    fn api_failure(code: Option<u32>) -> IsoApiFailure {
        IsoApiFailure::new(
            op::STOP_SESSION,
            code,
            Some("agent user not found".to_string()),
            Some("Re-provision the sandbox.".to_string()),
        )
    }

    // ── Best-effort text fields are normalised at construction ───────────

    /// `message` is required on the wire, and since the operation and status
    /// moved to their own fields nothing else backfills it. A failed or empty
    /// `Message()` getter must not reach a consumer as `"message": ""`.
    #[test]
    fn absent_or_empty_api_message_is_replaced_with_a_stand_in() {
        for supplied in [None, Some(String::new())] {
            let failure = IsoApiFailure::new(op::ADD_USER, Some(0x80004005), supplied, None);
            assert_eq!(failure.message, NO_API_MESSAGE);
            assert!(!failure.message.is_empty());
        }
    }

    #[test]
    fn a_supplied_api_message_is_kept_verbatim() {
        let failure = IsoApiFailure::new(
            op::ADD_USER,
            Some(0x80004005),
            Some("The provision was not found.".to_string()),
            None,
        );
        assert_eq!(failure.message, "The provision was not found.");
    }

    /// `remediation` is optional on the wire, so an empty one stays absent
    /// rather than being stood in for -- the opposite treatment to `message`,
    /// and the reason both go through one constructor.
    #[test]
    fn absent_or_empty_remediation_stays_absent() {
        for supplied in [None, Some(String::new())] {
            let failure = IsoApiFailure::new(op::ADD_USER, None, None, supplied);
            assert_eq!(failure.remediation, None);
        }
    }

    /// The stand-in must survive to the wire, not just to the internal type.
    #[test]
    fn stand_in_message_reaches_the_envelope() {
        let mapped = map_lifecycle_error(classify_api_failure(
            IsoApiFailure::new(op::STOP_SESSION, Some(0x80004005), None, None),
            StalePromotion::Eligible,
        ));
        assert_eq!(mapped.message, NO_API_MESSAGE);
        assert!(!mapped.to_envelope().message.is_empty());
    }

    // ── Constants pinned to the OS values they mirror ────────────────────

    #[test]
    fn error_not_found_hresult_constant_matches_win32() {
        // HRESULT_FROM_WIN32(ERROR_NOT_FOUND) = 0x80070000 | (1168 & 0xFFFF)
        // = 0x80070490. A regression in this constant would silently downgrade
        // stale-id detection to backend_error.
        use windows::Win32::Foundation::ERROR_NOT_FOUND;
        let expected = 0x8007_0000u32 | (ERROR_NOT_FOUND.0 & 0xFFFF);
        assert_eq!(ERROR_NOT_FOUND_HRESULT, expected);
        assert_eq!(ERROR_NOT_FOUND_HRESULT, 0x80070490);
    }

    #[test]
    fn activation_hresult_constants_match_win32() {
        use windows::Win32::Foundation::{CLASS_E_CLASSNOTAVAILABLE, REGDB_E_CLASSNOTREG};
        assert_eq!(
            CLASS_E_CLASSNOTAVAILABLE_HRESULT,
            CLASS_E_CLASSNOTAVAILABLE.0 as u32
        );
        assert_eq!(REGDB_E_CLASSNOTREG_HRESULT, REGDB_E_CLASSNOTREG.0 as u32);
    }

    // ── nativeCode rendering ─────────────────────────────────────────────

    #[test]
    fn native_code_renders_as_lowercase_hex() {
        assert_eq!(format_native_code(0x80070490), "0x80070490");
        assert_eq!(format_native_code(0x8004005a), "0x8004005a");
    }

    // ── Stale promotion ──────────────────────────────────────────────────

    #[test]
    fn error_not_found_promotes_to_stale_for_non_provision_ops() {
        let err = classify_api_failure(
            api_failure(Some(ERROR_NOT_FOUND_HRESULT)),
            StalePromotion::Eligible,
        );
        assert!(matches!(err, IsolationSessionError::Stale(_)));
        assert_eq!(map_lifecycle_error(err).code, MxcErrorCode::StaleId);
    }

    /// Provision mints the agent user, so it has no sandbox id to be stale.
    #[test]
    fn error_not_found_does_not_promote_for_provision() {
        let mut failure = api_failure(Some(ERROR_NOT_FOUND_HRESULT));
        failure.operation = op::ADD_USER.to_string();
        let err = classify_api_failure(failure, StalePromotion::NotEligible);
        assert!(matches!(
            err,
            IsolationSessionError::Lifecycle(LifecycleFailure::Api(_))
        ));
        assert_eq!(map_lifecycle_error(err).code, MxcErrorCode::BackendError);
    }

    #[test]
    fn other_hresults_do_not_promote_to_stale() {
        let err = classify_api_failure(api_failure(Some(0x80004005)), StalePromotion::Eligible);
        assert_eq!(map_lifecycle_error(err).code, MxcErrorCode::BackendError);
    }

    /// A transport-path `ERROR_NOT_FOUND` has none of the provenance that
    /// gives the semantic one its meaning, so it must stay `backend_error`.
    #[test]
    fn transport_error_not_found_does_not_promote_to_stale() {
        let err = windows_core::Error::from_hresult(windows_core::HRESULT(
            ERROR_NOT_FOUND_HRESULT as i32,
        ));
        let mapped = map_lifecycle_error(transport_err(op::STOP_SESSION, "call failed", &err));
        assert_eq!(mapped.code, MxcErrorCode::BackendError);
        assert_eq!(mapped.native_code(), Some("0x80070490"));
    }

    // ── Transport messages tolerate an absent platform text ──────────────

    /// An HRESULT with no OS message-table entry yields an empty
    /// `message()`. Joining unconditionally produced `"wait failed: "`, which
    /// is non-empty and therefore slipped past the guard in
    /// `IsoApiFailure::new` — the caller got a trailing colon and no
    /// explanation.
    #[test]
    fn transport_message_without_platform_text_is_the_step_alone() {
        assert_eq!(compose_transport_message("wait failed", ""), "wait failed");
    }

    #[test]
    fn transport_message_with_platform_text_keeps_the_step_prefix() {
        assert_eq!(
            compose_transport_message("wait failed", "Unspecified error"),
            "wait failed: Unspecified error"
        );
    }

    /// End-to-end over a real `windows_core::Error`: `0xDEADBEEF` has no
    /// message-table entry on any Windows build, so this pins the whole path
    /// rather than just the helper.
    #[test]
    fn transport_failure_with_unmapped_hresult_has_no_dangling_separator() {
        let err = windows_core::Error::from_hresult(windows_core::HRESULT(0xDEADBEEF_u32 as i32));
        assert!(
            err.message().is_empty(),
            "0xDEADBEEF unexpectedly has a message-table entry: {:?}",
            err.message()
        );
        let mapped = map_lifecycle_error(transport_err(op::ADD_USER, "wait failed", &err));
        assert_eq!(mapped.message, "wait failed");
        assert!(!mapped.message.ends_with(": "));
        assert_eq!(mapped.native_code(), Some("0xdeadbeef"));
    }

    // ── The status getter itself can fail ────────────────────────────────

    /// With no readable status there is nothing to classify on, so the
    /// failure stays a plain lifecycle error and `nativeCode` stays off the
    /// wire — carrying the getter's own HRESULT would describe reading the
    /// field, not the operation.
    #[test]
    fn unreadable_code_keeps_the_message_and_omits_native_code() {
        let err = unreadable_code_failure(
            op::STOP_SESSION,
            Some("agent user not found".to_string()),
            Some("Re-provision the sandbox.".to_string()),
            "RPC_E_DISCONNECTED",
        );
        let mapped = map_lifecycle_error(err);
        assert_eq!(mapped.code, MxcErrorCode::BackendError);
        assert_eq!(
            mapped.message,
            "agent user not found (could not read HRESULT code: RPC_E_DISCONNECTED)"
        );
        assert_eq!(mapped.operation(), Some("IsoSessionOps.StopSessionAsync"));
        assert_eq!(mapped.native_code(), None);
        assert_eq!(
            mapped.remediation.as_deref(),
            Some("Re-provision the sandbox.")
        );
    }

    /// Even an `ERROR_NOT_FOUND`-shaped failure cannot promote here: the code
    /// is precisely what could not be read.
    #[test]
    fn unreadable_code_never_promotes_to_stale() {
        let err = unreadable_code_failure(op::STOP_SESSION, None, None, "RPC_E_DISCONNECTED");
        assert!(matches!(
            err,
            IsolationSessionError::Lifecycle(LifecycleFailure::Api(_))
        ));
        let mapped = map_lifecycle_error(err);
        assert_eq!(mapped.code, MxcErrorCode::BackendError);
        assert_eq!(
            mapped.message,
            "could not read HRESULT code: RPC_E_DISCONNECTED"
        );
    }

    // ── Field population and the MxcError invariant ──────────────────────

    /// Appending cleanup context must not cost the failure its classification.
    ///
    /// The one-shot launch folds a failed teardown into the error it returns.
    /// Rebuilding the error as a message-only variant would have been the easy
    /// way to do that, and would have silently downgraded every structured
    /// failure on those paths.
    #[test]
    fn appending_context_keeps_the_code_and_the_structured_fields() {
        let err = classify_api_failure(
            api_failure(Some(ERROR_NOT_FOUND_HRESULT)),
            StalePromotion::Eligible,
        )
        .with_context(" (cleanup: the agent user could not be removed)");
        let mapped = map_lifecycle_error(err);

        assert_eq!(mapped.code, MxcErrorCode::StaleId);
        assert_eq!(mapped.operation(), Some("IsoSessionOps.StopSessionAsync"));
        assert_eq!(mapped.native_code(), Some("0x80070490"));
        assert_eq!(
            mapped.remediation.as_deref(),
            Some("Re-provision the sandbox.")
        );
        assert!(
            mapped.message.starts_with("agent user not found"),
            "the original message must survive: {}",
            mapped.message
        );
        assert!(
            mapped.message.contains("could not be removed"),
            "the cleanup failure must reach the caller: {}",
            mapped.message
        );
    }

    /// A policy refusal keeps its own code when cleanup context is appended.
    #[test]
    fn appending_context_keeps_a_policy_refusal_a_policy_refusal() {
        let mapped = map_lifecycle_error(
            IsolationSessionError::Policy("no proxy".into()).with_context(" (cleanup: x)"),
        );
        assert_eq!(mapped.code, MxcErrorCode::PolicyValidation);
        assert!(mapped.message.contains("no proxy"), "{}", mapped.message);
        assert!(mapped.message.contains("cleanup"), "{}", mapped.message);
    }

    #[test]
    fn semantic_failure_populates_all_structured_fields() {
        let err = classify_api_failure(
            api_failure(Some(ERROR_NOT_FOUND_HRESULT)),
            StalePromotion::Eligible,
        );
        let mapped = map_lifecycle_error(err);
        assert_eq!(mapped.code, MxcErrorCode::StaleId);
        assert_eq!(mapped.message, "agent user not found");
        assert_eq!(mapped.operation(), Some("IsoSessionOps.StopSessionAsync"));
        assert_eq!(mapped.native_code(), Some("0x80070490"));
        assert_eq!(
            mapped.remediation.as_deref(),
            Some("Re-provision the sandbox.")
        );
    }

    #[test]
    fn transport_failure_populates_operation_and_native_code_only() {
        let err = windows_core::Error::from_hresult(windows_core::HRESULT(0x800706ba_u32 as i32));
        let mapped = map_lifecycle_error(transport_err(op::ADD_USER, "call failed", &err));
        assert_eq!(mapped.code, MxcErrorCode::BackendError);
        assert_eq!(mapped.operation(), Some("IsoSessionOps.AddUserAsync2"));
        assert_eq!(mapped.native_code(), Some("0x800706ba"));
        assert_eq!(mapped.remediation.as_deref(), None);
        assert!(mapped.message.starts_with("call failed: "));
    }

    #[test]
    fn activation_failure_populates_operation_and_native_code() {
        let mapped = map_lifecycle_error(activation_error(
            CLASS_E_CLASSNOTAVAILABLE_HRESULT,
            "unused",
        ));
        assert_eq!(mapped.code, MxcErrorCode::BackendUnavailable);
        assert_eq!(mapped.operation(), Some("IsoSessionOps.ActivateInstance"));
        assert_eq!(mapped.native_code(), Some("0x80040111"));
        assert!(mapped.message.contains("not available"));
    }

    #[test]
    fn unknown_activation_hresult_keeps_the_underlying_detail() {
        let mapped = map_lifecycle_error(activation_error(0x80004005, "catastrophic failure"));
        assert_eq!(mapped.code, MxcErrorCode::BackendUnavailable);
        assert_eq!(mapped.native_code(), Some("0x80004005"));
        assert!(mapped.message.contains("catastrophic failure"));
    }

    #[test]
    fn mxc_internal_failure_carries_no_structured_fields() {
        let mapped = map_lifecycle_error(lifecycle_err("create stdout relay: out of memory"));
        assert_eq!(mapped.code, MxcErrorCode::BackendError);
        assert_eq!(mapped.operation(), None);
        assert_eq!(mapped.native_code(), None);
        assert_eq!(mapped.remediation.as_deref(), None);
    }

    #[test]
    fn policy_failure_carries_no_structured_fields() {
        let mapped = map_lifecycle_error(IsolationSessionError::Policy("no proxy".into()));
        assert_eq!(mapped.code, MxcErrorCode::PolicyValidation);
        assert_eq!(mapped.operation(), None);
        assert_eq!(mapped.native_code(), None);
        assert_eq!(mapped.remediation.as_deref(), None);
    }

    /// A status describes the call that produced it, so it never reaches the
    /// wire without the operation it belongs to.
    #[test]
    fn every_variant_upholds_the_field_invariant() {
        let com = windows_core::Error::from_hresult(windows_core::HRESULT(0x80004005_u32 as i32));
        let cases = vec![
            IsolationSessionError::Policy("x".into()),
            lifecycle_err("internal"),
            transport_err(op::RUN_PROCESS, "call failed", &com),
            activation_error(REGDB_E_CLASSNOTREG_HRESULT, "x"),
            classify_api_failure(api_failure(Some(0x80004005)), StalePromotion::Eligible),
            classify_api_failure(
                api_failure(Some(ERROR_NOT_FOUND_HRESULT)),
                StalePromotion::Eligible,
            ),
            classify_api_failure(api_failure(None), StalePromotion::Eligible),
        ];
        for case in cases {
            let label = case.to_string();
            let mapped = map_lifecycle_error(case);
            if mapped.native_code().is_some() {
                assert!(
                    mapped.operation().is_some(),
                    "nativeCode without operation: {label}"
                );
            }
        }
    }

    #[test]
    fn unreadable_hresult_yields_operation_without_native_code() {
        let mapped = map_lifecycle_error(classify_api_failure(
            api_failure(None),
            StalePromotion::Eligible,
        ));
        assert_eq!(mapped.code, MxcErrorCode::BackendError);
        assert!(mapped.operation().is_some());
        assert_eq!(mapped.native_code(), None);
    }

    #[test]
    fn the_identity_refusal_carries_a_hint_and_no_operation_or_native_code() {
        use windows::Win32::Foundation::E_ACCESSDENIED;

        let mapped = map_lifecycle_error(identity_refusal(E_ACCESSDENIED.into()));
        assert_eq!(mapped.code, MxcErrorCode::BackendError);
        assert_eq!(mapped.operation(), None);
        assert_eq!(mapped.native_code(), None);
        assert!(
            mapped
                .remediation
                .as_deref()
                .is_some_and(|hint| hint.contains("SecurityImpersonation")),
            "{:?}",
            mapped.remediation
        );
    }

    #[test]
    fn the_identity_refusal_folds_its_hint_into_the_one_shot_rendering() {
        use windows::Win32::Foundation::E_ACCESSDENIED;

        let rendered = identity_refusal(E_ACCESSDENIED.into()).to_string();
        assert!(rendered.contains("impersonation token"), "{rendered}");
        assert!(
            rendered.contains("remediation: Call without impersonating"),
            "{rendered}"
        );
    }

    // ── One-shot rendering (Display) ─────────────────────────────────────

    /// The one-shot path has no structured envelope, so `Display` must keep
    /// folding every component back into the message — including the
    /// category prefix, which is the only place the category appears there.
    #[test]
    fn display_composes_the_full_human_string() {
        let rendered = classify_api_failure(
            api_failure(Some(ERROR_NOT_FOUND_HRESULT)),
            StalePromotion::Eligible,
        )
        .to_string();
        assert!(
            rendered.starts_with("Isolation Session stale id: "),
            "{rendered}"
        );
        assert!(
            rendered.contains("IsoSessionOps.StopSessionAsync"),
            "{rendered}"
        );
        assert!(rendered.contains("agent user not found"), "{rendered}");
        assert!(rendered.contains("0x80070490"), "{rendered}");
        assert!(
            rendered.contains("remediation: Re-provision the sandbox."),
            "{rendered}"
        );
    }

    #[test]
    fn display_keeps_the_category_prefix_for_every_variant() {
        let com = windows_core::Error::from_hresult(windows_core::HRESULT(0x80004005_u32 as i32));
        assert!(IsolationSessionError::Policy("x".into())
            .to_string()
            .starts_with("Isolation Session policy error: "));
        assert!(activation_error(REGDB_E_CLASSNOTREG_HRESULT, "x")
            .to_string()
            .starts_with("Isolation Session service unavailable: "));
        assert!(lifecycle_err("x")
            .to_string()
            .starts_with("Isolation Session lifecycle error: "));
        assert!(transport_err(op::ADD_USER, "call failed", &com)
            .to_string()
            .starts_with("Isolation Session lifecycle error: "));
    }

    /// The one-shot conversion still carries the full composed detail — it
    /// is the only carrier on that path.
    #[test]
    fn script_response_conversion_keeps_the_rich_message() {
        let response: ScriptResponse =
            classify_api_failure(api_failure(Some(0x80004005)), StalePromotion::Eligible).into();
        assert!(response
            .error_message
            .contains("IsoSessionOps.StopSessionAsync"));
        assert!(response.error_message.contains("0x80004005"));
        assert!(response.error_message.contains("remediation"));
    }

    // ── operation values ─────────────────────────────────────────────────

    /// `operation` must stay interface-qualified and free of call
    /// parameters, so it can be aggregated in telemetry.
    #[test]
    fn operation_constants_are_qualified_and_parameter_free() {
        for value in [
            op::CO_INCREMENT_MTA_USAGE,
            op::ACTIVATE,
            op::ADD_USER,
            op::ADD_USER_LEGACY,
            op::ADD_USER_DEDUCED,
            op::START_SESSION,
            op::START_SESSION_DEDUCED,
            op::RUN_PROCESS,
            op::STOP_SESSION,
            op::REMOVE_USER,
            op::OPTIONS_NEW,
            op::OPTIONS_TIMEOUT,
            op::OPTIONS_WORKING_DIR,
            op::OPTIONS_INTERACTIVE,
            op::OPTIONS_REDIRECT_STDIN,
            op::OPTIONS_REDIRECT_STDOUT,
            op::OPTIONS_REDIRECT_STDERR,
            op::OPTIONS_ENVIRONMENT,
        ] {
            assert!(
                value.starts_with("IsoSessionOps.")
                    || value.starts_with("IsoSessionProcessOptions.")
                    || value.starts_with("Com."),
                "unqualified: {value}"
            );
            assert!(!value.contains('('), "carries parameters: {value}");
            assert!(!value.contains(' '), "not a bare member name: {value}");
        }
    }
}