1use chrono::{DateTime, Utc};
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: DateTime<Utc>,
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 #[serde(default, skip_serializing_if = "Option::is_none")]
57 pub signature_scheme: Option<String>,
58}
59
60pub 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 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 HandoffTransferBundleV1 {
128 schema_version: crate::core::contracts::HANDOFF_TRANSFER_BUNDLE_V1_SCHEMA_VERSION,
129 exported_at: Utc::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 let key = crate::core::agent_identity::get_or_create_keypair(agent_id)?;
149
150 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#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct VerifiedSignature {
172 pub claimed_signer: String,
174 pub key_fingerprint: String,
176 pub signer_bound: bool,
179 pub trusted: bool,
182}
183
184impl VerifiedSignature {
185 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 #[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#[derive(Debug, Clone, PartialEq, Eq)]
220pub enum BundleSignatureStatus {
221 Signed(VerifiedSignature),
224 Unsigned,
226 Invalid(String),
228}
229
230#[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 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
316pub 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 != ¤t_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 if name.is_empty() {
399 continue;
400 }
401 let bytes = p.metadata().map_or(0, |m| m.len());
402 let md5 = match std::fs::read(&p) {
403 Ok(b) => crate::core::hasher::hash_hex(&b),
404 Err(e) => {
405 out.warnings
406 .push(format!("proof read failed: {} ({e})", p.display()));
407 continue;
408 }
409 };
410 files.push(ProofFileV1 { name, md5, bytes });
411 }
412 files.sort_by(|a, b| a.name.cmp(&b.name));
413 out.proof_files = files.into_iter().take(MAX_PROOF_FILES).collect();
414 }
415
416 out
417}
418
419fn cap_ledger_in_place(ledger: &mut HandoffLedgerV1) {
420 if ledger.session_snapshot.len() > MAX_LEDGER_SNAPSHOT_CHARS {
421 ledger.session_snapshot =
422 truncate_chars(&ledger.session_snapshot, MAX_LEDGER_SNAPSHOT_CHARS);
423 }
424
425 if let Some(ref mut task) = ledger.session.task {
426 *task = truncate_chars(task, MAX_TASK_CHARS);
427 }
428
429 for d in &mut ledger.session.decisions {
430 *d = truncate_chars(d, MAX_DECISION_CHARS);
431 }
432 for f in &mut ledger.session.findings {
433 *f = truncate_chars(f, MAX_FINDING_CHARS);
434 }
435 for s in &mut ledger.session.next_steps {
436 *s = truncate_chars(s, MAX_NEXT_STEP_CHARS);
437 }
438
439 for r in &mut ledger.curated_refs {
440 if r.content.len() > MAX_CURATED_REF_CHARS {
441 r.content = truncate_chars(&r.content, MAX_CURATED_REF_CHARS);
442 }
443 }
444}
445
446fn redact_ledger_in_place(ledger: &mut HandoffLedgerV1) {
447 ledger.project_root = None;
448 ledger.session_snapshot.clear();
449
450 if let Some(ref mut task) = ledger.session.task {
451 *task = crate::core::redaction::redact_text(task);
452 }
453 for d in &mut ledger.session.decisions {
454 *d = crate::core::redaction::redact_text(d);
455 }
456 for f in &mut ledger.session.findings {
457 *f = crate::core::redaction::redact_text(f);
458 }
459 for s in &mut ledger.session.next_steps {
460 *s = crate::core::redaction::redact_text(s);
461 }
462
463 for fact in &mut ledger.knowledge.facts {
464 fact.value = crate::core::redaction::redact_text(&fact.value);
465 }
466
467 for r in &mut ledger.curated_refs {
468 r.content = crate::core::redaction::redact_text(&r.content);
469 }
470}
471
472fn truncate_chars(s: &str, max: usize) -> String {
473 if s.chars().count() <= max {
474 return s.to_string();
475 }
476 s.chars().take(max).collect::<String>()
477}
478
479#[cfg(test)]
480mod tests {
481 use super::*;
482
483 fn sample_ledger() -> HandoffLedgerV1 {
484 HandoffLedgerV1 {
485 schema_version: crate::core::contracts::HANDOFF_LEDGER_V1_SCHEMA_VERSION,
486 created_at: "20260503T000000Z".to_string(),
487 content_md5: "old".to_string(),
488 manifest_md5: "m".to_string(),
489 project_root: Some("/abs/project".to_string()),
490 agent_id: Some("a".to_string()),
491 client_name: Some("cursor".to_string()),
492 workflow: None,
493 session_snapshot: "snapshot".to_string(),
494 session: crate::core::handoff_ledger::SessionExcerpt {
495 id: "s".to_string(),
496 task: Some("task".to_string()),
497 decisions: vec!["d1".to_string()],
498 findings: vec!["f1".to_string()],
499 next_steps: vec!["n1".to_string()],
500 },
501 tool_calls: crate::core::handoff_ledger::ToolCallsSummary::default(),
502 evidence_keys: vec!["tool:ctx_read".to_string()],
503 knowledge: crate::core::handoff_ledger::KnowledgeExcerpt {
504 project_hash: None,
505 facts: vec![crate::core::handoff_ledger::KnowledgeFactMini {
506 category: "c".to_string(),
507 key: "k".to_string(),
508 value: "secret=abcdef0123456789abcdef0123456789".to_string(),
509 confidence: 0.9,
510 }],
511 },
512 curated_refs: vec![crate::core::handoff_ledger::CuratedRef {
513 path: "src/lib.rs".to_string(),
514 mode: "signatures".to_string(),
515 content_md5: "x".to_string(),
516 content: "fn a() {}".to_string(),
517 }],
518 active_overlays: Vec::new(),
519 merged_from: Vec::new(),
520 request_id: None,
521 request_digest: None,
522 }
523 }
524
525 #[test]
526 fn redacted_bundle_removes_sensitive_fields() {
527 let ledger = sample_ledger();
528 let b = build_bundle_v1(ledger, None, BundlePrivacyV1::Redacted);
529 assert_eq!(b.privacy, "redacted");
530 assert!(b.ledger.project_root.is_none());
531 assert!(
532 b.ledger.session_snapshot.is_empty(),
533 "{:?}",
534 b.ledger.session_snapshot
535 );
536 }
537
538 #[test]
539 fn serialize_parse_roundtrip() {
540 let ledger = sample_ledger();
541 let b = build_bundle_v1(ledger, None, BundlePrivacyV1::Redacted);
542 let json = serialize_bundle_v1_pretty(&b).expect("json");
543 assert!(json.len() < MAX_BUNDLE_BYTES);
544 let parsed = parse_bundle_v1(&json).expect("parse");
545 assert_eq!(parsed.schema_version, b.schema_version);
546 assert_eq!(parsed.privacy, "redacted");
547 }
548
549 #[test]
550 fn unicode_signature_material_is_invalid() {
551 for malformed in ["\u{1f512}", "0\u{20ac}", "\u{e9}\u{e9}"] {
552 for signature_is_malformed in [true, false] {
553 let mut bundle = build_bundle_v1(sample_ledger(), None, BundlePrivacyV1::Redacted);
554 bundle.signer_agent_id = Some("unicode-regression".to_string());
555 bundle.signature = Some(if signature_is_malformed {
556 malformed.to_string()
557 } else {
558 "00".repeat(64)
559 });
560 bundle.signer_public_key = Some(if signature_is_malformed {
561 "00".repeat(32)
562 } else {
563 malformed.to_string()
564 });
565 let serialized = serialize_bundle_v1_pretty(&bundle).unwrap();
566 let parsed = parse_bundle_v1(&serialized).unwrap();
567 assert_eq!(
568 check_bundle_signature(&parsed),
569 BundleSignatureStatus::Invalid("non-ASCII hex string".to_string())
570 );
571 }
572 }
573 }
574
575 #[test]
579 fn import_signature_check_verified_unsigned_invalid() {
580 let _lock = crate::core::data_dir::test_env_lock();
584 let data_dir = tempfile::tempdir().unwrap();
585 crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
586
587 let unsigned = build_bundle_v1(sample_ledger(), None, BundlePrivacyV1::Redacted);
588 assert_eq!(
589 check_bundle_signature(&unsigned),
590 BundleSignatureStatus::Unsigned
591 );
592
593 let mut signed = build_bundle_v1(sample_ledger(), None, BundlePrivacyV1::Redacted);
594 sign_bundle(&mut signed, "handoff-sig-test-agent").expect("sign");
595 match check_bundle_signature(&signed) {
597 BundleSignatureStatus::Signed(v) => {
598 assert_eq!(v.claimed_signer, "handoff-sig-test-agent");
599 assert!(v.signer_bound && v.trusted, "{v:?}");
600 assert_eq!(v.status(), "verified");
601 }
602 other => panic!("expected Signed, got {other:?}"),
603 }
604
605 let mut relabelled = signed.clone();
607 relabelled.signer_agent_id = Some("trusted-release-bot".to_string());
608 assert!(matches!(
609 check_bundle_signature(&relabelled),
610 BundleSignatureStatus::Invalid(_)
611 ));
612 let mut downgraded = signed.clone();
614 downgraded.signature_scheme = None;
615 assert!(matches!(
616 check_bundle_signature(&downgraded),
617 BundleSignatureStatus::Invalid(_)
618 ));
619
620 let mut tampered = signed.clone();
622 tampered.ledger.session.task = Some("tampered task".to_string());
623 assert!(matches!(
624 check_bundle_signature(&tampered),
625 BundleSignatureStatus::Invalid(_)
626 ));
627
628 let mut partial = signed;
630 partial.signer_public_key = None;
631 assert!(matches!(
632 check_bundle_signature(&partial),
633 BundleSignatureStatus::Invalid(_)
634 ));
635
636 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
637 }
638
639 #[test]
642 fn foreign_and_legacy_signatures_are_not_verified_identities() {
643 let _lock = crate::core::data_dir::test_env_lock();
644 let data_dir = tempfile::tempdir().unwrap();
645 crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
646 let key = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]);
647 let pk_hex = crate::core::agent_identity::hex_encode(&key.verifying_key().to_bytes());
648
649 let mut bound = build_bundle_v1(sample_ledger(), None, BundlePrivacyV1::Redacted);
651 bound.signer_public_key = Some(pk_hex.clone());
652 bound.signer_agent_id = Some("trusted-release-bot".to_string());
653 bound.signature_scheme = Some(BOUND_SIGNATURE_SCHEME.to_string());
654 let canonical = serde_json::to_string(&bound).unwrap();
655 bound.signature = Some(crate::core::agent_identity::hex_encode(
656 &crate::core::agent_identity::sign_bytes_with(&key, canonical.as_bytes()),
657 ));
658 let BundleSignatureStatus::Signed(v) = check_bundle_signature(&bound) else {
659 panic!("bound signature must verify");
660 };
661 assert!(v.signer_bound && !v.trusted);
662 assert_eq!(v.status(), "untrusted_signer");
663 assert!(v.describe().contains("(untrusted"), "{}", v.describe());
664 assert!(!v.describe().starts_with("verified"));
665
666 crate::core::signer_trust::pin_if_absent("trusted-release-bot", &pk_hex, "test").unwrap();
668 let BundleSignatureStatus::Signed(v) = check_bundle_signature(&bound) else {
669 panic!("bound signature must verify");
670 };
671 assert!(v.trusted);
672
673 let mut legacy = build_bundle_v1(sample_ledger(), None, BundlePrivacyV1::Redacted);
676 let canonical = serde_json::to_string(&legacy).unwrap();
677 legacy.signature = Some(crate::core::agent_identity::hex_encode(
678 &crate::core::agent_identity::sign_bytes_with(&key, canonical.as_bytes()),
679 ));
680 legacy.signer_public_key = Some(pk_hex);
681 legacy.signer_agent_id = Some("trusted-release-bot".to_string());
682 let BundleSignatureStatus::Signed(v) = check_bundle_signature(&legacy) else {
683 panic!("legacy signature must still verify");
684 };
685 assert!(!v.signer_bound && !v.trusted);
686 assert_eq!(v.status(), "legacy_unbound");
687 assert!(v.describe().contains("legacy signature"));
688
689 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
690 }
691}