cellos-core 0.8.0-pre

CellOS domain types and ports — typed authority, formation DAG, CloudEvent envelopes, RBAC primitives. No I/O.
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
//! Operator-managed trust-keyset verifying-keys file (SEC-25 Phase 2).
//!
//! W2 SEC-25 Phase 1 shipped the dataplane verifier
//! [`crate::verify_signed_trust_keyset_envelope`] which accepts a
//! `HashMap<String, TrustAnchorPublicKey>` keyring and an envelope. This
//! module is the **operator-side keyring loader** that turns the JSON file
//! described in `docs/trust-plane-runtime.md` § Signed keyset envelopes into
//! that map.
//!
//! Phase 2 wires this into the supervisor (see `cellos-supervisor::trust_keyset_load`)
//! behind `CELLOS_TRUST_VERIFY_KEYS_PATH`. Sibling consumers
//! (`cellos-trustd`, taudit, etc.) can also call into [`parse_trust_verify_keys`]
//! / [`load_trust_verify_keys_file`] directly to avoid re-implementing the
//! file format.
//!
//! ## File format
//!
//! Top-level JSON object whose keys are signer kids and whose values are the
//! base64url encoding of the raw 32-byte Ed25519 public key (no padding,
//! though padding is tolerated):
//!
//! ```json
//! {
//!   "ops-envelope-2026-q2": "kE3...base64url-32-bytes...",
//!   "ops-envelope-2026-q3": "vQp...base64url-32-bytes..."
//! }
//! ```
//!
//! Duplicate kids are rejected (JSON parsers vary in their dedup behavior;
//! `serde_json` collapses by default — we do not silently accept that).
//!
//! ## Symlink hardening
//!
//! [`load_trust_verify_keys_file`] opens the file with `O_NOFOLLOW` on Unix
//! (matching the SEC-15b protection applied to `CELLOS_POLICY_PACK_PATH` and
//! `CELLOS_AUTHORITY_KEYS_PATH`) so a swapped-in symlink at the final path
//! component cannot redirect verifying-key loading to an attacker-controlled
//! file.

use std::collections::HashMap;
use std::path::Path;

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::crypto::{provider, TrustAnchorPublicKey};
use crate::error::CellosError;
use crate::types::CloudEventV1;

/// Parse the verifying-keys JSON document into a `kid → TrustAnchorPublicKey` map.
///
/// The expected shape is a top-level JSON object (`{ "<kid>": "<base64url-pubkey>", ... }`).
/// Each value MUST decode under base64url to exactly 32 bytes (Ed25519 raw
/// public key length). Padding is tolerated to be friendly to publishers that
/// emit padded base64url.
///
/// # Errors
///
/// Returns [`CellosError::InvalidSpec`] when:
/// - the input is not valid JSON;
/// - the top-level value is not a JSON object;
/// - any value is not a string;
/// - any value fails base64url decode;
/// - any decoded value is not 32 bytes;
/// - the JSON parser surfaces a duplicate kid (defense in depth — `serde_json`
///   normally collapses duplicates).
///
/// An empty object is accepted (returns an empty map). The supervisor uses
/// that as the "no operator keyring configured" path: envelope verification
/// will then fail with `no signature verified` for any envelope whose signer
/// kid is not in the empty keyring, which is the intended behaviour.
pub fn parse_trust_verify_keys(
    raw: &str,
) -> Result<HashMap<String, TrustAnchorPublicKey>, CellosError> {
    let value: Value = serde_json::from_str(raw).map_err(|e| {
        CellosError::InvalidSpec(format!("trust verify keys: JSON parse error: {e}"))
    })?;

    let object = value.as_object().ok_or_else(|| {
        CellosError::InvalidSpec(
            "trust verify keys: top-level value must be a JSON object mapping kid -> base64url-pubkey".into(),
        )
    })?;

    // Defence in depth against parser-side duplicate-kid collapse: the JSON
    // text is re-scanned to count each kid. `serde_json` collapses duplicate
    // keys silently in `to_value`, so we walk the raw text via a streaming
    // pass below before deferring to the parsed object for value extraction.
    detect_duplicate_keys(raw)?;

    let mut keys: HashMap<String, TrustAnchorPublicKey> = HashMap::with_capacity(object.len());
    for (kid, value) in object {
        let pubkey_b64 = value.as_str().ok_or_else(|| {
            CellosError::InvalidSpec(format!(
                "trust verify keys: value for kid {kid:?} must be a base64url string, got {value}"
            ))
        })?;

        // Tolerate padded or unpadded base64url.
        let trimmed = pubkey_b64.trim_end_matches('=');
        let bytes = URL_SAFE_NO_PAD.decode(trimmed).map_err(|e| {
            CellosError::InvalidSpec(format!(
                "trust verify keys: kid {kid:?} value is not valid base64url: {e}"
            ))
        })?;

        let array: [u8; 32] = bytes.as_slice().try_into().map_err(|_| {
            CellosError::InvalidSpec(format!(
                "trust verify keys: kid {kid:?} decoded to {} bytes, expected 32",
                bytes.len()
            ))
        })?;

        // Preserve the historical load-time canonical-point check (formerly
        // `VerifyingKey::from_bytes`) — a malformed key still fails at load,
        // not deferred to verify. The dalek check is contained in `crypto/`.
        let public_key = TrustAnchorPublicKey::from_validated_bytes(array).map_err(|e| {
            CellosError::InvalidSpec(format!(
                "trust verify keys: kid {kid:?} is not a valid Ed25519 verifying key: {e}"
            ))
        })?;

        keys.insert(kid.clone(), public_key);
    }

    Ok(keys)
}

/// Read [`parse_trust_verify_keys`]'s input from a path and decode it.
///
/// On Unix this opens with `O_NOFOLLOW` (matching `CELLOS_POLICY_PACK_PATH` /
/// `CELLOS_AUTHORITY_KEYS_PATH` policy in `composition.rs` — SEC-15b) so the
/// final path component cannot be a symlink redirected at an
/// attacker-controlled file. Windows has no `O_NOFOLLOW` analogue in the std
/// API, so [`reject_reparse_point`] performs a best-effort pre-read check that
/// refuses a final-component reparse point (symlink/junction) — a weaker,
/// check-then-open guard with a declared TOCTOU residual (S37, ADR-0031).
///
/// # Errors
///
/// Returns [`CellosError::InvalidSpec`] when the file cannot be opened, read,
/// or decoded as UTF-8, plus every error class from [`parse_trust_verify_keys`].
pub fn load_trust_verify_keys_file(
    path: &Path,
) -> Result<HashMap<String, TrustAnchorPublicKey>, CellosError> {
    let raw = read_trust_file_to_string(path)?;
    parse_trust_verify_keys(&raw)
}

/// Read a trust file to a string with the symlink-swap defenses every trust-file
/// load shares: `O_NOFOLLOW` on Unix (the final path component cannot be a
/// symlink) and a best-effort reparse-point refusal on Windows (S37). Used by
/// both [`load_trust_verify_keys_file`] and [`load_revocation_list_file`] so the
/// at-rest protections — and the O_NOFOLLOW per-platform constants — live in one
/// place.
fn read_trust_file_to_string(path: &Path) -> Result<String, CellosError> {
    #[cfg(unix)]
    {
        use std::io::Read;
        use std::os::unix::fs::OpenOptionsExt;
        let mut opts = std::fs::OpenOptions::new();
        opts.read(true);
        // O_NOFOLLOW value is platform-specific. cellos-core deliberately
        // avoids a `libc` dependency, so we hard-code the kernel ABI values
        // for the runtime targets we care about. Adding a new Unix variant
        // here is a one-line change, not a libc-crate refactor.
        //   - Linux: octal 0o400000 == 0x20000  (asm-generic/fcntl.h)
        //   - macOS / *BSD:           == 0x100  (sys/fcntl.h)
        // Using the wrong constant silently maps to a different flag (on
        // Linux 0x100 is `O_NOCTTY`, which would *not* refuse a symlink),
        // so this MUST stay accurate per platform.
        #[cfg(target_os = "linux")]
        const O_NOFOLLOW: i32 = 0x20000;
        #[cfg(any(
            target_os = "macos",
            target_os = "ios",
            target_os = "freebsd",
            target_os = "netbsd",
            target_os = "openbsd",
            target_os = "dragonfly",
        ))]
        const O_NOFOLLOW: i32 = 0x100;
        // Build break here on a new Unix is intentional: pick the right
        // constant from the platform's <fcntl.h> rather than guessing.
        #[cfg(not(any(
            target_os = "linux",
            target_os = "macos",
            target_os = "ios",
            target_os = "freebsd",
            target_os = "netbsd",
            target_os = "openbsd",
            target_os = "dragonfly",
        )))]
        compile_error!(
            "cellos-core::trust_keys: O_NOFOLLOW value not yet defined for this Unix target — \
             add the platform-specific value (see <fcntl.h>) before building."
        );
        opts.custom_flags(O_NOFOLLOW);
        let mut file = opts.open(path).map_err(|e| {
            CellosError::InvalidSpec(format!("trust file: cannot open {}: {e}", path.display()))
        })?;
        let mut buf = String::new();
        file.read_to_string(&mut buf).map_err(|e| {
            CellosError::InvalidSpec(format!("trust file: cannot read {}: {e}", path.display()))
        })?;
        Ok(buf)
    }
    #[cfg(not(unix))]
    {
        #[cfg(windows)]
        reject_reparse_point(path)?;
        std::fs::read_to_string(path).map_err(|e| {
            CellosError::InvalidSpec(format!("trust file: cannot read {}: {e}", path.display()))
        })
    }
}

/// Load + verify a signed revocation list from `path` (S35, ADR-0031).
///
/// Reads the file with the same `O_NOFOLLOW` / reparse-point defenses as the
/// trust-verify keys (S37), parses the
/// [`crate::types::SignedTrustKeysetEnvelope`], and returns the revoked-kid set
/// via [`verify_and_parse_revocation_envelope`] (verified under `verifying_keys`,
/// media type re-asserted, inner list parsed). Fail-closed: any read / parse /
/// verify failure returns `Err` and yields no revocations — a caller under a
/// hardened profile MUST propagate that error rather than proceed unrevoked.
pub fn load_revocation_list_file(
    path: &Path,
    verifying_keys: &HashMap<String, TrustAnchorPublicKey>,
    now: std::time::SystemTime,
) -> Result<std::collections::HashSet<String>, CellosError> {
    let raw = read_trust_file_to_string(path)?;
    let envelope: crate::types::SignedTrustKeysetEnvelope =
        serde_json::from_str(&raw).map_err(|e| {
            CellosError::InvalidSpec(format!(
                "revocation list: {} is not a SignedTrustKeysetEnvelope: {e}",
                path.display()
            ))
        })?;
    verify_and_parse_revocation_envelope(&envelope, verifying_keys, now)
}

/// Best-effort Windows defense against a final-path-component reparse point
/// (symlink, junction, mount point) swapped in to redirect a trust-file read at
/// an attacker-controlled target. Closes the bare-`read_to_string` gap on
/// Windows, which has no `O_NOFOLLOW` analogue in the std API (S37).
///
/// **Residual (declared; key-lifecycle STIG row, ADR-0031 / S40).** This is a
/// check-then-open guard: there is a TOCTOU window between this
/// `symlink_metadata` check and the subsequent open/read, so it is NOT an
/// `O_NOFOLLOW`-equivalent atomic control — only best-effort hardening. The
/// owner/ACL portion of the gap (file must be SYSTEM/Administrators-owned, not
/// world-writable) is not yet enforced here and is tracked as the same residual.
#[cfg(windows)]
pub fn reject_reparse_point(path: &std::path::Path) -> Result<(), CellosError> {
    use std::os::windows::fs::MetadataExt;
    // FILE_ATTRIBUTE_REPARSE_POINT — covers symlinks, junctions, mount points.
    const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400;
    let meta = std::fs::symlink_metadata(path).map_err(|e| {
        CellosError::InvalidSpec(format!("trust file: cannot stat {}: {e}", path.display()))
    })?;
    if meta.file_type().is_symlink() || (meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT) != 0
    {
        return Err(CellosError::InvalidSpec(format!(
            "trust file: refusing {}: final path component is a reparse point \
             (symlink/junction); best-effort Windows symlink-swap defense (TOCTOU residual)",
            path.display()
        )));
    }
    Ok(())
}

/// Single-pass duplicate-key detector for the top-level JSON object.
///
/// `serde_json`'s `Value` collapses duplicate object keys with last-write-wins
/// semantics. For a verifying-keys file that's a silent footgun: an attacker
/// who can inject a second copy of an existing kid with a different pubkey
/// would silently substitute the verifier's key. This walker scans the raw
/// JSON text for top-level object string keys and rejects the file if any
/// kid appears twice.
///
/// The walker is deliberately simple — it tracks string state and a single
/// nesting depth so it only counts keys at the outermost object — and does
/// not attempt to fully reparse JSON. It is robust against escaped quotes,
/// nested objects, arrays, and whitespace; if the structure is malformed in
/// a way the walker can't reason about, it falls through and lets
/// `serde_json::from_str` (called by the caller) surface the parse error.
fn detect_duplicate_keys(raw: &str) -> Result<(), CellosError> {
    use std::collections::HashSet;

    let bytes = raw.as_bytes();
    let mut seen: HashSet<String> = HashSet::new();
    let mut idx = 0;
    let mut depth: i32 = 0;
    let mut in_string = false;
    let mut after_colon_in_outer = false;
    let mut current_key: Option<String> = None;
    let mut escape = false;
    let mut started = false;

    while idx < bytes.len() {
        let b = bytes[idx];
        if in_string {
            if escape {
                escape = false;
                if let Some(k) = current_key.as_mut() {
                    k.push(b as char);
                }
                idx += 1;
                continue;
            }
            match b {
                b'\\' => {
                    escape = true;
                    if let Some(k) = current_key.as_mut() {
                        k.push(b as char);
                    }
                }
                b'"' => {
                    in_string = false;
                    if depth == 1 && !after_colon_in_outer {
                        if let Some(key) = current_key.take() {
                            if !seen.insert(key.clone()) {
                                return Err(CellosError::InvalidSpec(format!(
                                    "trust verify keys: duplicate kid {key:?} in keys file"
                                )));
                            }
                        }
                    } else {
                        // string was a value, not a key — discard.
                        let _ = current_key.take();
                    }
                }
                _ => {
                    if let Some(k) = current_key.as_mut() {
                        k.push(b as char);
                    }
                }
            }
            idx += 1;
            continue;
        }

        match b {
            b'"' => {
                in_string = true;
                // Only collect strings that could be top-level keys: depth==1
                // AND we are NOT after a colon (i.e. we expect a key here).
                if depth == 1 && !after_colon_in_outer {
                    current_key = Some(String::new());
                } else {
                    current_key = Some(String::new()); // placeholder so the
                                                       // closing quote branch
                                                       // discards uniformly.
                }
            }
            b'{' => {
                depth += 1;
                started = true;
            }
            b'}' => {
                depth -= 1;
                after_colon_in_outer = false;
                if depth == 0 {
                    return Ok(());
                }
            }
            b'[' => {
                depth += 1;
            }
            b']' => {
                depth -= 1;
            }
            b':' if depth == 1 => {
                after_colon_in_outer = true;
            }
            b',' if depth == 1 => {
                after_colon_in_outer = false;
            }
            _ => {}
        }
        idx += 1;
    }

    // Reached end of input without closing the outermost object: let
    // serde_json surface the structural error. Treat as no-duplicate-detected
    // here (the parse will fail later regardless).
    let _ = started;
    Ok(())
}

// ── I5: Per-event signing (HMAC-SHA256 / Ed25519) ───────────────────────────
//
// Extends the SEC-25 envelope-verification model down to individual
// CloudEvents so JetStream consumers / projectors can independently verify
// authorship of a single event without re-walking the keyset envelope.
//
// Doctrine: D1 — this is an OPT-IN signing path. Producers that don't sign
// emit raw `CloudEventV1` envelopes exactly as before; consumers that don't
// verify see no change.
//
// Algorithms:
//   - "ed25519": producer signs the canonical-JSON serialization with an
//     Ed25519 signing key; consumer verifies with the matching public key.
//   - "hmac-sha256": shared symmetric key; FIPS 198 HMAC over the canonical
//     JSON serialization. Implemented inline over `sha2::Sha256` so we
//     don't pull a new crate dependency.
//
// `notBefore` / `notAfter` mirror the trust-keyset envelope schema and are
// advisory — this primitive does not enforce them.

/// Per-event signed envelope wrapping a single CloudEvent.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignedEventEnvelopeV1 {
    pub event: CloudEventV1,
    pub signer_kid: String,
    pub algorithm: String,
    pub signature: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub not_before: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub not_after: Option<String>,
}

/// Canonical JSON form of a CloudEvent for signing/verification.
///
/// Routes through the versioned sorted-keys canonicalizer
/// ([`crate::canonical::canonical_payload`], ADR-0028) so the signed byte
/// stream is a function of the event's *logical* JSON value — independent of
/// `struct` field-declaration order — and adding an optional CloudEvent
/// attribute that a given event omits can never shift the bytes signed for it.
/// Signing and verification both call this function, so swapping the encoder is
/// a transparent runtime round-trip change.
pub fn canonical_event_signing_payload(event: &CloudEventV1) -> Result<Vec<u8>, CellosError> {
    crate::canonical::canonical_payload(event)
}

/// Sign a CloudEvent with an Ed25519 signing key given as its raw 32-byte seed.
///
/// Routes through the active [`crate::crypto::CryptoProvider`] (ADR-0027, S04)
/// rather than calling `ed25519_dalek` directly, so a FIPS-validated provider
/// (S05) signs without any change here. The seed is the dalek
/// `SigningKey::from_bytes` representation.
pub fn sign_event_ed25519(
    event: &CloudEventV1,
    signer_kid: &str,
    signing_key_seed: &[u8; 32],
) -> Result<SignedEventEnvelopeV1, CellosError> {
    let payload = canonical_event_signing_payload(event)?;
    let signature = provider().sign_ed25519(signing_key_seed, &payload)?;
    Ok(SignedEventEnvelopeV1 {
        event: event.clone(),
        signer_kid: signer_kid.to_string(),
        algorithm: "ed25519".to_string(),
        signature: URL_SAFE_NO_PAD.encode(signature),
        not_before: None,
        not_after: None,
    })
}

/// A signer abstraction (ADR-0031, S32) so a call site need not hold a raw
/// signing seed: the private key can live behind a [`SoftwareSigner`] (seed in
/// process memory, the default custody mode) today, or an HSM / PKCS#11 signer
/// (S34) later, behind the same trait. Signing routes through the active
/// [`crate::crypto::CryptoProvider`] (ADR-0027), so a FIPS-validated provider is
/// transparent to holders of a `Signer`.
pub trait Signer: Send + Sync {
    /// The signer key id (`kid`) stamped into the envelope's `signerKid`.
    fn kid(&self) -> &str;

    /// Sign `message`, returning the raw 64-byte Ed25519 signature.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying provider/module rejects the operation.
    fn sign(&self, message: &[u8]) -> Result<[u8; 64], CellosError>;

    /// The public verifying key, for building a verifier-side keyring entry.
    fn verifying_key(&self) -> TrustAnchorPublicKey;
}

/// In-process Ed25519 signer holding the raw 32-byte seed (the default key
/// custody mode; HSM-backed custody is S34). The seed is wrapped in
/// [`zeroize::Zeroizing`] so it is wiped on drop. Behaviour-identical to
/// [`sign_event_ed25519`] for the same seed + kid — see
/// [`sign_event_with`].
pub struct SoftwareSigner {
    kid: String,
    seed: zeroize::Zeroizing<[u8; 32]>,
    public: TrustAnchorPublicKey,
}

impl SoftwareSigner {
    /// Build a signer from a raw 32-byte Ed25519 seed and a `kid`. The public
    /// key is derived once via the active provider's adapter and cached.
    ///
    /// # Errors
    ///
    /// Returns an error if the seed cannot be turned into a valid keypair.
    pub fn from_seed(kid: impl Into<String>, seed: [u8; 32]) -> Result<Self, CellosError> {
        // C07: derive via the active provider so the FIPS-pure build needs no
        // dalek call here.
        let public = TrustAnchorPublicKey::from_bytes_unchecked(
            crate::crypto::provider().public_key_from_seed(&seed)?,
        );
        Ok(Self {
            kid: kid.into(),
            seed: zeroize::Zeroizing::new(seed),
            public,
        })
    }
}

impl Signer for SoftwareSigner {
    fn kid(&self) -> &str {
        &self.kid
    }

    fn sign(&self, message: &[u8]) -> Result<[u8; 64], CellosError> {
        Ok(provider().sign_ed25519(&*self.seed, message)?)
    }

    fn verifying_key(&self) -> TrustAnchorPublicKey {
        self.public
    }
}

/// Sign a CloudEvent through a [`Signer`] (ADR-0031, S32).
///
/// Produces a [`SignedEventEnvelopeV1`] byte-identical to
/// [`sign_event_ed25519`] when `signer` is a [`SoftwareSigner`] built from the
/// same seed + kid — it is the same canonical payload, the same provider
/// signature, and the same envelope shape, just with the key held behind the
/// `Signer` seam instead of passed as raw bytes.
pub fn sign_event_with(
    signer: &dyn Signer,
    event: &CloudEventV1,
) -> Result<SignedEventEnvelopeV1, CellosError> {
    let payload = canonical_event_signing_payload(event)?;
    let signature = signer.sign(&payload)?;
    Ok(SignedEventEnvelopeV1 {
        event: event.clone(),
        signer_kid: signer.kid().to_string(),
        algorithm: "ed25519".to_string(),
        signature: URL_SAFE_NO_PAD.encode(signature),
        not_before: None,
        not_after: None,
    })
}

/// Sign a CloudEvent with HMAC-SHA256 (FIPS 198).
pub fn sign_event_hmac_sha256(
    event: &CloudEventV1,
    signer_kid: &str,
    key_bytes: &[u8],
) -> Result<SignedEventEnvelopeV1, CellosError> {
    let payload = canonical_event_signing_payload(event)?;
    let mac = provider().hmac_sha256(key_bytes, &payload);
    Ok(SignedEventEnvelopeV1 {
        event: event.clone(),
        signer_kid: signer_kid.to_string(),
        algorithm: "hmac-sha256".to_string(),
        signature: URL_SAFE_NO_PAD.encode(mac),
        not_before: None,
        not_after: None,
    })
}

/// Verify a [`SignedEventEnvelopeV1`], additionally rejecting a revoked signer
/// kid (S35, ADR-0031). A `signerKid` present in `revoked_kids` is rejected with
/// a `signer_kid_revoked` error **even when its signature is otherwise valid and
/// inside its `notAfter` window** — revocation takes precedence over expiry. With
/// an empty `revoked_kids` this is identical to [`verify_signed_event_envelope`].
pub fn verify_signed_event_envelope_with_revocations<'a>(
    envelope: &'a SignedEventEnvelopeV1,
    verifying_keys: &HashMap<String, TrustAnchorPublicKey>,
    hmac_keys: &HashMap<String, Vec<u8>>,
    revoked_kids: &std::collections::HashSet<String>,
) -> Result<&'a CloudEventV1, CellosError> {
    if revoked_kids.contains(&envelope.signer_kid) {
        return Err(CellosError::InvalidSpec(format!(
            "signed event envelope: signer_kid_revoked: {:?}",
            envelope.signer_kid
        )));
    }
    verify_signed_event_envelope(envelope, verifying_keys, hmac_keys)
}

/// Verify a [`crate::types::SignedTrustKeysetEnvelope`] carrying a
/// [`crate::types::RevocationListV1`] and return the set of revoked signer kids
/// (S35, ADR-0031).
///
/// Fail-closed: the envelope MUST verify under `verifying_keys` (org-root) via
/// the SEC-25 envelope verifier, its `payloadType` MUST be
/// [`crate::types::TRUST_REVOCATION_V1_PAYLOAD_TYPE`] (re-asserted after the
/// payload-agnostic verify, the same posture the ceiling loader uses), and the
/// inner payload MUST parse as a `RevocationListV1`. Any failure returns `Err`
/// and yields no revocations.
pub fn verify_and_parse_revocation_envelope(
    envelope: &crate::types::SignedTrustKeysetEnvelope,
    verifying_keys: &HashMap<String, TrustAnchorPublicKey>,
    now: std::time::SystemTime,
) -> Result<std::collections::HashSet<String>, CellosError> {
    let payload_bytes =
        crate::spec_validation::verify_signed_trust_keyset_envelope(envelope, verifying_keys, now)?;
    if envelope.payload_type != crate::types::TRUST_REVOCATION_V1_PAYLOAD_TYPE {
        return Err(CellosError::InvalidSpec(format!(
            "revocation list: expected payloadType {}, got '{}'",
            crate::types::TRUST_REVOCATION_V1_PAYLOAD_TYPE,
            envelope.payload_type
        )));
    }
    let list: crate::types::RevocationListV1 =
        serde_json::from_slice(&payload_bytes).map_err(|e| {
            CellosError::InvalidSpec(format!(
                "revocation list: payload is not a RevocationListV1: {e}"
            ))
        })?;
    Ok(list.revocations.into_iter().map(|r| r.kid).collect())
}

/// Verify a [`SignedEventEnvelopeV1`] against a verifier-side keyring.
pub fn verify_signed_event_envelope<'a>(
    envelope: &'a SignedEventEnvelopeV1,
    verifying_keys: &HashMap<String, TrustAnchorPublicKey>,
    hmac_keys: &HashMap<String, Vec<u8>>,
) -> Result<&'a CloudEventV1, CellosError> {
    let payload = canonical_event_signing_payload(&envelope.event)?;
    let sig_b64 = envelope.signature.trim_end_matches('=');
    let sig_bytes = URL_SAFE_NO_PAD.decode(sig_b64).map_err(|e| {
        CellosError::InvalidSpec(format!(
            "signed event envelope: signature is not valid base64url: {e}"
        ))
    })?;

    match envelope.algorithm.as_str() {
        "ed25519" => {
            let verifying_key = verifying_keys.get(&envelope.signer_kid).ok_or_else(|| {
                CellosError::InvalidSpec(format!(
                    "signed event envelope: unknown ed25519 signer kid {:?}",
                    envelope.signer_kid
                ))
            })?;
            if sig_bytes.len() != 64 {
                return Err(CellosError::InvalidSpec(format!(
                    "signed event envelope: ed25519 signature must be 64 bytes, got {}",
                    sig_bytes.len()
                )));
            }
            provider()
                .verify_ed25519(verifying_key.as_bytes(), &payload, &sig_bytes)
                .map_err(|e| {
                    CellosError::InvalidSpec(format!(
                        "signed event envelope: ed25519 verify failed: {e}"
                    ))
                })?;
            Ok(&envelope.event)
        }
        "hmac-sha256" => {
            let key = hmac_keys.get(&envelope.signer_kid).ok_or_else(|| {
                CellosError::InvalidSpec(format!(
                    "signed event envelope: unknown hmac-sha256 signer kid {:?}",
                    envelope.signer_kid
                ))
            })?;
            if sig_bytes.len() != 32 {
                return Err(CellosError::InvalidSpec(format!(
                    "signed event envelope: hmac-sha256 mac must be 32 bytes, got {}",
                    sig_bytes.len()
                )));
            }
            let expected = provider().hmac_sha256(key, &payload);
            if !provider().constant_time_eq(&expected, &sig_bytes) {
                return Err(CellosError::InvalidSpec(
                    "signed event envelope: hmac-sha256 verify failed".into(),
                ));
            }
            Ok(&envelope.event)
        }
        other => Err(CellosError::InvalidSpec(format!(
            "signed event envelope: unknown algorithm {other:?} (expected ed25519 or hmac-sha256)"
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::{load_trust_verify_keys_file, parse_trust_verify_keys};
    use crate::crypto::{provider, TrustAnchorPublicKey};
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
    use base64::Engine as _;
    use std::io::Write;

    /// Raw 32-byte Ed25519 seed for a deterministic test key.
    fn seed_bytes(seed: u8) -> [u8; 32] {
        [seed; 32]
    }

    /// The matching trust-anchor public key for a test seed.
    fn anchor(seed: u8) -> TrustAnchorPublicKey {
        TrustAnchorPublicKey::from_bytes_unchecked(
            provider()
                .public_key_from_seed(&seed_bytes(seed))
                .expect("derive pub"),
        )
    }

    fn pubkey_b64(seed: u8) -> String {
        URL_SAFE_NO_PAD.encode(
            provider()
                .public_key_from_seed(&seed_bytes(seed))
                .expect("derive pub"),
        )
    }

    #[test]
    fn parses_well_formed_two_key_map() {
        let raw = format!(
            r#"{{ "ops-envelope-2026-q2": "{}", "ops-envelope-2026-q3": "{}" }}"#,
            pubkey_b64(7),
            pubkey_b64(11)
        );
        let keys = parse_trust_verify_keys(&raw).expect("well-formed map must parse");
        assert_eq!(keys.len(), 2);
        assert!(keys.contains_key("ops-envelope-2026-q2"));
        assert!(keys.contains_key("ops-envelope-2026-q3"));
        assert_eq!(
            keys["ops-envelope-2026-q2"],
            anchor(7),
            "kid q2 must round-trip to its source verifying key"
        );
    }

    #[test]
    fn rejects_duplicate_kid() {
        let raw = format!(
            r#"{{ "ops-envelope-2026-q2": "{}", "ops-envelope-2026-q2": "{}" }}"#,
            pubkey_b64(7),
            pubkey_b64(11)
        );
        let err = parse_trust_verify_keys(&raw).expect_err("duplicate kid must be rejected");
        let msg = format!("{err}");
        assert!(
            msg.contains("duplicate kid"),
            "expected duplicate-kid error, got: {msg}"
        );
    }

    #[test]
    fn rejects_malformed_base64() {
        let raw = r#"{ "ops-bad": "@@@not-base64@@@" }"#;
        let err = parse_trust_verify_keys(raw).expect_err("malformed base64 must be rejected");
        let msg = format!("{err}");
        assert!(
            msg.contains("not valid base64url"),
            "expected base64-decode error, got: {msg}"
        );
    }

    #[test]
    fn rejects_wrong_length_pubkey() {
        // 16 bytes of zeros, base64url-encoded — too short for an Ed25519 pubkey.
        let too_short = URL_SAFE_NO_PAD.encode([0u8; 16]);
        let raw = format!(r#"{{ "ops-short": "{too_short}" }}"#);
        let err = parse_trust_verify_keys(&raw).expect_err("16-byte pubkey must be rejected");
        let msg = format!("{err}");
        assert!(
            msg.contains("expected 32"),
            "expected 32-byte length error, got: {msg}"
        );
    }

    #[test]
    fn empty_object_is_accepted() {
        let raw = "{}";
        let keys = parse_trust_verify_keys(raw).expect("empty object is the no-keys case");
        assert!(keys.is_empty());
    }

    #[test]
    fn missing_file_errors() {
        let path = std::path::Path::new("/nonexistent/path/that/should/not/exist.json");
        let err =
            load_trust_verify_keys_file(path).expect_err("missing file must surface an error");
        let msg = format!("{err}");
        assert!(
            msg.contains("cannot") && msg.contains("nonexistent"),
            "expected file-open error, got: {msg}"
        );
    }

    #[test]
    fn rejects_non_utf8_input() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let path = dir.path().join("trust-keys-non-utf8.json");
        let mut f = std::fs::File::create(&path).expect("create");
        // Bytes that are NOT valid UTF-8.
        f.write_all(&[0xFF, 0xFE, 0xFD, 0xFC]).expect("write");
        drop(f);
        let err = load_trust_verify_keys_file(&path).expect_err("non-utf8 must error");
        let msg = format!("{err}");
        // On Unix this surfaces from `read_to_string`'s utf8 check.
        assert!(
            msg.contains("cannot read") || msg.contains("utf-8") || msg.contains("UTF-8"),
            "expected non-utf8 read error, got: {msg}"
        );
    }

    #[test]
    fn rejects_top_level_non_object() {
        let raw = r#"["not", "an", "object"]"#;
        let err = parse_trust_verify_keys(raw).expect_err("top-level non-object must be rejected");
        let msg = format!("{err}");
        assert!(
            msg.contains("must be a JSON object"),
            "expected top-level-object error, got: {msg}"
        );
    }

    #[test]
    fn loads_valid_file_via_load_helper() {
        // Round-trip the file path: write a well-formed two-key map and load
        // it back via the on-disk helper, exercising the O_NOFOLLOW path on
        // Unix.
        let dir = tempfile::tempdir().expect("tmpdir");
        let path = dir.path().join("trust-keys.json");
        let raw = format!(
            r#"{{ "kid-active-7": "{}", "kid-active-11": "{}" }}"#,
            pubkey_b64(7),
            pubkey_b64(11)
        );
        std::fs::write(&path, raw).expect("write keys");
        let keys = load_trust_verify_keys_file(&path).expect("load via helper");
        assert_eq!(keys.len(), 2);
        assert_eq!(keys["kid-active-7"], anchor(7));
    }

    /// S37: on Windows the loader refuses a final-component reparse point
    /// (symlink/junction) before reading — best-effort symlink-swap defense
    /// (TOCTOU residual). Symlink creation needs privilege / Developer Mode, so
    /// the test skips with a note when it cannot create one.
    #[cfg(windows)]
    #[test]
    fn load_helper_rejects_reparse_point_at_final_component_windows() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let real_path = dir.path().join("trust-keys-real.json");
        let link_path = dir.path().join("trust-keys-link.json");
        let raw = format!(r#"{{ "kid-only-1": "{}" }}"#, pubkey_b64(7));
        std::fs::write(&real_path, raw).expect("write real keys file");

        // The real file loads.
        load_trust_verify_keys_file(&real_path).expect("real path loads");

        if std::os::windows::fs::symlink_file(&real_path, &link_path).is_err() {
            eprintln!(
                "load_helper_rejects_reparse_point_at_final_component_windows: skipping — \
                 cannot create a symlink (no SeCreateSymbolicLinkPrivilege / Developer Mode)"
            );
            return;
        }

        let err = load_trust_verify_keys_file(&link_path)
            .expect_err("a reparse point at the final component must be rejected");
        assert!(
            format!("{err}").contains("reparse point"),
            "expected reparse-point rejection, got: {err}"
        );
    }

    /// Symlink rejection — proves O_NOFOLLOW is the right kernel flag on this
    /// platform. Without this test we silently shipped `O_NOCTTY` on Linux
    /// (0x100 is O_NOCTTY there; O_NOFOLLOW is 0x20000) and the loader would
    /// accept attacker-swappable symlinks. Pin the property so a future rename
    /// or constant edit can't regress without a failing test.
    #[cfg(unix)]
    #[test]
    fn load_helper_rejects_symlink_at_final_component() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let real_path = dir.path().join("trust-keys-real.json");
        let symlink_path = dir.path().join("trust-keys-symlink.json");
        let raw = format!(r#"{{ "kid-only-1": "{}" }}"#, pubkey_b64(7));
        std::fs::write(&real_path, raw).expect("write real keys file");
        std::os::unix::fs::symlink(&real_path, &symlink_path).expect("create symlink");

        // Sanity: reading the real file works.
        load_trust_verify_keys_file(&real_path).expect("real path loads");

        // The symlink at the final component MUST be rejected by O_NOFOLLOW.
        let err = load_trust_verify_keys_file(&symlink_path)
            .expect_err("symlink at final component must be rejected");
        let msg = format!("{err}");
        assert!(
            msg.contains("cannot open"),
            "expected open-side rejection, got: {msg}"
        );
    }

    // ── I5: per-event signing primitives ───────────────────────────────────

    use super::{
        canonical_event_signing_payload, sign_event_ed25519, sign_event_hmac_sha256,
        sign_event_with, verify_signed_event_envelope, Signer, SoftwareSigner,
    };
    use crate::types::CloudEventV1;
    use std::collections::HashMap;

    fn sample_event() -> CloudEventV1 {
        CloudEventV1 {
            specversion: "1.0".into(),
            id: "ev-001".into(),
            source: "/cellos-supervisor".into(),
            ty: "dev.cellos.events.cell.lifecycle.v1.started".into(),
            datacontenttype: Some("application/json".into()),
            data: Some(serde_json::json!({"cellId": "test-cell-1"})),
            time: Some("2026-05-06T12:00:00Z".into()),
            traceparent: None,
            cex: None,
        }
    }

    #[test]
    fn ed25519_round_trip_verifies() {
        let seed = seed_bytes(31);
        let event = sample_event();
        let envelope = sign_event_ed25519(&event, "ops-event-2026-q2", &seed).expect("sign ok");

        assert_eq!(envelope.algorithm, "ed25519");
        assert_eq!(envelope.signer_kid, "ops-event-2026-q2");

        let mut keys = HashMap::new();
        keys.insert("ops-event-2026-q2".to_string(), anchor(31));
        let hmac_keys: HashMap<String, Vec<u8>> = HashMap::new();
        let verified =
            verify_signed_event_envelope(&envelope, &keys, &hmac_keys).expect("verify ok");
        assert_eq!(verified.id, event.id);
    }

    #[test]
    fn ed25519_tampered_event_fails_verify() {
        let seed = seed_bytes(31);
        let event = sample_event();
        let mut envelope = sign_event_ed25519(&event, "ops-event-2026-q2", &seed).expect("sign ok");
        envelope.event.id = "ev-tampered".into();

        let mut keys = HashMap::new();
        keys.insert("ops-event-2026-q2".to_string(), anchor(31));
        let hmac_keys: HashMap<String, Vec<u8>> = HashMap::new();
        let err = verify_signed_event_envelope(&envelope, &keys, &hmac_keys)
            .expect_err("tampered event must fail verify");
        assert!(format!("{err}").contains("ed25519 verify failed"));
    }

    #[test]
    fn ed25519_unknown_kid_fails_verify() {
        let seed = seed_bytes(31);
        let event = sample_event();
        let envelope = sign_event_ed25519(&event, "ops-event-2026-q2", &seed).expect("sign ok");
        let keys: HashMap<String, TrustAnchorPublicKey> = HashMap::new();
        let hmac_keys: HashMap<String, Vec<u8>> = HashMap::new();
        let err = verify_signed_event_envelope(&envelope, &keys, &hmac_keys)
            .expect_err("unknown kid must fail");
        assert!(format!("{err}").contains("unknown ed25519 signer kid"));
    }

    #[test]
    fn software_signer_matches_sign_event_ed25519_and_verifies() {
        // S32 (ADR-0031): a SoftwareSigner built from the same seed + kid
        // produces a byte-identical envelope to the raw-seed
        // `sign_event_ed25519`, and the result verifies offline against the
        // signer's own verifying key.
        let seed = seed_bytes(31);
        let event = sample_event();
        let kid = "ops-event-2026-q2";

        let legacy = sign_event_ed25519(&event, kid, &seed).expect("legacy sign");
        let signer = SoftwareSigner::from_seed(kid, seed).expect("build signer");
        let via_seam = sign_event_with(&signer, &event).expect("seam sign");

        assert_eq!(
            serde_json::to_vec(&legacy).unwrap(),
            serde_json::to_vec(&via_seam).unwrap(),
            "SoftwareSigner must produce a byte-identical envelope to sign_event_ed25519"
        );
        assert_eq!(signer.kid(), kid);
        assert_eq!(signer.verifying_key(), anchor(31));

        let mut keys = HashMap::new();
        keys.insert(kid.to_string(), signer.verifying_key());
        let hmac_keys: HashMap<String, Vec<u8>> = HashMap::new();
        let verified =
            verify_signed_event_envelope(&via_seam, &keys, &hmac_keys).expect("verify ok");
        assert_eq!(verified.id, event.id);
    }

    #[test]
    fn revocation_list_revokes_kid_and_fails_closed_on_tamper() {
        // S35 (ADR-0031) acceptance: a signed revocation envelope verifies under
        // the org-root key and yields the revoked set; a revoked kid is rejected
        // with signer_kid_revoked DESPITE a valid signature; an unrevoked kid
        // still verifies; a tampered revocation envelope fails closed.
        use crate::crypto::{provider, TrustAnchorPublicKey};
        use crate::types::{
            RevocationListV1, RevokedSigner, SignedTrustKeysetEnvelope, TrustKeysetSignature,
            TRUST_REVOCATION_V1_PAYLOAD_TYPE,
        };
        use crate::{
            verify_and_parse_revocation_envelope, verify_signed_event_envelope_with_revocations,
        };
        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
        use base64::Engine as _;
        use std::collections::HashSet;
        use std::fmt::Write as _;
        use std::time::SystemTime;

        // Org-root key that signs the revocation envelope.
        let org_seed = seed_bytes(42);
        let mut org_keys = HashMap::new();
        org_keys.insert(
            "org-root-2026".to_string(),
            TrustAnchorPublicKey::from_bytes_unchecked(
                provider().public_key_from_seed(&org_seed).unwrap(),
            ),
        );

        // Build + org-root-sign a revocation list naming "kid-bad".
        let list = RevocationListV1 {
            schema_version: "1.0.0".into(),
            revocation_epoch: 1,
            revocations: vec![RevokedSigner {
                kid: "kid-bad".into(),
                revoked_at: "2026-06-23T00:00:00Z".into(),
                reason: "key_compromise".into(),
            }],
        };
        let payload_bytes = serde_json::to_vec(&list).unwrap();
        let sig = provider().sign_ed25519(&org_seed, &payload_bytes).unwrap();
        let mut digest_hex = String::from("sha256:");
        for b in provider().sha256(&payload_bytes) {
            write!(digest_hex, "{b:02x}").unwrap();
        }
        let make_env = |payload_b64: String, digest: String| SignedTrustKeysetEnvelope {
            schema_version: "1.0.0".into(),
            payload_type: TRUST_REVOCATION_V1_PAYLOAD_TYPE.into(),
            payload: payload_b64,
            signatures: vec![TrustKeysetSignature {
                signer_kid: "org-root-2026".into(),
                algorithm: "ed25519".into(),
                signature: URL_SAFE_NO_PAD.encode(sig),
                not_before: None,
                not_after: None,
            }],
            payload_digest: digest,
            produced_at: "2026-06-23T00:00:00Z".into(),
            replaces_envelope_digest: None,
            required_signer_count: None,
        };
        let envelope = make_env(URL_SAFE_NO_PAD.encode(&payload_bytes), digest_hex.clone());

        // (3) The revocation envelope verifies under the org-root key.
        let revoked: HashSet<String> =
            verify_and_parse_revocation_envelope(&envelope, &org_keys, SystemTime::now())
                .expect("revocation envelope must verify under org-root");
        assert!(revoked.contains("kid-bad"));

        // An event signed by the revoked kid, with a VALID signature.
        let event = sample_event();
        let bad_env = sign_event_ed25519(&event, "kid-bad", &seed_bytes(7)).unwrap();
        let mut event_keys = HashMap::new();
        event_keys.insert("kid-bad".to_string(), anchor(7));
        let hmac_keys: HashMap<String, Vec<u8>> = HashMap::new();

        // (2) With no revocations the (valid) event verifies.
        let empty: HashSet<String> = HashSet::new();
        verify_signed_event_envelope_with_revocations(&bad_env, &event_keys, &hmac_keys, &empty)
            .expect("unrevoked kid with a valid signature must verify");

        // (1) With the revoked set it is rejected as signer_kid_revoked — despite
        // the signature being valid.
        let err = verify_signed_event_envelope_with_revocations(
            &bad_env,
            &event_keys,
            &hmac_keys,
            &revoked,
        )
        .expect_err("a revoked kid must be rejected even with a valid signature");
        assert!(
            format!("{err}").contains("signer_kid_revoked"),
            "expected signer_kid_revoked, got: {err}"
        );

        // (3, fail-closed) A tampered revocation envelope (payload swapped after
        // signing, so the digest/signature no longer match) yields no revocations.
        let tampered = make_env(
            URL_SAFE_NO_PAD
                .encode(br#"{"schemaVersion":"1.0.0","revocationEpoch":2,"revocations":[]}"#),
            digest_hex,
        );
        let err = verify_and_parse_revocation_envelope(&tampered, &org_keys, SystemTime::now())
            .expect_err("a tampered revocation envelope must fail closed");
        assert!(
            format!("{err}").contains("digest mismatch") || format!("{err}").contains("verify"),
            "expected fail-closed digest/verify error, got: {err}"
        );
    }

    #[test]
    fn hmac_sha256_round_trip_verifies() {
        let key = b"super-secret-shared-symmetric-key";
        let event = sample_event();
        let envelope = sign_event_hmac_sha256(&event, "ops-hmac-2026-q2", key).expect("sign ok");
        assert_eq!(envelope.algorithm, "hmac-sha256");

        let verifying_keys: HashMap<String, _> = HashMap::new();
        let mut hmac_keys: HashMap<String, Vec<u8>> = HashMap::new();
        hmac_keys.insert("ops-hmac-2026-q2".to_string(), key.to_vec());
        let verified = verify_signed_event_envelope(&envelope, &verifying_keys, &hmac_keys)
            .expect("verify ok");
        assert_eq!(verified.id, event.id);
    }

    #[test]
    fn hmac_sha256_tampered_event_fails_verify() {
        let key = b"super-secret-shared-symmetric-key";
        let event = sample_event();
        let mut envelope =
            sign_event_hmac_sha256(&event, "ops-hmac-2026-q2", key).expect("sign ok");
        envelope.event.ty = "dev.cellos.events.cell.lifecycle.v1.destroyed".into();

        let verifying_keys: HashMap<String, _> = HashMap::new();
        let mut hmac_keys: HashMap<String, Vec<u8>> = HashMap::new();
        hmac_keys.insert("ops-hmac-2026-q2".to_string(), key.to_vec());
        let err = verify_signed_event_envelope(&envelope, &verifying_keys, &hmac_keys)
            .expect_err("tampered event must fail");
        assert!(format!("{err}").contains("hmac-sha256 verify failed"));
    }

    #[test]
    fn unknown_algorithm_rejected() {
        let seed = seed_bytes(31);
        let event = sample_event();
        let mut envelope = sign_event_ed25519(&event, "ops-event-2026-q2", &seed).expect("sign ok");
        envelope.algorithm = "rsa-pss-sha512".into();

        let verifying_keys: HashMap<String, _> = HashMap::new();
        let hmac_keys: HashMap<String, Vec<u8>> = HashMap::new();
        let err = verify_signed_event_envelope(&envelope, &verifying_keys, &hmac_keys)
            .expect_err("unknown algorithm must be rejected");
        assert!(format!("{err}").contains("unknown algorithm"));
    }

    #[test]
    fn canonical_payload_is_deterministic() {
        let event = sample_event();
        let a = canonical_event_signing_payload(&event).expect("a");
        let b = canonical_event_signing_payload(&event).expect("b");
        assert_eq!(a, b, "canonical signing payload must be byte-identical");
    }
}