cellos-host-telemetry 0.5.0

Host-side telemetry receiver for CellOS — vsock listener that host-stamps and signs CloudEvents emitted by the in-guest cellos-telemetry agent.
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
//! F4b — supervisor-side signing of outbound guest-derived envelopes.
//!
//! Doctrine (ADR-0006 §5, channel-authenticity model):
//!
//! - The guest agent does NOT hold a signing key. It declares fields over
//!   vsock; the supervisor host-stamps the non-negotiable attribution fields
//!   ([`HostStamp`]) and signs the resulting [`CloudEventV1`] envelope.
//! - Signing payload is the canonical-JSON serialization of the FULL
//!   `CloudEventV1` (as established by I5 — `cellos_core::trust_keys::
//!   canonical_event_signing_payload`). Mutating any field after the signature
//!   is computed MUST cause verification to fail (O2 — observability that
//!   cannot be quietly retconned).
//!
//! ## Signing key material
//!
//! [`SigningKeyMaterial`] is the runtime knob. Three modes:
//!
//! - [`SigningKeyMaterial::Off`] — passthrough; outbound envelopes are emitted
//!   un-signed. This is the default when no env vars are set, matching the
//!   I5 doctrine that signing is OPT-IN.
//! - [`SigningKeyMaterial::Hmac`] — shared symmetric key (HMAC-SHA256, FIPS
//!   198). Verifier needs the same shared key in its `hmac_keys` map.
//! - [`SigningKeyMaterial::Ed25519`] — asymmetric; verifier needs only the
//!   public key in its `verifying_keys` map.
//!
//! Loading is from environment variables (the supervisor crate is the
//! consumer; this module is location-agnostic so any future host-side wiring
//! can call [`SigningKeyMaterial::from_env`] without touching the supervisor).
//!
//! ### Env vars
//!
//! - `CELLOS_HOST_TELEMETRY_SIGN_ALG` — `"off"` (default), `"hmac-sha256"`,
//!   or `"ed25519"`.
//! - `CELLOS_HOST_TELEMETRY_SIGN_KID` — required when alg != off. The signer
//!   kid embedded in the [`SignedEventEnvelopeV1`].
//! - `CELLOS_HOST_TELEMETRY_SIGN_HMAC_KEY` — base64url (no-pad, padding
//!   tolerated) of the shared HMAC key. Required when alg=hmac-sha256.
//! - `CELLOS_HOST_TELEMETRY_SIGN_ED25519_SK` — base64url of the 32-byte
//!   Ed25519 seed. Required when alg=ed25519.
//!
//! Setting both `*_HMAC_KEY` and `*_ED25519_SK` is rejected: the operator
//! must pick one to avoid ambiguity over which key signed the stream.
//!
//! ## F3b interlock
//!
//! [`StampedDeclaration`] is defined locally as a `{guest, host}` pair so
//! F4b can be merged before F3b. When F3b lands, lift this struct to
//! `cellos-host-telemetry::lib` (or its own module); F4b's signer accepts it
//! by value/by-reference and is location-agnostic.

use std::env;
use std::time::UNIX_EPOCH;

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use ed25519_dalek::SigningKey;
use zeroize::Zeroizing;

use cellos_core::trust_keys::{sign_event_ed25519, sign_event_hmac_sha256, SignedEventEnvelopeV1};
use cellos_core::CloudEventV1;

use crate::{GuestDeclaration, HostStamp};

// ── F3b interlock ──────────────────────────────────────────────────────────

/// Pair of guest declaration + host stamp.
///
/// **F3b note:** F4b ships this struct here so the signer doesn't depend on
/// F3b having landed first. When F3b lands it should hoist this definition to
/// `cellos-host-telemetry::lib` (or a sibling `stamped` module) and re-export
/// it; the signer below stays unchanged because it consumes the inputs by
/// reference. This is the F3b/F4b boundary contract.
#[derive(Debug, Clone)]
pub struct StampedDeclaration {
    /// What the guest agent declared over vsock.
    pub guest: GuestDeclaration,
    /// What the supervisor stamped on receive (overrides anything the guest
    /// claimed about cell_id / run_id / timestamp / spec hash).
    pub host: HostStamp,
}

// ── Provenance constant (events::Provenance is a struct, not the enum we
//    want here) ──────────────────────────────────────────────────────────────

/// CloudEvent extension/data marker for "this fact was declared by the guest
/// agent, not directly observed host-side."
///
/// `cellos_core::events::Provenance` is a struct
/// `{ parent, parent_type }` describing parent-event lineage — not an
/// epistemic-status enum. The canonical `Declared` / `Observed` distinction
/// lives in `cellos_core::authority::EpistemicStatus`. F4b only needs the
/// literal token; we hard-code it here to avoid pulling the authority
/// surface into the host-telemetry crate.
pub const PROVENANCE_DECLARED: &str = "declared";

// ── Signing key material ───────────────────────────────────────────────────

/// Env var: signing algorithm for outbound CloudEvents.
pub const ENV_SIGN_ALG: &str = "CELLOS_HOST_TELEMETRY_SIGN_ALG";
/// Env var: signer kid embedded in the envelope.
pub const ENV_SIGN_KID: &str = "CELLOS_HOST_TELEMETRY_SIGN_KID";
/// Env var: HMAC-SHA256 shared key (base64url).
pub const ENV_SIGN_HMAC_KEY: &str = "CELLOS_HOST_TELEMETRY_SIGN_HMAC_KEY";
/// Env var: Ed25519 32-byte seed (base64url).
pub const ENV_SIGN_ED25519_SK: &str = "CELLOS_HOST_TELEMETRY_SIGN_ED25519_SK";

/// Errors returned by the F4b signer.
#[derive(Debug, thiserror::Error)]
pub enum SignOutboundError {
    /// Env-driven configuration was internally inconsistent (e.g. both HMAC
    /// and Ed25519 keys set, or alg set without kid).
    #[error("invalid signing config: {0}")]
    InvalidConfig(String),

    /// Underlying signer rejected the canonical payload.
    #[error("signer error: {0}")]
    Signer(String),

    /// Canonical-JSON serialization failed.
    #[error("serialize error: {0}")]
    Serialize(String),
}

/// Runtime signing key material.
///
/// Note: `Debug` is implemented manually so that key bytes never leak into
/// log output. We surface the variant + kid only.
pub enum SigningKeyMaterial {
    /// Signing disabled — passthrough, no envelope wrapping.
    Off,
    /// HMAC-SHA256 with a shared symmetric key.
    Hmac {
        /// Signer kid embedded in the [`SignedEventEnvelopeV1`].
        kid: String,
        /// Shared HMAC key bytes. Red-team wave-2 T1b: `Zeroizing<Vec<u8>>`
        /// so the secret key is wiped on drop instead of lingering in freed
        /// allocations.
        key: Zeroizing<Vec<u8>>,
    },
    /// Ed25519 asymmetric signing.
    Ed25519 {
        /// Signer kid embedded in the [`SignedEventEnvelopeV1`].
        kid: String,
        /// Ed25519 signing key (private). Verifier holds the matching
        /// `VerifyingKey`.
        signing_key: SigningKey,
    },
}

impl std::fmt::Debug for SigningKeyMaterial {
    /// Custom `Debug` that NEVER prints key bytes — only variant + kid. This
    /// matters because operators sometimes pipe `tracing` output into log
    /// stores that retain forever; an accidental `{:?}` of a `SigningKeyMaterial`
    /// must not become a key-leak channel.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SigningKeyMaterial::Off => f.debug_struct("SigningKeyMaterial::Off").finish(),
            SigningKeyMaterial::Hmac { kid, key } => f
                .debug_struct("SigningKeyMaterial::Hmac")
                .field("kid", kid)
                .field(
                    "key",
                    &format_args!("<redacted {}-byte hmac key>", key.len()),
                )
                .finish(),
            SigningKeyMaterial::Ed25519 { kid, .. } => f
                .debug_struct("SigningKeyMaterial::Ed25519")
                .field("kid", kid)
                .field("signing_key", &"<redacted ed25519 signing key>")
                .finish(),
        }
    }
}

impl SigningKeyMaterial {
    /// True iff this is the [`SigningKeyMaterial::Off`] variant.
    pub fn is_off(&self) -> bool {
        matches!(self, SigningKeyMaterial::Off)
    }

    /// Signer kid for the active variant; `None` for [`SigningKeyMaterial::Off`].
    pub fn kid(&self) -> Option<&str> {
        match self {
            SigningKeyMaterial::Off => None,
            SigningKeyMaterial::Hmac { kid, .. } => Some(kid.as_str()),
            SigningKeyMaterial::Ed25519 { kid, .. } => Some(kid.as_str()),
        }
    }

    /// Load signing material from env vars (see module docs).
    ///
    /// - Unset / `"off"` → [`SigningKeyMaterial::Off`].
    /// - `"hmac-sha256"` → requires kid + HMAC key, rejects ed25519 key.
    /// - `"ed25519"` → requires kid + ed25519 seed, rejects HMAC key.
    pub fn from_env() -> Result<Self, SignOutboundError> {
        let alg_raw = env::var(ENV_SIGN_ALG).unwrap_or_default();
        let alg = alg_raw.trim().to_ascii_lowercase();

        if alg.is_empty() || alg == "off" {
            // Even in Off mode, refuse to silently swallow stray key material.
            // Operator most likely meant to enable signing; surface the
            // misconfig instead of pretending Off.
            if env::var(ENV_SIGN_HMAC_KEY).is_ok() || env::var(ENV_SIGN_ED25519_SK).is_ok() {
                return Err(SignOutboundError::InvalidConfig(format!(
                    "{ENV_SIGN_ALG} is off (or unset) but {ENV_SIGN_HMAC_KEY} \
                     or {ENV_SIGN_ED25519_SK} is set — refuse to silently \
                     drop key material; set {ENV_SIGN_ALG} explicitly"
                )));
            }
            return Ok(SigningKeyMaterial::Off);
        }

        let kid = env::var(ENV_SIGN_KID).map_err(|_| {
            SignOutboundError::InvalidConfig(format!(
                "{ENV_SIGN_ALG}={alg_raw:?} requires {ENV_SIGN_KID} to be set"
            ))
        })?;
        if kid.trim().is_empty() {
            return Err(SignOutboundError::InvalidConfig(format!(
                "{ENV_SIGN_KID} must be a non-empty signer kid"
            )));
        }

        let hmac_set = env::var(ENV_SIGN_HMAC_KEY).is_ok();
        let ed_set = env::var(ENV_SIGN_ED25519_SK).is_ok();
        if hmac_set && ed_set {
            return Err(SignOutboundError::InvalidConfig(format!(
                "mutual-exclusion violated: both {ENV_SIGN_HMAC_KEY} and \
                 {ENV_SIGN_ED25519_SK} are set — pick exactly one"
            )));
        }

        match alg.as_str() {
            "hmac-sha256" | "hmac" => {
                let key_b64 = env::var(ENV_SIGN_HMAC_KEY).map_err(|_| {
                    SignOutboundError::InvalidConfig(format!(
                        "{ENV_SIGN_ALG}=hmac-sha256 requires {ENV_SIGN_HMAC_KEY}"
                    ))
                })?;
                let trimmed = key_b64.trim().trim_end_matches('=');
                // T1b: wrap decoded key in Zeroizing immediately so it wipes
                // on the is_empty() error path too.
                let key: Zeroizing<Vec<u8>> =
                    Zeroizing::new(URL_SAFE_NO_PAD.decode(trimmed).map_err(|e| {
                        SignOutboundError::InvalidConfig(format!(
                            "{ENV_SIGN_HMAC_KEY} is not valid base64url: {e}"
                        ))
                    })?);
                if key.is_empty() {
                    return Err(SignOutboundError::InvalidConfig(format!(
                        "{ENV_SIGN_HMAC_KEY} decoded to zero bytes"
                    )));
                }
                Ok(SigningKeyMaterial::Hmac { kid, key })
            }
            "ed25519" => {
                let sk_b64 = env::var(ENV_SIGN_ED25519_SK).map_err(|_| {
                    SignOutboundError::InvalidConfig(format!(
                        "{ENV_SIGN_ALG}=ed25519 requires {ENV_SIGN_ED25519_SK}"
                    ))
                })?;
                let trimmed = sk_b64.trim().trim_end_matches('=');
                let bytes = URL_SAFE_NO_PAD.decode(trimmed).map_err(|e| {
                    SignOutboundError::InvalidConfig(format!(
                        "{ENV_SIGN_ED25519_SK} is not valid base64url: {e}"
                    ))
                })?;
                let seed: [u8; 32] = bytes.as_slice().try_into().map_err(|_| {
                    SignOutboundError::InvalidConfig(format!(
                        "{ENV_SIGN_ED25519_SK} decoded to {} bytes, expected 32",
                        bytes.len()
                    ))
                })?;
                let signing_key = SigningKey::from_bytes(&seed);
                Ok(SigningKeyMaterial::Ed25519 { kid, signing_key })
            }
            other => Err(SignOutboundError::InvalidConfig(format!(
                "unknown {ENV_SIGN_ALG}={other:?} (expected off, hmac-sha256, or ed25519)"
            ))),
        }
    }
}

// ── Outbound envelope construction ────────────────────────────────────────

/// Outcome of [`host_stamp_and_sign`]: either an unsigned passthrough or a
/// signed envelope, depending on the active [`SigningKeyMaterial`].
#[derive(Debug, Clone)]
pub enum SigningOutcome {
    /// Signing was [`SigningKeyMaterial::Off`]; the bare envelope is emitted.
    Unsigned(CloudEventV1),
    /// Signing was active; the wrapped envelope is emitted.
    Signed(SignedEventEnvelopeV1),
}

impl SigningOutcome {
    /// Borrow the underlying CloudEvent regardless of variant.
    pub fn event(&self) -> &CloudEventV1 {
        match self {
            SigningOutcome::Unsigned(ev) => ev,
            SigningOutcome::Signed(env) => &env.event,
        }
    }
}

/// Build the host-stamped outbound `CloudEventV1` for a guest declaration.
///
/// The `data` payload contains both the guest-declared fields and the
/// host-stamped attribution fields, with a `provenance` marker (literal
/// `"declared"`) so consumers can distinguish guest-declared facts from
/// host-observed ones.
pub fn host_stamped_envelope(
    stamped: &StampedDeclaration,
    event_id: &str,
    source: &str,
    event_type: &str,
) -> Result<CloudEventV1, SignOutboundError> {
    let host_received_unix_secs = stamped
        .host
        .host_received_at
        .duration_since(UNIX_EPOCH)
        .map_err(|e| {
            SignOutboundError::Serialize(format!("host_received_at predates UNIX_EPOCH: {e}"))
        })?
        .as_secs();
    let host_received_at_rfc3339 = format_unix_secs_rfc3339(host_received_unix_secs);

    let data = serde_json::json!({
        "provenance": PROVENANCE_DECLARED,
        "guest": {
            "probeSource": stamped.guest.probe_source,
            "guestPid": stamped.guest.guest_pid,
            "guestComm": stamped.guest.guest_comm,
            "guestMonotonicNs": stamped.guest.guest_monotonic_ns,
        },
        "host": {
            "cellId": stamped.host.cell_id,
            "runId": stamped.host.run_id,
            "hostReceivedAt": host_received_at_rfc3339,
            "specSignatureHash": stamped.host.spec_signature_hash,
        },
    });

    Ok(CloudEventV1 {
        specversion: "1.0".into(),
        id: event_id.to_string(),
        source: source.to_string(),
        ty: event_type.to_string(),
        datacontenttype: Some("application/json".into()),
        data: Some(data),
        time: Some(host_received_at_rfc3339),
        traceparent: None,
    })
}

/// Sign a host-stamped envelope under the active [`SigningKeyMaterial`].
///
/// Returns [`SigningOutcome::Unsigned`] when key material is
/// [`SigningKeyMaterial::Off`], else [`SigningOutcome::Signed`].
pub fn sign_host_stamped_envelope(
    envelope: CloudEventV1,
    material: &SigningKeyMaterial,
) -> Result<SigningOutcome, SignOutboundError> {
    match material {
        SigningKeyMaterial::Off => Ok(SigningOutcome::Unsigned(envelope)),
        SigningKeyMaterial::Hmac { kid, key } => {
            let signed = sign_event_hmac_sha256(&envelope, kid, key)
                .map_err(|e| SignOutboundError::Signer(format!("{e}")))?;
            Ok(SigningOutcome::Signed(signed))
        }
        SigningKeyMaterial::Ed25519 { kid, signing_key } => {
            let signed = sign_event_ed25519(&envelope, kid, signing_key)
                .map_err(|e| SignOutboundError::Signer(format!("{e}")))?;
            Ok(SigningOutcome::Signed(signed))
        }
    }
}

/// Composed: stamp + sign in one call. Most callers want this.
pub fn host_stamp_and_sign(
    stamped: &StampedDeclaration,
    event_id: &str,
    source: &str,
    event_type: &str,
    material: &SigningKeyMaterial,
) -> Result<SigningOutcome, SignOutboundError> {
    let envelope = host_stamped_envelope(stamped, event_id, source, event_type)?;
    sign_host_stamped_envelope(envelope, material)
}

// ── Self-contained RFC3339 formatter ──────────────────────────────────────
//
// We deliberately do NOT pull `chrono` for a single timestamp. The
// `host_received_at` field is `SystemTime`; for the outbound envelope we
// emit RFC3339 / ISO-8601 in UTC at second resolution (matching the
// `time` field convention used elsewhere in the codebase, e.g.
// `cellos_core::events::cloud_event_v1_*`).

/// Format `unix_secs` (seconds since UNIX epoch, UTC) as a Zulu-suffixed
/// RFC3339 timestamp (`"YYYY-MM-DDTHH:MM:SSZ"`). This is the minimal
/// formatter ADR-0006 needs; we avoid `chrono` because the supervisor's
/// existing time emitters already use this exact shape.
fn format_unix_secs_rfc3339(unix_secs: u64) -> String {
    // Algorithm from Howard Hinnant's "date" library / chrono: a closed-form
    // conversion from days-since-epoch to (year, month, day) using a shifted
    // calendar where March is month 1. Tested against std::time / chrono in
    // the unit tests below.
    let secs_per_day: u64 = 86_400;
    let days = (unix_secs / secs_per_day) as i64; // days since 1970-01-01
    let secs_of_day = unix_secs % secs_per_day;
    let hour = (secs_of_day / 3600) as u32;
    let minute = ((secs_of_day % 3600) / 60) as u32;
    let second = (secs_of_day % 60) as u32;

    // Shift epoch from 1970-01-01 to 0000-03-01 (Hinnant's reference).
    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = (z - era * 146_097) as u64; // [0, 146096]
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; // [0, 399]
    let y = yoe as i64 + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
    let mp = (5 * doy + 2) / 153; // [0, 11]
    let d = (doy - (153 * mp + 2) / 5 + 1) as u32; // [1, 31]
    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; // [1, 12]
    let year = if m <= 2 { y + 1 } else { y };

    format!(
        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
        year, m, d, hour, minute, second
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::sync::Mutex;
    use std::time::Duration;

    use cellos_core::trust_keys::verify_signed_event_envelope;

    // Env-mutating tests are serialized via this module-level mutex so
    // parallel cargo-test runs don't race on the process-global env table.
    // Tests that don't touch env do NOT need to take the lock.
    static ENV_MUTEX: Mutex<()> = Mutex::new(());

    fn fixture_decl() -> StampedDeclaration {
        StampedDeclaration {
            guest: GuestDeclaration {
                probe_source: "process_spawned".into(),
                guest_pid: 4242,
                guest_comm: "curl".into(),
                guest_monotonic_ns: 1_234_567_890,
            },
            host: HostStamp {
                cell_id: "cell-abc".into(),
                run_id: "run-xyz".into(),
                // Arbitrary fixed instant; only used to exercise stamping.
                host_received_at: UNIX_EPOCH + Duration::from_secs(1_762_348_800),
                spec_signature_hash: "sha256:deadbeef".into(),
            },
        }
    }

    fn signing_key(seed: u8) -> SigningKey {
        SigningKey::from_bytes(&[seed; 32])
    }

    fn clear_sign_env() {
        // SAFETY: process-wide env mutation is guarded by ENV_MUTEX.
        std::env::remove_var(ENV_SIGN_ALG);
        std::env::remove_var(ENV_SIGN_KID);
        std::env::remove_var(ENV_SIGN_HMAC_KEY);
        std::env::remove_var(ENV_SIGN_ED25519_SK);
    }

    // 1. HMAC round-trip ----------------------------------------------------

    #[test]
    fn hmac_round_trip_verifies_via_projector_path() {
        let key = b"f4b-shared-symmetric-key-for-tests";
        let material = SigningKeyMaterial::Hmac {
            kid: "ops-host-telem-2026-q2".into(),
            key: Zeroizing::new(key.to_vec()),
        };
        let outcome = host_stamp_and_sign(
            &fixture_decl(),
            "ev-hmac-001",
            "/cellos-supervisor/host-telemetry",
            "dev.cellos.events.cell.observability.guest.process_spawned",
            &material,
        )
        .expect("sign ok");
        let envelope = match outcome {
            SigningOutcome::Signed(env) => env,
            SigningOutcome::Unsigned(_) => panic!("expected Signed"),
        };
        assert_eq!(envelope.algorithm, "hmac-sha256");
        assert_eq!(envelope.signer_kid, "ops-host-telem-2026-q2");

        let verifying_keys: HashMap<String, _> = HashMap::new();
        let mut hmac_keys: HashMap<String, Vec<u8>> = HashMap::new();
        hmac_keys.insert("ops-host-telem-2026-q2".into(), key.to_vec());
        let verified = verify_signed_event_envelope(&envelope, &verifying_keys, &hmac_keys)
            .expect("hmac round-trip must verify");
        assert_eq!(verified.id, "ev-hmac-001");
    }

    // 2. Ed25519 round-trip -------------------------------------------------

    #[test]
    fn ed25519_round_trip_verifies_via_projector_path() {
        let signer = signing_key(13);
        let material = SigningKeyMaterial::Ed25519 {
            kid: "ops-host-telem-ed-2026-q2".into(),
            signing_key: signer.clone(),
        };
        let outcome = host_stamp_and_sign(
            &fixture_decl(),
            "ev-ed25519-001",
            "/cellos-supervisor/host-telemetry",
            "dev.cellos.events.cell.observability.guest.process_spawned",
            &material,
        )
        .expect("sign ok");
        let envelope = match outcome {
            SigningOutcome::Signed(env) => env,
            SigningOutcome::Unsigned(_) => panic!("expected Signed"),
        };
        assert_eq!(envelope.algorithm, "ed25519");

        let mut verifying_keys: HashMap<String, _> = HashMap::new();
        verifying_keys.insert("ops-host-telem-ed-2026-q2".into(), signer.verifying_key());
        let hmac_keys: HashMap<String, Vec<u8>> = HashMap::new();
        let verified = verify_signed_event_envelope(&envelope, &verifying_keys, &hmac_keys)
            .expect("ed25519 round-trip must verify");
        assert_eq!(verified.id, "ev-ed25519-001");
    }

    // 3. Mutation-post-sign rejected (O2 doctrine) -------------------------

    #[test]
    fn mutating_event_after_sign_breaks_verification() {
        let signer = signing_key(17);
        let material = SigningKeyMaterial::Ed25519 {
            kid: "kid-mut".into(),
            signing_key: signer.clone(),
        };
        let outcome = host_stamp_and_sign(
            &fixture_decl(),
            "ev-mut-001",
            "/cellos-supervisor/host-telemetry",
            "dev.cellos.events.cell.observability.guest.process_spawned",
            &material,
        )
        .expect("sign ok");
        let mut envelope = match outcome {
            SigningOutcome::Signed(env) => env,
            SigningOutcome::Unsigned(_) => panic!("expected Signed"),
        };

        // O2: tampering with the host-stamped attribution must invalidate
        // the signature. Mutate the inner data.host.cellId.
        if let Some(serde_json::Value::Object(map)) = envelope.event.data.as_mut() {
            if let Some(serde_json::Value::Object(host)) = map.get_mut("host") {
                host.insert(
                    "cellId".into(),
                    serde_json::Value::String("cell-EVIL".into()),
                );
            }
        }

        let mut verifying_keys: HashMap<String, _> = HashMap::new();
        verifying_keys.insert("kid-mut".into(), signer.verifying_key());
        let hmac_keys: HashMap<String, Vec<u8>> = HashMap::new();
        let err = verify_signed_event_envelope(&envelope, &verifying_keys, &hmac_keys)
            .expect_err("post-sign mutation must be rejected");
        let msg = format!("{err}");
        assert!(
            msg.contains("ed25519 verify failed"),
            "expected ed25519 verify failure, got: {msg}"
        );
    }

    // 4. Off mode passthrough ----------------------------------------------

    #[test]
    fn off_mode_emits_unsigned_passthrough() {
        let outcome = host_stamp_and_sign(
            &fixture_decl(),
            "ev-off-001",
            "/cellos-supervisor/host-telemetry",
            "dev.cellos.events.cell.observability.guest.process_spawned",
            &SigningKeyMaterial::Off,
        )
        .expect("off-mode stamp ok");
        match outcome {
            SigningOutcome::Unsigned(ev) => {
                assert_eq!(ev.id, "ev-off-001");
                let data = ev.data.expect("data present");
                assert_eq!(data["provenance"], "declared");
                assert_eq!(data["host"]["cellId"], "cell-abc");
            }
            SigningOutcome::Signed(_) => panic!("Off must passthrough"),
        }
    }

    // 5. Env load HMAC ------------------------------------------------------

    #[test]
    fn env_load_hmac_round_trips_a_signed_envelope() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|p| p.into_inner());
        clear_sign_env();
        let key = b"env-hmac-key-for-from_env-test";
        std::env::set_var(ENV_SIGN_ALG, "hmac-sha256");
        std::env::set_var(ENV_SIGN_KID, "kid-from-env");
        std::env::set_var(ENV_SIGN_HMAC_KEY, URL_SAFE_NO_PAD.encode(key));

        let material = SigningKeyMaterial::from_env().expect("from_env hmac ok");
        clear_sign_env();

        assert!(!material.is_off());
        assert_eq!(material.kid(), Some("kid-from-env"));

        let outcome = host_stamp_and_sign(
            &fixture_decl(),
            "ev-env-hmac",
            "/cellos-supervisor/host-telemetry",
            "dev.cellos.events.cell.observability.guest.process_spawned",
            &material,
        )
        .expect("sign ok");
        let envelope = match outcome {
            SigningOutcome::Signed(env) => env,
            SigningOutcome::Unsigned(_) => panic!("expected Signed"),
        };
        assert_eq!(envelope.algorithm, "hmac-sha256");

        let mut hmac_keys: HashMap<String, Vec<u8>> = HashMap::new();
        hmac_keys.insert("kid-from-env".into(), key.to_vec());
        let verifying: HashMap<String, _> = HashMap::new();
        verify_signed_event_envelope(&envelope, &verifying, &hmac_keys)
            .expect("env-loaded hmac must verify");
    }

    // 6. Env load Off -------------------------------------------------------

    #[test]
    fn env_load_unset_yields_off() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|p| p.into_inner());
        clear_sign_env();
        let material = SigningKeyMaterial::from_env().expect("unset env -> Off");
        assert!(material.is_off());
        assert_eq!(material.kid(), None);

        // Explicit "off" is also accepted.
        std::env::set_var(ENV_SIGN_ALG, "off");
        let material2 = SigningKeyMaterial::from_env().expect("explicit off");
        clear_sign_env();
        assert!(material2.is_off());
    }

    // 7. Env mutual-exclusion rejection ------------------------------------

    #[test]
    fn env_load_rejects_both_hmac_and_ed25519_keys_set() {
        let _guard = ENV_MUTEX.lock().unwrap_or_else(|p| p.into_inner());
        clear_sign_env();
        std::env::set_var(ENV_SIGN_ALG, "ed25519");
        std::env::set_var(ENV_SIGN_KID, "kid-conflict");
        std::env::set_var(ENV_SIGN_HMAC_KEY, URL_SAFE_NO_PAD.encode(b"hmac"));
        std::env::set_var(ENV_SIGN_ED25519_SK, URL_SAFE_NO_PAD.encode([0u8; 32]));

        let err = SigningKeyMaterial::from_env().expect_err("both keys set must be rejected");
        clear_sign_env();
        let msg = format!("{err}");
        assert!(
            msg.contains("mutual-exclusion"),
            "expected mutual-exclusion error, got: {msg}"
        );
    }

    // 8. Debug never prints key bytes --------------------------------------

    #[test]
    fn debug_format_does_not_leak_key_bytes() {
        let secret_pattern = b"NEVER-EVER-LOG-THIS-SECRET-XYZZY";
        let hmac = SigningKeyMaterial::Hmac {
            kid: "kid-redact".into(),
            key: Zeroizing::new(secret_pattern.to_vec()),
        };
        let dbg = format!("{:?}", hmac);
        assert!(
            !dbg.contains("NEVER-EVER-LOG-THIS-SECRET"),
            "Debug for Hmac MUST NOT print key bytes: {dbg}"
        );
        assert!(dbg.contains("kid-redact"));
        assert!(dbg.contains("redacted"));

        // Ed25519 — also redact.
        let signer = signing_key(99);
        let ed = SigningKeyMaterial::Ed25519 {
            kid: "kid-ed-redact".into(),
            signing_key: signer.clone(),
        };
        let dbg_ed = format!("{:?}", ed);
        // Bytes 0x99 (decimal 153) repeated 32 times — check the seed string
        // representation never appears in debug.
        let seed_hex: String = signer
            .to_bytes()
            .iter()
            .map(|b| format!("{:02x}", b))
            .collect();
        assert!(
            !dbg_ed.contains(&seed_hex),
            "Debug for Ed25519 MUST NOT print key bytes: {dbg_ed}"
        );
        assert!(dbg_ed.contains("kid-ed-redact"));
        assert!(dbg_ed.contains("redacted"));

        // Off variant has nothing to leak — but ensure Debug does not panic.
        let off = SigningKeyMaterial::Off;
        let dbg_off = format!("{:?}", off);
        assert!(dbg_off.contains("Off"));
    }

    // 9. End-to-end guest -> host-stamp -> sign -> projector-verify --------

    #[test]
    fn end_to_end_guest_to_projector_verify() {
        // Producer side: build the full pipeline as the supervisor will.
        let signer = signing_key(23);
        let material = SigningKeyMaterial::Ed25519 {
            kid: "kid-e2e".into(),
            signing_key: signer.clone(),
        };
        let stamped = fixture_decl();

        let outcome = host_stamp_and_sign(
            &stamped,
            "ev-e2e-001",
            "/cellos-supervisor/host-telemetry",
            "dev.cellos.events.cell.observability.guest.process_spawned",
            &material,
        )
        .expect("e2e sign ok");
        let signed = match outcome {
            SigningOutcome::Signed(env) => env,
            SigningOutcome::Unsigned(_) => panic!("expected Signed"),
        };

        // Wire the signed envelope through serde to mimic JetStream transit.
        let wire = serde_json::to_vec(&signed).expect("serialize");
        let arrived: SignedEventEnvelopeV1 = serde_json::from_slice(&wire).expect("deserialize");

        // Projector side: verify with the public key.
        let mut verifying: HashMap<String, _> = HashMap::new();
        verifying.insert("kid-e2e".into(), signer.verifying_key());
        let hmac_keys: HashMap<String, Vec<u8>> = HashMap::new();
        let event = verify_signed_event_envelope(&arrived, &verifying, &hmac_keys)
            .expect("projector verify");

        // Confirm the host-stamped attribution survived the round trip
        // intact AND is still the source of truth (overrode any guest-claimed
        // values per ADR-0006 §6).
        assert_eq!(event.id, "ev-e2e-001");
        assert_eq!(
            event.ty,
            "dev.cellos.events.cell.observability.guest.process_spawned"
        );
        let data = event.data.as_ref().expect("data");
        assert_eq!(data["provenance"], "declared");
        assert_eq!(data["host"]["cellId"], "cell-abc");
        assert_eq!(data["host"]["runId"], "run-xyz");
        assert_eq!(data["host"]["specSignatureHash"], "sha256:deadbeef");
        assert_eq!(data["guest"]["probeSource"], "process_spawned");
    }

    // ── Bonus coverage for the self-contained RFC3339 formatter ──────────

    #[test]
    fn rfc3339_formatter_matches_known_anchors() {
        // Epoch zero — definitionally fixed.
        assert_eq!(format_unix_secs_rfc3339(0), "1970-01-01T00:00:00Z");

        // One day later — exercises the day-rollover path.
        assert_eq!(format_unix_secs_rfc3339(86_400), "1970-01-02T00:00:00Z");

        // Time-of-day component: 1h1m1s past epoch.
        assert_eq!(format_unix_secs_rfc3339(3_661), "1970-01-01T01:01:01Z");

        // 2000-01-01T00:00:00Z is a well-known anchor (946684800 = 30 years
        // of seconds with 7 leap days: 30*365*86400 + 7*86400 = 946684800).
        assert_eq!(
            format_unix_secs_rfc3339(946_684_800),
            "2000-01-01T00:00:00Z"
        );

        // Leap-year edge: 2020-01-01 anchor = 50*365*86400 + 12*86400 leap
        // days (1972/76/80/84/88/92/96/2000/04/08/12/16) = 1577836800. Feb 29
        // is day index 59 from Jan 1 → +59*86400 + 12*3600 + 34*60 + 56
        // = 1582934400 + 45296 = 1582979696.
        assert_eq!(
            format_unix_secs_rfc3339(1_582_979_696),
            "2020-02-29T12:34:56Z"
        );
    }
}