Skip to main content

lean_ctx/core/
handoff_transfer_bundle.rs

1use lean_ctx_time::UtcDateTime;
2use serde::{Deserialize, Serialize};
3use std::path::Path;
4
5use crate::core::handoff_ledger::HandoffLedgerV1;
6
7const MAX_BUNDLE_BYTES: usize = 350_000;
8const MAX_PROOF_FILES: usize = 50;
9const MAX_ARTIFACT_ITEMS: usize = 80;
10const MAX_LEDGER_SNAPSHOT_CHARS: usize = 80_000;
11const MAX_CURATED_REF_CHARS: usize = 20_000;
12const MAX_DECISION_CHARS: usize = 2_000;
13const MAX_FINDING_CHARS: usize = 2_000;
14const MAX_NEXT_STEP_CHARS: usize = 1_000;
15const MAX_TASK_CHARS: usize = 4_000;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum BundlePrivacyV1 {
19    Redacted,
20    Full,
21}
22
23impl BundlePrivacyV1 {
24    pub fn parse(s: Option<&str>) -> Self {
25        match s.unwrap_or("redacted").trim().to_lowercase().as_str() {
26            "full" => Self::Full,
27            _ => Self::Redacted,
28        }
29    }
30
31    pub(crate) fn as_str(&self) -> &'static str {
32        match self {
33            Self::Redacted => "redacted",
34            Self::Full => "full",
35        }
36    }
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct HandoffTransferBundleV1 {
41    pub schema_version: u32,
42    pub exported_at: UtcDateTime,
43    pub privacy: String,
44    pub project: ProjectIdentityV1,
45    pub ledger: HandoffLedgerV1,
46    pub artifacts: ArtifactsExcerptV1,
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub signature: Option<String>,
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub signer_public_key: Option<String>,
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub signer_agent_id: Option<String>,
53    /// Signature scheme. [`BOUND_SIGNATURE_SCHEME`] covers `signer_agent_id`
54    /// and `signer_public_key` (GHSA-gvg8-285q-m62g); absent means a legacy
55    /// signature over the payload only, whose signer id is not bound.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub signature_scheme: Option<String>,
58}
59
60/// Signature over the whole bundle except `signature` itself.
61pub const BOUND_SIGNATURE_SCHEME: &str = "ed25519-bound-v2";
62
63#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct ProjectIdentityV1 {
65    pub project_root_hash: Option<String>,
66    pub project_identity_hash: Option<String>,
67}
68
69#[derive(Debug, Clone, Serialize, Deserialize, Default)]
70pub struct ArtifactsExcerptV1 {
71    pub resolved: Vec<crate::core::artifacts::ResolvedArtifact>,
72    pub proof_files: Vec<ProofFileV1>,
73    pub warnings: Vec<String>,
74}
75
76#[derive(Debug, Clone, Serialize, Deserialize)]
77pub struct ProofFileV1 {
78    pub name: String,
79    pub md5: String,
80    pub bytes: u64,
81}
82
83pub fn build_bundle_v1(
84    mut ledger: HandoffLedgerV1,
85    project_root: Option<&str>,
86    privacy: BundlePrivacyV1,
87) -> HandoffTransferBundleV1 {
88    let role_name = crate::core::roles::active_role_name();
89    let effective_privacy = match privacy {
90        BundlePrivacyV1::Full
91            if role_name == "admin"
92                && !crate::core::redaction::redaction_enabled_for_active_role() =>
93        {
94            BundlePrivacyV1::Full
95        }
96        _ => BundlePrivacyV1::Redacted,
97    };
98
99    let (project_root_hash, project_identity_hash) = project_root.map_or((None, None), |root| {
100        let root_hash = crate::core::project_hash::hash_project_root(root);
101        let identity = crate::core::project_hash::project_identity(root);
102        let identity_hash = identity.as_deref().map(crate::core::hasher::hash_str);
103        (Some(root_hash), identity_hash)
104    });
105
106    cap_ledger_in_place(&mut ledger);
107
108    match effective_privacy {
109        BundlePrivacyV1::Full => {}
110        BundlePrivacyV1::Redacted => {
111            redact_ledger_in_place(&mut ledger);
112        }
113    }
114
115    // Keep embedded ledger internally consistent.
116    ledger.content_md5 = crate::core::handoff_ledger::compute_content_md5_for_ledger(&ledger);
117
118    let artifacts = project_root
119        .map(Path::new)
120        .map(build_artifacts_excerpt_v1)
121        .unwrap_or_default();
122
123    // Built unsigned by design: signing is the exporter's responsibility
124    // (`ctx_handoff export` signs with the real agent identity, GL #465).
125    // The old implicit role-name signing here conflated role with identity
126    // and silently swallowed failures.
127    HandoffTransferBundleV1 {
128        schema_version: crate::core::contracts::HANDOFF_TRANSFER_BUNDLE_V1_SCHEMA_VERSION,
129        exported_at: UtcDateTime::now(),
130        privacy: effective_privacy.as_str().to_string(),
131        project: ProjectIdentityV1 {
132            project_root_hash,
133            project_identity_hash,
134        },
135        ledger,
136        artifacts,
137        signature: None,
138        signer_public_key: None,
139        signer_agent_id: None,
140        signature_scheme: None,
141    }
142}
143
144pub fn sign_bundle(bundle: &mut HandoffTransferBundleV1, agent_id: &str) -> Result<(), String> {
145    // One atomic key resolution — signature and embedded public key must come
146    // from the same keypair (two separate lookups raced with concurrent
147    // data-dir changes and produced unverifiable bundles).
148    let key = crate::core::agent_identity::get_or_create_keypair(agent_id)?;
149
150    // GHSA-gvg8-285q-m62g: signer id, public key and scheme are part of the
151    // signed payload, so relabelling the signer breaks the signature.
152    bundle.signature = None;
153    bundle.signer_public_key = Some(crate::core::agent_identity::hex_encode(
154        &key.verifying_key().to_bytes(),
155    ));
156    bundle.signer_agent_id = Some(agent_id.to_string());
157    bundle.signature_scheme = Some(BOUND_SIGNATURE_SCHEME.to_string());
158
159    let canonical =
160        serde_json::to_string(bundle).map_err(|e| format!("serialize for signing: {e}"))?;
161    let sig_bytes = crate::core::agent_identity::sign_bytes_with(&key, canonical.as_bytes());
162    bundle.signature = Some(crate::core::agent_identity::hex_encode(&sig_bytes));
163    Ok(())
164}
165
166/// A signature that verified against the bundle's embedded public key.
167///
168/// Integrity only: the key travels inside the bundle, so `claimed_signer` is
169/// an identity *claim* unless `trusted` is set (GHSA-gvg8-285q-m62g).
170#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct VerifiedSignature {
172    /// The bundle's `signer_agent_id`.
173    pub claimed_signer: String,
174    /// Fingerprint of the embedded public key (see `signer_trust::key_fingerprint`).
175    pub key_fingerprint: String,
176    /// `signer_agent_id` is covered by the signature (bound scheme). Legacy
177    /// signatures leave it unbound, so anyone can relabel the signer.
178    pub signer_bound: bool,
179    /// The key is anchored for `claimed_signer` (pinned in the signer trust
180    /// store, or held by a local agent identity). Never set when unbound.
181    pub trusted: bool,
182}
183
184impl VerifiedSignature {
185    /// Human-readable status that never claims identity without an anchor.
186    pub fn describe(&self) -> String {
187        let fp = &self.key_fingerprint;
188        let who = &self.claimed_signer;
189        if self.trusted {
190            format!("verified (signer={who}, key {fp}, trusted)")
191        } else if self.signer_bound {
192            format!("integrity ok, signer key {fp} (untrusted; claimed signer={who})")
193        } else {
194            format!(
195                "integrity ok, legacy signature (signer id not covered), signer key {fp} \
196                 (untrusted; claimed signer={who})"
197            )
198        }
199    }
200
201    /// Stable machine status for JSON responses.
202    #[cfg(any(test, feature = "http-server"))]
203    pub fn status(&self) -> &'static str {
204        if self.trusted {
205            "verified"
206        } else if self.signer_bound {
207            "untrusted_signer"
208        } else {
209            "legacy_unbound"
210        }
211    }
212}
213
214/// Outcome of checking a bundle's embedded Ed25519 signature on import
215/// (GL #465). Fail-closed semantics: any *present-but-broken* signature
216/// material is [`Invalid`](BundleSignatureStatus::Invalid) and must block the
217/// import; only the complete absence of all signature fields counts as
218/// [`Unsigned`](BundleSignatureStatus::Unsigned).
219#[derive(Debug, Clone, PartialEq, Eq)]
220pub enum BundleSignatureStatus {
221    /// Signature verifies against the embedded key; see [`VerifiedSignature`]
222    /// for whether the signer identity is bound and trusted.
223    Signed(VerifiedSignature),
224    /// No signature fields at all.
225    Unsigned,
226    /// Signature material present but not verifiable — reject the bundle.
227    Invalid(String),
228}
229
230/// Classify a bundle's signature for import-time enforcement (GL #465).
231#[must_use]
232pub fn check_bundle_signature(bundle: &HandoffTransferBundleV1) -> BundleSignatureStatus {
233    if bundle.signature.is_none()
234        && bundle.signer_public_key.is_none()
235        && bundle.signer_agent_id.is_none()
236        && bundle.signature_scheme.is_none()
237    {
238        return BundleSignatureStatus::Unsigned;
239    }
240    match verify_bundle_signature(bundle) {
241        Ok(verified) => BundleSignatureStatus::Signed(verified),
242        Err(e) => BundleSignatureStatus::Invalid(e),
243    }
244}
245
246pub(crate) fn verify_bundle_signature(
247    bundle: &HandoffTransferBundleV1,
248) -> Result<VerifiedSignature, String> {
249    let sig_hex = bundle
250        .signature
251        .as_deref()
252        .ok_or_else(|| "bundle has no signature".to_string())?;
253    let pk_hex = bundle
254        .signer_public_key
255        .as_deref()
256        .ok_or_else(|| "bundle has no signer_public_key".to_string())?;
257    let agent_id = bundle
258        .signer_agent_id
259        .as_deref()
260        .ok_or_else(|| "bundle has no signer_agent_id".to_string())?;
261
262    let sig_bytes = crate::core::agent_identity::hex_decode(sig_hex)?;
263    let pk_bytes = crate::core::agent_identity::hex_decode(pk_hex)?;
264
265    let mut verify_bundle = bundle.clone();
266    verify_bundle.signature = None;
267    let signer_bound = match bundle.signature_scheme.as_deref() {
268        Some(BOUND_SIGNATURE_SCHEME) => true,
269        None => {
270            // Legacy scheme: signed before the signer fields were filled in.
271            verify_bundle.signer_public_key = None;
272            verify_bundle.signer_agent_id = None;
273            false
274        }
275        Some(other) => return Err(format!("unsupported signature scheme `{other}`")),
276    };
277
278    let canonical =
279        serde_json::to_string(&verify_bundle).map_err(|e| format!("serialize for verify: {e}"))?;
280
281    if !crate::core::agent_identity::verify_signature(&pk_bytes, canonical.as_bytes(), &sig_bytes) {
282        return Err("signature verification failed".to_string());
283    }
284    Ok(VerifiedSignature {
285        claimed_signer: agent_id.to_string(),
286        key_fingerprint: crate::core::signer_trust::key_fingerprint(pk_hex),
287        signer_bound,
288        trusted: signer_bound && crate::core::signer_trust::is_trusted(agent_id, pk_hex),
289    })
290}
291
292pub fn serialize_bundle_v1_pretty(bundle: &HandoffTransferBundleV1) -> Result<String, String> {
293    let json = serde_json::to_string_pretty(bundle).map_err(|e| e.to_string())?;
294    if json.len() > MAX_BUNDLE_BYTES {
295        return Err(format!(
296            "ERROR: bundle too large ({} bytes > max {}). Use privacy=redacted and/or reduce curated refs.",
297            json.len(),
298            MAX_BUNDLE_BYTES
299        ));
300    }
301    Ok(json)
302}
303
304pub fn parse_bundle_v1(json: &str) -> Result<HandoffTransferBundleV1, String> {
305    let b: HandoffTransferBundleV1 = serde_json::from_str(json).map_err(|e| e.to_string())?;
306    if b.schema_version != crate::core::contracts::HANDOFF_TRANSFER_BUNDLE_V1_SCHEMA_VERSION {
307        return Err(format!(
308            "ERROR: unsupported schema_version {} (expected {})",
309            b.schema_version,
310            crate::core::contracts::HANDOFF_TRANSFER_BUNDLE_V1_SCHEMA_VERSION
311        ));
312    }
313    Ok(b)
314}
315
316/// Write a bundle to `requested` (jail-resolved as `jailed`) below the
317/// project `root`, refusing every symlinked component below the root.
318pub fn write_bundle_v1(
319    root: &Path,
320    requested: &Path,
321    jailed: &Path,
322    json: &str,
323) -> Result<(), String> {
324    crate::core::pathjail_write::write_requested_below(root, requested, jailed, json.as_bytes())
325        .map(|_| ())
326}
327
328pub fn read_bundle_v1(path: &Path) -> Result<HandoffTransferBundleV1, String> {
329    let json = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
330    if json.len() > MAX_BUNDLE_BYTES {
331        return Err(format!(
332            "ERROR: bundle file too large ({} bytes > max {})",
333            json.len(),
334            MAX_BUNDLE_BYTES
335        ));
336    }
337    parse_bundle_v1(&json)
338}
339
340pub fn project_identity_warning(
341    bundle: &HandoffTransferBundleV1,
342    project_root: &str,
343) -> Option<String> {
344    let current_root_hash = crate::core::project_hash::hash_project_root(project_root);
345    let current_identity_hash = crate::core::project_hash::project_identity(project_root)
346        .as_deref()
347        .map(crate::core::hasher::hash_str);
348
349    if let Some(ref exported) = bundle.project.project_root_hash
350        && exported != &current_root_hash
351    {
352        return Some(
353            "WARNING: project_root_hash mismatch (importing into different project root)."
354                .to_string(),
355        );
356    }
357
358    if let (Some(exported), Some(current)) = (
359        bundle.project.project_identity_hash.as_ref(),
360        current_identity_hash.as_ref(),
361    ) && exported != current
362    {
363        return Some(
364            "WARNING: project_identity_hash mismatch (importing into different project identity)."
365                .to_string(),
366        );
367    }
368
369    None
370}
371
372fn build_artifacts_excerpt_v1(project_root: &Path) -> ArtifactsExcerptV1 {
373    let mut out = ArtifactsExcerptV1::default();
374
375    let resolved = crate::core::artifacts::load_resolved(project_root);
376    out.warnings.extend(resolved.warnings);
377    out.resolved = resolved
378        .artifacts
379        .into_iter()
380        .take(MAX_ARTIFACT_ITEMS)
381        .collect();
382
383    let proofs_dir = match crate::core::pathutil::safe_project_data_dir(project_root) {
384        Ok(d) => d.join("proofs"),
385        Err(_) => return out,
386    };
387    if let Ok(rd) = std::fs::read_dir(&proofs_dir) {
388        let mut files = Vec::new();
389        for e in rd.flatten() {
390            let p = e.path();
391            if !p.is_file() {
392                continue;
393            }
394            let name = p
395                .file_name()
396                .map(|n| n.to_string_lossy().to_string())
397                .unwrap_or_default();
398            // Dot-files are store internals (the landing receipt store lock
399            // `.landing-receipts.lock`), not proofs.
400            if name.is_empty() || name.starts_with('.') {
401                continue;
402            }
403            let bytes = p.metadata().map_or(0, |m| m.len());
404            let md5 = match std::fs::read(&p) {
405                Ok(b) => crate::core::hasher::hash_hex(&b),
406                Err(e) => {
407                    out.warnings
408                        .push(format!("proof read failed: {} ({e})", p.display()));
409                    continue;
410                }
411            };
412            files.push(ProofFileV1 { name, md5, bytes });
413        }
414        files.sort_by(|a, b| a.name.cmp(&b.name));
415        out.proof_files = files.into_iter().take(MAX_PROOF_FILES).collect();
416    }
417
418    out
419}
420
421fn cap_ledger_in_place(ledger: &mut HandoffLedgerV1) {
422    if ledger.session_snapshot.len() > MAX_LEDGER_SNAPSHOT_CHARS {
423        ledger.session_snapshot =
424            truncate_chars(&ledger.session_snapshot, MAX_LEDGER_SNAPSHOT_CHARS);
425    }
426
427    if let Some(ref mut task) = ledger.session.task {
428        *task = truncate_chars(task, MAX_TASK_CHARS);
429    }
430
431    for d in &mut ledger.session.decisions {
432        *d = truncate_chars(d, MAX_DECISION_CHARS);
433    }
434    for f in &mut ledger.session.findings {
435        *f = truncate_chars(f, MAX_FINDING_CHARS);
436    }
437    for s in &mut ledger.session.next_steps {
438        *s = truncate_chars(s, MAX_NEXT_STEP_CHARS);
439    }
440
441    for r in &mut ledger.curated_refs {
442        if r.content.len() > MAX_CURATED_REF_CHARS {
443            r.content = truncate_chars(&r.content, MAX_CURATED_REF_CHARS);
444        }
445    }
446}
447
448fn redact_ledger_in_place(ledger: &mut HandoffLedgerV1) {
449    ledger.project_root = None;
450    ledger.session_snapshot.clear();
451
452    if let Some(ref mut task) = ledger.session.task {
453        *task = crate::core::redaction::redact_text(task);
454    }
455    for d in &mut ledger.session.decisions {
456        *d = crate::core::redaction::redact_text(d);
457    }
458    for f in &mut ledger.session.findings {
459        *f = crate::core::redaction::redact_text(f);
460    }
461    for s in &mut ledger.session.next_steps {
462        *s = crate::core::redaction::redact_text(s);
463    }
464
465    for fact in &mut ledger.knowledge.facts {
466        fact.value = crate::core::redaction::redact_text(&fact.value);
467    }
468
469    for r in &mut ledger.curated_refs {
470        r.content = crate::core::redaction::redact_text(&r.content);
471    }
472}
473
474fn truncate_chars(s: &str, max: usize) -> String {
475    if s.chars().count() <= max {
476        return s.to_string();
477    }
478    s.chars().take(max).collect::<String>()
479}
480
481#[cfg(test)]
482mod tests {
483    use super::*;
484
485    fn sample_ledger() -> HandoffLedgerV1 {
486        HandoffLedgerV1 {
487            schema_version: crate::core::contracts::HANDOFF_LEDGER_V1_SCHEMA_VERSION,
488            created_at: "20260503T000000Z".to_string(),
489            content_md5: "old".to_string(),
490            manifest_md5: "m".to_string(),
491            project_root: Some("/abs/project".to_string()),
492            agent_id: Some("a".to_string()),
493            client_name: Some("cursor".to_string()),
494            workflow: None,
495            session_snapshot: "snapshot".to_string(),
496            session: crate::core::handoff_ledger::SessionExcerpt {
497                id: "s".to_string(),
498                task: Some("task".to_string()),
499                decisions: vec!["d1".to_string()],
500                findings: vec!["f1".to_string()],
501                next_steps: vec!["n1".to_string()],
502            },
503            tool_calls: crate::core::handoff_ledger::ToolCallsSummary::default(),
504            evidence_keys: vec!["tool:ctx_read".to_string()],
505            knowledge: crate::core::handoff_ledger::KnowledgeExcerpt {
506                project_hash: None,
507                facts: vec![crate::core::handoff_ledger::KnowledgeFactMini {
508                    category: "c".to_string(),
509                    key: "k".to_string(),
510                    value: "secret=abcdef0123456789abcdef0123456789".to_string(),
511                    confidence: 0.9,
512                }],
513            },
514            curated_refs: vec![crate::core::handoff_ledger::CuratedRef {
515                path: "src/lib.rs".to_string(),
516                mode: "signatures".to_string(),
517                content_md5: "x".to_string(),
518                content: "fn a() {}".to_string(),
519            }],
520            active_overlays: Vec::new(),
521            merged_from: Vec::new(),
522            request_id: None,
523            request_digest: None,
524        }
525    }
526
527    #[test]
528    fn handoff_proof_files_skip_store_dot_files() {
529        let project = tempfile::tempdir().unwrap();
530        let proofs = project.path().join(".lean-ctx/proofs");
531        std::fs::create_dir_all(&proofs).unwrap();
532        std::fs::write(
533            proofs.join("landing-receipt-0123456789abcdef.json"),
534            b"{}\n",
535        )
536        .unwrap();
537        std::fs::write(proofs.join(".landing-receipts.lock"), b"").unwrap();
538        let names: Vec<String> = build_artifacts_excerpt_v1(project.path())
539            .proof_files
540            .into_iter()
541            .map(|file| file.name)
542            .collect();
543        assert_eq!(names, ["landing-receipt-0123456789abcdef.json"]);
544    }
545
546    #[test]
547    fn redacted_bundle_removes_sensitive_fields() {
548        let ledger = sample_ledger();
549        let b = build_bundle_v1(ledger, None, BundlePrivacyV1::Redacted);
550        assert_eq!(b.privacy, "redacted");
551        assert!(b.ledger.project_root.is_none());
552        assert!(
553            b.ledger.session_snapshot.is_empty(),
554            "{:?}",
555            b.ledger.session_snapshot
556        );
557    }
558
559    #[test]
560    fn serialize_parse_roundtrip() {
561        let ledger = sample_ledger();
562        let b = build_bundle_v1(ledger, None, BundlePrivacyV1::Redacted);
563        let json = serialize_bundle_v1_pretty(&b).expect("json");
564        assert!(json.len() < MAX_BUNDLE_BYTES);
565        let parsed = parse_bundle_v1(&json).expect("parse");
566        assert_eq!(parsed.schema_version, b.schema_version);
567        assert_eq!(parsed.privacy, "redacted");
568    }
569
570    #[test]
571    fn unicode_signature_material_is_invalid() {
572        for malformed in ["\u{1f512}", "0\u{20ac}", "\u{e9}\u{e9}"] {
573            for signature_is_malformed in [true, false] {
574                let mut bundle = build_bundle_v1(sample_ledger(), None, BundlePrivacyV1::Redacted);
575                bundle.signer_agent_id = Some("unicode-regression".to_string());
576                bundle.signature = Some(if signature_is_malformed {
577                    malformed.to_string()
578                } else {
579                    "00".repeat(64)
580                });
581                bundle.signer_public_key = Some(if signature_is_malformed {
582                    "00".repeat(32)
583                } else {
584                    malformed.to_string()
585                });
586                let serialized = serialize_bundle_v1_pretty(&bundle).unwrap();
587                let parsed = parse_bundle_v1(&serialized).unwrap();
588                assert_eq!(
589                    check_bundle_signature(&parsed),
590                    BundleSignatureStatus::Invalid("non-ASCII hex string".to_string())
591                );
592            }
593        }
594    }
595
596    /// GL #465: signed bundles verify; any tampering after signing flips the
597    /// status to `Invalid` (fail-closed); bundles without signature fields are
598    /// `Unsigned` (legacy, allowed with warning).
599    #[test]
600    fn import_signature_check_verified_unsigned_invalid() {
601        // Signing writes the agent key under the data dir. Own it for the
602        // test: a concurrent test that points LEAN_CTX_DATA_DIR at a temp dir
603        // and deletes it made `sign` fail with "path not found" (Windows CI).
604        let _lock = crate::core::data_dir::test_env_lock();
605        let data_dir = tempfile::tempdir().unwrap();
606        crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
607
608        let unsigned = build_bundle_v1(sample_ledger(), None, BundlePrivacyV1::Redacted);
609        assert_eq!(
610            check_bundle_signature(&unsigned),
611            BundleSignatureStatus::Unsigned
612        );
613
614        let mut signed = build_bundle_v1(sample_ledger(), None, BundlePrivacyV1::Redacted);
615        sign_bundle(&mut signed, "handoff-sig-test-agent").expect("sign");
616        // Signed by a key held by a local agent identity → trusted anchor.
617        match check_bundle_signature(&signed) {
618            BundleSignatureStatus::Signed(v) => {
619                assert_eq!(v.claimed_signer, "handoff-sig-test-agent");
620                assert!(v.signer_bound && v.trusted, "{v:?}");
621                assert_eq!(v.status(), "verified");
622            }
623            other => panic!("expected Signed, got {other:?}"),
624        }
625
626        // GHSA-gvg8-285q-m62g: relabelling the signer breaks the signature.
627        let mut relabelled = signed.clone();
628        relabelled.signer_agent_id = Some("trusted-release-bot".to_string());
629        assert!(matches!(
630            check_bundle_signature(&relabelled),
631            BundleSignatureStatus::Invalid(_)
632        ));
633        // Stripping the scheme (downgrade to legacy) does not verify either.
634        let mut downgraded = signed.clone();
635        downgraded.signature_scheme = None;
636        assert!(matches!(
637            check_bundle_signature(&downgraded),
638            BundleSignatureStatus::Invalid(_)
639        ));
640
641        // Tamper with the payload after signing → must be Invalid, not Unsigned.
642        let mut tampered = signed.clone();
643        tampered.ledger.session.task = Some("tampered task".to_string());
644        assert!(matches!(
645            check_bundle_signature(&tampered),
646            BundleSignatureStatus::Invalid(_)
647        ));
648
649        // Partial signature material (e.g. stripped pubkey) is Invalid too.
650        let mut partial = signed;
651        partial.signer_public_key = None;
652        assert!(matches!(
653            check_bundle_signature(&partial),
654            BundleSignatureStatus::Invalid(_)
655        ));
656
657        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
658    }
659
660    /// GHSA-gvg8-285q-m62g: a self-embedded key is never reported as a
661    /// verified identity, and legacy signatures surface as unbound.
662    #[test]
663    fn foreign_and_legacy_signatures_are_not_verified_identities() {
664        let _lock = crate::core::data_dir::test_env_lock();
665        let data_dir = tempfile::tempdir().unwrap();
666        crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
667        let key = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]);
668        let pk_hex = crate::core::agent_identity::hex_encode(&key.verifying_key().to_bytes());
669
670        // Bound signature from a key no anchor knows.
671        let mut bound = build_bundle_v1(sample_ledger(), None, BundlePrivacyV1::Redacted);
672        bound.signer_public_key = Some(pk_hex.clone());
673        bound.signer_agent_id = Some("trusted-release-bot".to_string());
674        bound.signature_scheme = Some(BOUND_SIGNATURE_SCHEME.to_string());
675        let canonical = serde_json::to_string(&bound).unwrap();
676        bound.signature = Some(crate::core::agent_identity::hex_encode(
677            &crate::core::agent_identity::sign_bytes_with(&key, canonical.as_bytes()),
678        ));
679        let BundleSignatureStatus::Signed(v) = check_bundle_signature(&bound) else {
680            panic!("bound signature must verify");
681        };
682        assert!(v.signer_bound && !v.trusted);
683        assert_eq!(v.status(), "untrusted_signer");
684        assert!(v.describe().contains("(untrusted"), "{}", v.describe());
685        assert!(!v.describe().starts_with("verified"));
686
687        // Pinning (subject, key) in the trust store anchors it.
688        crate::core::signer_trust::pin_if_absent("trusted-release-bot", &pk_hex, "test").unwrap();
689        let BundleSignatureStatus::Signed(v) = check_bundle_signature(&bound) else {
690            panic!("bound signature must verify");
691        };
692        assert!(v.trusted);
693
694        // Legacy signature (signer fields outside the payload) still verifies,
695        // but is reported unbound and never trusted — even for a pinned key.
696        let mut legacy = build_bundle_v1(sample_ledger(), None, BundlePrivacyV1::Redacted);
697        let canonical = serde_json::to_string(&legacy).unwrap();
698        legacy.signature = Some(crate::core::agent_identity::hex_encode(
699            &crate::core::agent_identity::sign_bytes_with(&key, canonical.as_bytes()),
700        ));
701        legacy.signer_public_key = Some(pk_hex);
702        legacy.signer_agent_id = Some("trusted-release-bot".to_string());
703        let BundleSignatureStatus::Signed(v) = check_bundle_signature(&legacy) else {
704            panic!("legacy signature must still verify");
705        };
706        assert!(!v.signer_bound && !v.trusted);
707        assert_eq!(v.status(), "legacy_unbound");
708        assert!(v.describe().contains("legacy signature"));
709
710        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
711    }
712}