treeship-core 0.12.0

Portable trust receipts for agent workflows - core library
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
//! Trust root pinning for self-signed verification surfaces.
//!
//! Three verification paths in Treeship trust a public key that travels
//! inside the artifact they're verifying:
//!
//! 1. `Checkpoint::verify` — the Merkle checkpoint's `public_key` field.
//! 2. `verify_hub_checkpoint_signature` — the `hub_public_key` field of a
//!    `JournalCheckpoint` of kind `hub-org`.
//! 3. `verify_certificate` — the Agent Certificate's
//!    `signature.public_key` field.
//!
//! Without an external pin every one of these is self-signed: an attacker
//! who mints a new keypair, embeds the public key in the artifact, signs
//! over the canonical bytes, and presents the result will verify.
//!
//! `TrustRootStore` is the pin: a small JSON file at
//! `~/.treeship/trust_roots.json` listing every public key the operator
//! has decided to trust as an issuer, keyed by `kind`. The three
//! verification functions reject any embedded public key that is not in
//! the store for the matching kind.
//!
//! The store deliberately mirrors the keystore: same `~/.treeship`
//! directory, same `0o600` permission expectation, same JSON-on-disk
//! shape. There is no remote sync in this release — operators add roots
//! by hand via `treeship trust add` after verifying the key fingerprint
//! out-of-band (`treeship hub sync-trust` is referenced in error
//! messages as the forward-looking automation hook).

use std::{
    fs,
    io::{self, Read},
    path::{Path, PathBuf},
    sync::Once,
};

use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use ed25519_dalek::VerifyingKey;
use serde::{Deserialize, Serialize};

// Audit lane J fix-up: warn once per process when an env var override
// is in effect. Silently honoring TREESHIP_TRUST_ROOTS or
// TREESHIP_ALLOW_INSECURE_KEY_PERMS is exactly the kind of thing a
// supply-chain attacker would set in a CI runner to redirect trust to
// a key they control. The warning shows up in stderr at every load
// (once, deduplicated) so it lands in CI logs.
static WARN_TRUST_PATH_OVERRIDE_ONCE: Once = Once::new();
static WARN_INSECURE_PERMS_ONCE: Once = Once::new();

fn warn_trust_path_override_if_set() {
    if let Some(p) = std::env::var_os("TREESHIP_TRUST_ROOTS") {
        WARN_TRUST_PATH_OVERRIDE_ONCE.call_once(|| {
            eprintln!(
                "treeship: WARNING: trust store path overridden by TREESHIP_TRUST_ROOTS={} (not the default ~/.treeship/trust_roots.json)",
                std::path::Path::new(&p).display(),
            );
        });
    }
}

fn warn_insecure_perms_if_bypassed() {
    if std::env::var_os("TREESHIP_ALLOW_INSECURE_KEY_PERMS")
        .map(|v| v == "1")
        .unwrap_or(false)
    {
        WARN_INSECURE_PERMS_ONCE.call_once(|| {
            eprintln!(
                "treeship: WARNING: trust file permission check bypassed by TREESHIP_ALLOW_INSECURE_KEY_PERMS=1 -- this opens a supply-chain hole if not a deliberate CI sandbox override"
            );
        });
    }
}

/// What this trust root is allowed to verify. Encoded kebab-case in JSON
/// because the rest of the codebase (CheckpointKind, etc.) does the same.
///
/// Adding a variant is a wire-format event: every JSON consumer that
/// matches exhaustively on this enum must add the new arm in the same
/// release. Phase 1 of the agent-invitations spec adds `SessionHost`
/// for invitation issuer pinning; that addition is called out as a
/// breaking change in the CHANGELOG for the same release.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TrustRootKind {
    /// Merkle `Checkpoint` produced by `treeship merkle checkpoint`. This is
    /// the ship-local journal checkpoint, distinct from the hub-org
    /// JournalCheckpoint kind below.
    HubCheckpoint,
    /// `JournalCheckpoint` of kind `hub-org` -- signed by a remote Hub to
    /// promote a local journal claim to a global single-use claim.
    Ship,
    /// `AgentCertificate` issued by a ship to one of its agents.
    AgentCert,
    /// Phase 1 of agent invitations: the host's signing key that mints
    /// `InvitationStatement` envelopes. Verifiers (and the
    /// `treeship session join` flow) require the invitation's issuer
    /// pubkey to be present in the trust root store under this kind
    /// before honoring the invitation. Separate from `Ship` so a
    /// machine can trust hub-org checkpoints without implicitly
    /// trusting that hub to host multi-agent rooms.
    SessionHost,
}

impl TrustRootKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::HubCheckpoint => "hub_checkpoint",
            Self::Ship          => "ship",
            Self::AgentCert     => "agent_cert",
            Self::SessionHost   => "session_host",
        }
    }

    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "hub_checkpoint" => Some(Self::HubCheckpoint),
            "ship"           => Some(Self::Ship),
            "agent_cert"     => Some(Self::AgentCert),
            "session_host"   => Some(Self::SessionHost),
            _                => None,
        }
    }
}

/// One pinned trust root.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TrustRoot {
    /// Opaque identifier. Matches the existing `KeyId` format used elsewhere,
    /// but the trust store does not require any particular shape -- any
    /// non-empty string is accepted so operators can use human labels like
    /// `hub_zerker_labs`.
    pub key_id: String,

    /// Public key encoded as `ed25519:<base64url-no-pad>`. The prefix is
    /// required so the format stays algorithm-agnostic when we add more
    /// signature schemes; today only `ed25519` is recognized.
    pub public_key: String,

    /// What this root is allowed to verify.
    pub kind: TrustRootKind,

    /// Human-readable label. Shown by `treeship trust list`. Optional in
    /// the file format; defaults to the empty string.
    #[serde(default)]
    pub label: String,

    /// RFC 3339 timestamp the root was added. Useful for auditing.
    #[serde(default)]
    pub added_at: String,
}

/// On-disk wire format. A separate type so we can evolve the file without
/// breaking the public `TrustRoot` API.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TrustRootFile {
    /// Schema version. Currently `1`.
    pub version: u8,
    pub roots:   Vec<TrustRoot>,
}

const SCHEMA_VERSION: u8 = 1;

/// In-memory view of the trust root file.
#[derive(Debug, Clone, Default)]
pub struct TrustRootStore {
    roots: Vec<TrustRoot>,
}

/// Errors loading or operating on a trust root file.
#[derive(Debug)]
pub enum TrustRootError {
    /// The file does not exist. The caller should surface the actionable
    /// remediation: run `treeship trust add` (or sync from a hub).
    NotConfigured { path: PathBuf },
    /// JSON parse or schema validation failed.
    Malformed { path: PathBuf, msg: String },
    /// The file exists and is well-formed but contains zero roots. Treated
    /// the same as `NotConfigured` by verifiers but kept distinct so the
    /// CLI can show a more targeted error.
    Empty { path: PathBuf },
    /// File mode allows group or world access. Refuse to load.
    PermissionsTooOpen { path: PathBuf, mode: u32 },
    /// Underlying I/O failure (read, write, mkdir).
    Io(io::Error),
}

impl std::fmt::Display for TrustRootError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotConfigured { path } => write!(
                f,
                "no trust roots configured (looked for {}). \
                 Run `treeship trust add <key_id> <pubkey> --kind <kind>` \
                 or sync from your hub via `treeship hub sync-trust`.",
                path.display(),
            ),
            Self::Malformed { path, msg } => write!(
                f,
                "trust root file {} is malformed: {msg}",
                path.display(),
            ),
            Self::Empty { path } => write!(
                f,
                "trust root file {} has no roots configured. \
                 Run `treeship trust add <key_id> <pubkey> --kind <kind>` \
                 to add an issuer.",
                path.display(),
            ),
            Self::PermissionsTooOpen { path, mode } => write!(
                f,
                "trust root file {} has insecure permissions (mode {:o}); \
                 chmod 600 the file and try again.",
                path.display(),
                mode & 0o777,
            ),
            Self::Io(e) => write!(f, "trust root io: {e}"),
        }
    }
}

impl std::error::Error for TrustRootError {}

impl From<io::Error> for TrustRootError {
    fn from(e: io::Error) -> Self { Self::Io(e) }
}

impl TrustRootStore {
    /// Default file location: `~/.treeship/trust_roots.json`.
    ///
    /// The `TREESHIP_TRUST_ROOTS` env var overrides the path. When set,
    /// a one-time warning is emitted on stderr (deduplicated per
    /// process via `std::sync::Once`) so CI logs show that the trust
    /// boundary moved.
    pub fn default_path() -> PathBuf {
        warn_trust_path_override_if_set();
        std::env::var_os("TREESHIP_TRUST_ROOTS")
            .map(PathBuf::from)
            .unwrap_or_else(|| {
                let home = std::env::var("HOME").unwrap_or_default();
                PathBuf::from(home).join(".treeship").join("trust_roots.json")
            })
    }

    /// Construct an empty in-memory store. Useful for tests; the
    /// verification path treats an empty store the same as a missing
    /// file (no trust configured).
    pub fn empty() -> Self {
        Self { roots: Vec::new() }
    }

    /// Construct a store from an explicit list of roots. Tests use this
    /// to thread a known trust set into the verifier; production callers
    /// should `open` the on-disk file.
    pub fn with_roots(roots: Vec<TrustRoot>) -> Self {
        Self { roots }
    }

    /// Convenience wrapper for code paths that want to "load if
    /// present, otherwise treat as no-trust-configured". Returns an
    /// empty store on `NotConfigured`/`Empty`, propagates `Malformed`
    /// and `PermissionsTooOpen` (operator misconfiguration that
    /// shouldn't silently downgrade to empty).
    pub fn open_or_empty(path: &Path) -> Result<Self, TrustRootError> {
        match Self::open(path) {
            Ok(s)                                          => Ok(s),
            Err(TrustRootError::NotConfigured { .. })      => Ok(Self::empty()),
            Err(TrustRootError::Empty { .. })              => Ok(Self::empty()),
            Err(e)                                         => Err(e),
        }
    }

    /// Convenience: open the default-path file or return empty if it's
    /// missing. Loud on malformed/perms errors. Suitable for the
    /// "thread trust through internal verify pipelines" use case.
    pub fn open_default_or_empty() -> Result<Self, TrustRootError> {
        Self::open_or_empty(&Self::default_path())
    }

    /// Open the trust root file at `path`. Returns `NotConfigured` if it
    /// does not exist, `Empty` if it exists but has zero roots.
    ///
    /// TOCTOU note: the file is opened ONCE, then the perm check runs
    /// on the resulting `File` (fstat on the fd), and the JSON bytes
    /// are read from the SAME fd. The path is never re-resolved after
    /// the open, so an attacker with write access to `~/.treeship/`
    /// cannot swap `trust_roots.json` between the perm gate and the
    /// content read. Mirrors the keystore single-open shape in
    /// `keys/mod.rs::read_entry_with_perm_check`.
    pub fn open(path: &Path) -> Result<Self, TrustRootError> {
        let mut file = match fs::File::open(path) {
            Ok(f) => f,
            Err(e) if e.kind() == io::ErrorKind::NotFound => {
                return Err(TrustRootError::NotConfigured { path: path.to_path_buf() });
            }
            Err(e) => return Err(TrustRootError::Io(e)),
        };
        check_open_trust_file_perms(path, &file)?;
        let mut bytes = Vec::new();
        file.read_to_end(&mut bytes)?;
        let file: TrustRootFile = serde_json::from_slice(&bytes)
            .map_err(|e| TrustRootError::Malformed {
                path: path.to_path_buf(),
                msg:  e.to_string(),
            })?;
        if file.version != SCHEMA_VERSION {
            return Err(TrustRootError::Malformed {
                path: path.to_path_buf(),
                msg:  format!(
                    "schema version mismatch: file has v{}, this binary supports v{}",
                    file.version, SCHEMA_VERSION,
                ),
            });
        }
        // Validate every embedded public key parses now -- catch a
        // malformed key at load time rather than at verify time.
        for root in &file.roots {
            decode_ed25519_pubkey(&root.public_key)
                .map_err(|msg| TrustRootError::Malformed {
                    path: path.to_path_buf(),
                    msg:  format!("root {}: {msg}", root.key_id),
                })?;
        }
        if file.roots.is_empty() {
            return Err(TrustRootError::Empty { path: path.to_path_buf() });
        }
        Ok(Self { roots: file.roots })
    }

    /// Save the store to `path`. Creates parent directories with mode
    /// 0o700 and writes the file with mode 0o600.
    pub fn save(&self, path: &Path) -> Result<(), TrustRootError> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let _ = fs::set_permissions(parent, fs::Permissions::from_mode(0o700));
            }
        }
        let file = TrustRootFile {
            version: SCHEMA_VERSION,
            roots:   self.roots.clone(),
        };
        let json = serde_json::to_vec_pretty(&file)
            .map_err(|e| TrustRootError::Malformed {
                path: path.to_path_buf(),
                msg:  e.to_string(),
            })?;
        fs::write(path, &json)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
        }
        Ok(())
    }

    /// Returns true if `key` is pinned for `kind`. The CLI helper does
    /// not pre-decode; callers that already hold a `VerifyingKey` should
    /// use this directly.
    pub fn contains(&self, key: &VerifyingKey, kind: TrustRootKind) -> bool {
        let key_bytes = key.to_bytes();
        self.roots.iter().any(|r| {
            r.kind == kind
                && decode_ed25519_pubkey(&r.public_key)
                    .map(|k| k.to_bytes() == key_bytes)
                    .unwrap_or(false)
        })
    }

    /// Convenience: lookup against a raw 32-byte Ed25519 key without first
    /// constructing a `VerifyingKey`. Returns false if the bytes are not
    /// a valid public key (mirrors the verifier's reject-on-decode-failure
    /// behavior).
    pub fn contains_bytes(&self, key_bytes: &[u8; 32], kind: TrustRootKind) -> bool {
        match VerifyingKey::from_bytes(key_bytes) {
            Ok(vk) => self.contains(&vk, kind),
            Err(_) => false,
        }
    }

    /// True when the store carries zero pinned roots. Verifiers reject
    /// any artifact when this returns true with a clear "configure trust"
    /// error.
    pub fn is_empty(&self) -> bool {
        self.roots.is_empty()
    }

    /// True when the store has no pinned root of `kind`. Used by
    /// verifiers to surface a kind-specific error message when an
    /// operator has set up `agent_cert` trust but is verifying a
    /// `hub_checkpoint` (or vice versa).
    pub fn is_empty_for_kind(&self, kind: TrustRootKind) -> bool {
        !self.roots.iter().any(|r| r.kind == kind)
    }

    /// Append a root. Idempotent: re-adding the same `(key_id, kind)`
    /// pair replaces the previous entry. The CLI `treeship trust add`
    /// goes through here.
    pub fn add(&mut self, root: TrustRoot) {
        self.roots.retain(|r| !(r.key_id == root.key_id && r.kind == root.kind));
        self.roots.push(root);
    }

    /// Remove a root by `key_id`. Returns true if a root was removed.
    /// Removes every entry matching the id across all kinds.
    pub fn remove(&mut self, key_id: &str) -> bool {
        let before = self.roots.len();
        self.roots.retain(|r| r.key_id != key_id);
        self.roots.len() != before
    }

    /// Iterate over every root.
    pub fn roots(&self) -> &[TrustRoot] {
        &self.roots
    }

    /// Number of roots configured.
    pub fn len(&self) -> usize {
        self.roots.len()
    }
}

/// Decode an `ed25519:<base64url>` or bare base64url public key into a
/// `VerifyingKey`. The `ed25519:` prefix is the canonical form; the bare
/// form is accepted for forward-compatibility with operator-typed input.
pub fn decode_ed25519_pubkey(s: &str) -> Result<VerifyingKey, String> {
    let b64 = s.strip_prefix("ed25519:").unwrap_or(s);
    let bytes = URL_SAFE_NO_PAD
        .decode(b64)
        .map_err(|e| format!("base64url decode failed: {e}"))?;
    let arr: [u8; 32] = bytes
        .as_slice()
        .try_into()
        .map_err(|_| format!("expected 32-byte public key, got {} bytes", bytes.len()))?;
    VerifyingKey::from_bytes(&arr).map_err(|e| format!("not a valid Ed25519 public key: {e}"))
}

/// Encode a `VerifyingKey` into the canonical `ed25519:<base64url>` form.
pub fn encode_ed25519_pubkey(key: &VerifyingKey) -> String {
    format!("ed25519:{}", URL_SAFE_NO_PAD.encode(key.to_bytes()))
}

#[allow(dead_code)]
fn check_trust_file_perms(path: &Path) -> Result<(), TrustRootError> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        // Honour the same bypass the keystore honors -- CI sandboxes and
        // recovery flows occasionally need to load on a loose-perm file.
        // Audit lane J fix-up: this bypass is a supply-chain hole if
        // set by a malicious build script. Emit a one-time stderr
        // warning every time it's honoured so CI logs surface it.
        if std::env::var_os("TREESHIP_ALLOW_INSECURE_KEY_PERMS")
            .map(|v| v == "1")
            .unwrap_or(false)
        {
            warn_insecure_perms_if_bypassed();
            return Ok(());
        }
        let meta = fs::metadata(path)?;
        let mode = meta.permissions().mode();
        if mode & 0o077 != 0 {
            return Err(TrustRootError::PermissionsTooOpen {
                path: path.to_path_buf(),
                mode,
            });
        }
    }
    let _ = path;
    Ok(())
}

/// Race-free perm gate for the trust root file: fstat on the
/// already-open `File`. The caller opens the file once, hands the
/// resulting `File` to this function, then reads JSON from the SAME
/// `File`. The path is never re-resolved, so a swap between the perm
/// check and the read cannot influence which bytes back the trust
/// roots we hand to the verifier.
///
/// `path` is carried only for error reporting; the gate operates on
/// the fd's inode, not the path. Bypass via
/// `TREESHIP_ALLOW_INSECURE_KEY_PERMS=1` is honored identically to
/// `check_trust_file_perms`.
#[allow(unused_variables)]
fn check_open_trust_file_perms(path: &Path, file: &fs::File) -> Result<(), TrustRootError> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if std::env::var_os("TREESHIP_ALLOW_INSECURE_KEY_PERMS")
            .map(|v| v == "1")
            .unwrap_or(false)
        {
            warn_insecure_perms_if_bypassed();
            return Ok(());
        }
        let meta = file.metadata()?;
        let mode = meta.permissions().mode();
        if mode & 0o077 != 0 {
            return Err(TrustRootError::PermissionsTooOpen {
                path: path.to_path_buf(),
                mode,
            });
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn tmp_dir(tag: &str) -> PathBuf {
        let mut p = std::env::temp_dir();
        let mut b = [0u8; 4];
        use rand::RngCore;
        rand::thread_rng().fill_bytes(&mut b);
        p.push(format!("treeship-trust-test-{tag}-{}", hex::encode(b)));
        std::fs::create_dir_all(&p).unwrap();
        p
    }

    fn cleanup(p: &Path) {
        let _ = fs::remove_dir_all(p);
    }

    fn fresh_root(key_id: &str, kind: TrustRootKind) -> (SigningKey, TrustRoot) {
        let sk = SigningKey::generate(&mut rand::thread_rng());
        let pk = sk.verifying_key();
        let root = TrustRoot {
            key_id:     key_id.into(),
            public_key: encode_ed25519_pubkey(&pk),
            kind,
            label:      format!("test root {key_id}"),
            added_at:   "2026-05-15T00:00:00Z".into(),
        };
        (sk, root)
    }

    #[test]
    fn roundtrip_save_load() {
        let dir = tmp_dir("roundtrip");
        let path = dir.join("trust_roots.json");
        let (_, r1) = fresh_root("hub_a", TrustRootKind::HubCheckpoint);
        let (_, r2) = fresh_root("ship_b", TrustRootKind::Ship);
        let store = TrustRootStore::with_roots(vec![r1.clone(), r2.clone()]);
        store.save(&path).unwrap();
        let loaded = TrustRootStore::open(&path).unwrap();
        assert_eq!(loaded.roots().len(), 2);
        assert_eq!(loaded.roots()[0], r1);
        assert_eq!(loaded.roots()[1], r2);
        cleanup(&dir);
    }

    #[test]
    fn rejects_missing_file() {
        let dir = tmp_dir("missing");
        let path = dir.join("nope.json");
        match TrustRootStore::open(&path).unwrap_err() {
            TrustRootError::NotConfigured { path: p } => assert_eq!(p, path),
            other => panic!("expected NotConfigured, got {other:?}"),
        }
        cleanup(&dir);
    }

    #[test]
    fn rejects_malformed_json() {
        let dir = tmp_dir("malformed");
        let path = dir.join("trust_roots.json");
        fs::write(&path, b"{ this is not json").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
        }
        match TrustRootStore::open(&path).unwrap_err() {
            TrustRootError::Malformed { path: p, .. } => assert_eq!(p, path),
            other => panic!("expected Malformed, got {other:?}"),
        }
        cleanup(&dir);
    }

    #[test]
    fn rejects_empty_roots() {
        let dir = tmp_dir("empty");
        let path = dir.join("trust_roots.json");
        let file = serde_json::json!({"version": 1, "roots": []});
        fs::write(&path, serde_json::to_vec_pretty(&file).unwrap()).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
        }
        match TrustRootStore::open(&path).unwrap_err() {
            TrustRootError::Empty { path: p } => assert_eq!(p, path),
            other => panic!("expected Empty, got {other:?}"),
        }
        cleanup(&dir);
    }

    #[test]
    #[cfg(unix)]
    fn permission_too_open_warns() {
        use std::os::unix::fs::PermissionsExt;
        // Ensure the bypass env var isn't leaking in from the host.
        std::env::remove_var("TREESHIP_ALLOW_INSECURE_KEY_PERMS");

        let dir = tmp_dir("perms");
        let path = dir.join("trust_roots.json");
        let (_, r) = fresh_root("hub_a", TrustRootKind::HubCheckpoint);
        let file = TrustRootFile { version: SCHEMA_VERSION, roots: vec![r] };
        fs::write(&path, serde_json::to_vec_pretty(&file).unwrap()).unwrap();
        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();

        match TrustRootStore::open(&path).unwrap_err() {
            TrustRootError::PermissionsTooOpen { path: p, mode } => {
                assert_eq!(p, path);
                assert_eq!(mode & 0o777, 0o644);
            }
            other => panic!("expected PermissionsTooOpen, got {other:?}"),
        }
        cleanup(&dir);
    }

    /// v0.10.4 P2 sibling fix: the trust root loader now opens the
    /// file ONCE and fstat's the resulting fd, mirroring the keystore
    /// single-open shape. This test pins the gate behavior on a
    /// loose-perm file: the single-open `open()` path must reject
    /// without ever parsing the body. (The pre-fix path-based check
    /// also rejected on loose perms; what changed is that the gate
    /// now runs on the SAME inode the body read would use, closing
    /// the TOCTOU window.)
    #[test]
    #[cfg(unix)]
    fn open_rejects_loose_perms_on_open_fd() {
        use std::os::unix::fs::PermissionsExt;
        std::env::remove_var("TREESHIP_ALLOW_INSECURE_KEY_PERMS");

        let dir = tmp_dir("perms-fd");
        let path = dir.join("trust_roots.json");
        let (_, r) = fresh_root("hub_b", TrustRootKind::HubCheckpoint);
        let file = TrustRootFile { version: SCHEMA_VERSION, roots: vec![r] };
        // Valid JSON body -- proves the gate stops us before we
        // parse, since a successful parse would have returned a
        // populated store rather than the perms error.
        fs::write(&path, serde_json::to_vec_pretty(&file).unwrap()).unwrap();
        fs::set_permissions(&path, fs::Permissions::from_mode(0o640)).unwrap();

        let err = TrustRootStore::open(&path).unwrap_err();
        match err {
            TrustRootError::PermissionsTooOpen { path: p, mode } => {
                assert_eq!(p, path);
                assert_eq!(mode & 0o777, 0o640);
            }
            other => panic!("expected PermissionsTooOpen, got {other:?}"),
        }
        cleanup(&dir);
    }

    #[test]
    fn contains_matches_kind_correctly() {
        let (sk, r) = fresh_root("hub_a", TrustRootKind::HubCheckpoint);
        let store = TrustRootStore::with_roots(vec![r]);
        let vk = sk.verifying_key();

        assert!(store.contains(&vk, TrustRootKind::HubCheckpoint),
                "must accept matching kind");
        assert!(!store.contains(&vk, TrustRootKind::Ship),
                "must reject mismatching kind");
        assert!(!store.contains(&vk, TrustRootKind::AgentCert),
                "must reject mismatching kind");
    }

    #[test]
    fn add_replaces_same_key_id_and_kind() {
        let mut store = TrustRootStore::empty();
        let (_, r1) = fresh_root("hub_a", TrustRootKind::HubCheckpoint);
        let (_, r1b) = fresh_root("hub_a", TrustRootKind::HubCheckpoint);
        store.add(r1);
        store.add(r1b.clone());
        assert_eq!(store.len(), 1, "same (id, kind) replaces previous");
        assert_eq!(&store.roots()[0], &r1b);
    }

    #[test]
    fn add_keeps_same_key_id_across_kinds() {
        let mut store = TrustRootStore::empty();
        let (_, r_hub) = fresh_root("issuer_x", TrustRootKind::HubCheckpoint);
        let (_, r_ship) = fresh_root("issuer_x", TrustRootKind::Ship);
        store.add(r_hub);
        store.add(r_ship);
        assert_eq!(store.len(), 2, "same id is allowed across different kinds");
    }

    #[test]
    fn remove_strips_all_kinds_for_id() {
        let mut store = TrustRootStore::empty();
        let (_, r_hub) = fresh_root("issuer_x", TrustRootKind::HubCheckpoint);
        let (_, r_ship) = fresh_root("issuer_x", TrustRootKind::Ship);
        store.add(r_hub);
        store.add(r_ship);
        assert!(store.remove("issuer_x"));
        assert!(store.is_empty());
        assert!(!store.remove("issuer_x"), "second remove is a no-op");
    }

    #[test]
    fn encode_decode_roundtrip() {
        let sk = SigningKey::generate(&mut rand::thread_rng());
        let pk = sk.verifying_key();
        let encoded = encode_ed25519_pubkey(&pk);
        assert!(encoded.starts_with("ed25519:"));
        let decoded = decode_ed25519_pubkey(&encoded).unwrap();
        assert_eq!(decoded.to_bytes(), pk.to_bytes());
    }

    #[test]
    fn decode_accepts_bare_base64() {
        let sk = SigningKey::generate(&mut rand::thread_rng());
        let pk = sk.verifying_key();
        let bare = URL_SAFE_NO_PAD.encode(pk.to_bytes());
        let decoded = decode_ed25519_pubkey(&bare).unwrap();
        assert_eq!(decoded.to_bytes(), pk.to_bytes());
    }
}