mxc-sdk 1.1.0

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
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Canonical policy identity — a stable hash of the *effective* enforcement
//! policy for a run.
//!
//! [`policy_hash`] answers "which policy is this sandbox running under?" with a
//! value that is:
//!
//! * **stable** across formatting, key ordering, and base64-vs-file input, so
//!   two runs of the same policy produce the same hash;
//! * **sensitive** to every enforcement-relevant field, so changing one
//!   `readwritePaths` entry changes it;
//! * **insensitive** to things that do not change enforcement (telemetry
//!   settings, backend authorization, dry-run, testing flags);
//! * **free of credential material**, so it cannot be used as a confirmation
//!   oracle against a secret embedded in a config.
//!
//! The value is emitted on the `mxc.PolicyHash` audit record.
//!
//! # What is hashed
//!
//! An explicit **allow-list** projection of [`ExecutionRequest`], not the whole
//! struct. An allow-list is deliberate: a field added to the model later is
//! excluded until someone opts it in, which fails safe (a missing field
//! weakens sensitivity) rather than unsafe (an accidentally-hashed secret is a
//! disclosure risk that cannot be undone once hashes are in logs).
//!
//! To stop that safety property from silently rotting into a coverage gap,
//! [`policy_projection`] **exhaustively destructures** `ExecutionRequest`.
//! Adding a field is a compile error until it is classified as hashed or
//! explicitly excluded with a reason.
//!
//! # What is excluded, and why
//!
//! | Excluded | Reason |
//! |---|---|
//! | `script_code` | The command line is *what runs*, not the policy under which it runs; it also routinely embeds credentials (`curl -H "Authorization: …"`). |
//! | `env` | Environment variables are the classic secret carrier. |
//! | `telemetry`, internal `test_feature` | No enforcement effect. |
//! | `network_proxy.original_url` | A proxy URL can embed `user:password@`. The host and port *are* hashed. |
//! | `capture_denials.output_path` | Only decides where the diagnostic JSON deliverable is written; not enforcement. `capture_denials.mode` remains hashed. |
//! | `dry_run` | Invocation mode, not policy. |
//! | `experimental_enabled` | Authorizes selecting an experimental backend; it does not change the selected backend's enforcement. |
//! | `source_contract` | Contract attribution used only for diagnostics and telemetry. |
//! | `requested_sandbox_kind` | Caller-requested containment used only for telemetry attribution. |
//!
//! WSLC and Windows Sandbox configuration is hashed at the `wslc` and
//! `windowsSandbox` root keys.
//!
//! `ContainerPolicy::network_proxy` is `#[serde(skip)]`, so the proxy's
//! credential-bearing URL cannot reach the hash through the blanket policy
//! serialization even by accident; the enforcement-relevant parts (enabled,
//! host, port) are added back explicitly.
//!
//! # Residual disclosure property (accepted, documented)
//!
//! The hash is deterministic and unkeyed, so it is a **confirmation oracle for
//! the fields it covers**: a reader who already knows every hashed field but one
//! can brute-force the remaining one. In practice that means someone holding the
//! log can test a guess at, say, a single `readwritePaths` entry — but only if
//! they already know the container id, working directory, timeout, capability
//! list, network policy, and every other path exactly. This is deliberately
//! accepted:
//!
//! * the alternative (a keyed digest) needs a machine-local secret whose
//!   storage, rotation, and failure modes are out of scope for a local
//!   diagnostic log;
//! * the fields covered are the operator's own policy, already visible to anyone
//!   who can read the config the log sits next to;
//! * the genuinely sensitive inputs — command line, environment, tokens, proxy
//!   userinfo — are excluded from the hash entirely, so no oracle exists for
//!   them at any difficulty.
//!
//! Do not add a low-entropy secret to the projection without switching to a
//! keyed construction first.

use serde_json::{Map, Value};

use crate::mxc_common::hashing::sha256_hex;
use crate::mxc_common::models::{
    ExecutionRequest, IsolationSessionProvisionConfig, MicroVmProvisionConfig, WslcProvisionConfig,
    WslcProvisionSessionConfig,
};
use crate::mxc_common::state_aware_operation::{StateAwareOperation, StateAwareProvision};

/// Algorithm tag prefixed to the hex digest, so the algorithm can change
/// without breaking a consumer that only does equality comparison.
const ALGORITHM_TAG: &str = "sha256";

/// Compute the canonical policy hash for `request`, formatted as
/// `"sha256:<64 lowercase hex chars>"`.
///
/// Call this **after** every mutation that changes enforcement (CLI command
/// override, `--audit`'s permissive-learning-mode injection, capability
/// injection), so the hash describes what actually ran rather than what was
/// requested.
pub fn policy_hash(request: &ExecutionRequest) -> String {
    let canonical = canonical_json(&policy_projection(request));
    hash_canonical_json(&canonical)
}

/// Hash the declared lifecycle policy without resolving the session's CPU, memory, or GPU settings.
pub fn state_aware_policy_hash(
    request: &ExecutionRequest,
    backend: &str,
    operation: &StateAwareOperation,
) -> String {
    let mut projection = policy_projection(request);
    if let Value::Object(root) = &mut projection {
        root.insert("containment".into(), Value::String(backend.to_string()));
        root.insert(
            "stateAware".into(),
            serde_json::json!({
                "backend": backend,
                "phase": operation.phase().as_str(),
                "config": state_aware_config_projection(operation),
            }),
        );
    }
    hash_canonical_json(&canonical_json(&projection))
}

fn state_aware_config_projection(operation: &StateAwareOperation) -> Value {
    match operation {
        StateAwareOperation::Provision(StateAwareProvision::IsolationSession(Some(
            IsolationSessionProvisionConfig { app_id },
        ))) => {
            let mut config = Map::new();
            if let Some(app_id) = app_id {
                config.insert("appId".into(), Value::String(app_id.clone()));
            }
            Value::Object(config)
        }
        StateAwareOperation::Provision(StateAwareProvision::Wslc(Some(WslcProvisionConfig {
            image,
            image_tar_path,
            session_id,
            port_mappings,
        }))) => {
            let mut config = Map::new();
            if let Some(image) = image {
                config.insert("image".into(), Value::String(image.clone()));
            }
            if let Some(image_tar_path) = image_tar_path {
                config.insert("imageTarPath".into(), Value::String(image_tar_path.clone()));
            }

            // Session IDs are capabilities, so record their presence without their values.
            if session_id.is_some() {
                config.insert("joinsNamedSession".into(), Value::Bool(true));
            }

            // A forwarded host port is policy, so it belongs in the identity.
            if let Some(port_mappings) = port_mappings {
                let mappings = port_mappings
                    .iter()
                    .map(|mapping| {
                        let mut entry = Map::new();
                        entry.insert("windowsPort".into(), Value::from(mapping.windows_port));
                        entry.insert("containerPort".into(), Value::from(mapping.container_port));
                        entry.insert("protocol".into(), Value::String(mapping.protocol.clone()));
                        Value::Object(entry)
                    })
                    .collect();
                config.insert("portMappings".into(), Value::Array(mappings));
            }
            Value::Object(config)
        }
        StateAwareOperation::Provision(StateAwareProvision::MicroVm(Some(
            MicroVmProvisionConfig { image, memory_mib },
        ))) => {
            let mut config = Map::new();
            config.insert("image".into(), Value::String(image.clone()));
            if let Some(memory_mib) = memory_mib {
                config.insert("memoryMib".into(), Value::from(*memory_mib));
            }
            Value::Object(config)
        }
        StateAwareOperation::Provision(
            StateAwareProvision::IsolationSession(None)
            | StateAwareProvision::WindowsSandbox
            | StateAwareProvision::MicroVm(None)
            | StateAwareProvision::Wslc(None)
            // Pool/account coordinates are not containment policy.
            | StateAwareProvision::W365Agents(_),
        ) => Value::Null,

        StateAwareOperation::ProvisionSession(Some(WslcProvisionSessionConfig {
            cpu_count,
            memory_mb,
            gpu,
        })) => {
            let mut config = Map::new();
            if let Some(cpu_count) = cpu_count {
                config.insert("cpuCount".into(), Value::from(*cpu_count));
            }
            if let Some(memory_mb) = memory_mb {
                config.insert("memoryMb".into(), Value::from(*memory_mb));
            }
            if let Some(gpu) = gpu {
                config.insert("gpu".into(), Value::Bool(*gpu));
            }
            Value::Object(config)
        }
        StateAwareOperation::ProvisionSession(None) => Value::Null,

        // Sandbox and session IDs are not policy and can contain account
        // identities.
        StateAwareOperation::Start {
            sandbox_id: _excluded_sandbox_id,
        }
        | StateAwareOperation::Exec {
            sandbox_id: _excluded_sandbox_id,
        }
        | StateAwareOperation::Stop {
            sandbox_id: _excluded_sandbox_id,
        }
        | StateAwareOperation::Deprovision {
            sandbox_id: _excluded_sandbox_id,
        } => Value::Null,
        StateAwareOperation::DeprovisionSession {
            session_id: _excluded_session_id,
        } => Value::Null,
    }
}

fn hash_canonical_json(canonical: &str) -> String {
    let digest = sha256_hex(canonical.as_bytes());
    let mut out = String::with_capacity(ALGORITHM_TAG.len() + 1 + digest.len());
    out.push_str(ALGORITHM_TAG);
    out.push(':');
    out.push_str(&digest);
    out
}

/// Build the allow-listed projection of the request that the hash covers.
///
/// `ExecutionRequest` is **exhaustively destructured** (no `..`), so adding a
/// field to the model is a compile error here until it is either hashed or
/// bound to a named `_excluded_*` local with a reason. That is the tripwire
/// that keeps the allow-list from silently falling behind the model.
fn policy_projection(request: &ExecutionRequest) -> Value {
    let ExecutionRequest {
        // External contract provenance is diagnostics/telemetry attribution,
        // not enforcement.
        source_contract: _excluded_source_contract,
        // Requested containment is telemetry attribution, not the resolved policy.
        requested_sandbox_kind: _excluded_requested_sandbox_kind,
        container_id,
        working_directory,
        script_timeout,
        containment,
        lifecycle,
        policy,
        lxc_config,
        wslc,
        seatbelt,
        windows_sandbox,
        hyperlight,
        microvm_image,
        microvm_memory_mib,
        // Telemetry settings do not affect enforcement.
        telemetry: _excluded_telemetry,
        // A placeholder feature with no enforcement effect.
        test_feature: _excluded_test_feature,
        // Backend selection authorization is not an enforcement decision.
        experimental_enabled: _excluded_experimental_authorization,
        // --- deliberately excluded; see the module docs ---
        // The command line is what runs, not the policy it runs under, and it
        // routinely embeds credentials.
        script_code: _excluded_command_line,
        // Environment variables are the classic secret carrier.
        env: _excluded_environment,
        // Whether the default environment is merged is process launch
        // behavior, not an enforcement decision.
        inherit_default_env: _excluded_environment_mode,
        // Invocation modes, not policy.
        dry_run: _excluded_dry_run,
    } = request;

    let mut root = Map::new();
    if let Some(image) = microvm_image {
        let mut config = serde_json::json!({"image": image});
        if let Some(memory) = microvm_memory_mib {
            config["provision"] = serde_json::json!({"memoryMib": memory});
        }
        root.insert("microvm".into(), config);
    }

    root.insert(
        "containment".into(),
        Value::String(containment.wire_name().to_string()),
    );
    root.insert("containerId".into(), Value::String(container_id.clone()));
    root.insert(
        "workingDirectory".into(),
        Value::String(working_directory.clone()),
    );
    root.insert(
        "scriptTimeout".into(),
        Value::Number((*script_timeout).into()),
    );
    root.insert(
        "lifecycle".into(),
        serde_json::to_value(lifecycle).unwrap_or(Value::Null),
    );
    // `ContainerPolicy` serialization already omits `network_proxy`
    // (`#[serde(skip)]`), so no credential-bearing proxy URL can reach the hash
    // through this line.
    //
    // `captureDenials.outputPath` is stripped: it only controls where the
    // diagnostic JSON deliverable is written and has no effect on enforcement.
    // Hashing it would perturb the policy identity across otherwise-identical
    // runs whose only difference is the output-file location — an operator
    // moving the diagnostic file has not changed the policy the sandbox ran
    // under. `captureDenials.mode` DOES stay hashed: it decides whether each
    // recorded access is blocked or allowed, which is an enforcement change.
    let mut policy_value = serde_json::to_value(policy).unwrap_or(Value::Null);
    if let Value::Object(policy_map) = &mut policy_value {
        if let Some(Value::Object(cd)) = policy_map.get_mut("capture_denials") {
            cd.remove("output_path");
        }
    }
    root.insert("policy".into(), policy_value);
    root.insert("proxy".into(), proxy_projection(request));
    root.insert(
        "lxc".into(),
        serde_json::to_value(lxc_config).unwrap_or(Value::Null),
    );
    let mut seatbelt_value = serde_json::to_value(seatbelt).unwrap_or(Value::Null);
    if let Value::Object(seatbelt_map) = &mut seatbelt_value {
        if let Some(Value::Object(cd)) = seatbelt_map.get_mut("captureDenials") {
            cd.remove("output_path");
        }
    }
    root.insert("seatbelt".into(), seatbelt_value);
    root.insert(
        "wslc".into(),
        serde_json::to_value(wslc).unwrap_or(Value::Null),
    );
    root.insert(
        "windowsSandbox".into(),
        serde_json::to_value(windows_sandbox).unwrap_or(Value::Null),
    );
    // The guest runtime picks the image the sandbox boots. Hashed as the
    // effective value whenever the backend is Hyperlight, so an omitted
    // section and an explicit default are one policy; other backends carry
    // no key and hash as they did before the section existed.
    if *containment == crate::mxc_common::models::ContainmentBackend::Hyperlight {
        root.insert(
            "hyperlight".into(),
            serde_json::to_value(hyperlight.clone().unwrap_or_default()).unwrap_or(Value::Null),
        );
    }

    Value::Object(root)
}

/// The enforcement-relevant, non-credential parts of the proxy configuration:
/// whether a proxy is in force, its host, and its port. The original URL is
/// deliberately dropped because it can carry `user:password@` userinfo.
fn proxy_projection(request: &ExecutionRequest) -> Value {
    let proxy = &request.policy.network_proxy;
    let mut out = Map::new();
    out.insert("enabled".into(), Value::Bool(proxy.is_enabled()));
    match &proxy.address {
        Some(addr) => {
            out.insert("address".into(), Value::String(addr.address.clone()));
            out.insert("port".into(), Value::Number(addr.port.into()));
        }
        None => {
            out.insert("address".into(), Value::Null);
            out.insert("port".into(), Value::Null);
        }
    }
    Value::Object(out)
}

/// Render `value` as canonical JSON: object keys sorted lexicographically at
/// every depth, array order preserved (array order is semantically meaningful
/// for path lists), and no insignificant whitespace.
///
/// Only the *container* kinds are walked by hand, and only to pin key ordering:
/// `serde_json::Map` is a `BTreeMap` unless the `preserve_order` feature is on,
/// so its iteration order is usually already sorted — but a feature flag flipped
/// by an unrelated crate in the dependency graph must not silently change every
/// hash MXC has ever emitted. Scalars are handed straight to `serde_json`, so
/// string escaping and number formatting are not reimplemented here.
///
/// Writes into a single growing `Vec<u8>` buffer and converts to `String`
/// exactly once at the end, rather than allocating (and immediately
/// discarding) a separate `String` per object key and per scalar value —
/// which this hash computation used to do at every level of every request's
/// policy tree.
fn canonical_json(value: &Value) -> String {
    let mut out = Vec::new();
    write_canonical(value, &mut out);
    // `write_canonical` only ever appends JSON structural bytes (all ASCII)
    // and `serde_json`'s own string/number encoding, both of which are
    // guaranteed valid UTF-8.
    String::from_utf8(out).expect("canonical JSON writer only ever emits valid UTF-8")
}

fn write_canonical(value: &Value, out: &mut Vec<u8>) {
    match value {
        Value::Object(map) => {
            let mut keys: Vec<&String> = map.keys().collect();
            keys.sort_unstable();
            out.push(b'{');
            for (i, key) in keys.iter().enumerate() {
                if i > 0 {
                    out.push(b',');
                }
                write_scalar(key.as_str(), out);
                out.push(b':');
                // A key present in `keys` is by construction present in `map`.
                if let Some(child) = map.get(*key) {
                    write_canonical(child, out);
                }
            }
            out.push(b'}');
        }
        Value::Array(items) => {
            out.push(b'[');
            for (i, item) in items.iter().enumerate() {
                if i > 0 {
                    out.push(b',');
                }
                write_canonical(item, out);
            }
            out.push(b']');
        }
        // Null / Bool / Number / String have no ordering concern, so there is
        // nothing to hand-roll: `serde_json` already renders them canonically.
        scalar => write_scalar(scalar, out),
    }
}

/// Serialize any `serde_json::Serialize` scalar (a `&str` object key or a
/// non-container `Value`) directly into `out`. Serializing a `&str` renders
/// identically to serializing the equivalent `Value::String`, so object keys
/// need no intermediate `Value` wrapper. Writing to a `Vec<u8>` is infallible
/// (the only failure mode of `serde_json`'s writer is an I/O error, which
/// cannot occur for an in-memory buffer).
fn write_scalar<T: serde::Serialize + ?Sized>(value: &T, out: &mut Vec<u8>) {
    serde_json::to_writer(out, value).expect("serializing a scalar value to JSON is infallible");
}

/// Render a sandbox identity so it is safe to write to a diagnostic log file.
///
/// Three distinct hazards are handled:
///
/// 1. **IsolationSession identities.** The state-aware `iso:` payload carries
///    the OS account name used to address later lifecycle phases. Even though
///    the payload is encoded, it is reversible and must not reach diagnostics.
/// 2. **UPN-shaped identities.** For Entra sandboxes the `provisionId` is the
///    user's UPN. A UPN must never be written to a file routinely attached to a
///    bug report.
/// 3. **Caller-supplied identities.** On the ProcessContainer path the identity
///    is the AppContainer profile name, i.e. the config's `containerId`. That is
///    a config value and is handled by [`crate::mxc_common::audit::sanitize_identity`].
///
/// For (1) and (2), this function emits bounded constant markers and **no
/// account-derived value at all**.
///
/// > A truncated SHA-256 of a UPN was considered and rejected. A UPN is
/// > low-entropy and enumerable within a tenant, so an unsalted digest is
/// > trivially reversed by dictionary attack — it is pseudonymisation, not
/// > redaction, and would have made the log's privacy posture look stronger than
/// > it is. A keyed HMAC would work but needs a machine-local secret whose own
/// > storage, rotation, and failure modes are out of scope here. The cost of the
/// > marker is that Entra sandboxes have **no MXC-side join key** in the local
/// > log; the OS-side `Microsoft.Windows.IsolationSession` records still carry
/// > the real `provisionId` for anyone who legitimately needs to correlate.
pub fn redact_identity(identity: &str) -> String {
    if is_upn_shaped(identity) {
        return ENTRA_UPN_MARKER.to_string();
    }
    if identity.starts_with("iso:") {
        return ISOLATION_SESSION_MARKER.to_string();
    }
    crate::mxc_common::audit::sanitize_identity(identity).to_string()
}

/// Marker written in place of an IsolationSession state-aware identity.
pub const ISOLATION_SESSION_MARKER: &str = "isolation-session";

/// Marker written in place of a UPN-derived identity. Bounded and constant, so
/// it discloses only the *kind* of identity, never the account.
pub const ENTRA_UPN_MARKER: &str = "entra-upn";

/// Whether `identity` looks like a UPN (or a `<prefix>:<upn>` sandbox id).
///
/// An `@` is the discriminator: none of the identity shapes MXC mints itself
/// (`wxc-<token>`, `wsb:<hex>`) contains one, and every UPN
/// does.
fn is_upn_shaped(identity: &str) -> bool {
    identity.contains('@')
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mxc_common::models::{ContainmentBackend, ProxyAddress};

    fn request() -> ExecutionRequest {
        let mut r = ExecutionRequest {
            source_contract: Some(crate::mxc_contract::ContractVersion::V0_9_0Alpha),
            container_id: "test".to_string(),
            script_code: "echo hello".to_string(),
            working_directory: "C:\\work".to_string(),
            script_timeout: 30,
            containment: ContainmentBackend::ProcessContainer,
            ..Default::default()
        };
        r.policy.readwrite_paths.push("C:\\tmp".to_string());
        r.policy.readonly_paths.push("C:\\ro".to_string());
        r
    }

    #[test]
    fn hash_is_prefixed_and_hex() {
        let h = policy_hash(&request());
        let Some(hex) = h.strip_prefix("sha256:") else {
            panic!("missing algorithm tag: {h}");
        };
        assert_eq!(hex.len(), 64, "got: {h}");
        assert!(
            hex.chars()
                .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)),
            "not lowercase hex: {h}"
        );
    }

    #[test]
    fn identical_policies_hash_identically() {
        assert_eq!(policy_hash(&request()), policy_hash(&request()));
    }

    #[test]
    fn source_contract_attribution_does_not_change_the_hash() {
        let baseline = policy_hash(&request());
        let mut changed = request();
        changed.source_contract = None;
        assert_eq!(baseline, policy_hash(&changed));
    }

    #[test]
    fn creation_memory_is_hashed_at_its_permanent_optional_location() {
        let mut request = request();
        request.microvm_image = Some("docker.io/library/python:3.12-alpine".to_owned());
        let absent = policy_projection(&request);
        assert_eq!(
            absent["microvm"],
            serde_json::json!({"image":"docker.io/library/python:3.12-alpine"})
        );
        request.microvm_memory_mib = Some(512);
        let explicit = policy_projection(&request);
        assert_eq!(
            explicit["microvm"],
            serde_json::json!({
                "image":"docker.io/library/python:3.12-alpine","provision":{"memoryMib":512}
            })
        );
        assert_ne!(absent, explicit);
    }

    #[test]
    fn backend_policy_uses_root_keys() {
        let mut request = request();
        let wslc = crate::mxc_common::models::WslcConfig {
            image: "python:3.12".to_string(),
            ..Default::default()
        };
        let windows_sandbox = crate::mxc_common::models::WindowsSandboxConfig {
            idle_timeout_ms: 1_000,
            ..Default::default()
        };
        request.wslc = Some(wslc.clone());
        request.windows_sandbox = Some(windows_sandbox.clone());

        let Value::Object(projection) = policy_projection(&request) else {
            panic!("policy projection must be an object");
        };
        assert_eq!(
            projection.get("wslc"),
            Some(&serde_json::to_value(wslc).expect("WSLC config must serialize"))
        );
        assert_eq!(
            projection.get("windowsSandbox"),
            Some(
                &serde_json::to_value(windows_sandbox)
                    .expect("Windows Sandbox config must serialize")
            )
        );
        assert_eq!(
            projection
                .keys()
                .map(String::as_str)
                .collect::<std::collections::BTreeSet<_>>(),
            std::collections::BTreeSet::from([
                "containerId",
                "containment",
                "lifecycle",
                "lxc",
                "policy",
                "proxy",
                "scriptTimeout",
                "seatbelt",
                "windowsSandbox",
                "workingDirectory",
                "wslc",
            ])
        );
    }

    #[test]
    fn hyperlight_runtime_hashes_as_its_effective_value() {
        use crate::mxc_common::models::{ContainmentBackend, HyperlightConfig, HyperlightRuntime};
        let mut omitted = request();
        omitted.containment = ContainmentBackend::Hyperlight;
        let mut explicit_default = omitted.clone();
        explicit_default.hyperlight = Some(HyperlightConfig::default());
        let mut node = omitted.clone();
        node.hyperlight = Some(HyperlightConfig {
            runtime: HyperlightRuntime::Node,
        });
        assert_eq!(policy_hash(&omitted), policy_hash(&explicit_default));
        assert_ne!(policy_hash(&omitted), policy_hash(&node));

        let Value::Object(projection) = policy_projection(&request()) else {
            panic!("policy projection must be an object");
        };
        assert!(!projection.contains_key("hyperlight"));
    }

    #[test]
    fn changing_a_readwrite_path_changes_the_hash() {
        let baseline = policy_hash(&request());
        let mut changed = request();
        changed.policy.readwrite_paths[0] = "C:\\other".to_string();
        assert_ne!(baseline, policy_hash(&changed));
    }

    #[test]
    fn adding_a_denied_path_changes_the_hash() {
        let baseline = policy_hash(&request());
        let mut changed = request();
        changed.policy.denied_paths.push("C:\\secret".to_string());
        assert_ne!(baseline, policy_hash(&changed));
    }

    #[test]
    fn adding_an_enumerate_path_changes_the_hash() {
        let baseline = policy_hash(&request());
        let mut changed = request();
        changed.policy.enumerate_paths.push("C:\\tools".to_string());
        assert_ne!(baseline, policy_hash(&changed));
    }

    #[test]
    fn changing_the_network_policy_changes_the_hash() {
        let baseline = policy_hash(&request());
        let mut changed = request();
        changed.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
            default: crate::mxc_common::models::NetworkAction::Allow,
            ..Default::default()
        });
        assert_ne!(baseline, policy_hash(&changed));

        changed.policy.network_egress = None;
        changed.policy.network_ingress = Some(crate::mxc_common::models::NetworkIngressPolicy {
            default: crate::mxc_common::models::NetworkAction::Allow,
            ..Default::default()
        });
        assert_ne!(baseline, policy_hash(&changed));
    }

    #[test]
    fn changing_the_containment_backend_changes_the_hash() {
        let baseline = policy_hash(&request());
        let mut changed = request();
        changed.containment = ContainmentBackend::Lxc;
        assert_ne!(baseline, policy_hash(&changed));
    }

    #[test]
    fn changing_the_proxy_port_changes_the_hash() {
        let baseline = policy_hash(&request());
        let mut changed = request();
        changed.policy.network_proxy.address =
            Some(ProxyAddress::new("localhost".to_string(), 8080));
        let with_8080 = policy_hash(&changed);
        assert_ne!(baseline, with_8080);

        changed.policy.network_proxy.address =
            Some(ProxyAddress::new("localhost".to_string(), 9090));
        assert_ne!(with_8080, policy_hash(&changed));
    }

    /// `captureDenials.outputPath` decides where the diagnostic JSON file is
    /// written and has no effect on enforcement. It must not perturb the
    /// policy identity: moving the output file is a diagnostic-plumbing
    /// change, not a policy change.
    #[test]
    fn capture_denials_output_path_does_not_change_the_hash() {
        use crate::mxc_common::models::{CaptureDenialsConfig, CaptureDenialsMode};

        let mut baseline = request();
        baseline.policy.capture_denials = Some(CaptureDenialsConfig {
            mode: CaptureDenialsMode::Block,
            output_path: None,
            ..Default::default()
        });
        let base = policy_hash(&baseline);

        for path in [
            Some("C:\\logs\\denials.json".to_string()),
            Some("D:\\other\\denials.json".to_string()),
            None,
        ] {
            let mut changed = baseline.clone();
            if let Some(cd) = changed.policy.capture_denials.as_mut() {
                cd.output_path = path;
            }
            assert_eq!(
                base,
                policy_hash(&changed),
                "output_path controls diagnostic plumbing only and must not enter the hash"
            );
        }
    }

    /// `captureDenials.mode` decides whether each recorded access is blocked
    /// or allowed, which is an enforcement decision. Changing it MUST change
    /// the hash — this is the other half of the finding-3 contract.
    #[test]
    fn capture_denials_mode_changes_the_hash() {
        use crate::mxc_common::models::{CaptureDenialsConfig, CaptureDenialsMode};

        let mut baseline = request();
        baseline.policy.capture_denials = Some(CaptureDenialsConfig {
            mode: CaptureDenialsMode::Block,
            output_path: Some("C:\\logs\\denials.json".to_string()),
            ..Default::default()
        });
        let block_hash = policy_hash(&baseline);

        let mut allow = baseline.clone();
        if let Some(cd) = allow.policy.capture_denials.as_mut() {
            cd.mode = CaptureDenialsMode::Allow;
        }
        let allow_hash = policy_hash(&allow);
        assert_ne!(
            block_hash, allow_hash,
            "capture_denials.mode is an enforcement decision and MUST enter the hash"
        );
    }

    #[test]
    fn seatbelt_capture_denials_output_path_does_not_change_the_hash() {
        use crate::mxc_common::models::{CaptureDenialsConfig, CaptureDenialsMode, SeatbeltConfig};

        let with_path = |output_path: Option<&str>, mode| {
            let mut r = request();
            r.seatbelt = Some(SeatbeltConfig {
                capture_denials: Some(CaptureDenialsConfig {
                    mode,
                    output_path: output_path.map(str::to_string),
                    ..Default::default()
                }),
                ..Default::default()
            });
            policy_hash(&r)
        };
        let base = with_path(None, CaptureDenialsMode::Block);
        assert_eq!(
            base,
            with_path(Some("/tmp/denials.json"), CaptureDenialsMode::Block)
        );
        assert_ne!(base, with_path(None, CaptureDenialsMode::Allow));
    }

    #[test]
    fn telemetry_settings_do_not_change_the_hash() {
        let baseline = policy_hash(&request());
        let mut changed = request();
        changed.requested_sandbox_kind = Some("process");
        assert_eq!(baseline, policy_hash(&changed));
        changed.telemetry = Some(crate::mxc_common::models::TelemetryConfig {
            enabled: Some(true),
        });
        assert_eq!(
            baseline,
            policy_hash(&changed),
            "telemetry does not affect enforcement and must not perturb the policy identity"
        );
    }

    #[test]
    fn credential_bearing_fields_do_not_change_the_hash() {
        let baseline = policy_hash(&request());

        // A proxy URL that embeds userinfo must not become a confirmation
        // oracle: only host + port are hashed.
        let mut with_userinfo = request();
        with_userinfo.policy.network_proxy.address = Some(ProxyAddress::from_url(
            "http://user:hunter2@localhost:8080",
            "localhost".to_string(),
            8080,
        ));
        let mut without_userinfo = request();
        without_userinfo.policy.network_proxy.address =
            Some(ProxyAddress::new("localhost".to_string(), 8080));
        assert_eq!(
            policy_hash(&with_userinfo),
            policy_hash(&without_userinfo),
            "the proxy URL's userinfo must not reach the hash"
        );

        // Environment variables and the command line routinely carry secrets.
        let mut with_secrets = request();
        with_secrets.env = Some(vec!["API_KEY=hunter2".to_string()]);
        with_secrets.inherit_default_env = true;
        with_secrets.script_code = "curl -H 'Authorization: Bearer hunter2'".to_string();
        assert_eq!(
            baseline,
            policy_hash(&with_secrets),
            "env, environment mode, and command line are excluded from the policy identity"
        );
    }

    #[test]
    fn invocation_modes_do_not_change_the_hash() {
        let baseline = policy_hash(&request());
        let mut changed = request();
        changed.dry_run = true;
        changed.experimental_enabled = true;
        assert_eq!(baseline, policy_hash(&changed));
    }

    #[test]
    fn backend_authorization_does_not_change_the_policy_hash() {
        for backend in [
            ContainmentBackend::ProcessContainer,
            ContainmentBackend::Wslc,
            ContainmentBackend::Lxc,
            ContainmentBackend::Vm,
            ContainmentBackend::MicroVm,
            ContainmentBackend::Hyperlight,
            ContainmentBackend::WindowsSandbox,
            ContainmentBackend::IsolationSession,
            ContainmentBackend::Seatbelt,
            ContainmentBackend::Bubblewrap,
        ] {
            let mut changed = request();
            changed.containment = backend;
            let baseline = policy_hash(&changed);
            changed.experimental_enabled = true;
            assert_eq!(
                baseline,
                policy_hash(&changed),
                "backend authorization must not change {} policy identity",
                changed.containment.wire_name()
            );
            assert!(policy_projection(&changed)
                .get("experimentalEnabled")
                .is_none());
        }
    }

    #[test]
    fn canonical_json_sorts_keys_at_every_depth() {
        let value: Value =
            serde_json::from_str(r#"{"b":1,"a":{"z":[3,1,2],"y":true}}"#).expect("valid JSON");
        assert_eq!(
            canonical_json(&value),
            r#"{"a":{"y":true,"z":[3,1,2]},"b":1}"#
        );
    }

    #[test]
    fn canonical_json_preserves_array_order() {
        // Path lists are order-bearing in the policy, so reordering them is a
        // real change and must produce a different canonical form.
        let a: Value = serde_json::from_str(r#"["x","y"]"#).expect("valid JSON");
        let b: Value = serde_json::from_str(r#"["y","x"]"#).expect("valid JSON");
        assert_ne!(canonical_json(&a), canonical_json(&b));
    }

    #[test]
    fn canonical_json_escapes_strings() {
        let value = Value::String("quote\" and \\ backslash".to_string());
        let rendered = canonical_json(&value);
        assert_eq!(rendered, r#""quote\" and \\ backslash""#);
        // Round-trips, so the canonical form is still parseable JSON.
        let reparsed: Value = serde_json::from_str(&rendered).expect("valid JSON");
        assert_eq!(reparsed, value);
    }

    #[test]
    fn mxc_minted_identities_pass_through_unredacted() {
        for id in ["wsb:deadbeef", "CLI", ""] {
            assert_eq!(redact_identity(id), id);
        }
    }

    #[test]
    fn isolation_session_identities_never_reach_the_log() {
        for id in [
            "iso:wxc-abcd1234",
            "iso:eyJhZ2VudFVzZXJOYW1lIjoid3hjLWFiY2QxMjM0In0",
        ] {
            assert_eq!(redact_identity(id), ISOLATION_SESSION_MARKER);
        }
    }

    #[test]
    fn upn_shaped_identities_never_reach_the_log() {
        for upn in [
            "alice@contoso.com",
            "iso:alice@contoso.com",
            "BOB@Contoso.OnMicrosoft.com",
        ] {
            let redacted = redact_identity(upn);
            assert_eq!(redacted, ENTRA_UPN_MARKER, "got: {redacted}");
        }
    }

    /// The marker must be constant, so it cannot be reversed by dictionary
    /// attack the way a truncated unsalted digest of a low-entropy UPN could.
    #[test]
    fn the_upn_marker_carries_no_account_derived_entropy() {
        assert_eq!(
            redact_identity("alice@contoso.com"),
            redact_identity("bob@fabrikam.com"),
            "distinct accounts must render identically; any per-account value \
             would be a reversible pseudonym"
        );
    }

    /// A caller-supplied `containerId` becomes the sandbox identity on the
    /// ProcessContainer path, so it must be redacted rather than echoed into a
    /// record — even when it happens to look like an opaque token, since
    /// character/length checks alone cannot prove it wasn't chosen by the
    /// caller (e.g. `alice`, `ticket-1234`).
    #[test]
    fn caller_supplied_identities_are_redacted() {
        for id in ["C:\\Users\\alice\\ticket-1234", "alice", "ticket-1234"] {
            assert_eq!(
                redact_identity(id),
                crate::mxc_common::audit::REDACTED_IDENTITY
            );
        }
    }

    #[test]
    fn wslc_backend_policy_changes_the_hash() {
        let mut baseline = request();
        baseline.containment = ContainmentBackend::Wslc;
        let before = policy_hash(&baseline);

        let mut changed = baseline.clone();
        changed.wslc = Some(crate::mxc_common::models::WslcConfig {
            image: "python:3.12".to_string(),
            gpu: true,
            ..Default::default()
        });
        assert_ne!(before, policy_hash(&changed));

        let mut more = changed.clone();
        if let Some(cfg) = more.wslc.as_mut() {
            cfg.memory_mb = Some(4096);
        }
        assert_ne!(policy_hash(&changed), policy_hash(&more));
    }

    #[test]
    fn state_aware_session_hash_preserves_exact_sizing_shape() {
        let request = request();
        let sizing = |cpu_count, memory_mb, gpu| {
            Some(WslcProvisionSessionConfig {
                cpu_count,
                memory_mb,
                gpu,
            })
        };
        let mut hashes = std::collections::HashSet::new();
        for (config, expected_config) in [
            (None, Value::Null),
            (sizing(None, None, None), serde_json::json!({})),
            (
                sizing(Some(4), None, None),
                serde_json::json!({"cpuCount": 4}),
            ),
            (
                sizing(Some(8), None, None),
                serde_json::json!({"cpuCount": 8}),
            ),
            (
                sizing(None, Some(4), None),
                serde_json::json!({"memoryMb": 4}),
            ),
            (
                sizing(None, Some(4096), None),
                serde_json::json!({"memoryMb": 4096}),
            ),
            (
                sizing(None, None, Some(false)),
                serde_json::json!({"gpu": false}),
            ),
            (
                sizing(None, None, Some(true)),
                serde_json::json!({"gpu": true}),
            ),
            (
                sizing(Some(4), Some(4), Some(true)),
                serde_json::json!({"cpuCount": 4, "memoryMb": 4, "gpu": true}),
            ),
        ] {
            let operation = StateAwareOperation::ProvisionSession(config);
            assert_eq!(
                state_aware_config_projection(&operation),
                expected_config,
                "{operation:?}"
            );
            let hash = state_aware_policy_hash(&request, "wslc", &operation);
            assert_eq!(
                hash,
                expected_state_aware_hash(&request, "wslc", "provision-session", expected_config),
                "{operation:?}"
            );
            assert!(
                hashes.insert(hash),
                "absent, empty and supplied sizing fields must stay distinct, even when two \
                 fields carry the same value: {operation:?}"
            );
        }
    }

    #[test]
    fn state_aware_session_hash_excludes_the_session_id() {
        let request = request();
        for session_id in ["wslcsess:aaaa", "wslcsess:bbbb"] {
            let operation = StateAwareOperation::DeprovisionSession {
                session_id: session_id.into(),
            };
            assert_eq!(
                state_aware_policy_hash(&request, "wslc", &operation),
                expected_state_aware_hash(&request, "wslc", "deprovision-session", Value::Null),
                "the session id must not enter the policy identity"
            );
        }
    }

    #[test]
    fn joining_a_session_is_recorded_without_distinguishing_which_session() {
        let base = request();
        let joined = |session_id: Option<&str>| {
            state_aware_policy_hash(
                &base,
                "wslc",
                &StateAwareOperation::Provision(StateAwareProvision::Wslc(Some(
                    WslcProvisionConfig {
                        image: Some("alpine:latest".to_string()),
                        session_id: session_id.map(str::to_string),
                        ..Default::default()
                    },
                ))),
            )
        };

        let implicit = joined(None);
        let named = joined(Some("wslcsess:aaaa"));
        assert_ne!(
            implicit, named,
            "a sandbox sized by the host defaults must not share an identity with one whose \
             sizing was chosen by another request"
        );
        assert_eq!(
            named,
            joined(Some("wslcsess:bbbb")),
            "the session id is a bearer capability and must not reach the identity"
        );
    }

    #[test]
    fn an_unnamed_session_leaves_the_provision_identity_untouched() {
        let base = request();
        let hash = |config: WslcProvisionConfig| {
            state_aware_policy_hash(
                &base,
                "wslc",
                &StateAwareOperation::Provision(StateAwareProvision::Wslc(Some(config))),
            )
        };

        assert_eq!(
            hash(WslcProvisionConfig {
                image: Some("alpine:latest".to_string()),
                ..Default::default()
            }),
            hash(WslcProvisionConfig {
                image: Some("alpine:latest".to_string()),
                session_id: None,
                ..Default::default()
            })
        );
    }

    fn parse_state_aware(
        json: &str,
    ) -> crate::mxc_common::state_aware_request::ParsedStateAwareRequest {
        let mut logger =
            crate::mxc_common::logger::Logger::new(crate::mxc_common::logger::Mode::Buffer);
        let parsed =
            crate::mxc_common::config_parser::load_mxc_request_from_json(json, &mut logger)
                .expect("accepted exact state-aware request");
        let crate::mxc_common::state_aware_request::MxcRequest::StateAware(parsed) = parsed else {
            panic!("expected state-aware request");
        };
        parsed
    }

    fn parsed_state_aware_hash(json: &str, backend: &str) -> String {
        let parsed = parse_state_aware(json);
        state_aware_policy_hash(parsed.request(), backend, parsed.operation())
    }

    #[test]
    fn state_aware_backend_authorization_does_not_change_the_policy_hash() {
        for backend in ["isolation_session", "wslc", "windows_sandbox"] {
            let mut parsed = parse_state_aware(&provision_json(backend, ""));
            let baseline = state_aware_policy_hash(parsed.request(), backend, parsed.operation());
            parsed.set_experimental_enabled(true);
            assert_eq!(
                baseline,
                state_aware_policy_hash(parsed.request(), backend, parsed.operation()),
                "state-aware authorization must not change {backend} policy identity"
            );
        }
    }

    fn provision_json(backend: &str, extra_fields: &str) -> String {
        let network = if backend == "isolation_session" {
            r#","network":{"egress":{"default":"allow"},"ingress":{"default":"allow","hostLoopback":"allow"}}"#
        } else {
            ""
        };
        format!(
            r#"{{"version":"{}","phase":"provision","containment":"{backend}"{network}{extra_fields}}}"#,
            if backend == "isolation_session" {
                "0.9.0-alpha"
            } else {
                "1.1.0-alpha"
            }
        )
    }

    // Preserve the historical stateAware envelope independently of the typed
    // projection. Each caller supplies explicit expected phase/config values,
    // never values read back from the operation under test.
    fn expected_state_aware_hash(
        request: &ExecutionRequest,
        backend: &str,
        phase: &str,
        config: Value,
    ) -> String {
        let mut expected = policy_projection(request);
        expected["containment"] = serde_json::json!(backend);
        expected["stateAware"] = serde_json::json!({
            "backend": backend,
            "phase": phase,
            "config": config,
        });
        hash_canonical_json(&canonical_json(&expected))
    }

    #[test]
    fn state_aware_provision_hash_preserves_exact_config_shape() {
        let mut hashes = std::collections::HashSet::new();
        for (backend, payload, expected_config) in [
            ("isolation_session", None, Value::Null),
            ("isolation_session", Some("{}"), serde_json::json!({})),
            (
                "isolation_session",
                Some(r#"{"appId":""}"#),
                serde_json::json!({"appId": ""}),
            ),
            (
                "isolation_session",
                Some(r#"{"appId":"Contoso.App"}"#),
                serde_json::json!({"appId": "Contoso.App"}),
            ),
            ("windows_sandbox", None, Value::Null),
            ("wslc", None, Value::Null),
            ("wslc", Some("{}"), serde_json::json!({})),
            (
                "wslc",
                Some(r#"{"image":""}"#),
                serde_json::json!({"image": ""}),
            ),
            (
                "wslc",
                Some(r#"{"imageTarPath":""}"#),
                serde_json::json!({"imageTarPath": ""}),
            ),
            (
                "wslc",
                Some(r#"{"image":"","imageTarPath":""}"#),
                serde_json::json!({"image": "", "imageTarPath": ""}),
            ),
            (
                "wslc",
                Some(r#"{"image":"alpine:latest"}"#),
                serde_json::json!({"image": "alpine:latest"}),
            ),
            (
                "wslc",
                Some(r#"{"imageTarPath":"C:\\images\\custom.tar"}"#),
                serde_json::json!({"imageTarPath": "C:\\images\\custom.tar"}),
            ),
            (
                "wslc",
                Some(r#"{"image":"alpine:latest","imageTarPath":"C:\\images\\custom.tar"}"#),
                serde_json::json!({
                    "image": "alpine:latest",
                    "imageTarPath": "C:\\images\\custom.tar",
                }),
            ),
            (
                "wslc",
                Some(r#"{"portMappings":[]}"#),
                serde_json::json!({"portMappings": []}),
            ),
            (
                "wslc",
                Some(r#"{"portMappings":[{"windowsPort":8080,"containerPort":80}]}"#),
                serde_json::json!({
                    "portMappings": [
                        {"windowsPort": 8080, "containerPort": 80, "protocol": "tcp"},
                    ],
                }),
            ),
            (
                "wslc",
                Some(r#"{"portMappings":[{"windowsPort":8081,"containerPort":80}]}"#),
                serde_json::json!({
                    "portMappings": [
                        {"windowsPort": 8081, "containerPort": 80, "protocol": "tcp"},
                    ],
                }),
            ),
            (
                "wslc",
                Some(r#"{"portMappings":[{"windowsPort":8080,"containerPort":81}]}"#),
                serde_json::json!({
                    "portMappings": [
                        {"windowsPort": 8080, "containerPort": 81, "protocol": "tcp"},
                    ],
                }),
            ),
            (
                "wslc",
                Some(
                    r#"{"image":"alpine:latest","portMappings":[{"windowsPort":8080,"containerPort":80}]}"#,
                ),
                serde_json::json!({
                    "image": "alpine:latest",
                    "portMappings": [
                        {"windowsPort": 8080, "containerPort": 80, "protocol": "tcp"},
                    ],
                }),
            ),
        ] {
            let backend_section = match (backend, payload) {
                (_, None) => String::new(),
                ("isolation_session", Some(payload)) => {
                    format!(r#","isolationSession":{{"provision":{payload}}}"#)
                }
                ("wslc", Some(payload)) => {
                    format!(r#","wslc":{{"provision":{payload}}}"#)
                }
                ("windows_sandbox", Some(_)) => unreachable!(),
                _ => unreachable!(),
            };
            let json = provision_json(backend, &backend_section);
            let parsed = parse_state_aware(&json);
            assert_eq!(
                state_aware_config_projection(parsed.operation()),
                expected_config,
                "{json}"
            );
            let hash = state_aware_policy_hash(parsed.request(), backend, parsed.operation());
            assert_eq!(
                hash,
                expected_state_aware_hash(parsed.request(), backend, "provision", expected_config),
                "{json}"
            );
            assert!(
                hashes.insert(hash),
                "absent, empty and supplied provision fields must stay distinct: {json}"
            );
        }
    }

    #[test]
    fn state_aware_hash_uses_each_operations_phase() {
        let request = request();
        let mut hashes = std::collections::HashSet::new();
        for (operation, expected_phase) in [
            (
                StateAwareOperation::ProvisionSession(None),
                "provision-session",
            ),
            (
                StateAwareOperation::Provision(StateAwareProvision::Wslc(None)),
                "provision",
            ),
            (
                StateAwareOperation::Start {
                    sandbox_id: "wslc:deadbeef".into(),
                },
                "start",
            ),
            (
                StateAwareOperation::Exec {
                    sandbox_id: "wslc:deadbeef".into(),
                },
                "exec",
            ),
            (
                StateAwareOperation::Stop {
                    sandbox_id: "wslc:deadbeef".into(),
                },
                "stop",
            ),
            (
                StateAwareOperation::Deprovision {
                    sandbox_id: "wslc:deadbeef".into(),
                },
                "deprovision",
            ),
            (
                StateAwareOperation::DeprovisionSession {
                    session_id: "wslcsess:deadbeef".into(),
                },
                "deprovision-session",
            ),
        ] {
            let hash = state_aware_policy_hash(&request, "wslc", &operation);
            assert_eq!(
                hash,
                expected_state_aware_hash(&request, "wslc", expected_phase, Value::Null)
            );
            assert!(hashes.insert(hash), "phase must affect the policy hash");
        }
    }

    #[test]
    fn state_aware_hash_ignores_empty_non_policy_fields_through_public_parser() {
        for backend in ["isolation_session", "windows_sandbox", "wslc"] {
            let baseline = parsed_state_aware_hash(&provision_json(backend, ""), backend);
            for extra_fields in [
                r#","telemetry":{}"#.to_string(),
                r#","_comment":{"user":{"CLIENTSECRET":"ignored"},"UPN":"alice@example.test"}"#
                    .to_string(),
            ] {
                assert_eq!(
                    baseline,
                    parsed_state_aware_hash(&provision_json(backend, &extra_fields), backend),
                    "{backend}: {extra_fields}"
                );
            }
            if backend == "isolation_session" {
                assert_eq!(
                    baseline,
                    parsed_state_aware_hash(
                        &provision_json(backend, r#","isolationSession":{}"#),
                        backend
                    ),
                    "{backend}: an empty backend section is not a provision config"
                );
            } else if backend == "wslc" {
                assert_eq!(
                    baseline,
                    parsed_state_aware_hash(&provision_json(backend, r#","wslc":{}"#), backend),
                    "{backend}: an empty backend section is not a provision config"
                );
            }
        }

        for phase in ["start", "exec", "stop", "deprovision"] {
            let process = if phase == "exec" {
                r#","process":{"commandLine":"echo hello"}"#
            } else {
                ""
            };
            let source = |extra_fields: &str| {
                format!(
                    r#"{{"version":"1.1.0-alpha","phase":"{phase}","sandboxId":"wsb:deadbeef"{process}{extra_fields}}}"#
                )
            };
            assert_eq!(
                parsed_state_aware_hash(&source(""), "windows_sandbox"),
                parsed_state_aware_hash(&source(r#","telemetry":{}"#), "windows_sandbox"),
                "{phase}: empty telemetry does not affect policy identity"
            );
        }
    }

    #[test]
    fn state_aware_hash_excludes_credentials_and_unverified_ids() {
        let baseline = parse_state_aware(
            r#"{
                "version":"0.9.0-alpha",
                "phase":"exec",
                "sandboxId":"wslc:0123456789abcdef0123456789abcdef",
                "process":{"commandLine":"echo hello"},
                "runtimeConfig":{"networkProxy":"http://localhost:8080"}
            }"#,
        );
        let mut changed = parse_state_aware(
            r#"{
                "version":"0.9.0-alpha",
                "phase":"exec",
                "sandboxId":"wslc:alice@example.test",
                "process":{
                    "commandLine":"echo synthetic-command-secret",
                    "env":["API_KEY=synthetic-environment-secret"]
                },
                "runtimeConfig":{"networkProxy":"http://localhost:8080"},
                "telemetry":{"enabled":true},
                "_comment":{"user":{"wamToken":"synthetic-comment-secret"}}
            }"#,
        );
        changed.set_dry_run(true);
        assert_eq!(
            state_aware_policy_hash(baseline.request(), "wslc", baseline.operation()),
            state_aware_policy_hash(changed.request(), "wslc", changed.operation()),
            "command, env, telemetry, comments, dry-run and unverified IDs are excluded"
        );
    }
}