From 47e97b1b6a5d41f985848b6394a967c61b2724bb Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:14:53 -0600 Subject: [PATCH 01/18] feat(core): add signed encrypted manifest wire format --- crates/twigpine-core/src/encrypt.rs | 13 + .../twigpine-core/src/encrypted_manifest.rs | 527 ++++++++++++++++++ crates/twigpine-core/src/lib.rs | 1 + crates/twigpine-node/src/api/encrypted.rs | 3 +- crates/twigpine-node/src/api/ipfs.rs | 2 +- 5 files changed, 544 insertions(+), 2 deletions(-) create mode 100644 crates/twigpine-core/src/encrypted_manifest.rs diff --git a/crates/twigpine-core/src/encrypt.rs b/crates/twigpine-core/src/encrypt.rs index a3e62a15e..d02a9a6a4 100644 --- a/crates/twigpine-core/src/encrypt.rs +++ b/crates/twigpine-core/src/encrypt.rs @@ -92,6 +92,19 @@ const VERSION: u8 = 2; /// readers, so 256 is far above real use. pub const MAX_RECIPIENTS: usize = 256; +/// Maximum plaintext git object bytes the node serving path is willing to +/// buffer and verify. Shared with client-side public-gateway recovery so the +/// recovery reader cannot accept an envelope the node would never serve. +pub const MAX_ENCRYPTED_OBJECT_BYTES: u64 = 32 * 1024 * 1024; + +/// Allowance above object bytes for the sealed envelope header at the maximum +/// recipient count plus AEAD overhead. +pub const ENCRYPTED_ENVELOPE_HEADER_ALLOWANCE_BYTES: usize = 64 * 1024; + +/// Maximum bytes in one encrypted envelope. +pub const MAX_ENCRYPTED_ENVELOPE_BYTES: usize = + MAX_ENCRYPTED_OBJECT_BYTES as usize + ENCRYPTED_ENVELOPE_HEADER_ALLOWANCE_BYTES; + #[derive(Serialize, Deserialize)] struct Recipient { eph: String, // base64 ephemeral x25519 pubkey (32B) diff --git a/crates/twigpine-core/src/encrypted_manifest.rs b/crates/twigpine-core/src/encrypted_manifest.rs new file mode 100644 index 000000000..ff9e65def --- /dev/null +++ b/crates/twigpine-core/src/encrypted_manifest.rs @@ -0,0 +1,527 @@ +//! Signed encrypted-blob recovery manifests. +//! +//! The manifest is permanent public data, so the wire format signs exact bytes +//! instead of a canonicalization recipe. The outer JSON carries the signed +//! payload as a string; verification signs and verifies that string byte for +//! byte under a caller-supplied node DID. + +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use chrono::DateTime; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::HashSet; +use std::str::FromStr; + +use crate::cid::is_hex_oid; +use crate::did::Did; +use crate::identity::{self, Keypair}; +use crate::{Error, Result}; + +pub const SCHEMA_V1: &str = "gitlawb/encrypted-manifest/v1"; +pub const SCHEMA_V2: &str = "gitlawb/encrypted-manifest/v2"; +pub const REPO_DIGEST_TAG: &str = "Repo-Digest"; +pub const SIGNING_DOMAIN: &[u8] = b"gitlawb-encrypted-manifest-sig/v2\n"; + +/// Largest outer manifest body a verifier accepts. +pub const VERIFIER_MANIFEST_CAP_BYTES: usize = 256 * 1024; +/// Largest outer manifest body the current writer intentionally produces. +pub const WRITER_MANIFEST_TARGET_BYTES: usize = 96 * 1024; +/// Largest blob count a verifier accepts in one manifest. +pub const VERIFIER_MANIFEST_MAX_ENTRIES: usize = 1024; +/// Largest blob count the writer places in one shard. +pub const WRITER_SHARD_MAX_ENTRIES: usize = 256; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EncryptedBlobRef { + pub oid: String, + pub cid: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct ManifestPayload { + schema: String, + repo: String, + owner_did: String, + node_did: String, + timestamp: String, + blobs: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct ManifestEnvelope { + schema: String, + payload: String, + signature: String, +} + +/// A verified signed manifest. Identity fields are exposed because callers may +/// need diagnostics, but they are never the source of the verification anchor. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VerifiedManifest { + pub repo: String, + pub owner_did: String, + pub node_did: String, + pub timestamp: String, + pub blobs: Vec, +} + +fn invalid(reason: impl Into) -> Error { + Error::Encoding(format!("invalid encrypted manifest: {}", reason.into())) +} + +/// The wire owner key. This is the shared owner-canonicalization contract: +/// strip `did:key:` only when doing so leaves a bare key with no further colon. +pub fn canonical_owner_key(did: &str) -> &str { + match did.strip_prefix("did:key:") { + Some(rest) if !rest.contains(':') => rest, + _ => did, + } +} + +/// Canonical repository slug used by writers and verifiers. +pub fn canonical_repo_slug(owner_did: &str, repo_name: &str) -> String { + format!("{}/{repo_name}", canonical_owner_key(owner_did)) +} + +/// Fixed-length discovery digest: base64url-unpadded SHA-256 of the exact +/// canonical repo slug bytes. +pub fn repo_digest(canonical_repo: &str) -> String { + URL_SAFE_NO_PAD.encode(Sha256::digest(canonical_repo.as_bytes())) +} + +/// Validate a did:key trust anchor strictly enough for signature verification: +/// it must resolve to a non-weak Ed25519 key and spell canonically. +pub fn validate_did_key_anchor(did: &str) -> Result { + let parsed = Did::from_str(did)?; + let key = parsed.to_verifying_key()?; + let canonical = Did::from_verifying_key(&key); + if canonical.as_str() != did { + return Err(Error::InvalidDid("non-canonical did:key spelling".to_string())); + } + Ok(parsed) +} + +fn validate_common( + repo: &str, + owner_did: &str, + node_did: &str, + timestamp: &str, + blobs: &[EncryptedBlobRef], +) -> Result<()> { + if repo.trim().is_empty() || repo.split('/').any(str::is_empty) { + return Err(invalid("repo slug is empty or malformed")); + } + if owner_did.trim().is_empty() { + return Err(invalid("owner DID is empty")); + } + Did::from_str(owner_did).map_err(|e| invalid(e.to_string()))?; + validate_did_key_anchor(node_did).map_err(|e| invalid(e.to_string()))?; + DateTime::parse_from_rfc3339(timestamp).map_err(|_| invalid("timestamp is not RFC3339"))?; + if blobs.len() > VERIFIER_MANIFEST_MAX_ENTRIES { + return Err(invalid("too many blob entries")); + } + let owner_part = repo.split_once('/').map(|(owner, _)| owner).unwrap_or(""); + if canonical_owner_key(owner_did) != owner_part { + return Err(invalid("owner DID does not canonicalize to repo owner")); + } + let mut seen = HashSet::with_capacity(blobs.len()); + for blob in blobs { + if !is_hex_oid(&blob.oid) { + return Err(invalid("blob oid is not a 40-or-64 hex object id")); + } + if !seen.insert(blob.oid.as_str()) { + return Err(invalid("duplicate blob oid")); + } + let parsed = blob + .cid + .parse::>() + .map_err(|_| invalid("blob cid is not a valid CID"))?; + if parsed.version() != cid::Version::V1 { + return Err(invalid("blob cid must be CIDv1")); + } + } + Ok(()) +} + +fn serialize_payload(payload: &ManifestPayload) -> Result { + serde_json::to_string(payload).map_err(Error::Serde) +} + +fn signing_input(payload_bytes: &[u8]) -> Vec { + let mut input = Vec::with_capacity(SIGNING_DOMAIN.len() + payload_bytes.len()); + input.extend_from_slice(SIGNING_DOMAIN); + input.extend_from_slice(payload_bytes); + input +} + +fn validate_and_encode_envelope(payload: ManifestPayload, keypair: &Keypair) -> Result> { + validate_common( + &payload.repo, + &payload.owner_did, + &payload.node_did, + &payload.timestamp, + &payload.blobs, + )?; + let payload_bytes = serialize_payload(&payload)?; + let input = signing_input(payload_bytes.as_bytes()); + let signature = URL_SAFE_NO_PAD.encode(keypair.sign(&input).to_bytes()); + let envelope = ManifestEnvelope { + schema: SCHEMA_V2.to_string(), + payload: payload_bytes, + signature, + }; + serde_json::to_vec(&envelope).map_err(Error::Serde) +} + +/// Construct one signed v2 manifest. `node_did` is derived from the signing +/// key, so the signed identity cannot disagree with the key that signed it. +pub fn build_signed_manifest( + repo: &str, + owner_did: &str, + timestamp: &str, + blobs: &[EncryptedBlobRef], + keypair: &Keypair, +) -> Result> { + let payload = ManifestPayload { + schema: SCHEMA_V2.to_string(), + repo: repo.to_string(), + owner_did: owner_did.to_string(), + node_did: keypair.did().to_string(), + timestamp: timestamp.to_string(), + blobs: blobs.to_vec(), + }; + validate_and_encode_envelope(payload, keypair) +} + +/// Construct complete disjoint signed shards at the writer's count and byte +/// targets. Empty input produces no shards. A single entry that cannot fit the +/// target is rejected rather than published malformed. +pub fn build_signed_manifest_shards( + repo: &str, + owner_did: &str, + timestamp: &str, + blobs: &[EncryptedBlobRef], + keypair: &Keypair, +) -> Result>> { + validate_common( + repo, + owner_did, + &keypair.did().to_string(), + timestamp, + blobs, + )?; + let mut ordered = blobs.to_vec(); + ordered.sort_by(|a, b| a.oid.cmp(&b.oid).then_with(|| a.cid.cmp(&b.cid))); + let blobs = ordered.as_slice(); + let mut shards = Vec::new(); + let mut start = 0usize; + while start < blobs.len() { + let mut end = start; + let mut encoded = Vec::new(); + while end < blobs.len() && end - start < WRITER_SHARD_MAX_ENTRIES { + let candidate = build_signed_manifest( + repo, + owner_did, + timestamp, + &blobs[start..=end], + keypair, + )?; + if candidate.len() > WRITER_MANIFEST_TARGET_BYTES { + break; + } + end += 1; + encoded = candidate; + } + if end == start { + return Err(invalid("one blob entry exceeds the writer shard byte target")); + } + shards.push(encoded); + start = end; + } + Ok(shards) +} + +/// Parse and verify a v2 manifest against caller-supplied trust. The expected +/// DID and repo come from outside the artifact; artifact identity fields are +/// equality inputs only. +pub fn verify_signed_manifest( + bytes: &[u8], + expected_node_did: &str, + expected_repo: &str, +) -> Result { + if bytes.len() > VERIFIER_MANIFEST_CAP_BYTES { + return Err(invalid("outer body exceeds verifier cap")); + } + validate_did_key_anchor(expected_node_did).map_err(|e| invalid(e.to_string()))?; + let expected_key = Did::from_str(expected_node_did) + .and_then(|d| d.to_verifying_key()) + .map_err(|e| invalid(e.to_string()))?; + + #[derive(Deserialize)] + struct SchemaProbe { + schema: String, + } + if let Ok(probe) = serde_json::from_slice::(bytes) { + if probe.schema != SCHEMA_V2 { + return Err(invalid("unsupported outer schema")); + } + } + let envelope: ManifestEnvelope = + serde_json::from_slice(bytes).map_err(|_| invalid("outer JSON shape"))?; + if envelope.schema != SCHEMA_V2 { + return Err(invalid("unsupported outer schema")); + } + let payload: ManifestPayload = serde_json::from_str(&envelope.payload) + .map_err(|_| invalid("inner payload JSON shape"))?; + if payload.schema != SCHEMA_V2 { + return Err(invalid("unsupported inner schema")); + } + validate_common( + &payload.repo, + &payload.owner_did, + &payload.node_did, + &payload.timestamp, + &payload.blobs, + )?; + if payload.repo != expected_repo { + return Err(invalid("signed repo does not match cloned repository")); + } + if payload.node_did != expected_node_did { + return Err(invalid("signer DID does not match expected node")); + } + let sig_bytes: [u8; 64] = URL_SAFE_NO_PAD + .decode(envelope.signature.as_bytes()) + .map_err(|_| invalid("signature is not base64url"))? + .try_into() + .map_err(|_| invalid("signature must be 64 bytes"))?; + identity::verify( + &expected_key, + &signing_input(envelope.payload.as_bytes()), + &sig_bytes, + ) + .map_err(|_| invalid("signature verification failed"))?; + + Ok(VerifiedManifest { + repo: payload.repo, + owner_did: payload.owner_did, + node_did: payload.node_did, + timestamp: payload.timestamp, + blobs: payload.blobs, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn keypair() -> Keypair { + Keypair::generate() + } + + fn oid(byte: u8) -> String { + hex::encode([byte; 20]) + } + + fn cid_for(byte: u8) -> String { + crate::cid::Cid::from_git_object_bytes(&[byte]).to_string() + } + + fn entries(count: usize) -> Vec { + (0..count) + .map(|i| EncryptedBlobRef { + oid: format!("{:040x}", i), + cid: cid_for((i % 251) as u8), + }) + .collect() + } + + fn fixture(kp: &Keypair) -> (Vec, String, String) { + let owner = kp.did().to_string(); + let repo = canonical_repo_slug(&owner, "repo"); + let body = build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &entries(1), kp) + .unwrap(); + (body, repo, kp.did().to_string()) + } + + #[test] + fn honest_manifest_verifies_and_returns_exact_entries() { + let kp = keypair(); + let (body, repo, did) = fixture(&kp); + let got = verify_signed_manifest(&body, &did, &repo).unwrap(); + assert_eq!(got.repo, repo); + assert_eq!(got.blobs, entries(1)); + } + + #[test] + fn signing_input_is_domain_plus_exact_payload_bytes() { + let payload = br#"{"schema":"s","repo":"r","owner_did":"o","node_did":"n","timestamp":"t","blobs":[]}"#; + let mut expected = SIGNING_DOMAIN.to_vec(); + expected.extend_from_slice(payload); + assert_eq!(signing_input(payload), expected); + } + + #[test] + fn valid_attacker_signature_is_rejected_for_wrong_expected_node() { + let attacker = keypair(); + let expected = keypair(); + let (body, repo, _) = fixture(&attacker); + assert!(verify_signed_manifest(&body, &expected.did().to_string(), &repo).is_err()); + } + + #[test] + fn correct_signer_for_another_repo_is_rejected() { + let kp = keypair(); + let owner = kp.did().to_string(); + let other_repo = canonical_repo_slug(&owner, "other"); + let body = build_signed_manifest( + &other_repo, + &owner, + "2026-01-01T00:00:00Z", + &entries(1), + &kp, + ) + .unwrap(); + assert!(verify_signed_manifest(&body, &kp.did().to_string(), &canonical_repo_slug(&owner, "repo")).is_err()); + } + + #[test] + fn canonical_owner_and_repo_slug_matrix() { + assert_eq!(canonical_owner_key("did:key:z6Mkabc"), "z6Mkabc"); + assert_eq!(canonical_owner_key("z6Mkabc"), "z6Mkabc"); + assert_eq!(canonical_owner_key("did:web:example.com:alice"), "did:web:example.com:alice"); + assert_eq!(canonical_owner_key("did:gitlawb:z6Mkfoo"), "did:gitlawb:z6Mkfoo"); + assert_eq!(canonical_owner_key("did:key:did:gitlawb:z6Mkfoo"), "did:key:did:gitlawb:z6Mkfoo"); + assert_eq!(canonical_repo_slug("did:key:z6Mkabc", "repo"), "z6Mkabc/repo"); + assert_eq!(canonical_repo_slug("did:web:example.com:alice", "repo"), "did:web:example.com:alice/repo"); + } + + #[test] + fn owner_must_canonicalize_to_repo_owner() { + let kp = keypair(); + let owner = kp.did().to_string(); + let wrong_repo = format!("someone-else/repo"); + assert!(build_signed_manifest(&wrong_repo, &owner, "2026-01-01T00:00:00Z", &entries(1), &kp).is_err()); + } + + #[test] + fn malformed_shape_cases_are_rejected_before_verification() { + let kp = keypair(); + let owner = kp.did().to_string(); + let repo = canonical_repo_slug(&owner, "repo"); + for (timestamp, blobs) in [ + ("not-a-time", entries(1)), + ("2026-01-01T00:00:00Z", vec![EncryptedBlobRef { oid: "abc".into(), cid: cid_for(1) }]), + ("2026-01-01T00:00:00Z", vec![EncryptedBlobRef { oid: oid(1), cid: "not-a-cid".into() }]), + ] { + assert!(build_signed_manifest(&repo, &owner, timestamp, &blobs, &kp).is_err()); + } + let duplicate = vec![ + EncryptedBlobRef { oid: oid(1), cid: cid_for(1) }, + EncryptedBlobRef { oid: oid(1), cid: cid_for(2) }, + ]; + assert!(build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &duplicate, &kp).is_err()); + } + + #[test] + fn outer_and_inner_schema_unknown_fields_and_bad_signature_are_rejected() { + let kp = keypair(); + let (body, repo, did) = fixture(&kp); + for raw in [ + br#"{"schema":"gitlawb/encrypted-manifest/v1","payload":"{}","signature":"x"}"#.to_vec(), + br#"{"schema":"gitlawb/encrypted-manifest/v2","payload":"{}","signature":"x","extra":1}"#.to_vec(), + br#"{"schema":"gitlawb/encrypted-manifest/v2","payload":"{}"}"#.to_vec(), + ] { + assert!(verify_signed_manifest(&raw, &did, &repo).is_err()); + } + let mut tampered = body.clone(); + let pos = tampered.len() - 3; + tampered[pos] = if tampered[pos] == b'A' { b'B' } else { b'A' }; + assert!(verify_signed_manifest(&tampered, &did, &repo).is_err()); + } + + #[test] + fn oid_shape_matrix() { + assert!(is_hex_oid(&"a".repeat(40))); + assert!(is_hex_oid(&"a".repeat(64))); + for bad in ["", "abc", &"z".repeat(40), "../".repeat(14).trim_end_matches('/')] { + assert!(!is_hex_oid(bad), "{bad:?}"); + } + } + + #[test] + fn longest_slugs_share_a_fixed_length_collision_resistant_digest() { + let owner = "z6Mk".to_string() + &"a".repeat(44); + let a = canonical_repo_slug(&owner, &format!("{}a", "r".repeat(79))); + let b = canonical_repo_slug(&owner, &format!("{}b", "r".repeat(79))); + assert!(a.len() > 128); + assert_eq!(repo_digest(&a).len(), 43); + assert_eq!(repo_digest(&b).len(), 43); + assert_ne!(repo_digest(&a), repo_digest(&b)); + } + + #[test] + fn cidv1_raw_and_dag_pb_pass_but_cidv0_and_paths_fail() { + let kp = keypair(); + let owner = kp.did().to_string(); + let repo = canonical_repo_slug(&owner, "repo"); + assert!(build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &[EncryptedBlobRef { oid: oid(1), cid: cid_for(1) }], &kp).is_ok()); + for bad in ["", "../x", "QmYwAPJzv5CZsnAzt8auVZRn7YHf7zq8Sa3s7kk6N6E5B1", "not-a-cid"] { + assert!(build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &[EncryptedBlobRef { oid: oid(1), cid: bad.into() }], &kp).is_err(), "{bad}"); + } + } + + #[test] + fn shard_boundaries_are_disjoint_and_within_targets() { + let kp = keypair(); + let owner = kp.did().to_string(); + let repo = canonical_repo_slug(&owner, "repo"); + let one = build_signed_manifest_shards(&repo, &owner, "2026-01-01T00:00:00Z", &entries(256), &kp).unwrap(); + assert_eq!(one.len(), 1); + assert!(one[0].len() <= WRITER_MANIFEST_TARGET_BYTES); + let two = build_signed_manifest_shards(&repo, &owner, "2026-01-01T00:00:00Z", &entries(257), &kp).unwrap(); + assert_eq!(two.len(), 2); + let mut seen = HashSet::new(); + for shard in two { + assert!(shard.len() <= WRITER_MANIFEST_TARGET_BYTES); + let verified = verify_signed_manifest(&shard, &kp.did().to_string(), &repo).unwrap(); + assert!(verified.blobs.len() <= WRITER_SHARD_MAX_ENTRIES); + for blob in verified.blobs { + assert!(seen.insert(blob.oid)); + } + } + assert_eq!(seen.len(), 257); + } + + #[test] + fn verifier_entry_count_boundary() { + let kp = keypair(); + let owner = kp.did().to_string(); + let repo = canonical_repo_slug(&owner, "repo"); + let ok = build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &entries(VERIFIER_MANIFEST_MAX_ENTRIES), &kp).unwrap(); + assert_eq!(verify_signed_manifest(&ok, &kp.did().to_string(), &repo).unwrap().blobs.len(), VERIFIER_MANIFEST_MAX_ENTRIES); + assert!(build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &entries(VERIFIER_MANIFEST_MAX_ENTRIES + 1), &kp).is_err()); + } + + #[test] + fn fixed_key_signs_and_verifies_fixed_payload_bytes() { + let kp = Keypair::from_seed(&[7u8; 32]).unwrap(); + let owner = kp.did().to_string(); + let repo = canonical_repo_slug(&owner, "repo"); + let first = build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &entries(1), &kp).unwrap(); + let second = build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &entries(1), &kp).unwrap(); + assert_eq!(first, second, "Ed25519 signing and exact payload bytes must be deterministic"); + verify_signed_manifest(&first, &kp.did().to_string(), &repo).unwrap(); + } + + #[test] + fn unsigned_v1_shaped_bytes_are_rejected() { + let kp = keypair(); + let owner = kp.did().to_string(); + let repo = canonical_repo_slug(&owner, "repo"); + let v1 = br#"{"schema":"gitlawb/encrypted-manifest/v1","repo":"x","owner_did":"x","node_did":"x","timestamp":"2026-01-01T00:00:00Z","blobs":[]}"#; + assert!(verify_signed_manifest(v1, &kp.did().to_string(), &repo).is_err()); + } +} diff --git a/crates/twigpine-core/src/lib.rs b/crates/twigpine-core/src/lib.rs index ba0f19b8a..6d2c1bf1c 100644 --- a/crates/twigpine-core/src/lib.rs +++ b/crates/twigpine-core/src/lib.rs @@ -2,6 +2,7 @@ pub mod cert; pub mod cid; pub mod did; pub mod encrypt; +pub mod encrypted_manifest; pub mod error; pub mod http_sig; pub mod identity; diff --git a/crates/twigpine-node/src/api/encrypted.rs b/crates/twigpine-node/src/api/encrypted.rs index 436cf47d4..aa969bb8a 100644 --- a/crates/twigpine-node/src/api/encrypted.rs +++ b/crates/twigpine-node/src/api/encrypted.rs @@ -27,7 +27,8 @@ pub(crate) const ENCRYPTED_BLOB_RATE_PER_MINUTE: usize = 120; /// Room for the envelope prefix, the JSON header at the maximum recipient /// count, and the body's AEAD tag. -const ENVELOPE_HEADER_ALLOWANCE: usize = 64 * 1024; +const ENVELOPE_HEADER_ALLOWANCE: usize = + twigpine_core::encrypt::ENCRYPTED_ENVELOPE_HEADER_ALLOWANCE_BYTES; /// Envelope bytes per body frame. const SERVE_CHUNK_BYTES: usize = 64 * 1024; diff --git a/crates/twigpine-node/src/api/ipfs.rs b/crates/twigpine-node/src/api/ipfs.rs index 944fecf0d..98379564f 100644 --- a/crates/twigpine-node/src/api/ipfs.rs +++ b/crates/twigpine-node/src/api/ipfs.rs @@ -156,7 +156,7 @@ pub(crate) const MAX_LEGACY_SCAN_RULE_BYTES_PER_REQUEST: usize = 4 * 1024 * 1024 /// (raise the cap if a class of legitimate objects legitimately exceeds it; never /// stream unverified). 32 MiB is generous for git blobs/trees/commits. Tunable via /// `AppState` for the test seam, like the sibling caps. -pub(crate) const MAX_SERVED_OBJECT_BYTES: u64 = 32 * 1024 * 1024; +pub(crate) const MAX_SERVED_OBJECT_BYTES: u64 = twigpine_core::encrypt::MAX_ENCRYPTED_OBJECT_BYTES; /// Keyset pager for the legacy (NULL-provenance) scan fallback in `get_by_cid`. /// From fddf1b855c53781ddb9bfdb9c414fb0880f854d8 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:02:12 -0600 Subject: [PATCH 02/18] feat(node): sign encrypted recovery manifest shards --- .../twigpine-core/src/encrypted_manifest.rs | 182 ++++++++-- crates/twigpine-node/src/api/repos.rs | 43 ++- crates/twigpine-node/src/arweave.rs | 324 +++++++++++++----- crates/twigpine-node/src/reconciliation.rs | 8 +- 4 files changed, 417 insertions(+), 140 deletions(-) diff --git a/crates/twigpine-core/src/encrypted_manifest.rs b/crates/twigpine-core/src/encrypted_manifest.rs index ff9e65def..a644b1c0d 100644 --- a/crates/twigpine-core/src/encrypted_manifest.rs +++ b/crates/twigpine-core/src/encrypted_manifest.rs @@ -99,7 +99,9 @@ pub fn validate_did_key_anchor(did: &str) -> Result { let key = parsed.to_verifying_key()?; let canonical = Did::from_verifying_key(&key); if canonical.as_str() != did { - return Err(Error::InvalidDid("non-canonical did:key spelling".to_string())); + return Err(Error::InvalidDid( + "non-canonical did:key spelling".to_string(), + )); } Ok(parsed) } @@ -222,13 +224,8 @@ pub fn build_signed_manifest_shards( let mut end = start; let mut encoded = Vec::new(); while end < blobs.len() && end - start < WRITER_SHARD_MAX_ENTRIES { - let candidate = build_signed_manifest( - repo, - owner_did, - timestamp, - &blobs[start..=end], - keypair, - )?; + let candidate = + build_signed_manifest(repo, owner_did, timestamp, &blobs[start..=end], keypair)?; if candidate.len() > WRITER_MANIFEST_TARGET_BYTES { break; } @@ -236,7 +233,9 @@ pub fn build_signed_manifest_shards( encoded = candidate; } if end == start { - return Err(invalid("one blob entry exceeds the writer shard byte target")); + return Err(invalid( + "one blob entry exceeds the writer shard byte target", + )); } shards.push(encoded); start = end; @@ -274,8 +273,8 @@ pub fn verify_signed_manifest( if envelope.schema != SCHEMA_V2 { return Err(invalid("unsupported outer schema")); } - let payload: ManifestPayload = serde_json::from_str(&envelope.payload) - .map_err(|_| invalid("inner payload JSON shape"))?; + let payload: ManifestPayload = + serde_json::from_str(&envelope.payload).map_err(|_| invalid("inner payload JSON shape"))?; if payload.schema != SCHEMA_V2 { return Err(invalid("unsupported inner schema")); } @@ -341,8 +340,8 @@ mod tests { fn fixture(kp: &Keypair) -> (Vec, String, String) { let owner = kp.did().to_string(); let repo = canonical_repo_slug(&owner, "repo"); - let body = build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &entries(1), kp) - .unwrap(); + let body = + build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &entries(1), kp).unwrap(); (body, repo, kp.did().to_string()) } @@ -384,18 +383,38 @@ mod tests { &kp, ) .unwrap(); - assert!(verify_signed_manifest(&body, &kp.did().to_string(), &canonical_repo_slug(&owner, "repo")).is_err()); + assert!(verify_signed_manifest( + &body, + &kp.did().to_string(), + &canonical_repo_slug(&owner, "repo") + ) + .is_err()); } #[test] fn canonical_owner_and_repo_slug_matrix() { assert_eq!(canonical_owner_key("did:key:z6Mkabc"), "z6Mkabc"); assert_eq!(canonical_owner_key("z6Mkabc"), "z6Mkabc"); - assert_eq!(canonical_owner_key("did:web:example.com:alice"), "did:web:example.com:alice"); - assert_eq!(canonical_owner_key("did:gitlawb:z6Mkfoo"), "did:gitlawb:z6Mkfoo"); - assert_eq!(canonical_owner_key("did:key:did:gitlawb:z6Mkfoo"), "did:key:did:gitlawb:z6Mkfoo"); - assert_eq!(canonical_repo_slug("did:key:z6Mkabc", "repo"), "z6Mkabc/repo"); - assert_eq!(canonical_repo_slug("did:web:example.com:alice", "repo"), "did:web:example.com:alice/repo"); + assert_eq!( + canonical_owner_key("did:web:example.com:alice"), + "did:web:example.com:alice" + ); + assert_eq!( + canonical_owner_key("did:gitlawb:z6Mkfoo"), + "did:gitlawb:z6Mkfoo" + ); + assert_eq!( + canonical_owner_key("did:key:did:gitlawb:z6Mkfoo"), + "did:key:did:gitlawb:z6Mkfoo" + ); + assert_eq!( + canonical_repo_slug("did:key:z6Mkabc", "repo"), + "z6Mkabc/repo" + ); + assert_eq!( + canonical_repo_slug("did:web:example.com:alice", "repo"), + "did:web:example.com:alice/repo" + ); } #[test] @@ -403,7 +422,14 @@ mod tests { let kp = keypair(); let owner = kp.did().to_string(); let wrong_repo = format!("someone-else/repo"); - assert!(build_signed_manifest(&wrong_repo, &owner, "2026-01-01T00:00:00Z", &entries(1), &kp).is_err()); + assert!(build_signed_manifest( + &wrong_repo, + &owner, + "2026-01-01T00:00:00Z", + &entries(1), + &kp + ) + .is_err()); } #[test] @@ -413,16 +439,36 @@ mod tests { let repo = canonical_repo_slug(&owner, "repo"); for (timestamp, blobs) in [ ("not-a-time", entries(1)), - ("2026-01-01T00:00:00Z", vec![EncryptedBlobRef { oid: "abc".into(), cid: cid_for(1) }]), - ("2026-01-01T00:00:00Z", vec![EncryptedBlobRef { oid: oid(1), cid: "not-a-cid".into() }]), + ( + "2026-01-01T00:00:00Z", + vec![EncryptedBlobRef { + oid: "abc".into(), + cid: cid_for(1), + }], + ), + ( + "2026-01-01T00:00:00Z", + vec![EncryptedBlobRef { + oid: oid(1), + cid: "not-a-cid".into(), + }], + ), ] { assert!(build_signed_manifest(&repo, &owner, timestamp, &blobs, &kp).is_err()); } let duplicate = vec![ - EncryptedBlobRef { oid: oid(1), cid: cid_for(1) }, - EncryptedBlobRef { oid: oid(1), cid: cid_for(2) }, + EncryptedBlobRef { + oid: oid(1), + cid: cid_for(1), + }, + EncryptedBlobRef { + oid: oid(1), + cid: cid_for(2), + }, ]; - assert!(build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &duplicate, &kp).is_err()); + assert!( + build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &duplicate, &kp).is_err() + ); } #[test] @@ -446,7 +492,12 @@ mod tests { fn oid_shape_matrix() { assert!(is_hex_oid(&"a".repeat(40))); assert!(is_hex_oid(&"a".repeat(64))); - for bad in ["", "abc", &"z".repeat(40), "../".repeat(14).trim_end_matches('/')] { + for bad in [ + "", + "abc", + &"z".repeat(40), + "../".repeat(14).trim_end_matches('/'), + ] { assert!(!is_hex_oid(bad), "{bad:?}"); } } @@ -467,9 +518,37 @@ mod tests { let kp = keypair(); let owner = kp.did().to_string(); let repo = canonical_repo_slug(&owner, "repo"); - assert!(build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &[EncryptedBlobRef { oid: oid(1), cid: cid_for(1) }], &kp).is_ok()); - for bad in ["", "../x", "QmYwAPJzv5CZsnAzt8auVZRn7YHf7zq8Sa3s7kk6N6E5B1", "not-a-cid"] { - assert!(build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &[EncryptedBlobRef { oid: oid(1), cid: bad.into() }], &kp).is_err(), "{bad}"); + assert!(build_signed_manifest( + &repo, + &owner, + "2026-01-01T00:00:00Z", + &[EncryptedBlobRef { + oid: oid(1), + cid: cid_for(1) + }], + &kp + ) + .is_ok()); + for bad in [ + "", + "../x", + "QmYwAPJzv5CZsnAzt8auVZRn7YHf7zq8Sa3s7kk6N6E5B1", + "not-a-cid", + ] { + assert!( + build_signed_manifest( + &repo, + &owner, + "2026-01-01T00:00:00Z", + &[EncryptedBlobRef { + oid: oid(1), + cid: bad.into() + }], + &kp + ) + .is_err(), + "{bad}" + ); } } @@ -478,10 +557,14 @@ mod tests { let kp = keypair(); let owner = kp.did().to_string(); let repo = canonical_repo_slug(&owner, "repo"); - let one = build_signed_manifest_shards(&repo, &owner, "2026-01-01T00:00:00Z", &entries(256), &kp).unwrap(); + let one = + build_signed_manifest_shards(&repo, &owner, "2026-01-01T00:00:00Z", &entries(256), &kp) + .unwrap(); assert_eq!(one.len(), 1); assert!(one[0].len() <= WRITER_MANIFEST_TARGET_BYTES); - let two = build_signed_manifest_shards(&repo, &owner, "2026-01-01T00:00:00Z", &entries(257), &kp).unwrap(); + let two = + build_signed_manifest_shards(&repo, &owner, "2026-01-01T00:00:00Z", &entries(257), &kp) + .unwrap(); assert_eq!(two.len(), 2); let mut seen = HashSet::new(); for shard in two { @@ -500,9 +583,29 @@ mod tests { let kp = keypair(); let owner = kp.did().to_string(); let repo = canonical_repo_slug(&owner, "repo"); - let ok = build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &entries(VERIFIER_MANIFEST_MAX_ENTRIES), &kp).unwrap(); - assert_eq!(verify_signed_manifest(&ok, &kp.did().to_string(), &repo).unwrap().blobs.len(), VERIFIER_MANIFEST_MAX_ENTRIES); - assert!(build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &entries(VERIFIER_MANIFEST_MAX_ENTRIES + 1), &kp).is_err()); + let ok = build_signed_manifest( + &repo, + &owner, + "2026-01-01T00:00:00Z", + &entries(VERIFIER_MANIFEST_MAX_ENTRIES), + &kp, + ) + .unwrap(); + assert_eq!( + verify_signed_manifest(&ok, &kp.did().to_string(), &repo) + .unwrap() + .blobs + .len(), + VERIFIER_MANIFEST_MAX_ENTRIES + ); + assert!(build_signed_manifest( + &repo, + &owner, + "2026-01-01T00:00:00Z", + &entries(VERIFIER_MANIFEST_MAX_ENTRIES + 1), + &kp + ) + .is_err()); } #[test] @@ -510,9 +613,14 @@ mod tests { let kp = Keypair::from_seed(&[7u8; 32]).unwrap(); let owner = kp.did().to_string(); let repo = canonical_repo_slug(&owner, "repo"); - let first = build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &entries(1), &kp).unwrap(); - let second = build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &entries(1), &kp).unwrap(); - assert_eq!(first, second, "Ed25519 signing and exact payload bytes must be deterministic"); + let first = + build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &entries(1), &kp).unwrap(); + let second = + build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &entries(1), &kp).unwrap(); + assert_eq!( + first, second, + "Ed25519 signing and exact payload bytes must be deterministic" + ); verify_signed_manifest(&first, &kp.did().to_string(), &repo).unwrap(); } diff --git a/crates/twigpine-node/src/api/repos.rs b/crates/twigpine-node/src/api/repos.rs index fd2a3d2d1..691b2871c 100644 --- a/crates/twigpine-node/src/api/repos.rs +++ b/crates/twigpine-node/src/api/repos.rs @@ -1429,7 +1429,6 @@ struct EncryptTaskCtx { repo_name: String, irys_url: String, http_client: Arc, - node_did: String, node_keypair: Arc, git_bin: String, git_timeout: std::time::Duration, @@ -1503,6 +1502,37 @@ pub(crate) async fn run_encrypt_pin_task_for_test( snapshot_objects: Vec, snapshot_rules: Option>, snapshot_is_public: bool, +) { + run_encrypt_pin_task_for_test_with_irys( + state, + guard, + disk_path, + repo_id, + owner_did, + repo_name, + ipfs_api, + snapshot_objects, + snapshot_rules, + snapshot_is_public, + String::new(), + ) + .await; +} + +#[cfg(test)] +#[allow(clippy::too_many_arguments)] +pub(crate) async fn run_encrypt_pin_task_for_test_with_irys( + state: &AppState, + guard: crate::state::EncryptInflightGuard, + disk_path: std::path::PathBuf, + repo_id: String, + owner_did: String, + repo_name: String, + ipfs_api: String, + snapshot_objects: Vec, + snapshot_rules: Option>, + snapshot_is_public: bool, + irys_url: String, ) { let ctx = EncryptTaskCtx { ipfs_api, @@ -1511,10 +1541,9 @@ pub(crate) async fn run_encrypt_pin_task_for_test( repo_id, owner_did, repo_name, - irys_url: String::new(), + irys_url, // Only used for the operator-configured Irys endpoint. http_client: Arc::new(crate::operator_http_client().clone()), - node_did: state.node_did.to_string(), node_keypair: std::sync::Arc::clone(&state.node_keypair), git_bin: state.git_bin.clone(), git_timeout: std::time::Duration::from_secs(state.config.git_service_timeout_secs), @@ -2165,7 +2194,6 @@ async fn pin_and_encrypt_objects( let manifest = crate::arweave::EncryptedManifest { repo: &repo_slug, owner_did: &ctx.owner_did, - node_did: &ctx.node_did, timestamp: &ts, blobs: &delta, }; @@ -2173,12 +2201,13 @@ async fn pin_and_encrypt_objects( &ctx.http_client, &ctx.irys_url, &manifest, + &ctx.node_keypair, ) .await { - Ok(tx) if !tx.is_empty() => tracing::info!( + Ok(tx_ids) if !tx_ids.is_empty() => tracing::info!( repo = %repo_slug, - tx_id = %tx, + tx_ids = ?tx_ids, "anchored encrypted manifest to Arweave" ), Ok(_) => {} @@ -4917,7 +4946,6 @@ pub(crate) async fn post_receive_replication_tail( irys_url: state.config.irys_url.clone(), // Only used for the operator-configured Irys endpoint. http_client: Arc::new(crate::operator_http_client().clone()), - node_did: state.node_did.to_string(), node_keypair: std::sync::Arc::clone(&state.node_keypair), git_bin: state.git_bin.clone(), git_timeout: std::time::Duration::from_secs(state.config.git_service_timeout_secs), @@ -14988,7 +15016,6 @@ mod tests { repo_name: rec.name.clone(), irys_url: String::new(), http_client: std::sync::Arc::clone(&state.http_client), - node_did: state.node_did.to_string(), node_keypair: std::sync::Arc::clone(&state.node_keypair), git_bin: git_bin.to_string(), git_timeout: std::time::Duration::from_secs(600), diff --git a/crates/twigpine-node/src/arweave.rs b/crates/twigpine-node/src/arweave.rs index ca0267620..b065f7b3e 100644 --- a/crates/twigpine-node/src/arweave.rs +++ b/crates/twigpine-node/src/arweave.rs @@ -227,56 +227,28 @@ fn build_release_tags_header(anchor: &ReleaseAnchor) -> String { } /// A per-push manifest of the blobs encrypted this push (Option B3). The -/// `blobs` slice is `(oid, cid)` tuples. Anchored directly to Arweave as its JSON -/// body so the discovery index survives total node loss. Recipient identities are -/// never part of the manifest. +/// `blobs` slice is `(oid, cid)` tuples. Anchored directly to Arweave as signed +/// JSON shards so the discovery index survives total node loss. Recipient +/// identities are never part of the manifest. pub struct EncryptedManifest<'a> { pub repo: &'a str, pub owner_did: &'a str, - pub node_did: &'a str, pub timestamp: &'a str, pub blobs: &'a [(String, String)], } -/// Anchor a per-push encrypted-blob manifest to Arweave via Irys. The manifest -/// JSON body is the payload (not a CID pointer to IPFS), so the index is -/// permanent and self-contained. Recipient identities are deliberately omitted: -/// the anchor is permanent and public, and the v2 envelopes no longer expose -/// recipients, so the reader set must not be written to Arweave either. -/// -/// Returns the Irys/Arweave transaction ID, or `Ok("")` when `irys_url` is empty -/// (anchoring disabled) or there are no blobs to anchor. -pub async fn anchor_encrypted_manifest( +/// Upload one already-constructed manifest shard and return its transaction id. +async fn upload_manifest_shard( client: &reqwest::Client, irys_url: &str, - manifest: &EncryptedManifest<'_>, + tags: &str, + body: Vec, ) -> Result { - if irys_url.is_empty() || manifest.blobs.is_empty() { - return Ok(String::new()); - } - - let blobs_json: Vec = manifest - .blobs - .iter() - .map(|(oid, cid)| manifest_blob_json(oid, cid)) - .collect(); - - let payload = json!({ - "schema": "gitlawb/encrypted-manifest/v1", - "repo": manifest.repo, - "owner_did": manifest.owner_did, - "node_did": manifest.node_did, - "timestamp": manifest.timestamp, - "blobs": blobs_json, - }); - - let body = serde_json::to_vec(&payload)?; let url = format!("{}/upload", irys_url.trim_end_matches('/')); - let resp = client .post(&url) .header("Content-Type", "application/json") - .header("x-irys-tags", build_manifest_tags_header(manifest)) + .header("x-irys-tags", tags) .body(body) .send() .await @@ -292,39 +264,97 @@ pub async fn anchor_encrypted_manifest( .json() .await .map_err(|e| anyhow::anyhow!("failed to parse Irys response: {e}"))?; - - let tx_id = json["id"] + json["id"] .as_str() - .ok_or_else(|| anyhow::anyhow!("no 'id' in Irys response: {json}"))? - .to_string(); + .map(str::to_string) + .ok_or_else(|| anyhow::anyhow!("no 'id' in Irys response: {json}")) +} - tracing::info!( - repo = %manifest.repo, - tx_id = %tx_id, - blobs = manifest.blobs.len(), - "anchored encrypted manifest to Arweave" - ); +/// Anchor a per-push encrypted-blob manifest to Arweave via Irys as one or +/// more signed v2 shards. Every shard is complete for a disjoint subset of the +/// delta. Uploads stay best-effort: a failed shard is logged and later shards +/// are still attempted. Returns the transaction ids for shards that uploaded; +/// an empty vector means anchoring was disabled or there was no delta. +pub async fn anchor_encrypted_manifest( + client: &reqwest::Client, + irys_url: &str, + manifest: &EncryptedManifest<'_>, + keypair: &twigpine_core::identity::Keypair, +) -> Result> { + if irys_url.is_empty() || manifest.blobs.is_empty() { + return Ok(Vec::new()); + } - Ok(tx_id) -} + let blobs: Vec = manifest + .blobs + .iter() + .map( + |(oid, cid)| twigpine_core::encrypted_manifest::EncryptedBlobRef { + oid: oid.clone(), + cid: cid.clone(), + }, + ) + .collect(); + let shards = twigpine_core::encrypted_manifest::build_signed_manifest_shards( + manifest.repo, + manifest.owner_did, + manifest.timestamp, + &blobs, + keypair, + )?; + + let tags = build_manifest_tags_header(manifest, &keypair.did().to_string()); + let mut tx_ids = Vec::new(); + let mut failures = Vec::new(); + for body in shards { + let bytes = body.len(); + match upload_manifest_shard(client, irys_url, &tags, body).await { + Ok(tx_id) => { + tracing::info!( + repo = %manifest.repo, + tx_id = %tx_id, + bytes, + "anchored encrypted manifest shard to Arweave" + ); + tx_ids.push(tx_id); + } + Err(e) => { + tracing::warn!( + repo = %manifest.repo, + err = %e, + "encrypted manifest shard upload failed" + ); + failures.push(e.to_string()); + } + } + } -/// Serialize one blob for the Arweave manifest. Recipient identities are -/// intentionally absent so the permanent public anchor never records who can -/// read a blob. -fn manifest_blob_json(oid: &str, cid: &str) -> serde_json::Value { - json!({ "oid": oid, "cid": cid }) + if tx_ids.is_empty() && !failures.is_empty() { + return Err(anyhow::anyhow!( + "all encrypted manifest shard uploads failed: {}", + failures.join("; ") + )); + } + Ok(tx_ids) } -/// Build the Irys tag header for an encrypted-blob manifest. `Repo` and `Schema` -/// are the tags the `twigpine` recovery query filters on. -fn build_manifest_tags_header(manifest: &EncryptedManifest<'_>) -> String { +/// Build the Irys tag header for encrypted-blob manifest shards. `Schema` and +/// `Repo-Digest` are the v2 discovery keys; the truncated human-readable `Repo` +/// tag remains diagnostic because legacy tag values cannot represent every +/// canonical long slug exactly. +fn build_manifest_tags_header(manifest: &EncryptedManifest<'_>, node_did: &str) -> String { [ // Written under the old name until writers switch: see docs/LEGACY-NAMES.md. "App-Name:gitlawb".to_string(), - "Schema:gitlawb/encrypted-manifest/v1".to_string(), + format!("Schema:{}", twigpine_core::encrypted_manifest::SCHEMA_V2), + format!( + "{}:{}", + twigpine_core::encrypted_manifest::REPO_DIGEST_TAG, + twigpine_core::encrypted_manifest::repo_digest(manifest.repo) + ), format!("Repo:{}", sanitize_tag(manifest.repo)), format!("Owner-DID:{}", sanitize_tag(manifest.owner_did)), - format!("Node-DID:{}", sanitize_tag(manifest.node_did)), + format!("Node-DID:{}", sanitize_tag(node_did)), ] .join(",") } @@ -458,77 +488,189 @@ mod tests { ); } + fn manifest_fixture( + count: usize, + ) -> ( + twigpine_core::identity::Keypair, + String, + String, + Vec<(String, String)>, + ) { + let kp = twigpine_core::identity::Keypair::generate(); + let owner = kp.did().to_string(); + let repo = twigpine_core::encrypted_manifest::canonical_repo_slug(&owner, "r"); + let blobs = (0..count) + .map(|i| { + ( + format!("{i:040x}"), + twigpine_core::cid::Cid::from_git_object_bytes(&[i as u8]).to_string(), + ) + }) + .collect(); + (kp, owner, repo, blobs) + } + #[tokio::test] async fn test_manifest_anchor_noop_when_url_empty() { let client = reqwest::Client::new(); - let blobs = vec![("oid1".to_string(), "cid1".to_string())]; + let (kp, owner, repo, blobs) = manifest_fixture(1); let m = EncryptedManifest { - repo: "alice/r", - owner_did: "did:key:zO", - node_did: "did:key:zN", + repo: &repo, + owner_did: &owner, timestamp: "2026-06-11T00:00:00Z", blobs: &blobs, }; - assert_eq!( - anchor_encrypted_manifest(&client, "", &m).await.unwrap(), - "" - ); + assert!(anchor_encrypted_manifest(&client, "", &m, &kp) + .await + .unwrap() + .is_empty()); } #[tokio::test] async fn test_manifest_anchor_noop_when_no_blobs() { let client = reqwest::Client::new(); + let (kp, owner, repo, _blobs) = manifest_fixture(1); let blobs: Vec<(String, String)> = vec![]; let m = EncryptedManifest { - repo: "alice/r", - owner_did: "did:key:zO", - node_did: "did:key:zN", + repo: &repo, + owner_did: &owner, timestamp: "2026-06-11T00:00:00Z", blobs: &blobs, }; - // Non-empty URL, but no blobs: still a no-op. - assert_eq!( - anchor_encrypted_manifest(&client, "https://example.invalid", &m) + assert!( + anchor_encrypted_manifest(&client, "https://example.invalid", &m, &kp) .await - .unwrap(), - "" + .unwrap() + .is_empty() ); } #[tokio::test] - async fn test_manifest_anchor_success() { + async fn test_manifest_anchor_success_posts_signed_v2_exact_bytes() { + let (kp, owner, repo, blobs) = manifest_fixture(1); + let expected_did = kp.did().to_string(); + let expected_repo = repo.clone(); + let expected_oid = blobs[0].0.clone(); + let expected_cid = blobs[0].1.clone(); let mut server = mockito::Server::new_async().await; let _mock = server .mock("POST", "/upload") + .match_header( + "x-irys-tags", + mockito::Matcher::Regex( + "App-Name:gitlawb,Schema:gitlawb/encrypted-manifest/v2,Repo-Digest:" + .to_string(), + ), + ) .with_status(200) .with_header("content-type", "application/json") - .with_body(r#"{"id":"MANIFESTTX123","timestamp":1710000000000,"version":"1.0.0"}"#) + .with_body_from_request(move |req| { + let body: &[u8] = req.body().map(|b| b.as_slice()).unwrap_or(&[]); + let text = String::from_utf8_lossy(body); + assert!(!text.contains("recipients")); + let verified = twigpine_core::encrypted_manifest::verify_signed_manifest( + body, + &expected_did, + &expected_repo, + ) + .expect("uploaded shard must verify against the node key"); + assert_eq!(verified.blobs.len(), 1); + assert_eq!(verified.blobs[0].oid, expected_oid); + assert_eq!(verified.blobs[0].cid, expected_cid); + br#"{"id":"MANIFESTTX123","timestamp":1710000000000,"version":"1.0.0"}"#.to_vec() + }) .create_async() .await; let client = reqwest::Client::new(); - let blobs = vec![("oid1".to_string(), "cid1".to_string())]; let m = EncryptedManifest { - repo: "alice/r", - owner_did: "did:key:zO", - node_did: "did:key:zN", + repo: &repo, + owner_did: &owner, timestamp: "2026-06-11T00:00:00Z", blobs: &blobs, }; - let r = anchor_encrypted_manifest(&client, &server.url(), &m).await; - assert_eq!(r.unwrap(), "MANIFESTTX123"); + let r = anchor_encrypted_manifest(&client, &server.url(), &m, &kp).await; + assert_eq!(r.unwrap(), vec!["MANIFESTTX123".to_string()]); _mock.assert_async().await; } - #[test] - fn manifest_blob_json_omits_recipients() { - let v = manifest_blob_json("oid1", "cidA"); - assert_eq!(v["oid"], "oid1"); - assert_eq!(v["cid"], "cidA"); - assert!( - v.get("recipients").is_none(), - "Arweave manifest must not anchor recipient identities" - ); + #[tokio::test] + async fn test_manifest_anchor_shards_257_entries_into_two_signed_uploads() { + let (kp, owner, repo, blobs) = manifest_fixture(257); + let expected_did = kp.did().to_string(); + let expected_repo = repo.clone(); + let mut server = mockito::Server::new_async().await; + let _mock = server + .mock("POST", "/upload") + .expect(2) + .with_status(200) + .with_header("content-type", "application/json") + .with_body_from_request(move |req| { + let body: &[u8] = req.body().map(|b| b.as_slice()).unwrap_or(&[]); + let verified = twigpine_core::encrypted_manifest::verify_signed_manifest( + body, + &expected_did, + &expected_repo, + ) + .expect("every uploaded shard must verify"); + assert!( + verified.blobs.len() + <= twigpine_core::encrypted_manifest::WRITER_SHARD_MAX_ENTRIES + ); + br#"{"id":"SHARDTX","timestamp":1710000000000,"version":"1.0.0"}"#.to_vec() + }) + .create_async() + .await; + + let client = reqwest::Client::new(); + let m = EncryptedManifest { + repo: &repo, + owner_did: &owner, + timestamp: "2026-06-11T00:00:00Z", + blobs: &blobs, + }; + let ids = anchor_encrypted_manifest(&client, &server.url(), &m, &kp) + .await + .unwrap(); + assert_eq!(ids.len(), 2); + _mock.assert_async().await; + } + + #[tokio::test] + async fn test_one_shard_failure_does_not_prevent_other_shard_uploads() { + let (kp, owner, repo, blobs) = manifest_fixture(257); + let first_oid = blobs[0].0.clone(); + let mut server = mockito::Server::new_async().await; + let failing = server + .mock("POST", "/upload") + .match_body(mockito::Matcher::Regex(first_oid)) + .expect(1) + .with_status(500) + .with_body("shard failure") + .create_async() + .await; + let succeeding = server + .mock("POST", "/upload") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"id":"SURVIVINGSHARD","timestamp":1710000000000,"version":"1.0.0"}"#) + .create_async() + .await; + + let client = reqwest::Client::new(); + let m = EncryptedManifest { + repo: &repo, + owner_did: &owner, + timestamp: "2026-06-11T00:00:00Z", + blobs: &blobs, + }; + let ids = anchor_encrypted_manifest(&client, &server.url(), &m, &kp) + .await + .unwrap(); + assert_eq!(ids, vec!["SURVIVINGSHARD".to_string()]); + failing.assert_async().await; + succeeding.assert_async().await; } #[test] diff --git a/crates/twigpine-node/src/reconciliation.rs b/crates/twigpine-node/src/reconciliation.rs index 6d26b20ee..8f5ca2000 100644 --- a/crates/twigpine-node/src/reconciliation.rs +++ b/crates/twigpine-node/src/reconciliation.rs @@ -710,13 +710,15 @@ async fn run_pass( config: &Config, http_client: &reqwest::Client, node_seed: &[u8; 32], - node_did: &twigpine_core::did::Did, + _node_did: &twigpine_core::did::Did, pin_sem: &Arc, rederive_budget: Duration, cursor: &mut Option, shutdown_rx: &mut watch::Receiver, repo_store: Option, ) -> anyhow::Result<(usize, usize, usize)> { + let manifest_keypair = twigpine_core::identity::Keypair::from_seed(node_seed)?; + // Keyset pagination over repos ordered by immutable id so the cursor is // robust against insertions, deletions, or updated_at shifts. The LIMIT // is pushed into the SQL query so the hourly pass does not allocate, @@ -1860,12 +1862,9 @@ async fn run_pass( let owner_short = crate::db::normalize_owner_key(&fresh_repo2.owner_did); let slug = format!("{}/{}", owner_short, fresh_repo2.name); let ts = chrono::Utc::now().to_rfc3339(); - let node_did_str = node_did.to_string(); - let manifest = crate::arweave::EncryptedManifest { repo: &slug, owner_did: &fresh_repo2.owner_did, - node_did: &node_did_str, timestamp: &ts, blobs: &sealed, }; @@ -1873,6 +1872,7 @@ async fn run_pass( http_client, &config.irys_url, &manifest, + &manifest_keypair, ) .await { From 6d694d5592babcbe74aec2a2d8eb435ff6a2fdcc Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:15:50 -0600 Subject: [PATCH 03/18] fix(core): scale encrypted manifest sharding --- .../twigpine-core/src/encrypted_manifest.rs | 131 +++++++++++++++--- 1 file changed, 112 insertions(+), 19 deletions(-) diff --git a/crates/twigpine-core/src/encrypted_manifest.rs b/crates/twigpine-core/src/encrypted_manifest.rs index a644b1c0d..19cd70bdf 100644 --- a/crates/twigpine-core/src/encrypted_manifest.rs +++ b/crates/twigpine-core/src/encrypted_manifest.rs @@ -122,9 +122,6 @@ fn validate_common( Did::from_str(owner_did).map_err(|e| invalid(e.to_string()))?; validate_did_key_anchor(node_did).map_err(|e| invalid(e.to_string()))?; DateTime::parse_from_rfc3339(timestamp).map_err(|_| invalid("timestamp is not RFC3339"))?; - if blobs.len() > VERIFIER_MANIFEST_MAX_ENTRIES { - return Err(invalid("too many blob entries")); - } let owner_part = repo.split_once('/').map(|(owner, _)| owner).unwrap_or(""); if canonical_owner_key(owner_did) != owner_part { return Err(invalid("owner DID does not canonicalize to repo owner")); @@ -134,7 +131,7 @@ fn validate_common( if !is_hex_oid(&blob.oid) { return Err(invalid("blob oid is not a 40-or-64 hex object id")); } - if !seen.insert(blob.oid.as_str()) { + if !seen.insert(blob.oid.to_ascii_lowercase()) { return Err(invalid("duplicate blob oid")); } let parsed = blob @@ -187,6 +184,9 @@ pub fn build_signed_manifest( blobs: &[EncryptedBlobRef], keypair: &Keypair, ) -> Result> { + if blobs.len() > VERIFIER_MANIFEST_MAX_ENTRIES { + return Err(invalid("too many blob entries")); + } let payload = ManifestPayload { schema: SCHEMA_V2.to_string(), repo: repo.to_string(), @@ -221,24 +221,44 @@ pub fn build_signed_manifest_shards( let mut shards = Vec::new(); let mut start = 0usize; while start < blobs.len() { - let mut end = start; - let mut encoded = Vec::new(); - while end < blobs.len() && end - start < WRITER_SHARD_MAX_ENTRIES { - let candidate = - build_signed_manifest(repo, owner_did, timestamp, &blobs[start..=end], keypair)?; - if candidate.len() > WRITER_MANIFEST_TARGET_BYTES { - break; - } - end += 1; - encoded = candidate; - } - if end == start { + let max_end = blobs.len().min(start + WRITER_SHARD_MAX_ENTRIES); + let first = build_signed_manifest( + repo, + owner_did, + timestamp, + &blobs[start..start + 1], + keypair, + )?; + if first.len() > WRITER_MANIFEST_TARGET_BYTES { return Err(invalid( "one blob entry exceeds the writer shard byte target", )); } - shards.push(encoded); - start = end; + + // Entry order is fixed and every entry adds positive length, so shard + // size is monotonic in the entry count. Binary-search the largest + // fitting prefix instead of re-signing every intermediate prefix. + let mut low = start + 1; + let mut high = max_end; + let mut best_end = start + 1; + let mut best_encoded = first; + while low <= high { + let mid = low + (high - low) / 2; + let candidate = + build_signed_manifest(repo, owner_did, timestamp, &blobs[start..mid], keypair)?; + if candidate.len() <= WRITER_MANIFEST_TARGET_BYTES { + best_end = mid; + best_encoded = candidate; + low = mid + 1; + } else { + if mid == start + 1 { + break; + } + high = mid - 1; + } + } + shards.push(best_encoded); + start = best_end; } Ok(shards) } @@ -278,6 +298,9 @@ pub fn verify_signed_manifest( if payload.schema != SCHEMA_V2 { return Err(invalid("unsupported inner schema")); } + if payload.blobs.len() > VERIFIER_MANIFEST_MAX_ENTRIES { + return Err(invalid("too many blob entries")); + } validate_common( &payload.repo, &payload.owner_did, @@ -303,12 +326,23 @@ pub fn verify_signed_manifest( ) .map_err(|_| invalid("signature verification failed"))?; + let blobs = payload + .blobs + .into_iter() + .map(|mut blob| { + // Git object ids are hexadecimal and case-insensitive. The wire + // accepts either spelling, while recovery compares against git's + // lowercase tree output. + blob.oid = blob.oid.to_ascii_lowercase(); + blob + }) + .collect(); Ok(VerifiedManifest { repo: payload.repo, owner_did: payload.owner_did, node_did: payload.node_did, timestamp: payload.timestamp, - blobs: payload.blobs, + blobs, }) } @@ -632,4 +666,63 @@ mod tests { let v1 = br#"{"schema":"gitlawb/encrypted-manifest/v1","repo":"x","owner_did":"x","node_did":"x","timestamp":"2026-01-01T00:00:00Z","blobs":[]}"#; assert!(verify_signed_manifest(v1, &kp.did().to_string(), &repo).is_err()); } + + #[test] + fn verifier_normalizes_uppercase_oids_and_duplicates_are_case_insensitive() { + let kp = keypair(); + let owner = kp.did().to_string(); + let repo = canonical_repo_slug(&owner, "repo"); + let upper = vec![EncryptedBlobRef { + oid: oid(1).to_ascii_uppercase(), + cid: cid_for(1), + }]; + let body = + build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &upper, &kp).unwrap(); + let verified = verify_signed_manifest(&body, &kp.did().to_string(), &repo).unwrap(); + assert_eq!(verified.blobs[0].oid, oid(1)); + + let duplicate = vec![ + EncryptedBlobRef { + oid: oid(1).to_ascii_uppercase(), + cid: cid_for(1), + }, + EncryptedBlobRef { + oid: oid(1), + cid: cid_for(2), + }, + ]; + assert!( + build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &duplicate, &kp).is_err() + ); + } + + #[test] + fn sharding_is_not_capped_by_one_manifests_verifier_entry_limit() { + let kp = keypair(); + let owner = kp.did().to_string(); + let repo = canonical_repo_slug(&owner, "repo"); + let total = VERIFIER_MANIFEST_MAX_ENTRIES + 1; + let shards = build_signed_manifest_shards( + &repo, + &owner, + "2026-01-01T00:00:00Z", + &entries(total), + &kp, + ) + .unwrap(); + assert!(shards.len() >= 5); + let mut count = 0usize; + let mut seen = HashSet::new(); + for shard in shards { + assert!(shard.len() <= WRITER_MANIFEST_TARGET_BYTES); + let verified = verify_signed_manifest(&shard, &kp.did().to_string(), &repo).unwrap(); + assert!(verified.blobs.len() <= WRITER_SHARD_MAX_ENTRIES); + count += verified.blobs.len(); + for blob in verified.blobs { + assert!(seen.insert(blob.oid)); + } + } + assert_eq!(count, total); + assert_eq!(seen.len(), total); + } } From a9604220bcaa7de2fac6f82d1b0370f2e0fffdab Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:18:42 -0600 Subject: [PATCH 04/18] feat(cli): authenticate arweave encrypted recovery manifests --- crates/twigpine-cli/src/clone.rs | 2102 +++++++++++++++++++++--------- 1 file changed, 1517 insertions(+), 585 deletions(-) diff --git a/crates/twigpine-cli/src/clone.rs b/crates/twigpine-cli/src/clone.rs index 8c7ff1d08..f4dc96901 100644 --- a/crates/twigpine-cli/src/clone.rs +++ b/crates/twigpine-cli/src/clone.rs @@ -12,8 +12,12 @@ use serde::Deserialize; use std::path::Path; use std::process::Command; -use crate::http::{sanitize_node_msg, NodeClient}; +use crate::http::{read_body_capped_bytes, sanitize_node_msg, NodeClient}; use crate::identity::load_keypair_from_dir; +use twigpine_core::encrypted_manifest::{ + canonical_repo_slug, repo_digest, validate_did_key_anchor, verify_signed_manifest, + VerifiedManifest, VERIFIER_MANIFEST_CAP_BYTES, +}; /// Report why one candidate blob could not be recovered, in the register of the /// recovery loop's other warnings. @@ -32,15 +36,6 @@ fn warn_skip(oid: &str, why: &str) { )); } -/// The same report for a manifest rather than a blob. The manifest is one step -/// earlier in the same recovery: losing it silently means every blob it would have -/// named is missing with no reason given anywhere. -fn warn_skip_manifest(id: &str, why: &str) { - emit_warning(&format!( - "warning: could not fetch blob manifest {id}: {why}; skipping" - )); -} - /// Sanitize a warning and write it, once. /// /// The write goes to [`warn_sink`], which is stderr in a normal build and the tests' @@ -100,19 +95,43 @@ pub struct CloneArgs { pub arweave_gateway: String, /// Public IPFS gateway for fetching encrypted envelopes during B3 recovery. - #[arg( - long, - default_value = "https://dweb.link", - env = "TWIGPINE_IPFS_GATEWAY" - )] + /// Must be a path-style gateway: the same-origin redirect policy refuses the + /// subdomain redirect that subdomain-only gateways such as `dweb.link` answer + /// path requests with. + #[arg(long, default_value = "https://ipfs.io", env = "TWIGPINE_IPFS_GATEWAY")] pub ipfs_gateway: String, + + /// Pin the node DID trusted to sign B3 encrypted-blob recovery manifests. + /// Without it, the effective clone node's self-reported DID is the implicit + /// anchor; a caller cloning through a replica who needs the origin node's + /// anchors pins that DID here. Must be a canonical Ed25519 did:key. + #[arg(long)] + pub expect_node: Option, +} + +/// Apply the effective clone node to a git subprocess environment. Any git +/// operation that can reach the remote helper (`clone`, a lazy-fetching +/// `checkout` or `cat-file`) must use the same node the clone's API and +/// recovery traffic used: the helper resolves `TWIGPINE_NODE` independently +/// and would otherwise default to localhost or inherit a conflicting value +/// while recovery talked to `--node`. Both variable names are set so current +/// and pre-rename remote helpers agree, and `.env` overrides any inherited +/// conflicting value rather than losing to it. +fn apply_node_env(cmd: &mut Command, node: Option<&str>) { + if let Some(node) = node { + cmd.env("TWIGPINE_NODE", node); + cmd.env("GITLAWB_NODE", node); + } } /// Run a git command inside `dir`, erroring with stderr on failure. -fn git(dir: &Path, args: &[&str]) -> Result<()> { - let out = Command::new("git") - .args(args) - .current_dir(dir) +/// `node` is the effective clone node for the subprocess environment; `None` +/// leaves the environment untouched (direct local git operations in tests). +fn git(dir: &Path, args: &[&str], node: Option<&str>) -> Result<()> { + let mut cmd = Command::new("git"); + cmd.args(args).current_dir(dir); + apply_node_env(&mut cmd, node); + let out = cmd .output() .with_context(|| format!("running git {args:?}"))?; if !out.status.success() { @@ -125,9 +144,11 @@ fn git(dir: &Path, args: &[&str]) -> Result<()> { } /// Run a git command not tied to a working tree (e.g. `clone`). -fn git_global(args: &[&str]) -> Result<()> { - let out = Command::new("git") - .args(args) +fn git_global(args: &[&str], node: Option<&str>) -> Result<()> { + let mut cmd = Command::new("git"); + cmd.args(args); + apply_node_env(&mut cmd, node); + let out = cmd .output() .with_context(|| format!("running git {args:?}"))?; if !out.status.success() { @@ -163,6 +184,28 @@ pub fn setup_partial_clone( withheld_globs: &[String], reinclude_globs: &[String], branch: Option<&str>, +) -> Result<()> { + setup_partial_clone_node( + dest, + remote_url, + withheld_globs, + reinclude_globs, + branch, + None, + ) +} + +/// [`setup_partial_clone`] with the effective clone node threaded into every +/// git subprocess environment. `run` passes `Some(node)` so a remote-helper +/// invocation during clone or checkout uses the node that served the clone; +/// direct local test setups pass `None` and leave the environment untouched. +fn setup_partial_clone_node( + dest: &Path, + remote_url: &str, + withheld_globs: &[String], + reinclude_globs: &[String], + branch: Option<&str>, + node: Option<&str>, ) -> Result<()> { let dest_str = dest .to_str() @@ -170,22 +213,28 @@ pub fn setup_partial_clone( if withheld_globs.is_empty() { match branch { - Some(b) => git_global(&["clone", "-q", "--branch", b, "--", remote_url, dest_str])?, - None => git_global(&["clone", "-q", "--", remote_url, dest_str])?, + Some(b) => git_global( + &["clone", "-q", "--branch", b, "--", remote_url, dest_str], + node, + )?, + None => git_global(&["clone", "-q", "--", remote_url, dest_str], node)?, } return Ok(()); } - git_global(&[ - "clone", - "-q", - "--filter=blob:none", - "--no-checkout", - "--", - remote_url, - dest_str, - ])?; - git(dest, &["sparse-checkout", "init", "--no-cone"])?; + git_global( + &[ + "clone", + "-q", + "--filter=blob:none", + "--no-checkout", + "--", + remote_url, + dest_str, + ], + node, + )?; + git(dest, &["sparse-checkout", "init", "--no-cone"], node)?; // Non-cone sparse-checkout, gitignore-style: include everything, exclude the // withheld globs, then re-include any allowed globs nested under an excluded // one. Emitting all excludes before the re-includes is safe even for deeper @@ -210,15 +259,17 @@ pub fn setup_partial_clone( .context("writing sparse-checkout spec")?; match branch { - Some(b) => git(dest, &["checkout", "-q", b])?, + Some(b) => git(dest, &["checkout", "-q", b], node)?, None => { // Read the default branch from the local `origin/HEAD` symref that // clone just set, instead of parsing `git remote show origin`, whose // "HEAD branch:" line is localized and needs a network round-trip. - let out = Command::new("git") + let mut symref_cmd = Command::new("git"); + symref_cmd .args(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]) - .current_dir(dest) - .output()?; + .current_dir(dest); + apply_node_env(&mut symref_cmd, node); + let out = symref_cmd.output()?; if !out.status.success() { bail!( "could not determine default branch: {}", @@ -230,7 +281,7 @@ pub fn setup_partial_clone( .trim() .strip_prefix("origin/") .context("unexpected origin/HEAD format")?; - git(dest, &["checkout", "-q", head])?; + git(dest, &["checkout", "-q", head], node)?; } } Ok(()) @@ -410,6 +461,7 @@ async fn recover_encrypted_blobs( let dest_str = dest.to_str().context("dest path not utf-8")?; let client = NodeClient::new(node, Some(keypair.clone())); + let node_env = Some(node); let resp = match client .get_signed(&format!("/api/v1/repos/{owner}/{name}/encrypted-blobs")) @@ -445,11 +497,10 @@ async fn recover_encrypted_blobs( for entry in body.blobs { let oid = entry.oid.as_str(); // Skip if already present locally. - let present = Command::new("git") - .args(["-C", dest_str, "cat-file", "-e", oid]) - .status() - .map(|s| s.success()) - .unwrap_or(false); + let mut catfile = Command::new("git"); + catfile.args(["-C", dest_str, "cat-file", "-e", oid]); + apply_node_env(&mut catfile, node_env); + let present = catfile.status().map(|s| s.success()).unwrap_or(false); if present { continue; } @@ -509,23 +560,96 @@ async fn recover_encrypted_blobs( Ok(recovered) } -/// One blob entry in an Arweave-anchored encrypted manifest. The manifest also -/// carries a `recipients` field per blob, but `twigpine` does not need it: authorization -/// is enforced by whether `open_blob` can decrypt with the caller's key. Unknown -/// JSON fields are ignored by serde, so `recipients` is simply not declared here. -#[derive(Deserialize)] -struct ManifestBlob { - oid: String, - cid: String, +/// Byte ceiling for the node-info root body read when deriving the implicit +/// trust anchor (KTD6). +const NODE_INFO_CAP_BYTES: usize = 64 * 1024; + +/// Byte ceiling for one Arweave GraphQL page response (KTD6). +const GRAPHQL_PAGE_CAP_BYTES: usize = 256 * 1024; + +/// Hard discovery ceilings and the wall-clock metadata budget (KTD10). The +/// budget covers discovery plus manifest fetch/verification only; envelope +/// recovery sits outside it because legitimate large repositories may need +/// long downloads and fabricated entries are filtered before it. +const ARWEAVE_MAX_PAGES: usize = 8; +const ARWEAVE_MAX_TX_IDS: usize = 512; +const ARWEAVE_METADATA_BUDGET: std::time::Duration = std::time::Duration::from_secs(120); + +/// Detailed B3 warning lines are capped at this count; anything beyond it is +/// folded into one aggregate line so a spamming gateway cannot flood the +/// terminal (KTD10). +const MAX_DETAILED_WARNINGS: usize = 20; + +/// The strict protocol-body read idiom (KTD7): read at most `cap + 1` bytes so +/// a body of exactly `cap` bytes is accepted, while anything larger (or a body +/// that died mid-read) is rejected before it is parsed or allocated further. +async fn read_protocol_body(resp: reqwest::Response, cap: usize) -> Result> { + let raw = read_body_capped_bytes(resp, cap + 1).await; + if raw.read_failed { + bail!("response body could not be read completely"); + } + if raw.truncated || raw.bytes.len() > cap { + bail!("response body exceeds the {cap}-byte protocol cap"); + } + Ok(raw.bytes) } -/// An Arweave-anchored per-push encrypted manifest (Option B3). -#[derive(Deserialize)] -struct Manifest { - #[serde(default)] - timestamp: String, - #[serde(default)] - blobs: Vec, +/// Arweave transaction ids are exactly 43 base64url characters. Anything else +/// is gateway spam and must never reach a request URL (KTD4). +fn is_valid_txid(id: &str) -> bool { + id.len() == 43 + && id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + +/// Volume cap for detailed B3 warnings. Up to [`MAX_DETAILED_WARNINGS`] lines +/// are emitted verbatim (each already sanitized by [`emit_warning`]); further +/// problems are counted and reported as one aggregate line when `flush` runs, +/// so one spamming gateway or manifest publisher cannot produce unbounded +/// terminal output. +struct WarningCap { + detailed: usize, + suppressed: usize, +} + +impl WarningCap { + fn new() -> Self { + WarningCap { + detailed: 0, + suppressed: 0, + } + } + + fn warn(&mut self, line: &str) { + if self.detailed < MAX_DETAILED_WARNINGS { + emit_warning(line); + self.detailed += 1; + } else { + self.suppressed += 1; + } + } + + fn warn_skip(&mut self, oid: &str, why: &str) { + self.warn(&format!( + "warning: could not fetch encrypted blob {oid}: {why}; skipping" + )); + } + + fn warn_skip_manifest(&mut self, id: &str, why: &str) { + self.warn(&format!( + "warning: could not fetch blob manifest {id}: {why}; skipping" + )); + } + + fn flush(self) { + if self.suppressed > 0 { + emit_warning(&format!( + "warning: {} further arweave recovery warning(s) suppressed", + self.suppressed + )); + } + } } /// One discovered manifest transaction: its Arweave id and block height. The @@ -545,9 +669,29 @@ pub(crate) struct TxRef { /// the brace-heavy GraphQL body would be error-prone). pub(crate) const ARWEAVE_PAGE_SIZE: usize = 100; -/// Paginated discovery query: manifests tagged for this repo, newest first, with -/// `pageInfo` for cursor pagination and `block{height}` for the recency tie-break. -const ARWEAVE_DISCOVERY_QUERY: &str = r#"query($repo:String!,$cursor:String){transactions(tags:[{name:"App-Name",values:["twigpine","gitlawb"]},{name:"Schema",values:["gitlawb/encrypted-manifest/v1"]},{name:"Repo",values:[$repo]}],first:100,after:$cursor){pageInfo{hasNextPage endCursor}edges{cursor node{id block{height}}}}}"#; +/// Paginated v2 discovery query: signed manifests tagged for this repo by the +/// fixed-length `Repo-Digest` (base64url SHA-256 of the exact canonical slug, +/// so long slugs do not depend on legacy 128-character tag truncation), newest +/// first by explicit `sort:HEIGHT_DESC`, with `pageInfo` for cursor pagination +/// and `block{height}` for the recency ordering. Tags are discovery hints only; +/// the signed payload is the authority. The human-readable `Repo` tag is +/// diagnostic and is never a v2 discovery key. +const ARWEAVE_DISCOVERY_QUERY: &str = r#"query($digest:String!,$cursor:String){transactions(tags:[{name:"App-Name",values:["twigpine","gitlawb"]},{name:"Schema",values:["gitlawb/encrypted-manifest/v2"]},{name:"Repo-Digest",values:[$digest]}],sort:HEIGHT_DESC,first:100,after:$cursor){pageInfo{hasNextPage endCursor}edges{cursor node{id block{height}}}}}"#; + +/// One-page legacy probe: unsigned v1 manifests used the old truncated `Repo` +/// tag rule because v1 writers had no digest. This query exists only to tell +/// "unsigned legacy anchors exist but are not trusted" apart from silent +/// absence; v1 bodies are never fetched or interpreted as recovery authority. +const ARWEAVE_LEGACY_PROBE_QUERY: &str = r#"query($repo:String!){transactions(tags:[{name:"App-Name",values:["twigpine","gitlawb"]},{name:"Schema",values:["gitlawb/encrypted-manifest/v1"]},{name:"Repo",values:[$repo]}],first:1){edges{node{id}}}}"#; + +/// The legacy v1 writer's tag rule, reproduced for the presence probe only: +/// strip characters outside the Irys tag charset and truncate to 128. +fn legacy_repo_tag(slug: &str) -> String { + slug.chars() + .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '/' | ':')) + .take(128) + .collect() +} /// A parsed page of an Arweave GraphQL `transactions` response: the edge refs /// plus pagination state. `has_next` is `None` when the response omitted @@ -568,9 +712,8 @@ pub(crate) struct TxPage { /// for `first:100`, so a response with more edges is a misbehaving (or hostile) /// gateway. Bounding here caps the per-page `TxRef` vec and the downstream per-id /// fetch loop so the `MAX_TX_IDS` budget can't be defeated by one oversized page. -/// (It does not bound the response body itself: `reqwest` buffers and deserializes -/// the whole body before this runs — an unbounded-body concern shared by every -/// gateway read in this file, addressed separately if it ever matters.) +/// (The response body itself is bounded before this runs: B3 reads GraphQL pages +/// through the strict `GRAPHQL_PAGE_CAP_BYTES` protocol-body idiom.) pub(crate) fn parse_tx_page(v: &serde_json::Value) -> TxPage { let txns = v.get("data").and_then(|d| d.get("transactions")); let refs: Vec = txns @@ -630,43 +773,59 @@ pub(crate) fn height_rank(h: Option) -> (u8, u64) { } } -/// Merge per-push manifests into a single `oid -> cid` map. A later seal of an -/// oid overrides an earlier one, ranked by the composite key -/// `(timestamp, block height, cid)`: -/// - manifest `timestamp` (RFC3339, lexicographic) is primary — the unchanged -/// latest-wins behavior; -/// - Arweave block height breaks equal-timestamp ties by anchor recency (a -/// pending anchor counts as newest), preserving the "newest wins" that -/// single-page `HEIGHT_DESC` discovery used to provide by insertion order. -/// The height is gateway-reported (chain-derived but not independently -/// verified here), so it removes order-dependence and honest-node clock skew, -/// not trust in the gateway — discovery already assumes an honest gateway; -/// - cid is a final lexicographic tiebreak so two anchors in the *same* block -/// still resolve deterministically (arbitrary, not recency-ordered, within a -/// block), independent of discovery order. -fn merge_manifests( - manifests: Vec<(Manifest, Option)>, +/// Merge verified per-push manifests into a single `oid -> cid` map, ranked by +/// the composite key `(block height rank, timestamp instant, cid)`: +/// - Arweave block height rank is primary: chain-inclusion metadata is +/// monotonic, so a correct-but-misconfigured node clock moving backwards +/// cannot permanently regress recovery, and a pending (not yet mined) +/// anchor counts as newest. Height is gateway-reported availability +/// metadata; it never enters the authenticity decision, which already +/// happened in `verify_signed_manifest` before anything reached this merge. +/// A hostile gateway can reorder what it shows, but it can already censor +/// newer anchors, so this grants it no new authority; +/// - the signed manifest timestamp breaks equal-height ties, compared as +/// parsed RFC3339 instants rather than strings (offsets and fractional +/// seconds order wrongly as text). Verification already rejected malformed +/// timestamps, so a parse failure here is impossible but ranks lowest +/// rather than panicking; +/// - the lexicographically larger cid is the final deterministic tiebreak so +/// two anchors in the *same* block with the same timestamp still resolve +/// order-independently. +/// +/// Entries for oids absent from the cloned tree are discarded on insertion: +/// a fabricated oid can never become a valid recovered path, so it must not +/// enter merge retention, trigger a `git cat-file`, or trigger an IPFS fetch. +fn merge_authenticated( + manifests: Vec<(VerifiedManifest, Option)>, + tree_oids: &std::collections::HashSet, ) -> std::collections::HashMap { - // oid -> (cid, timestamp, height_rank) - let mut best: std::collections::HashMap = - std::collections::HashMap::new(); + // oid -> (cid, height_rank, timestamp instant) + let mut best: std::collections::HashMap< + String, + (String, (u8, u64), chrono::DateTime), + > = std::collections::HashMap::new(); for (m, height) in manifests { let cand_rank = height_rank(height); + let cand_ts = chrono::DateTime::parse_from_rfc3339(&m.timestamp).unwrap_or_else(|_| { + chrono::DateTime::parse_from_rfc3339("1970-01-01T00:00:00Z").unwrap() + }); for b in m.blobs { + if !tree_oids.contains(&b.oid) { + continue; + } let keep_incumbent = match best.get(&b.oid) { // Incumbent wins iff its composite key is >= the candidate's. The // `>=` (not `>`) keeps the incumbent only on a full tie, where the // entries are identical anyway. A strictly-greater candidate key - // (newer timestamp, or equal timestamp + higher block, or equal - // both + larger cid) replaces it. - Some((cur_cid, cur_ts, cur_rank)) => { - (cur_ts.as_str(), cur_rank, cur_cid.as_str()) - >= (m.timestamp.as_str(), &cand_rank, b.cid.as_str()) + // (higher block rank, or equal rank + later timestamp instant, or + // equal both + larger cid) replaces it. + Some((cur_cid, cur_rank, cur_ts)) => { + (*cur_rank, *cur_ts, cur_cid.as_str()) >= (cand_rank, cand_ts, b.cid.as_str()) } None => false, }; if !keep_incumbent { - best.insert(b.oid, (b.cid, m.timestamp.clone(), cand_rank)); + best.insert(b.oid, (b.cid, cand_rank, cand_ts)); } } } @@ -675,12 +834,20 @@ fn merge_manifests( .collect() } -/// Option B3 fallback recovery, with no dependency on a Twigpine node API. Query -/// the Arweave gateway for this repo's encrypted manifests, merge them, and for -/// each blob still missing locally that the caller can decrypt, pull the envelope -/// from a public IPFS gateway, decrypt, and install it as a loose object. Returns -/// the repo-relative paths recovered. Best-effort; silent when gateways are -/// unreachable, leaving the clone exactly as node-based recovery left it. +/// Option B3 fallback recovery, with no dependency on a Twigpine node API. +/// +/// Discovery infrastructure (Arweave, gateways, indexers, tags, transaction +/// ids) is untrusted: it can only *find* candidates. Authority is the exact +/// signed v2 payload verified against `expected_node_did`, which the caller +/// anchored outside the artifact (`--expect-node`, or the effective clone +/// node's self-reported DID). Each candidate body is byte-capped, verified, +/// and only then merged; entries naming oids absent from the cloned tree are +/// discarded before they can cost a local object check or a gateway fetch. +/// For each surviving blob still missing locally that the caller can decrypt, +/// pull the envelope from a public IPFS gateway, decrypt, and install it as a +/// loose object. Returns the repo-relative paths recovered. Best-effort; +/// silent when gateways are unreachable, leaving the clone exactly as +/// node-based recovery left it. async fn recover_from_arweave( arweave_gateway: &str, ipfs_gateway: &str, @@ -688,58 +855,126 @@ async fn recover_from_arweave( name: &str, dest: &Path, keypair: &twigpine_core::identity::Keypair, + expected_node_did: &str, ) -> Result> { - use std::collections::HashMap; + recover_from_arweave_inner( + arweave_gateway, + ipfs_gateway, + owner, + name, + dest, + keypair, + expected_node_did, + &DiscoveryLimits::production(), + ) + .await +} + +/// Discovery, pagination, and budget ceilings for B3 metadata work. A struct +/// (rather than bare constants) so tests can drive the boundary behavior with +/// small values instead of hundreds of mocked pages or a two-minute wait; the +/// production values are the KTD10 ceilings. +struct DiscoveryLimits { + max_pages: usize, + max_tx_ids: usize, + metadata_budget: std::time::Duration, +} + +impl DiscoveryLimits { + fn production() -> Self { + DiscoveryLimits { + max_pages: ARWEAVE_MAX_PAGES, + max_tx_ids: ARWEAVE_MAX_TX_IDS, + metadata_budget: ARWEAVE_METADATA_BUDGET, + } + } +} + +#[allow(clippy::too_many_arguments)] +async fn recover_from_arweave_inner( + arweave_gateway: &str, + ipfs_gateway: &str, + owner: &str, + name: &str, + dest: &Path, + keypair: &twigpine_core::identity::Keypair, + expected_node_did: &str, + limits: &DiscoveryLimits, +) -> Result> { + use std::collections::{HashMap, HashSet}; use std::io::Write; - use twigpine_core::encrypt::open_blob; + use twigpine_core::encrypt::{open_blob, MAX_ENCRYPTED_ENVELOPE_BYTES}; let dest_str = dest.to_str().context("dest path not utf-8")?; - let owner_short = owner.split(':').next_back().unwrap_or(owner); - let slug = format!("{owner_short}/{name}"); + let slug = canonical_repo_slug(owner, name); + let digest = repo_digest(&slug); let ag = arweave_gateway.trim_end_matches('/'); let ig = ipfs_gateway.trim_end_matches('/'); // Bound every gateway request: this runs on every clone, so a slow or hung // public gateway must not stall it. Best-effort recovery, so a timeout just - // skips the affected blob. + // skips the affected blob. Redirects follow the shared same-origin policy: + // a gateway may not bounce recovery traffic onto another origin, which is + // also why the default IPFS gateway is the path-style `https://ipfs.io` + // (subdomain-only gateways such as `dweb.link` redirect path requests + // cross-origin and cannot work under this policy). let client = reqwest::Client::builder() .timeout(std::time::Duration::from_secs(30)) + .redirect(reqwest::redirect::Policy::custom( + crate::http::same_origin_redirect, + )) .build() - .unwrap_or_else(|_| reqwest::Client::new()); - - // 1. Discover manifest transactions via paginated Arweave GraphQL. Collect - // (tx id, block height) refs across every page, deduping by id and bounding - // the loop so a hostile or buggy gateway cannot grow the set, the page - // count, or the downstream per-id fetch loop without limit. Best-effort: a - // page-1 failure (gateway down/unconfigured) stays silent as before; a - // failure or cap reached *after* discovery began warns, since the recovery - // is then knowingly partial. - const MAX_PAGES: usize = 1000; - const MAX_TX_IDS: usize = 10_000; + .expect("failed to build HTTP client"); + + let started = std::time::Instant::now(); + let mut budget_warned = false; + let mut warnings = WarningCap::new(); + + // 1. Discover v2 manifest transactions via paginated Arweave GraphQL. + // Collect (tx id, block height) refs across every page, deduping by id + // and bounding the loop so a hostile or buggy gateway cannot grow the + // set, the page count, or the downstream per-id fetch loop without + // limit. Best-effort: a page-1 failure (gateway down/unconfigured) + // stays silent as before; a failure or cap reached *after* discovery + // began warns, since the recovery is then knowingly partial. let query = ARWEAVE_DISCOVERY_QUERY; let mut after: Option = None; - let mut seen: std::collections::HashSet = std::collections::HashSet::new(); + let mut seen: HashSet = HashSet::new(); let mut refs: Vec = Vec::new(); let mut prev_cursor: Option = None; let mut page_num = 0usize; loop { - if page_num >= MAX_PAGES { - eprintln!( - "warning: Arweave manifest discovery hit the {MAX_PAGES}-page cap; \ - some authorized files may not be recovered" + if started.elapsed() >= limits.metadata_budget { + budget_warned = true; + emit_warning( + "warning: arweave manifest discovery exceeded its time budget; recovery is incomplete and some authorized files may not be recovered", ); break; } + if page_num >= limits.max_pages { + emit_warning(&format!( + "warning: Arweave manifest discovery hit the {}-page cap; some authorized files may not be recovered", + limits.max_pages + )); + break; + } page_num += 1; - let gql_body = - serde_json::json!({ "query": query, "variables": { "repo": slug, "cursor": after } }); - // Any gateway failure (non-2xx, send error, unparseable body) ends the loop. + let gql_body = serde_json::json!({ "query": query, "variables": { "digest": digest, "cursor": after } }); + // Any gateway failure (non-2xx, send error, oversized or unparseable + // body) ends the loop. + let remaining = limits.metadata_budget.saturating_sub(started.elapsed()); let response = match client .post(format!("{ag}/graphql")) + .timeout(remaining) .json(&gql_body) .send() .await { - Ok(r) if r.status().is_success() => r.json::().await.ok(), + Ok(r) if r.status().is_success() => { + match read_protocol_body(r, GRAPHQL_PAGE_CAP_BYTES).await { + Ok(bytes) => serde_json::from_slice::(&bytes).ok(), + Err(_) => None, + } + } _ => None, }; let value = match response { @@ -749,9 +984,8 @@ async fn recover_from_arweave( // partial, so warn. A page-1 failure is the benign unconfigured/ // unreachable-gateway case and stays silent, exactly as before. if !refs.is_empty() { - eprintln!( - "warning: Arweave manifest discovery was interrupted by a gateway \ - error; some authorized files may not be recovered" + emit_warning( + "warning: Arweave manifest discovery was interrupted by a gateway error; some authorized files may not be recovered", ); } break; @@ -760,16 +994,20 @@ async fn recover_from_arweave( let page = parse_tx_page(&value); let full = page.refs.len() >= ARWEAVE_PAGE_SIZE; for r in page.refs { + // A malformed tx id is gateway spam and never reaches a request URL. + if !is_valid_txid(&r.id) { + continue; + } if seen.insert(r.id.clone()) { refs.push(r); } } // Cap checked at the page boundary so a partial page is never half-merged. - if refs.len() >= MAX_TX_IDS { - eprintln!( - "warning: Arweave manifest discovery hit the {MAX_TX_IDS}-transaction cap; \ - some authorized files may not be recovered" - ); + if refs.len() >= limits.max_tx_ids { + emit_warning(&format!( + "warning: Arweave manifest discovery hit the {}-transaction cap; some authorized files may not be recovered", + limits.max_tx_ids + )); break; } match page.has_next { @@ -787,45 +1025,106 @@ async fn recover_from_arweave( // truncated gateway, so flag that; a short page is genuinely the end. None => { if full { - eprintln!( - "warning: Arweave gateway returned a full page without pagination \ - metadata; discovery may be incomplete and some authorized files may \ - not be recovered" + emit_warning( + "warning: Arweave gateway returned a full page without pagination metadata; discovery may be incomplete and some authorized files may not be recovered", ); } break; } } } - if refs.is_empty() { - return Ok(vec![]); - } - // 2. Fetch each manifest body, pair it with its anchor's block height, then - // merge (latest-wins by timestamp, tie-broken by block height then cid). - let mut manifests: Vec<(Manifest, Option)> = Vec::new(); + // 2. Fetch each manifest body through `/raw/` (the exact bytes, not + // the manifest-resolving endpoint), byte-capped, and verify it against + // the externally anchored node DID BEFORE anything merges. A rejection + // is cheap and bounded; it never fetches or interprets a v1 body. + let mut manifests: Vec<(VerifiedManifest, Option)> = Vec::new(); for r in refs { - let m = match client.get(format!("{ag}/{}", r.id)).send().await { + if started.elapsed() >= limits.metadata_budget { + if !budget_warned { + emit_warning( + "warning: arweave manifest verification exceeded its time budget; recovery is incomplete and some authorized files may not be recovered", + ); + } + break; + } + let remaining = limits.metadata_budget.saturating_sub(started.elapsed()); + let resp = match client + .get(format!("{ag}/raw/{}", r.id)) + .timeout(remaining) + .send() + .await + { Ok(resp) if resp.status().is_success() => resp, Ok(resp) => { - warn_skip_manifest(&r.id, &format!("gateway returned {}", resp.status())); + warnings.warn_skip_manifest(&r.id, &format!("gateway returned {}", resp.status())); continue; } Err(e) => { - warn_skip_manifest(&r.id, &format!("gateway request failed: {e}")); + warnings.warn_skip_manifest(&r.id, &format!("gateway request failed: {e}")); + continue; + } + }; + let bytes = match read_protocol_body(resp, VERIFIER_MANIFEST_CAP_BYTES).await { + Ok(b) => b, + Err(e) => { + warnings.warn_skip_manifest(&r.id, &e.to_string()); continue; } }; - if let Ok(parsed) = m.json::().await { - manifests.push((parsed, r.height)); + match verify_signed_manifest(&bytes, expected_node_did, &slug) { + Ok(verified) => manifests.push((verified, r.height)), + Err(e) => { + warnings.warn_skip_manifest(&r.id, &format!("not a trusted signed manifest: {e}")); + } } } - let oid_cid = merge_manifests(manifests); - if oid_cid.is_empty() { - return Ok(vec![]); + + // 3. When no usable signed v2 manifest was found, run one cheap + // metadata-only legacy probe so "unsigned legacy anchors exist but are + // not trusted" is said out loud instead of looking like silent absence. + // The probe reads one GraphQL page of v1 tags; v1 bodies are never + // fetched or used as recovery authority. + if manifests.is_empty() && started.elapsed() < limits.metadata_budget { + let probe_body = serde_json::json!({ + "query": ARWEAVE_LEGACY_PROBE_QUERY, + "variables": { "repo": legacy_repo_tag(&slug) }, + }); + let remaining = limits.metadata_budget.saturating_sub(started.elapsed()); + let legacy_found = match client + .post(format!("{ag}/graphql")) + .timeout(remaining) + .json(&probe_body) + .send() + .await + { + Ok(r) if r.status().is_success() => { + match read_protocol_body(r, GRAPHQL_PAGE_CAP_BYTES).await { + Ok(bytes) => serde_json::from_slice::(&bytes) + .ok() + .and_then(|v| { + v.get("data")? + .get("transactions")? + .get("edges")? + .as_array() + .map(|edges| !edges.is_empty()) + }) + .unwrap_or(false), + Err(_) => false, + } + } + _ => false, + }; + if legacy_found { + emit_warning( + "warning: unsigned legacy encrypted-blob manifests exist for this repo but are ignored as unauthenticated; some authorized files may not be recovered", + ); + } } - // Map oid -> repo-relative path from the cloned tree. + // 4. Map oid -> repo-relative path from the cloned tree BEFORE merging: + // the tree oid set is the prefilter that keeps fabricated entries out + // of merge retention, `git cat-file`, and gateway fetches entirely. let ls = Command::new("git") .args(["-C", dest_str, "ls-tree", "-r", "HEAD"]) .output()?; @@ -837,8 +1136,13 @@ async fn recover_from_arweave( } } } + let tree_oids: HashSet = oid_to_path.keys().cloned().collect(); - // 3. Recover each missing blob the caller can decrypt. + // 5. Merge authenticated entries only: height rank first (pending newest), + // then the signed timestamp instant, then the larger cid. + let oid_cid = merge_authenticated(manifests, &tree_oids); + + // 6. Recover each missing blob the caller can decrypt. let mut recovered = Vec::new(); for (oid, cid) in oid_cid { // Local presence check. GIT_NO_LAZY_FETCH stops git from making a wasted @@ -864,21 +1168,22 @@ async fn recover_from_arweave( // the next candidate either way: one unreachable blob must not end the // recovery of the rest. Ok(r) => { - warn_skip(&oid, &format!("gateway returned {}", r.status())); + warnings.warn_skip(&oid, &format!("gateway returned {}", r.status())); continue; } Err(e) => { - warn_skip(&oid, &format!("gateway request failed: {e}")); + warnings.warn_skip(&oid, &format!("gateway request failed: {e}")); continue; } }; - // A body that dies part-way through is the same mid-read failure the capped - // read exists to stop rendering as silence, and it sits INSIDE the loop whose - // status arms were already fixed. - let envelope = match env_resp.bytes().await { + // The public gateway is untrusted infrastructure, so the envelope read + // is bounded by the shared serving ceiling (32 MiB object bytes plus + // the 64 KiB envelope allowance). An over-cap or mid-body-failed read + // skips this one blob; the rest of the recovery continues. + let envelope = match read_protocol_body(env_resp, MAX_ENCRYPTED_ENVELOPE_BYTES).await { Ok(b) => b, Err(e) => { - warn_skip(&oid, &format!("reading the envelope failed: {e}")); + warnings.warn_skip(&oid, &format!("reading the envelope failed: {e}")); continue; } }; @@ -901,15 +1206,59 @@ async fn recover_from_arweave( recovered.push(p.clone()); } } else { - emit_warning(&format!( + warnings.warn(&format!( "warning: recovered blob {oid} hashed to {written}; discarding" )); } } + warnings.flush(); Ok(recovered) } +/// Validate an explicit `--expect-node` pin: it must be a canonical Ed25519 +/// `did:key` that recovers a verifying key and re-derives to the same string. +/// This runs before cloning creates the destination, so a malformed pin fails +/// the invocation rather than half-completing a clone. +fn validate_expect_node_pin(did: &str) -> Result<()> { + validate_did_key_anchor(did) + .map_err(|e| anyhow::anyhow!("--expect-node must be a canonical Ed25519 did:key: {e}"))?; + Ok(()) +} + +/// Derive the implicit trust anchor: the effective clone node's self-reported +/// root `did`, read once through the strict 64 KiB bounded protocol-body idiom +/// and validated exactly like an explicit pin. The implicit anchor is a +/// deliberate clone trust model, not independent verification: the selected +/// node already serves the base clone and primary recovery. A caller who needs +/// issuer independence after node loss pins `--expect-node` instead. +async fn resolve_implicit_node_did(node: &str) -> Result { + let client = NodeClient::new(node, None); + let resp = client + .get("/") + .await + .context("reading the clone node's root metadata")?; + if !resp.status().is_success() { + bail!("node root metadata returned {}", resp.status()); + } + let bytes = read_protocol_body(resp, NODE_INFO_CAP_BYTES).await?; + let info: serde_json::Value = + serde_json::from_slice(&bytes).context("parsing the clone node's root metadata")?; + let did = info + .get("did") + .and_then(|d| d.as_str()) + .context("node root metadata carries no did")?; + validate_did_key_anchor(did).context("node-reported did is not a canonical Ed25519 did:key")?; + Ok(did.to_string()) +} + pub async fn run(args: CloneArgs) -> Result<()> { + // A malformed explicit pin fails before the destination is created or any + // network recovery runs: the pin is the caller's trust anchor, and a clone + // that proceeded under a mistyped one would silently verify against nothing. + if let Some(pin) = args.expect_node.as_deref() { + validate_expect_node_pin(pin)?; + } + let (url, owner, name) = parse_repo(&args.repo)?; let dest_name = args.dir.unwrap_or_else(|| name.clone()); let dest = std::path::PathBuf::from(&dest_name); @@ -927,7 +1276,18 @@ pub async fn run(args: CloneArgs) -> Result<()> { ); } - setup_partial_clone(&dest, &url, &withheld, &reinclude, args.branch.as_deref())?; + // The effective node is threaded into every git subprocess that can invoke + // the remote helper, so transport and recovery cannot silently use + // different nodes (the helper would otherwise resolve TWIGPINE_NODE + // independently or inherit a conflicting GITLAWB_NODE). + setup_partial_clone_node( + &dest, + &url, + &withheld, + &reinclude, + args.branch.as_deref(), + Some(&args.node), + )?; if let Ok(keypair) = load_keypair_from_dir(None) { // Node-based recovery first (B1/B2), then the B3 Arweave/IPFS gateway @@ -941,20 +1301,41 @@ pub async fn run(args: CloneArgs) -> Result<()> { // `.unwrap_or_default()` silently swallow it into "no paths". warn_recovery_failed("encrypted-blobs recovery", &e) }); - let from_arweave = recover_from_arweave( - &args.arweave_gateway, - &args.ipfs_gateway, - &owner, - &name, - &dest, - &keypair, - ) - .await - .unwrap_or_else(|e| { - // Same rule as the node-recovery arm above: warn, never abort. - warn_recovery_failed("arweave/ipfs gateway recovery", &e) - }); - paths.extend(from_arweave); + + // The B3 trust anchor: the explicit pin when supplied (a caller can pin + // an origin node while cloning through a replica), otherwise the + // effective clone node's self-reported DID. A failed or invalid implicit + // lookup disables only Arweave recovery, never the rest of the clone. + let expected_did = match args.expect_node.as_deref() { + Some(pin) => Some(pin.to_string()), + None => match resolve_implicit_node_did(&args.node).await { + Ok(did) => Some(did), + Err(e) => { + emit_warning(&format!( + "warning: skipping Arweave encrypted-blob recovery: \ + could not derive the clone node's signing identity: {e}" + )); + None + } + }, + }; + if let Some(expected_did) = expected_did { + let from_arweave = recover_from_arweave( + &args.arweave_gateway, + &args.ipfs_gateway, + &owner, + &name, + &dest, + &keypair, + &expected_did, + ) + .await + .unwrap_or_else(|e| { + // Same rule as the node-recovery arm above: warn, never abort. + warn_recovery_failed("arweave/ipfs gateway recovery", &e) + }); + paths.extend(from_arweave); + } if !paths.is_empty() { // Re-include recovered paths if this was a sparse clone, then @@ -979,7 +1360,9 @@ pub async fn run(args: CloneArgs) -> Result<()> { } } } - if let Err(e) = git(&dest, &["checkout", "--", "."]) { + // A checkout can lazy-fetch through the remote helper, so it runs + // under the same effective-node environment as the clone itself. + if let Err(e) = git(&dest, &["checkout", "--", "."], Some(&args.node)) { eprintln!( "warning: checkout after recovery failed, recovered files may not appear: {e}" ); @@ -1420,165 +1803,275 @@ mod tests { ); } - #[test] - fn manifest_parses_and_ignores_recipients() { - let m: Manifest = serde_json::from_str( - r#"{"timestamp":"2026-06-11T00:00:00Z","blobs":[{"oid":"o1","cid":"c1","recipients":["did:key:zA"]}]}"#, - ) - .unwrap(); - assert_eq!(m.timestamp, "2026-06-11T00:00:00Z"); - assert_eq!(m.blobs.len(), 1); - assert_eq!(m.blobs[0].oid, "o1"); - assert_eq!(m.blobs[0].cid, "c1"); + // ── signed v2 fixture helpers ──────────────────────────────────────── + + /// A CIDv1 raw cid for fixture use. Manifest verification requires CIDv1 + /// shape, so tests cannot use the old bare strings like "cid123". + fn test_cid(byte: u8) -> String { + twigpine_core::cid::Cid::from_git_object_bytes(&[byte]) + .as_str() + .to_string() } - #[test] - fn merge_manifests_latest_wins_per_oid() { - let older = Manifest { - timestamp: "2026-06-10T00:00:00Z".to_string(), - blobs: vec![ManifestBlob { - oid: "o1".to_string(), - cid: "cidOLD".to_string(), - }], - }; - let newer = Manifest { - timestamp: "2026-06-11T00:00:00Z".to_string(), - blobs: vec![ - ManifestBlob { - oid: "o1".to_string(), - cid: "cidNEW".to_string(), - }, - ManifestBlob { - oid: "o2".to_string(), - cid: "cid2".to_string(), + /// A syntactically valid Arweave transaction id: exactly 43 base64url + /// characters, so discovery accepts it and it can appear in `/raw/` URLs. + fn valid_txid(seed: &str) -> String { + let mut s = seed.to_string(); + while s.len() < 43 { + s.push('x'); + } + s.truncate(43); + s + } + + /// Build a signed v2 manifest body exactly as the node writer would: + /// canonical repo slug derived from owner DID and repo name, signed by + /// `signer` (whose DID becomes the signed `node_did`). + fn signed_manifest_json( + signer: &twigpine_core::identity::Keypair, + owner: &str, + name: &str, + timestamp: &str, + blobs: &[(&str, &str)], + ) -> String { + let repo = canonical_repo_slug(owner, name); + let entries: Vec = blobs + .iter() + .map( + |(oid, cid)| twigpine_core::encrypted_manifest::EncryptedBlobRef { + oid: oid.to_string(), + cid: cid.to_string(), }, - ], - }; - let merged = merge_manifests(vec![(older, Some(1)), (newer, Some(2))]); - assert_eq!(merged.get("o1").map(String::as_str), Some("cidNEW")); - assert_eq!(merged.get("o2").map(String::as_str), Some("cid2")); + ) + .collect(); + String::from_utf8( + twigpine_core::encrypted_manifest::build_signed_manifest( + &repo, owner, timestamp, &entries, signer, + ) + .unwrap(), + ) + .unwrap() } - #[test] - fn merge_manifests_is_order_independent() { - let older = Manifest { - timestamp: "2026-06-10T00:00:00Z".to_string(), - blobs: vec![ManifestBlob { - oid: "o1".to_string(), - cid: "cidOLD".to_string(), - }], - }; - let newer = Manifest { - timestamp: "2026-06-11T00:00:00Z".to_string(), - blobs: vec![ManifestBlob { - oid: "o1".to_string(), - cid: "cidNEW".to_string(), - }], - }; - // Newer first, older second: newer must still win. - let merged = merge_manifests(vec![(newer, Some(2)), (older, Some(1))]); - assert_eq!(merged.get("o1").map(String::as_str), Some("cidNEW")); + /// Clone a repo whose `/secret/**` is withheld and then delete the promisor + /// remote, so the withheld blobs are genuinely absent locally and only + /// gateway recovery can restore them (the B3 premise). + fn clone_with_missing_secrets(files: &[(&str, &[u8])]) -> (TempDir, std::path::PathBuf) { + let (td, url) = bare_remote(files); + let dest = td.path().join("dest"); + let bare = url.strip_prefix("file://").unwrap().to_string(); + assert!(Command::new("git") + .args(["-C", &bare, "config", "uploadpack.allowFilter", "true"]) + .status() + .unwrap() + .success()); + setup_partial_clone(&dest, &url, &["/secret/**".to_string()], &[], None).unwrap(); + std::fs::remove_dir_all(&bare).unwrap(); + (td, dest) + } + + fn oid_of(dest: &Path, path: &str) -> String { + let out = Command::new("git") + .args([ + "-C", + dest.to_str().unwrap(), + "rev-parse", + &format!("HEAD:{path}"), + ]) + .output() + .unwrap(); + String::from_utf8_lossy(&out.stdout).trim().to_string() + } + + /// The B3 actor triple fixture tests need: the signing node keypair (the + /// trust anchor), the repo owner's DID (valid DID shape, because the v2 + /// payload validates it), and the reader the envelopes are sealed to. + struct B3Actors { + signer: twigpine_core::identity::Keypair, + owner: String, + reader: twigpine_core::identity::Keypair, + } + + fn b3_actors() -> B3Actors { + let signer = twigpine_core::identity::Keypair::generate(); + let owner_kp = twigpine_core::identity::Keypair::generate(); + B3Actors { + owner: owner_kp.did().to_string(), + signer, + reader: twigpine_core::identity::Keypair::generate(), + } } - // Helper: a single-blob manifest for the merge tie-break tests. - fn manifest_with(ts: &str, oid: &str, cid: &str) -> Manifest { - Manifest { - timestamp: ts.to_string(), - blobs: vec![ManifestBlob { + /// A one-page GraphQL discovery response listing the given tx ids with no + /// block (pending) or at the given heights. + fn gql_page(ids_and_heights: &[(&str, Option)]) -> String { + let edges: Vec = ids_and_heights + .iter() + .map(|(id, h)| match h { + Some(h) => format!(r#"{{"node":{{"id":"{id}","block":{{"height":{h}}}}}}}"#), + None => format!(r#"{{"node":{{"id":"{id}"}}}}"#), + }) + .collect(); + format!( + r#"{{"data":{{"transactions":{{"edges":[{}]}}}}}}"#, + edges.join(",") + ) + } + + // ── merge ordering over authenticated v2 manifests ─────────────────── + + /// A verified-manifest-shaped merge input. Merge tests construct these + /// directly because the signature verification itself is pinned in + /// `twigpine-core` and in the through-the-real-path tests below; what is + /// under test here is ordering and filtering AFTER authentication. + fn vmanifest(timestamp: &str, oid: &str, cid: &str) -> VerifiedManifest { + VerifiedManifest { + repo: "owner/repo".to_string(), + owner_did: "did:key:zOwner".to_string(), + node_did: "did:key:zNode".to_string(), + timestamp: timestamp.to_string(), + blobs: vec![twigpine_core::encrypted_manifest::EncryptedBlobRef { oid: oid.to_string(), cid: cid.to_string(), }], } } + fn tree(oids: &[&str]) -> std::collections::HashSet { + oids.iter().map(|s| s.to_string()).collect() + } + #[test] - fn merge_equal_timestamp_breaks_by_block_height() { - // Same timestamp, different block heights: the higher block (newer - // anchor) must win, regardless of input order. - let lo = manifest_with("2026-06-11T00:00:00Z", "o1", "cidLO"); - let hi = manifest_with("2026-06-11T00:00:00Z", "o1", "cidHI"); - let a = merge_manifests(vec![ - ( - manifest_with("2026-06-11T00:00:00Z", "o1", "cidLO"), - Some(10), - ), - ( - manifest_with("2026-06-11T00:00:00Z", "o1", "cidHI"), - Some(20), - ), - ]); - assert_eq!(a.get("o1").map(String::as_str), Some("cidHI")); - // Reversed order, same result. - let b = merge_manifests(vec![(hi, Some(20)), (lo, Some(10))]); - assert_eq!(b.get("o1").map(String::as_str), Some("cidHI")); + fn merge_latest_height_wins_per_oid() { + let lo = vmanifest("2026-06-10T00:00:00Z", "o1", "cidLO"); + let mut two = vmanifest("2026-06-11T00:00:00Z", "o1", "cidHI"); + two.blobs + .push(twigpine_core::encrypted_manifest::EncryptedBlobRef { + oid: "o2".to_string(), + cid: "cid2".to_string(), + }); + let merged = merge_authenticated(vec![(lo, Some(1)), (two, Some(2))], &tree(&["o1", "o2"])); + assert_eq!(merged.get("o1").map(String::as_str), Some("cidHI")); + assert_eq!(merged.get("o2").map(String::as_str), Some("cid2")); + // Order-independence. + let lo2 = vmanifest("2026-06-10T00:00:00Z", "o1", "cidLO"); + let hi2 = vmanifest("2026-06-11T00:00:00Z", "o1", "cidHI"); + let rev = merge_authenticated(vec![(hi2, Some(2)), (lo2, Some(1))], &tree(&["o1"])); + assert_eq!(rev.get("o1").map(String::as_str), Some("cidHI")); + } + + #[test] + fn merge_height_rank_beats_timestamp() { + // Inverted from the unsigned-v1 rule: a higher block height wins even + // when the lower-height manifest carries the later timestamp. Height + // is monotonic chain-inclusion metadata, so a correct-but-misconfigured + // node clock moving backwards cannot permanently regress recovery. + let newer_ts_lo_block = vmanifest("2026-06-11T00:00:00Z", "o1", "cidNEWERTS"); + let older_ts_hi_block = vmanifest("2026-06-10T00:00:00Z", "o1", "cidHIBLOCK"); + let merged = merge_authenticated( + vec![ + (newer_ts_lo_block, Some(1)), + (older_ts_hi_block, Some(9999)), + ], + &tree(&["o1"]), + ); + assert_eq!(merged.get("o1").map(String::as_str), Some("cidHIBLOCK")); } #[test] - fn merge_pending_anchor_is_newest_on_tie() { - // Same timestamp; one mined anchor, one pending (None height). The - // pending one is the most recent and must win, order-independently. - let mined = manifest_with("2026-06-11T00:00:00Z", "o1", "cidMINED"); - let pending = manifest_with("2026-06-11T00:00:00Z", "o1", "cidPENDING"); - let a = merge_manifests(vec![(mined, Some(99)), (pending, None)]); + fn merge_pending_anchor_beats_any_mined_anchor() { + // A pending (not yet mined) anchor ranks newest, order-independently, + // even against a far higher mined block. + let mined = vmanifest("2026-06-11T00:00:00Z", "o1", "cidMINED"); + let pending = vmanifest("2026-06-10T00:00:00Z", "o1", "cidPENDING"); + let a = merge_authenticated(vec![(mined, Some(99)), (pending, None)], &tree(&["o1"])); assert_eq!(a.get("o1").map(String::as_str), Some("cidPENDING")); - let mined2 = manifest_with("2026-06-11T00:00:00Z", "o1", "cidMINED"); - let pending2 = manifest_with("2026-06-11T00:00:00Z", "o1", "cidPENDING"); - let b = merge_manifests(vec![(pending2, None), (mined2, Some(99))]); + let mined2 = vmanifest("2026-06-11T00:00:00Z", "o1", "cidMINED"); + let pending2 = vmanifest("2026-06-10T00:00:00Z", "o1", "cidPENDING"); + let b = merge_authenticated(vec![(pending2, None), (mined2, Some(99))], &tree(&["o1"])); assert_eq!(b.get("o1").map(String::as_str), Some("cidPENDING")); } #[test] - fn merge_same_block_breaks_by_cid_deterministically() { - // Equal timestamp AND equal height: the cid tiebreak makes the result - // deterministic and order-independent (lexicographically-larger cid wins). - let a = merge_manifests(vec![ - ( - manifest_with("2026-06-11T00:00:00Z", "o1", "cidAAA"), - Some(5), - ), - ( - manifest_with("2026-06-11T00:00:00Z", "o1", "cidBBB"), - Some(5), - ), - ]); - let b = merge_manifests(vec![ - ( - manifest_with("2026-06-11T00:00:00Z", "o1", "cidBBB"), - Some(5), - ), - ( - manifest_with("2026-06-11T00:00:00Z", "o1", "cidAAA"), - Some(5), - ), - ]); - assert_eq!(a.get("o1"), b.get("o1")); - assert_eq!(a.get("o1").map(String::as_str), Some("cidBBB")); + fn merge_equal_height_breaks_by_timestamp_instant() { + let earlier = vmanifest("2026-06-10T00:00:00Z", "o1", "cidEARLY"); + let later = vmanifest("2026-06-11T00:00:00Z", "o1", "cidLATE"); + let a = merge_authenticated(vec![(earlier, Some(5)), (later, Some(5))], &tree(&["o1"])); + assert_eq!(a.get("o1").map(String::as_str), Some("cidLATE")); } #[test] - fn merge_newer_timestamp_wins_regardless_of_height() { - // Timestamp is primary: a newer timestamp wins even with a lower block - // height than the older-timestamp manifest. - let older_hi_block = manifest_with("2026-06-10T00:00:00Z", "o1", "cidOLD"); - let newer_lo_block = manifest_with("2026-06-11T00:00:00Z", "o1", "cidNEW"); - let merged = merge_manifests(vec![ - (older_hi_block, Some(9999)), - (newer_lo_block, Some(1)), - ]); - assert_eq!(merged.get("o1").map(String::as_str), Some("cidNEW")); + fn merge_timestamp_comparison_uses_instants_not_strings() { + // "2026-06-11T00:30:00+01:00" is string-wise LARGER than + // "2026-06-11T00:00:00Z" but its instant is 2026-06-10T23:30:00Z, which + // is earlier. Instant comparison must pick the Zulu one. + let offset = vmanifest("2026-06-11T00:30:00+01:00", "o1", "cidOFFSET"); + let zulu = vmanifest("2026-06-11T00:00:00Z", "o1", "cidZULU"); + let merged = merge_authenticated(vec![(offset, Some(5)), (zulu, Some(5))], &tree(&["o1"])); + assert_eq!(merged.get("o1").map(String::as_str), Some("cidZULU")); + // Fractional seconds: .500 is the later instant at equal height. + let plain = vmanifest("2026-06-11T00:00:00Z", "o1", "cidPLAIN"); + let frac = vmanifest("2026-06-11T00:00:00.500Z", "o1", "cidFRAC"); + let merged2 = merge_authenticated(vec![(plain, Some(5)), (frac, Some(5))], &tree(&["o1"])); + assert_eq!(merged2.get("o1").map(String::as_str), Some("cidFRAC")); + } + + #[test] + fn merge_equal_height_and_instant_breaks_by_larger_cid() { + // Two spellings of the same instant compare equal as instants, so the + // lexicographically larger cid wins deterministically in both orders. + let a = merge_authenticated( + vec![ + ( + vmanifest("2026-06-11T01:00:00+01:00", "o1", "cidAAA"), + Some(5), + ), + (vmanifest("2026-06-11T00:00:00Z", "o1", "cidBBB"), Some(5)), + ], + &tree(&["o1"]), + ); + let b = merge_authenticated( + vec![ + (vmanifest("2026-06-11T00:00:00Z", "o1", "cidBBB"), Some(5)), + ( + vmanifest("2026-06-11T01:00:00+01:00", "o1", "cidAAA"), + Some(5), + ), + ], + &tree(&["o1"]), + ); + assert_eq!(a.get("o1"), b.get("o1")); + assert_eq!(a.get("o1").map(String::as_str), Some("cidBBB")); } #[test] - fn merge_empty_timestamp_loses_to_timestamped() { - // A manifest with a missing/empty timestamp (serde default) sorts lowest - // and loses to any timestamped manifest for the same oid. Pins the - // empty-sorts-lowest precondition as a deliberate decision. - let untimestamped = manifest_with("", "o1", "cidEMPTY"); - let timestamped = manifest_with("2026-06-11T00:00:00Z", "o1", "cidTS"); - let a = merge_manifests(vec![(untimestamped, Some(50)), (timestamped, Some(1))]); - assert_eq!(a.get("o1").map(String::as_str), Some("cidTS")); + fn merge_drops_entries_absent_from_the_tree() { + // Fabricated oids can never become valid recovered paths, so they are + // discarded on insertion: with none of the entries in the tree, the + // merge is empty even across many manifests, and with an empty merge + // no `git cat-file` or IPFS fetch can be triggered downstream. + let m1 = vmanifest("2026-06-11T00:00:00Z", "fabricated1", "cidA"); + let mut m2 = vmanifest("2026-06-11T00:00:00Z", "fabricated2", "cidB"); + m2.blobs + .push(twigpine_core::encrypted_manifest::EncryptedBlobRef { + oid: "real".to_string(), + cid: "cidREAL".to_string(), + }); + let merged = merge_authenticated(vec![(m1, Some(1)), (m2, Some(2))], &tree(&["real"])); + assert_eq!(merged.len(), 1); + assert_eq!(merged.get("real").map(String::as_str), Some("cidREAL")); + let all_fake = merge_authenticated( + vec![( + vmanifest("2026-06-11T00:00:00Z", "fabricated", "cidA"), + Some(1), + )], + &tree(&[]), + ); + assert!(all_fake.is_empty()); } + // ── through-the-real-path recovery tests (signed v2 fixtures) ──────── + /// A gateway that refuses one blob must SAY so, and must not take the rest of the /// recovery down with it. /// @@ -1591,64 +2084,42 @@ mod tests { #[tokio::test] async fn recover_from_arweave_reports_a_refusing_gateway_and_continues() { use twigpine_core::encrypt::seal_blob; - use twigpine_core::identity::Keypair; reset_warnings(); - let (td, url) = bare_remote(&[ + let (_td, dest) = clone_with_missing_secrets(&[ ("public/a.txt", b"pub\n"), ("secret/b.txt", b"SECRET B\n"), ("secret/c.txt", b"SECRET C\n"), ]); - let dest = td.path().join("dest"); - let bare = url.strip_prefix("file://").unwrap(); - assert!(Command::new("git") - .args(["-C", bare, "config", "uploadpack.allowFilter", "true"]) - .status() - .unwrap() - .success()); - setup_partial_clone(&dest, &url, &["/secret/**".to_string()], &[], None).unwrap(); - - let oid_of = |path: &str| { - let out = Command::new("git") - .args([ - "-C", - dest.to_str().unwrap(), - "rev-parse", - &format!("HEAD:{path}"), - ]) - .output() - .unwrap(); - String::from_utf8_lossy(&out.stdout).trim().to_string() - }; - let refused_oid = oid_of("secret/b.txt"); - let served_oid = oid_of("secret/c.txt"); - - // Origin death, so recovery has to go through the gateways. - std::fs::remove_dir_all(bare).unwrap(); + let refused_oid = oid_of(&dest, "secret/b.txt"); + let served_oid = oid_of(&dest, "secret/c.txt"); - let reader = Keypair::generate(); - let envelope = seal_blob(b"SECRET C\n", &[reader.verifying_key()]).unwrap(); + let actors = b3_actors(); + let envelope = seal_blob(b"SECRET C\n", &[actors.reader.verifying_key()]).unwrap(); - let refused_cid = "cidrefused"; - let served_cid = "cidserved"; + let refused_cid = test_cid(1); + let served_cid = test_cid(2); + let txid = valid_txid("txmain"); let mut server = mockito::Server::new_async().await; let _gql = server .mock("POST", "/graphql") .with_status(200) .with_header("content-type", "application/json") - .with_body(r#"{"data":{"transactions":{"edges":[{"node":{"id":"TX1"}}]}}}"#) + .with_body(gql_page(&[(txid.as_str(), None)])) .create_async() .await; - let manifest_body = serde_json::json!({ - "timestamp": "2026-06-11T00:00:00Z", - "blobs": [ - { "oid": refused_oid, "cid": refused_cid }, - { "oid": served_oid, "cid": served_cid }, + let manifest_body = signed_manifest_json( + &actors.signer, + &actors.owner, + "myrepo", + "2026-06-11T00:00:00Z", + &[ + (refused_oid.as_str(), refused_cid.as_str()), + (served_oid.as_str(), served_cid.as_str()), ], - }) - .to_string(); + ); let _tx = server - .mock("GET", "/TX1") + .mock("GET", format!("/raw/{txid}").as_str()) .with_status(200) .with_header("content-type", "application/json") .with_body(manifest_body) @@ -1673,10 +2144,11 @@ mod tests { let paths = recover_from_arweave( &server.url(), &server.url(), - "alice", + &actors.owner, "myrepo", &dest, - &reader, + &actors.reader, + &actors.signer.did().to_string(), ) .await .unwrap(); @@ -1711,61 +2183,39 @@ mod tests { #[tokio::test] async fn recover_from_arweave_installs_authorized_blob() { use twigpine_core::encrypt::seal_blob; - use twigpine_core::identity::Keypair; - let (td, url) = bare_remote(&[("public/a.txt", b"pub\n"), ("secret/b.txt", b"SECRET\n")]); - let dest = td.path().join("dest"); - // Make the bare honor `--filter=blob:none` over file:// so the withheld - // blob is genuinely omitted from the local store, not just unchecked-out. - let bare = url.strip_prefix("file://").unwrap(); - assert!(Command::new("git") - .args(["-C", bare, "config", "uploadpack.allowFilter", "true"]) - .status() - .unwrap() - .success()); - setup_partial_clone(&dest, &url, &["/secret/**".to_string()], &[], None).unwrap(); + let (_td, dest) = clone_with_missing_secrets(&[ + ("public/a.txt", b"pub\n"), + ("secret/b.txt", b"SECRET\n"), + ]); assert!( !dest.join("secret/b.txt").exists(), "secret starts withheld" ); + let oid = oid_of(&dest, "secret/b.txt"); - let oid = { - let out = Command::new("git") - .args([ - "-C", - dest.to_str().unwrap(), - "rev-parse", - "HEAD:secret/b.txt", - ]) - .output() - .unwrap(); - String::from_utf8_lossy(&out.stdout).trim().to_string() - }; - - // Simulate origin death: drop the promisor remote so `cat-file -e` cannot - // lazily fetch the withheld blob. This is exactly the B3 premise (the node - // can no longer serve it), and forces recovery to go through Arweave/IPFS. - std::fs::remove_dir_all(url.strip_prefix("file://").unwrap()).unwrap(); + let actors = b3_actors(); + let envelope = seal_blob(b"SECRET\n", &[actors.reader.verifying_key()]).unwrap(); + let cid = test_cid(3); + let txid = valid_txid("txinstall"); - let reader = Keypair::generate(); - let envelope = seal_blob(b"SECRET\n", &[reader.verifying_key()]).unwrap(); - - let cid = "testcid123"; let mut server = mockito::Server::new_async().await; let _gql = server .mock("POST", "/graphql") .with_status(200) .with_header("content-type", "application/json") - .with_body(r#"{"data":{"transactions":{"edges":[{"node":{"id":"TX1"}}]}}}"#) + .with_body(gql_page(&[(txid.as_str(), None)])) .create_async() .await; - let manifest_body = serde_json::json!({ - "timestamp": "2026-06-11T00:00:00Z", - "blobs": [{ "oid": oid, "cid": cid, "recipients": [] }], - }) - .to_string(); + let manifest_body = signed_manifest_json( + &actors.signer, + &actors.owner, + "myrepo", + "2026-06-11T00:00:00Z", + &[(oid.as_str(), cid.as_str())], + ); let _tx = server - .mock("GET", "/TX1") + .mock("GET", format!("/raw/{txid}").as_str()) .with_status(200) .with_header("content-type", "application/json") .with_body(manifest_body) @@ -1781,10 +2231,11 @@ mod tests { let paths = recover_from_arweave( &server.url(), &server.url(), - "alice", + &actors.owner, "myrepo", &dest, - &reader, + &actors.reader, + &actors.signer.did().to_string(), ) .await .unwrap(); @@ -1803,43 +2254,309 @@ mod tests { ); } + /// The reproduction carried forward from `65d55405`, updated for the signed + /// wire: a forged manifest (cryptographically valid but self-signed by an + /// attacker, carrying a far-future timestamp and a bogus cid for the real + /// oid) enters discovery alongside the honest signed manifest. Under the + /// unsigned wire the forged future anchor displaced the honest mapping and + /// recovery returned no paths. Now the forgery is rejected before merge, + /// so only the honest mapping survives and the withheld file is recovered. + #[tokio::test] + async fn forged_future_manifest_cannot_displace_honest_anchor() { + use twigpine_core::encrypt::seal_blob; + + reset_warnings(); + let (_td, dest) = clone_with_missing_secrets(&[ + ("public/a.txt", b"pub\n"), + ("secret/b.txt", b"SECRET\n"), + ]); + let oid = oid_of(&dest, "secret/b.txt"); + + let actors = b3_actors(); + let attacker = twigpine_core::identity::Keypair::generate(); + let envelope = seal_blob(b"SECRET\n", &[actors.reader.verifying_key()]).unwrap(); + let honest_cid = test_cid(4); + let bogus_cid = test_cid(5); + let tx_honest = valid_txid("txhonest"); + let tx_forged = valid_txid("txforged"); + + let mut server = mockito::Server::new_async().await; + let _gql = server + .mock("POST", "/graphql") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(gql_page(&[ + (tx_forged.as_str(), Some(9999)), + (tx_honest.as_str(), Some(10)), + ])) + .create_async() + .await; + // The forgery is well-formed and cryptographically valid, but signed + // by the attacker's key rather than the expected node, and carries a + // far-future timestamp that would have won the old timestamp-first + // merge. It must be rejected before merge. + let forged_body = signed_manifest_json( + &attacker, + &actors.owner, + "myrepo", + "2999-01-01T00:00:00Z", + &[(oid.as_str(), bogus_cid.as_str())], + ); + let _tx_forged = server + .mock("GET", format!("/raw/{tx_forged}").as_str()) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(forged_body) + .create_async() + .await; + let honest_body = signed_manifest_json( + &actors.signer, + &actors.owner, + "myrepo", + "2026-06-11T00:00:00Z", + &[(oid.as_str(), honest_cid.as_str())], + ); + let _tx_honest = server + .mock("GET", format!("/raw/{tx_honest}").as_str()) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(honest_body) + .create_async() + .await; + let bogus_fetch = server + .mock("GET", format!("/ipfs/{bogus_cid}").as_str()) + .with_status(200) + .with_body(b"bogus".to_vec()) + .expect(0) + .create_async() + .await; + let _blob = server + .mock("GET", format!("/ipfs/{honest_cid}").as_str()) + .with_status(200) + .with_body(envelope) + .create_async() + .await; + + let paths = recover_from_arweave( + &server.url(), + &server.url(), + &actors.owner, + "myrepo", + &dest, + &actors.reader, + &actors.signer.did().to_string(), + ) + .await + .unwrap(); + assert_eq!( + paths, + vec!["secret/b.txt".to_string()], + "only the honest signed mapping may survive; the forgery is rejected before merge" + ); + bogus_fetch.assert_async().await; + assert!( + warnings().contains("not a trusted signed manifest"), + "the rejection must be reported, got: {:?}", + warnings() + ); + } + + /// A correctly signed manifest for a DIFFERENT repo must be rejected before + /// merge even when the gateway's tags were right: tags are hints, the + /// signed payload is the authority. + #[tokio::test] + async fn recover_from_arweave_rejects_correct_signer_wrong_repo() { + use twigpine_core::encrypt::seal_blob; + + reset_warnings(); + let (_td, dest) = clone_with_missing_secrets(&[ + ("public/a.txt", b"pub\n"), + ("secret/b.txt", b"SECRET\n"), + ]); + let oid = oid_of(&dest, "secret/b.txt"); + + let actors = b3_actors(); + let envelope = seal_blob(b"SECRET\n", &[actors.reader.verifying_key()]).unwrap(); + let cid = test_cid(6); + let txid = valid_txid("txwrongrepo"); + + let mut server = mockito::Server::new_async().await; + let _gql = server + .mock("POST", "/graphql") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(gql_page(&[(txid.as_str(), None)])) + .create_async() + .await; + let wrong_repo_body = signed_manifest_json( + &actors.signer, + &actors.owner, + "otherrepo", + "2026-06-11T00:00:00Z", + &[(oid.as_str(), cid.as_str())], + ); + let _tx = server + .mock("GET", format!("/raw/{txid}").as_str()) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(wrong_repo_body) + .create_async() + .await; + let ipfs = server + .mock("GET", format!("/ipfs/{cid}").as_str()) + .with_status(200) + .with_body(envelope) + .expect(0) + .create_async() + .await; + + let paths = recover_from_arweave( + &server.url(), + &server.url(), + &actors.owner, + "myrepo", + &dest, + &actors.reader, + &actors.signer.did().to_string(), + ) + .await + .unwrap(); + assert!(paths.is_empty(), "a wrong-repo manifest must be rejected"); + ipfs.assert_async().await; + } + + /// Unsigned legacy v1 data is never recovery authority: when the v2 + /// discovery finds nothing but the cheap metadata-only probe finds v1 + /// candidates, the caller is told legacy anchors are ignored rather than + /// left with silent absence. No v1 body is ever fetched. + #[tokio::test] + async fn recover_from_arweave_warns_when_only_unsigned_legacy_exists() { + use twigpine_core::identity::Keypair; + + reset_warnings(); + let (_td, dest) = clone_with_missing_secrets(&[ + ("public/a.txt", b"pub\n"), + ("secret/b.txt", b"SECRET\n"), + ]); + + let actors = b3_actors(); + let reader = Keypair::generate(); + let slug = canonical_repo_slug(&actors.owner, "myrepo"); + let legacy_tag = legacy_repo_tag(&slug); + + let mut server = mockito::Server::new_async().await; + // v2 discovery (carries the digest variable): no candidates. + let _gql_v2 = server + .mock("POST", "/graphql") + .match_body(mockito::Matcher::PartialJsonString( + r#"{"variables":{"cursor":null}}"#.into(), + )) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"data":{"transactions":{"edges":[]}}}"#) + .create_async() + .await; + // The legacy probe (carries the repo variable, no cursor): one v1 hit. + let probe = server + .mock("POST", "/graphql") + .match_body(mockito::Matcher::PartialJsonString(format!( + r#"{{"variables":{{"repo":"{legacy_tag}"}}}}"# + ))) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"data":{"transactions":{"edges":[{"node":{"id":"legacytx"}}]}}}"#) + .expect(1) + .create_async() + .await; + + let paths = recover_from_arweave( + &server.url(), + &server.url(), + &actors.owner, + "myrepo", + &dest, + &reader, + &actors.signer.did().to_string(), + ) + .await + .unwrap(); + assert!(paths.is_empty()); + probe.assert_async().await; + assert!( + warnings().contains("unsigned legacy"), + "the legacy-presence warning must fire, got: {:?}", + warnings() + ); + } + + /// A gateway-invented malformed transaction id must never appear in a + /// request URL: exactly-43-base64url validation drops it before the fetch. + #[tokio::test] + async fn recover_from_arweave_never_fetches_a_malformed_txid() { + use twigpine_core::identity::Keypair; + + reset_warnings(); + let (_td, dest) = clone_with_missing_secrets(&[ + ("public/a.txt", b"pub\n"), + ("secret/b.txt", b"SECRET\n"), + ]); + let reader = Keypair::generate(); + let actors = b3_actors(); + + let mut server = mockito::Server::new_async().await; + let _gql = server + .mock("POST", "/graphql") + .with_status(200) + .with_header("content-type", "application/json") + // "TX1" is 3 chars, "lorem" is 5: both invalid. + .with_body( + r#"{"data":{"transactions":{"edges":[{"node":{"id":"TX1"}},{"node":{"id":"lorem"}},{"node":{"id":"../..//../..//../..//../..//../..//../"} }]}}}"#, + ) + .create_async() + .await; + let any_raw = server + .mock("GET", mockito::Matcher::Regex(r"^/raw/.*".into())) + .with_status(200) + .expect(0) + .create_async() + .await; + + let paths = recover_from_arweave( + &server.url(), + &server.url(), + &actors.owner, + "myrepo", + &dest, + &reader, + &actors.signer.did().to_string(), + ) + .await + .unwrap(); + assert!(paths.is_empty()); + any_raw.assert_async().await; + } + /// Discovery must follow cursor pagination: a blob whose manifest is anchored /// only on the SECOND page is still recovered. If the loop stopped at page 1 /// (the old `first:100` behavior), this blob would be lost. #[tokio::test] async fn recover_from_arweave_paginates_to_later_page() { use twigpine_core::encrypt::seal_blob; - use twigpine_core::identity::Keypair; - let (td, url) = bare_remote(&[("public/a.txt", b"pub\n"), ("secret/b.txt", b"SECRET\n")]); - let dest = td.path().join("dest"); - let bare = url.strip_prefix("file://").unwrap(); - assert!(Command::new("git") - .args(["-C", bare, "config", "uploadpack.allowFilter", "true"]) - .status() - .unwrap() - .success()); - setup_partial_clone(&dest, &url, &["/secret/**".to_string()], &[], None).unwrap(); - let oid = { - let out = Command::new("git") - .args([ - "-C", - dest.to_str().unwrap(), - "rev-parse", - "HEAD:secret/b.txt", - ]) - .output() - .unwrap(); - String::from_utf8_lossy(&out.stdout).trim().to_string() - }; - std::fs::remove_dir_all(url.strip_prefix("file://").unwrap()).unwrap(); + let (_td, dest) = clone_with_missing_secrets(&[ + ("public/a.txt", b"pub\n"), + ("secret/b.txt", b"SECRET\n"), + ]); + let oid = oid_of(&dest, "secret/b.txt"); - let reader = Keypair::generate(); - let envelope = seal_blob(b"SECRET\n", &[reader.verifying_key()]).unwrap(); - let cid = "testcid123"; + let actors = b3_actors(); + let envelope = seal_blob(b"SECRET\n", &[actors.reader.verifying_key()]).unwrap(); + let cid = test_cid(7); + let tx_p1 = valid_txid("txpageone"); + let tx_p2 = valid_txid("txpagetwo"); let mut server = mockito::Server::new_async().await; - // Page 1 (cursor null): hasNextPage=true, endCursor C1, an empty manifest + // Page 1 (cursor null): hasNextPage=true, endCursor C1, an empty-manifest // anchor that does NOT carry the withheld blob. let _gql_p1 = server .mock("POST", "/graphql") @@ -1848,9 +2565,9 @@ mod tests { )) .with_status(200) .with_header("content-type", "application/json") - .with_body( - r#"{"data":{"transactions":{"pageInfo":{"hasNextPage":true,"endCursor":"C1"},"edges":[{"node":{"id":"TXP1","block":{"height":10}}}]}}}"#, - ) + .with_body(format!( + r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":true,"endCursor":"C1"}},"edges":[{{"node":{{"id":"{tx_p1}","block":{{"height":10}}}}}}]}}}}}}"# + )) .create_async() .await; // Page 2 (cursor "C1"): hasNextPage=false, the anchor with the blob. @@ -1861,25 +2578,34 @@ mod tests { )) .with_status(200) .with_header("content-type", "application/json") - .with_body( - r#"{"data":{"transactions":{"pageInfo":{"hasNextPage":false,"endCursor":"C2"},"edges":[{"node":{"id":"TX1","block":{"height":20}}}]}}}"#, - ) + .with_body(format!( + r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":false,"endCursor":"C2"}},"edges":[{{"node":{{"id":"{tx_p2}","block":{{"height":20}}}}}}]}}}}}}"# + )) .create_async() .await; + let empty_body = signed_manifest_json( + &actors.signer, + &actors.owner, + "myrepo", + "2026-06-10T00:00:00Z", + &[], + ); let _tx_p1 = server - .mock("GET", "/TXP1") + .mock("GET", format!("/raw/{tx_p1}").as_str()) .with_status(200) .with_header("content-type", "application/json") - .with_body(r#"{"timestamp":"2026-06-10T00:00:00Z","blobs":[]}"#) + .with_body(empty_body) .create_async() .await; - let manifest_body = serde_json::json!({ - "timestamp": "2026-06-11T00:00:00Z", - "blobs": [{ "oid": oid, "cid": cid, "recipients": [] }], - }) - .to_string(); - let _tx1 = server - .mock("GET", "/TX1") + let manifest_body = signed_manifest_json( + &actors.signer, + &actors.owner, + "myrepo", + "2026-06-11T00:00:00Z", + &[(oid.as_str(), cid.as_str())], + ); + let _tx_p2 = server + .mock("GET", format!("/raw/{tx_p2}").as_str()) .with_status(200) .with_header("content-type", "application/json") .with_body(manifest_body) @@ -1895,10 +2621,11 @@ mod tests { let paths = recover_from_arweave( &server.url(), &server.url(), - "alice", + &actors.owner, "myrepo", &dest, - &reader, + &actors.reader, + &actors.signer.did().to_string(), ) .await .unwrap(); @@ -1915,42 +2642,27 @@ mod tests { #[tokio::test] async fn recover_from_arweave_partial_on_midpagination_failure() { use twigpine_core::encrypt::seal_blob; - use twigpine_core::identity::Keypair; - let (td, url) = bare_remote(&[("public/a.txt", b"pub\n"), ("secret/b.txt", b"SECRET\n")]); - let dest = td.path().join("dest"); - let bare = url.strip_prefix("file://").unwrap(); - assert!(Command::new("git") - .args(["-C", bare, "config", "uploadpack.allowFilter", "true"]) - .status() - .unwrap() - .success()); - setup_partial_clone(&dest, &url, &["/secret/**".to_string()], &[], None).unwrap(); - let oid = { - let out = Command::new("git") - .args([ - "-C", - dest.to_str().unwrap(), - "rev-parse", - "HEAD:secret/b.txt", - ]) - .output() - .unwrap(); - String::from_utf8_lossy(&out.stdout).trim().to_string() - }; - std::fs::remove_dir_all(url.strip_prefix("file://").unwrap()).unwrap(); + let (_td, dest) = clone_with_missing_secrets(&[ + ("public/a.txt", b"pub\n"), + ("secret/b.txt", b"SECRET\n"), + ]); + let oid = oid_of(&dest, "secret/b.txt"); - let reader = Keypair::generate(); - let envelope = seal_blob(b"SECRET\n", &[reader.verifying_key()]).unwrap(); - let cid = "testcid123"; + let actors = b3_actors(); + let envelope = seal_blob(b"SECRET\n", &[actors.reader.verifying_key()]).unwrap(); + let cid = test_cid(8); + let txid = valid_txid("txpartial"); let mut server = mockito::Server::new_async().await; // Page 1 (cursor null): the blob anchor, hasNextPage=true. - let manifest_body = serde_json::json!({ - "timestamp": "2026-06-11T00:00:00Z", - "blobs": [{ "oid": oid, "cid": cid, "recipients": [] }], - }) - .to_string(); + let manifest_body = signed_manifest_json( + &actors.signer, + &actors.owner, + "myrepo", + "2026-06-11T00:00:00Z", + &[(oid.as_str(), cid.as_str())], + ); let _gql_p1 = server .mock("POST", "/graphql") .match_body(mockito::Matcher::PartialJsonString( @@ -1958,9 +2670,9 @@ mod tests { )) .with_status(200) .with_header("content-type", "application/json") - .with_body( - r#"{"data":{"transactions":{"pageInfo":{"hasNextPage":true,"endCursor":"C1"},"edges":[{"node":{"id":"TX1","block":{"height":20}}}]}}}"#, - ) + .with_body(format!( + r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":true,"endCursor":"C1"}},"edges":[{{"node":{{"id":"{txid}","block":{{"height":20}}}}}}]}}}}}}"# + )) .create_async() .await; // Page 2 (cursor "C1"): gateway error. @@ -1973,7 +2685,7 @@ mod tests { .create_async() .await; let _tx1 = server - .mock("GET", "/TX1") + .mock("GET", format!("/raw/{txid}").as_str()) .with_status(200) .with_header("content-type", "application/json") .with_body(manifest_body) @@ -1989,10 +2701,11 @@ mod tests { let paths = recover_from_arweave( &server.url(), &server.url(), - "alice", + &actors.owner, "myrepo", &dest, - &reader, + &actors.reader, + &actors.signer.did().to_string(), ) .await .expect("mid-pagination failure must not abort recovery"); @@ -2010,36 +2723,18 @@ mod tests { #[tokio::test] async fn recover_from_arweave_terminates_on_nonadvancing_cursor() { use twigpine_core::encrypt::seal_blob; - use twigpine_core::identity::Keypair; - let (td, url) = bare_remote(&[("public/a.txt", b"pub\n"), ("secret/b.txt", b"SECRET\n")]); - let dest = td.path().join("dest"); - let bare = url.strip_prefix("file://").unwrap(); - assert!(Command::new("git") - .args(["-C", bare, "config", "uploadpack.allowFilter", "true"]) - .status() - .unwrap() - .success()); - setup_partial_clone(&dest, &url, &["/secret/**".to_string()], &[], None).unwrap(); - let oid = { - let out = Command::new("git") - .args([ - "-C", - dest.to_str().unwrap(), - "rev-parse", - "HEAD:secret/b.txt", - ]) - .output() - .unwrap(); - String::from_utf8_lossy(&out.stdout).trim().to_string() - }; - std::fs::remove_dir_all(url.strip_prefix("file://").unwrap()).unwrap(); + let (_td, dest) = clone_with_missing_secrets(&[ + ("public/a.txt", b"pub\n"), + ("secret/b.txt", b"SECRET\n"), + ]); + let oid = oid_of(&dest, "secret/b.txt"); - let reader = Keypair::generate(); - let envelope = seal_blob(b"SECRET\n", &[reader.verifying_key()]).unwrap(); - let cid = "testcid123"; + let actors = b3_actors(); + let envelope = seal_blob(b"SECRET\n", &[actors.reader.verifying_key()]).unwrap(); + let cid = test_cid(9); + let txid = valid_txid("txstuck"); - let mut server = mockito::Server::new_async().await; // Every GraphQL POST returns hasNextPage=true with the SAME endCursor. // The guard fires on the second page (cursor repeats prev_cursor) and // breaks, so discovery makes exactly two POSTs: page 1 (cursor null) records @@ -2047,23 +2742,26 @@ mod tests { // exact count below — a regression in the advance logic that loops extra // times in the happy path fails the expect(2). (MAX_PAGES is the hard // infinite-loop backstop independent of this guard.) - let manifest_body = serde_json::json!({ - "timestamp": "2026-06-11T00:00:00Z", - "blobs": [{ "oid": oid, "cid": cid, "recipients": [] }], - }) - .to_string(); + let mut server = mockito::Server::new_async().await; + let manifest_body = signed_manifest_json( + &actors.signer, + &actors.owner, + "myrepo", + "2026-06-11T00:00:00Z", + &[(oid.as_str(), cid.as_str())], + ); let gql = server .mock("POST", "/graphql") .expect(2) .with_status(200) .with_header("content-type", "application/json") - .with_body( - r#"{"data":{"transactions":{"pageInfo":{"hasNextPage":true,"endCursor":"STUCK"},"edges":[{"node":{"id":"TX1","block":{"height":20}}}]}}}"#, - ) + .with_body(format!( + r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":true,"endCursor":"STUCK"}},"edges":[{{"node":{{"id":"{txid}","block":{{"height":20}}}}}}]}}}}}}"# + )) .create_async() .await; let _tx1 = server - .mock("GET", "/TX1") + .mock("GET", format!("/raw/{txid}").as_str()) .with_status(200) .with_header("content-type", "application/json") .with_body(manifest_body) @@ -2079,10 +2777,11 @@ mod tests { let paths = recover_from_arweave( &server.url(), &server.url(), - "alice", + &actors.owner, "myrepo", &dest, - &reader, + &actors.reader, + &actors.signer.did().to_string(), ) .await .expect("non-advancing cursor must terminate, not hang or error"); @@ -2091,42 +2790,25 @@ mod tests { } /// A tx id repeated across pages must be fetched only once: the cross-page - /// dedup (R8) bounds the downstream per-id manifest fetch loop. + /// dedup bounds the downstream per-id manifest fetch loop. #[tokio::test] async fn recover_from_arweave_dedups_tx_ids_across_pages() { use twigpine_core::encrypt::seal_blob; - use twigpine_core::identity::Keypair; - let (td, url) = bare_remote(&[("public/a.txt", b"pub\n"), ("secret/b.txt", b"SECRET\n")]); - let dest = td.path().join("dest"); - let bare = url.strip_prefix("file://").unwrap(); - assert!(Command::new("git") - .args(["-C", bare, "config", "uploadpack.allowFilter", "true"]) - .status() - .unwrap() - .success()); - setup_partial_clone(&dest, &url, &["/secret/**".to_string()], &[], None).unwrap(); - let oid = { - let out = Command::new("git") - .args([ - "-C", - dest.to_str().unwrap(), - "rev-parse", - "HEAD:secret/b.txt", - ]) - .output() - .unwrap(); - String::from_utf8_lossy(&out.stdout).trim().to_string() - }; - std::fs::remove_dir_all(url.strip_prefix("file://").unwrap()).unwrap(); + let (_td, dest) = clone_with_missing_secrets(&[ + ("public/a.txt", b"pub\n"), + ("secret/b.txt", b"SECRET\n"), + ]); + let oid = oid_of(&dest, "secret/b.txt"); - let reader = Keypair::generate(); - let envelope = seal_blob(b"SECRET\n", &[reader.verifying_key()]).unwrap(); - let cid = "testcid123"; + let actors = b3_actors(); + let envelope = seal_blob(b"SECRET\n", &[actors.reader.verifying_key()]).unwrap(); + let cid = test_cid(10); + let txid = valid_txid("txdup"); let mut server = mockito::Server::new_async().await; - // Page 1 and page 2 both list TX1 (cursor advances); the dedup must fetch - // the /TX1 manifest exactly once. + // Page 1 and page 2 both list the same tx (cursor advances); the dedup + // must fetch the manifest exactly once. let _gql_p1 = server .mock("POST", "/graphql") .match_body(mockito::Matcher::PartialJsonString( @@ -2134,9 +2816,9 @@ mod tests { )) .with_status(200) .with_header("content-type", "application/json") - .with_body( - r#"{"data":{"transactions":{"pageInfo":{"hasNextPage":true,"endCursor":"C1"},"edges":[{"node":{"id":"TX1","block":{"height":20}}}]}}}"#, - ) + .with_body(format!( + r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":true,"endCursor":"C1"}},"edges":[{{"node":{{"id":"{txid}","block":{{"height":20}}}}}}]}}}}}}"# + )) .create_async() .await; let _gql_p2 = server @@ -2146,18 +2828,20 @@ mod tests { )) .with_status(200) .with_header("content-type", "application/json") - .with_body( - r#"{"data":{"transactions":{"pageInfo":{"hasNextPage":false,"endCursor":"C2"},"edges":[{"node":{"id":"TX1","block":{"height":20}}}]}}}"#, - ) + .with_body(format!( + r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":false,"endCursor":"C2"}},"edges":[{{"node":{{"id":"{txid}","block":{{"height":20}}}}}}]}}}}}}"# + )) .create_async() .await; - let manifest_body = serde_json::json!({ - "timestamp": "2026-06-11T00:00:00Z", - "blobs": [{ "oid": oid, "cid": cid, "recipients": [] }], - }) - .to_string(); + let manifest_body = signed_manifest_json( + &actors.signer, + &actors.owner, + "myrepo", + "2026-06-11T00:00:00Z", + &[(oid.as_str(), cid.as_str())], + ); let tx1 = server - .mock("GET", "/TX1") + .mock("GET", format!("/raw/{txid}").as_str()) .expect(1) // dedup: fetched once despite appearing on both pages .with_status(200) .with_header("content-type", "application/json") @@ -2174,15 +2858,16 @@ mod tests { let paths = recover_from_arweave( &server.url(), &server.url(), - "alice", + &actors.owner, "myrepo", &dest, - &reader, + &actors.reader, + &actors.signer.did().to_string(), ) .await .unwrap(); assert_eq!(paths, vec!["secret/b.txt".to_string()]); - tx1.assert_async().await; // exactly one /TX1 fetch + tx1.assert_async().await; // exactly one manifest fetch } /// A caller who is not a recipient cannot decrypt the envelope, so nothing is @@ -2192,54 +2877,37 @@ mod tests { use twigpine_core::encrypt::seal_blob; use twigpine_core::identity::Keypair; - let (td, url) = bare_remote(&[("public/a.txt", b"pub\n"), ("secret/b.txt", b"SECRET\n")]); - let dest = td.path().join("dest"); - let bare = url.strip_prefix("file://").unwrap(); - assert!(Command::new("git") - .args(["-C", bare, "config", "uploadpack.allowFilter", "true"]) - .status() - .unwrap() - .success()); - setup_partial_clone(&dest, &url, &["/secret/**".to_string()], &[], None).unwrap(); - - let oid = { - let out = Command::new("git") - .args([ - "-C", - dest.to_str().unwrap(), - "rev-parse", - "HEAD:secret/b.txt", - ]) - .output() - .unwrap(); - String::from_utf8_lossy(&out.stdout).trim().to_string() - }; - - // Simulate origin death (see the authorized test) so the withheld blob - // cannot be lazily fetched from the promisor remote. - std::fs::remove_dir_all(url.strip_prefix("file://").unwrap()).unwrap(); + let (_td, dest) = clone_with_missing_secrets(&[ + ("public/a.txt", b"pub\n"), + ("secret/b.txt", b"SECRET\n"), + ]); + let oid = oid_of(&dest, "secret/b.txt"); + let actors = b3_actors(); // Sealed to a different reader; the caller below is not a recipient. let authorized = Keypair::generate(); let envelope = seal_blob(b"SECRET\n", &[authorized.verifying_key()]).unwrap(); let intruder = Keypair::generate(); - let cid = "testcid123"; + let cid = test_cid(11); + let txid = valid_txid("txunauth"); let mut server = mockito::Server::new_async().await; let _gql = server .mock("POST", "/graphql") .with_status(200) .with_header("content-type", "application/json") - .with_body(r#"{"data":{"transactions":{"edges":[{"node":{"id":"TX1"}}]}}}"#) + .with_body(gql_page(&[(txid.as_str(), None)])) .create_async() .await; - let manifest_body = serde_json::json!({ - "timestamp": "2026-06-11T00:00:00Z", - "blobs": [{ "oid": oid, "cid": cid, "recipients": [] }], - }) - .to_string(); + let manifest_body = signed_manifest_json( + &actors.signer, + &actors.owner, + "myrepo", + "2026-06-11T00:00:00Z", + &[(oid.as_str(), cid.as_str())], + ); let _tx = server - .mock("GET", "/TX1") + .mock("GET", format!("/raw/{txid}").as_str()) .with_status(200) .with_header("content-type", "application/json") .with_body(manifest_body) @@ -2255,10 +2923,11 @@ mod tests { let paths = recover_from_arweave( &server.url(), &server.url(), - "alice", + &actors.owner, "myrepo", &dest, &intruder, + &actors.signer.did().to_string(), ) .await .unwrap(); @@ -2274,6 +2943,269 @@ mod tests { assert!(!present, "non-recipient must not install the blob"); } + // ── trust anchor, protocol caps, budgets, and warnings ─────────────── + + #[test] + fn expect_node_pin_validation() { + use twigpine_core::identity::Keypair; + let kp = Keypair::generate(); + assert!(validate_expect_node_pin(&kp.did().to_string()).is_ok()); + // Malformed entirely. + assert!(validate_expect_node_pin("not-a-did").is_err()); + // A syntactically valid non-did:key method. + assert!(validate_expect_node_pin("did:web:example.com").is_err()); + // did:gitlawb is not a did:key either. + assert!(validate_expect_node_pin("did:gitlawb:z6Mkabc").is_err()); + } + + #[test] + fn txid_validation_requires_exactly_43_base64url() { + assert!(is_valid_txid(&valid_txid("anything"))); + assert!(is_valid_txid(&"a".repeat(43))); + assert!(is_valid_txid(&format!("{}-_", "a".repeat(41)))); + for bad in [ + "", + "TX1", + &"a".repeat(42), + &"a".repeat(44), + &format!("{}!", "a".repeat(42)), + &format!("{}/", "a".repeat(42)), + ] { + assert!(!is_valid_txid(bad), "{bad:?}"); + } + } + + /// The strict cap+1 protocol-body idiom: exactly-at-cap is accepted, + /// cap+1 is rejected before parse. + #[tokio::test] + async fn read_protocol_body_accepts_exact_cap_and_rejects_cap_plus_one() { + let mut server = mockito::Server::new_async().await; + let exact = server + .mock("GET", "/exact") + .with_status(200) + .with_body("x".repeat(64)) + .create_async() + .await; + let over = server + .mock("GET", "/over") + .with_status(200) + .with_body("x".repeat(65)) + .create_async() + .await; + let client = reqwest::Client::new(); + let resp = client + .get(format!("{}/exact", server.url())) + .send() + .await + .unwrap(); + let body = read_protocol_body(resp, 64).await.unwrap(); + assert_eq!(body.len(), 64); + let resp = client + .get(format!("{}/over", server.url())) + .send() + .await + .unwrap(); + assert!( + read_protocol_body(resp, 64).await.is_err(), + "cap+1 bytes must be rejected" + ); + exact.assert_async().await; + over.assert_async().await; + } + + #[tokio::test] + async fn resolve_implicit_node_did_reads_the_root_did() { + use twigpine_core::identity::Keypair; + let kp = Keypair::generate(); + let mut server = mockito::Server::new_async().await; + let _root = server + .mock("GET", "/") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(serde_json::json!({ "did": kp.did().to_string() }).to_string()) + .create_async() + .await; + let did = resolve_implicit_node_did(&server.url()).await.unwrap(); + assert_eq!(did, kp.did().to_string()); + } + + #[tokio::test] + async fn resolve_implicit_node_did_rejects_missing_or_non_key_dids() { + for body in [ + serde_json::json!({}).to_string(), + serde_json::json!({ "did": "did:web:example.com" }).to_string(), + serde_json::json!({ "did": "not-a-did" }).to_string(), + ] { + let mut server = mockito::Server::new_async().await; + let _root = server + .mock("GET", "/") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + assert!( + resolve_implicit_node_did(&server.url()).await.is_err(), + "invalid or missing implicit anchor must error (B3 then skips with a warning)" + ); + } + } + + /// The git subprocess environment carries the effective node as both + /// TWIGPINE_NODE and GITLAWB_NODE, overriding an inherited conflicting + /// value. `env` prints exactly what the child sees, so this observes the + /// real subprocess environment rather than a proxy. + #[test] + fn node_env_is_threaded_and_overrides_inherited_values() { + let node = "https://node.example.test"; + // An inherited conflicting value must lose to the effective node. + std::env::set_var("GITLAWB_NODE", "http://conflicting-legacy"); + let mut cmd = Command::new("env"); + apply_node_env(&mut cmd, Some(node)); + let out = cmd.output().unwrap(); + std::env::remove_var("GITLAWB_NODE"); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + stdout.contains(&format!("TWIGPINE_NODE={node}")), + "subprocess must see TWIGPINE_NODE, got: {stdout}" + ); + assert!( + stdout.contains(&format!("GITLAWB_NODE={node}")), + "the effective node must override the inherited conflicting GITLAWB_NODE, got: {stdout}" + ); + assert!(!stdout.contains("conflicting-legacy")); + + // None leaves the environment untouched for direct local git operations. + let mut bare = Command::new("env"); + apply_node_env(&mut bare, None); + let out = bare.output().unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(!stdout.contains("TWIGPINE_NODE=")); + } + + /// Detailed B3 warnings are capped: at most 20 detail lines reach the + /// terminal, then one aggregate line reports the suppressed remainder. + #[test] + fn warning_cap_limits_detail_lines_and_aggregates() { + reset_warnings(); + let mut cap = WarningCap::new(); + for i in 0..25 { + cap.warn(&format!("warning: detail line {i}")); + } + cap.flush(); + let w = warnings(); + assert!(w.contains("detail line 0")); + assert!(w.contains("detail line 19")); + assert!( + !w.contains("detail line 20"), + "line 21 onward must be suppressed, got: {w}" + ); + assert!( + w.contains("5 further arweave recovery warning(s) suppressed"), + "the aggregate must report the suppressed count, got: {w}" + ); + } + + /// An exhausted metadata budget stops discovery before the first page and + /// warns that recovery is incomplete; no transaction is ever fetched. + #[tokio::test] + async fn metadata_budget_expiry_stops_discovery_with_a_warning() { + use twigpine_core::identity::Keypair; + + reset_warnings(); + let (_td, dest) = clone_with_missing_secrets(&[ + ("public/a.txt", b"pub\n"), + ("secret/b.txt", b"SECRET\n"), + ]); + let reader = Keypair::generate(); + let actors = b3_actors(); + + let mut server = mockito::Server::new_async().await; + let gql = server + .mock("POST", "/graphql") + .expect(0) + .create_async() + .await; + + let limits = DiscoveryLimits { + max_pages: 8, + max_tx_ids: 512, + metadata_budget: std::time::Duration::ZERO, + }; + let paths = recover_from_arweave_inner( + &server.url(), + &server.url(), + &actors.owner, + "myrepo", + &dest, + &reader, + &actors.signer.did().to_string(), + &limits, + ) + .await + .unwrap(); + assert!(paths.is_empty()); + gql.assert_async().await; + assert!( + warnings().contains("time budget"), + "the incomplete recovery must be warned, got: {:?}", + warnings() + ); + } + + /// Discovery stops at the page cap and warns, even when the gateway keeps + /// offering a fresh cursor. + #[tokio::test] + async fn discovery_page_cap_is_enforced_with_a_warning() { + use twigpine_core::identity::Keypair; + + reset_warnings(); + let (_td, dest) = clone_with_missing_secrets(&[ + ("public/a.txt", b"pub\n"), + ("secret/b.txt", b"SECRET\n"), + ]); + let reader = Keypair::generate(); + let actors = b3_actors(); + let txid = valid_txid("txpagecap"); + + let mut server = mockito::Server::new_async().await; + // The page claims hasNextPage, so an uncapped loop would continue; the + // page cap of 1 must end discovery after this first page either way. + let _gql = server + .mock("POST", "/graphql") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(format!( + r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":true,"endCursor":"C1"}},"edges":[{{"node":{{"id":"{txid}","block":{{"height":1}}}}}}]}}}}}}"# + )) + .create_async() + .await; + + let limits = DiscoveryLimits { + max_pages: 1, + max_tx_ids: 512, + metadata_budget: std::time::Duration::from_secs(60), + }; + let paths = recover_from_arweave_inner( + &server.url(), + &server.url(), + &actors.owner, + "myrepo", + &dest, + &reader, + &actors.signer.did().to_string(), + &limits, + ) + .await + .unwrap(); + assert!(paths.is_empty()); + assert!( + warnings().contains("1-page cap"), + "the page cap must warn, got: {:?}", + warnings() + ); + } + #[test] fn parse_repo_accepts_url_and_bare() { let (url, o, n) = parse_repo("gitlawb://did:key:zAbc/myrepo").unwrap(); From 8d81609d808738d8a8c35436f4f049345e6aaeba Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:18:42 -0600 Subject: [PATCH 05/18] docs: document signed encrypted recovery manifests --- PROTOCOL.md | 115 +++++++++++++++++++++++++++++++++++++++++++ README.md | 27 ++++++++++ docs/LEGACY-NAMES.md | 3 +- 3 files changed, 144 insertions(+), 1 deletion(-) diff --git a/PROTOCOL.md b/PROTOCOL.md index ba5e97f80..4ddcf157c 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -119,3 +119,118 @@ they are documented with the node's HTTP API, not here. serves it over REST (the repo `refs` endpoint maps branch heads to CIDs). *Planned:* IPNS-backed branch pointers; IPNS is not part of the shipped wire contract. +## 6. Signed encrypted-blob recovery manifests + +Encrypted-blob recovery uses a permanent index that maps git object ids to the +CIDs of encrypted envelopes. Version 2 is the only schema a current client may +use as recovery authority. Version 1 manifests may still exist in permanent +storage, but they are unsigned and current clients MUST NOT fetch or interpret +their bodies as authority. + +### Artifact shape + +A v2 artifact is one compact JSON object with exactly these fields: + +```json +{"schema":"gitlawb/encrypted-manifest/v2","payload":"","signature":""} +``` + +The `payload` value is a JSON string, not a nested object. The exact UTF-8 +bytes of that string are the signed bytes. When parsed as JSON, the payload has +exactly these fields: + +- `schema`: exactly `gitlawb/encrypted-manifest/v2`. +- `repo`: the canonical repository slug described below. +- `owner_did`: the repository owner DID. +- `node_did`: the signing node's canonical Ed25519 `did:key`. +- `timestamp`: an RFC 3339 timestamp. +- `blobs`: an array of objects with exactly `oid` and `cid`. + +The signing input is the ASCII bytes `gitlawb-encrypted-manifest-sig/v2\n` +followed by the exact payload-string bytes. The signature is base64url without +padding over a 64-byte Ed25519 signature. Unknown or missing fields, a schema +mismatch, malformed base64url, a wrong signature length, or a signature that +does not verify are all rejection conditions. + +The canonical owner key strips a leading `did:key:` only when the remainder +contains no further colon. Other DID spellings remain whole. The canonical +repository slug is `/`. The signed `owner_did` +must canonicalize to the owner portion of the signed `repo`. Object ids are 40 +or 64 lowercase or uppercase hexadecimal characters and must not repeat within +one manifest. Blob CIDs must parse as CIDv1; any CIDv1 codec is valid because +large envelopes may sit behind a chunked root. + +A verifier accepts at most 256 KiB of outer artifact bytes and at most 1024 +blob entries. Current writers produce complete disjoint shards of at most 256 +entries and at most 96 KiB of outer bytes each. No shard index exists because +the entries are disjoint and recovery is their union. A shard that cannot be +made valid must not be published. + +### Discovery and retrieval + +Discovery tags are hints, never authority. Current discovery uses: + +- `App-Name`: `twigpine` or `gitlawb` +- `Schema`: `gitlawb/encrypted-manifest/v2` +- `Repo-Digest`: base64url-unpadded SHA-256 over the exact UTF-8 bytes of the + canonical repository slug + +The human-readable `Repo` tag is diagnostic only. It may be truncated by the +uploader's tag rules and is not a v2 discovery key. Legacy v1 probing uses the +old truncated `Repo` tag only as a metadata-only presence check; v1 bodies are +never recovery input. + +A client requests Arweave transaction bodies from `/raw/`, not +from the manifest-resolving `/` endpoint. Transaction ids are +exactly 43 base64url characters before they may appear in a request URL. The +CLI discovery query asks for `sort: HEIGHT_DESC` and reads at most 8 pages or +512 transaction ids. Each GraphQL page response is capped at 256 KiB. +Discovery plus manifest fetch and verification has a 120 second wall-clock +budget. Hitting a count or time budget means recovery is incomplete and must +produce a warning. + +### Verification and trust anchor + +The signer DID is anchored outside the artifact. `twigpine clone --expect-node +` supplies the pin explicitly. Without it, the CLI reads the effective +clone node's root metadata once, accepts its `did` field only when it is a +canonical Ed25519 `did:key`, and uses that as the implicit anchor. The implicit +anchor is not independent verification: clone already trusts the selected node +for the base repository and primary recovery. It exists so the ordinary clone +path can use B3. A caller cloning through a replica who needs the origin +node's anchors should pin that origin DID with `--expect-node`; the pin is not +required to equal the replica's self-reported DID. If no valid implicit anchor +can be derived, only Arweave recovery is skipped. + +The artifact's `node_did` may be compared with the externally anchored DID, +but it must never supply that anchor. The signed repo must equal the canonical +slug of the repository being cloned. Wrong signer, wrong repository, unsigned +v1 data, malformed identity or timestamp fields, malformed object ids or CIDs, +repeated object ids, and schema drift are all rejected before merge. Clone +passes the effective node to git subprocesses as both `TWIGPINE_NODE` and +`GITLAWB_NODE`, so the git transport and recovery API use the same node. + +### Merge and recovery rules + +Authentication happens before merge. Entries naming object ids absent from the +cloned tree are discarded before merge retention, local object checks, or +gateway fetches. Surviving entries for the same object rank by: + +1. block-height rank: a pending anchor is newest, otherwise larger height wins; +2. the signed timestamp compared as an RFC 3339 instant; +3. the lexicographically larger CID as the final deterministic tie-break. + +Height is gateway-reported availability metadata only. It is never evidence of +authenticity. + +Public-gateway envelope bodies are capped at 32 MiB of object bytes plus 64 +KiB of envelope allowance. A body exactly at the cap is valid; a larger body, +a mid-body read failure, or a cross-origin redirect cannot become recovery +input. Redirects are followed only within the same origin, only when path and +query are unchanged, never on a downgrade from https, and only within the +shared ten-hop bound. The default IPFS gateway is path-style `https://ipfs.io`. +Subdomain-only gateways such as `dweb.link` redirect path requests to another +origin and are incompatible with that policy. + +Gateway-controlled terminal output is sanitized. At most 20 detailed B3 warning +lines are emitted, followed by one aggregate suppression count. diff --git a/README.md b/README.md index 3b71f5df4..646e5908e 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,33 @@ a cleartext hop to a remote node exposes the pack contents and the `Signature` header. A remote `http://` node is refused, and `TWIGPINE_ALLOW_INSECURE_HTTP=1` overrides that for a trusted private network. +### Encrypted-blob recovery trust pins + +`twigpine clone` can recover authorized withheld blobs from signed Arweave +manifests when the node cannot supply their encrypted envelopes. The manifest +signer is pinned as a node DID. By default the clone uses the DID reported by +the node selected with `--node` or `TWIGPINE_NODE`, and passes that same node +to the git transport as both `TWIGPINE_NODE` and `GITLAWB_NODE`. This implicit +anchor is part of the clone trust boundary, not independent proof against a +malicious selected node. + +Use `--expect-node ` when the signer must be pinned explicitly, especially +when cloning through a replica while recovering manifests signed by the origin +node: + +```bash +twigpine clone gitlawb:///my-repo \ + --node https://replica.example \ + --expect-node did:key:z6Mk... +``` + +The value must be the origin node's canonical Ed25519 `did:key`. One way to +read it is the `did` field of that node's root metadata. A pin mismatch does +not fall back to artifact-supplied identity. Unsigned legacy manifests are +ignored as unauthenticated. Public-gateway fallback uses path-style IPFS +gateway URLs; the default is `https://ipfs.io`, and subdomain-only gateways +such as `dweb.link` are incompatible with the same-origin redirect policy. + ### Full lifecycle against an iCaptcha-enforcing node Public nodes (e.g. `node.twigpine.com`) require two things on writes: diff --git a/docs/LEGACY-NAMES.md b/docs/LEGACY-NAMES.md index c43d35f47..5222ea1da 100644 --- a/docs/LEGACY-NAMES.md +++ b/docs/LEGACY-NAMES.md @@ -17,7 +17,8 @@ or would invalidate data already stored, and would buy nothing a user can see. |---|---|---| | `refs/gitlawb/*` | `twigpine-node`: the internal-ref gate in `api/repos.rs`, `hideRefs` in `git/store.rs`, the mirror prune in `sync.rs`, issues in `git/issues.rs` | The namespace holds node-managed data (issues, request markers) in every repository, and nodes copy it from each other with `+refs/*:refs/*`. Renaming it means migrating that data on every node; during the change an older node would treat the new namespace as ordinary user refs. | | `gitlawb/ref-update/v1` | `CERT_TYPE` in `twigpine-core/src/cert.rs` and `twigpine-attest/src/cert.rs`; the Arweave `Schema` tag written in `twigpine-node/src/arweave.rs` | Signed into every ref-update certificate. Peers refuse a type they do not know, and certificates already signed and anchored carry this one forever. | -| `gitlawb/encrypted-manifest/v1` | `twigpine-node/src/arweave.rs`; CLI Arweave discovery in `clone.rs` | Schema of anchored manifests, stored permanently. | +| `gitlawb/encrypted-manifest/v1` | Permanently stored Arweave artifacts; the CLI legacy-presence probe in `clone.rs` | Unsigned legacy schema of anchored manifests. Existing artifacts remain permanently stored, but current clients never trust them as recovery authority. | +| `gitlawb/encrypted-manifest/v2` | `twigpine-core/src/encrypted_manifest.rs`; the Arweave `Schema` tag written in `twigpine-node/src/arweave.rs`; CLI Arweave discovery in `clone.rs` | Current signed schema of encrypted-blob recovery manifests, stored permanently and signed into every artifact. | | `gitlawb/ref-updates/v1` | `REF_UPDATES_TOPIC` in `twigpine-node/src/p2p/mod.rs` | The gossip topic. A node on another topic hears nothing. | | `/gitlawb/did/` | DHT record key in `twigpine-node/src/p2p/mod.rs` | Key prefix of DHT records other nodes look up. | | `gitlawb/hkdf-salt/webhook-secret`, `gitlawb/webhook-secret/v1` | `twigpine-node/src/state.rs` | Salt and label of the key that seals webhook secrets at rest. Changing either means re-sealing every stored secret. | From a4fa801e32babf68a29059076f164279dc15ab53 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:56:21 -0600 Subject: [PATCH 06/18] fix(node): anchor manifests under canonical repository identity Share the signed-manifest canonical owner and tag rules across the core wire primitive, writers, and legacy discovery. Pin writer integration coverage so post-push and reconciliation uploads verify against the node key and index the resealed blob. --- .../twigpine-core/src/encrypted_manifest.rs | 30 ++++++------- crates/twigpine-node/src/api/repos.rs | 6 ++- crates/twigpine-node/src/arweave.rs | 24 +++++----- crates/twigpine-node/src/db/mod.rs | 5 +-- crates/twigpine-node/src/reconciliation.rs | 44 +++++++++++++++++-- crates/twigpine-node/src/test_support.rs | 31 ++++++++++++- 6 files changed, 101 insertions(+), 39 deletions(-) diff --git a/crates/twigpine-core/src/encrypted_manifest.rs b/crates/twigpine-core/src/encrypted_manifest.rs index 19cd70bdf..0e387e03f 100644 --- a/crates/twigpine-core/src/encrypted_manifest.rs +++ b/crates/twigpine-core/src/encrypted_manifest.rs @@ -92,9 +92,18 @@ pub fn repo_digest(canonical_repo: &str) -> String { URL_SAFE_NO_PAD.encode(Sha256::digest(canonical_repo.as_bytes())) } +/// Irys/Arweave tag-value sanitation used by writers and by legacy discovery +/// probes that must reproduce the writer's exact tag spelling. +pub fn sanitize_tag_value(s: &str) -> String { + s.chars() + .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '/' | ':')) + .take(128) + .collect() +} + /// Validate a did:key trust anchor strictly enough for signature verification: /// it must resolve to a non-weak Ed25519 key and spell canonically. -pub fn validate_did_key_anchor(did: &str) -> Result { +pub fn validate_did_key_anchor(did: &str) -> Result { let parsed = Did::from_str(did)?; let key = parsed.to_verifying_key()?; let canonical = Did::from_verifying_key(&key); @@ -103,7 +112,7 @@ pub fn validate_did_key_anchor(did: &str) -> Result { "non-canonical did:key spelling".to_string(), )); } - Ok(parsed) + Ok(key) } fn validate_common( @@ -166,7 +175,7 @@ fn validate_and_encode_envelope(payload: ManifestPayload, keypair: &Keypair) -> )?; let payload_bytes = serialize_payload(&payload)?; let input = signing_input(payload_bytes.as_bytes()); - let signature = URL_SAFE_NO_PAD.encode(keypair.sign(&input).to_bytes()); + let signature = keypair.sign_b64(&input); let envelope = ManifestEnvelope { schema: SCHEMA_V2.to_string(), payload: payload_bytes, @@ -274,20 +283,9 @@ pub fn verify_signed_manifest( if bytes.len() > VERIFIER_MANIFEST_CAP_BYTES { return Err(invalid("outer body exceeds verifier cap")); } - validate_did_key_anchor(expected_node_did).map_err(|e| invalid(e.to_string()))?; - let expected_key = Did::from_str(expected_node_did) - .and_then(|d| d.to_verifying_key()) - .map_err(|e| invalid(e.to_string()))?; + let expected_key = + validate_did_key_anchor(expected_node_did).map_err(|e| invalid(e.to_string()))?; - #[derive(Deserialize)] - struct SchemaProbe { - schema: String, - } - if let Ok(probe) = serde_json::from_slice::(bytes) { - if probe.schema != SCHEMA_V2 { - return Err(invalid("unsupported outer schema")); - } - } let envelope: ManifestEnvelope = serde_json::from_slice(bytes).map_err(|_| invalid("outer JSON shape"))?; if envelope.schema != SCHEMA_V2 { diff --git a/crates/twigpine-node/src/api/repos.rs b/crates/twigpine-node/src/api/repos.rs index 691b2871c..52657caf1 100644 --- a/crates/twigpine-node/src/api/repos.rs +++ b/crates/twigpine-node/src/api/repos.rs @@ -2188,8 +2188,10 @@ async fn pin_and_encrypt_objects( // push to Arweave, so the oid->cid index survives total node loss. // Best-effort; never fails the push. if !delta.is_empty() && !ctx.irys_url.is_empty() { - let owner_short = crate::db::normalize_owner_key(&ctx.owner_did); - let repo_slug = format!("{owner_short}/{}", ctx.repo_name); + let repo_slug = twigpine_core::encrypted_manifest::canonical_repo_slug( + &ctx.owner_did, + &ctx.repo_name, + ); let ts = chrono::Utc::now().to_rfc3339(); let manifest = crate::arweave::EncryptedManifest { repo: &repo_slug, diff --git a/crates/twigpine-node/src/arweave.rs b/crates/twigpine-node/src/arweave.rs index b065f7b3e..20cc5afa6 100644 --- a/crates/twigpine-node/src/arweave.rs +++ b/crates/twigpine-node/src/arweave.rs @@ -381,10 +381,7 @@ fn build_tags_header(anchor: &RefAnchor) -> String { /// Strip characters that are invalid in Irys/Arweave tag values. fn sanitize_tag(s: &str) -> String { - s.chars() - .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '/' | ':')) - .take(128) - .collect() + twigpine_core::encrypted_manifest::sanitize_tag_value(s) } #[cfg(test)] @@ -497,7 +494,9 @@ mod tests { Vec<(String, String)>, ) { let kp = twigpine_core::identity::Keypair::generate(); - let owner = kp.did().to_string(); + let owner = twigpine_core::identity::Keypair::generate() + .did() + .to_string(); let repo = twigpine_core::encrypted_manifest::canonical_repo_slug(&owner, "r"); let blobs = (0..count) .map(|i| { @@ -552,16 +551,17 @@ mod tests { let expected_repo = repo.clone(); let expected_oid = blobs[0].0.clone(); let expected_cid = blobs[0].1.clone(); + let expected_tags = format!( + "App-Name:gitlawb,Schema:gitlawb/encrypted-manifest/v2,Repo-Digest:{},Repo:{},Owner-DID:{},Node-DID:{}", + twigpine_core::encrypted_manifest::repo_digest(&repo), + repo, + owner, + kp.did() + ); let mut server = mockito::Server::new_async().await; let _mock = server .mock("POST", "/upload") - .match_header( - "x-irys-tags", - mockito::Matcher::Regex( - "App-Name:gitlawb,Schema:gitlawb/encrypted-manifest/v2,Repo-Digest:" - .to_string(), - ), - ) + .match_header("x-irys-tags", expected_tags.as_str()) .with_status(200) .with_header("content-type", "application/json") .with_body_from_request(move |req| { diff --git a/crates/twigpine-node/src/db/mod.rs b/crates/twigpine-node/src/db/mod.rs index e458c6b4a..5453e18a1 100644 --- a/crates/twigpine-node/src/db/mod.rs +++ b/crates/twigpine-node/src/db/mod.rs @@ -3322,10 +3322,7 @@ pub const MAX_PIN_SOURCES: i64 = 16; // ── Repos ───────────────────────────────────────────────────────────────────── pub(crate) fn normalize_owner_key(did: &str) -> &str { - match did.strip_prefix("did:key:") { - Some(rest) if !rest.contains(':') => rest, - _ => did, - } + twigpine_core::encrypted_manifest::canonical_owner_key(did) } /// The canonical spelling of an identity for a column that stores one identity diff --git a/crates/twigpine-node/src/reconciliation.rs b/crates/twigpine-node/src/reconciliation.rs index 8f5ca2000..67284301e 100644 --- a/crates/twigpine-node/src/reconciliation.rs +++ b/crates/twigpine-node/src/reconciliation.rs @@ -1859,8 +1859,10 @@ async fn run_pass( // the pin boundary (`fresh_repo2`), not the batch snapshot: // a renamed/ownership-changed repo must not anchor encrypted // recovery copies under a stale owner (R1-P2). - let owner_short = crate::db::normalize_owner_key(&fresh_repo2.owner_did); - let slug = format!("{}/{}", owner_short, fresh_repo2.name); + let slug = twigpine_core::encrypted_manifest::canonical_repo_slug( + &fresh_repo2.owner_did, + &fresh_repo2.name, + ); let ts = chrono::Utc::now().to_rfc3339(); let manifest = crate::arweave::EncryptedManifest { repo: &slug, @@ -2795,7 +2797,7 @@ mod tests { .await .unwrap(); - // Exactly one POST may land: the encrypted seal envelope. Any + // Exactly one IPFS POST may land: the encrypted seal envelope. Any // cleartext public upload would be a second hit and fail the mock. let mut server = mockito::Server::new_async().await; let m = server @@ -2806,12 +2808,45 @@ mod tests { .create_async() .await; + let kp = twigpine_core::identity::Keypair::generate(); + let expected_node_did = kp.did().to_string(); + let expected_repo = format!( + "{}/{}", + crate::db::normalize_owner_key(&owner_did), + rec.name + ); + let expected_oid = blob.clone(); + let mut irys_server = mockito::Server::new_async().await; + let irys_mock = irys_server + .mock("POST", "/upload") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body_from_request(move |req| { + let body: &[u8] = req.body().map(|b| b.as_slice()).unwrap_or(&[]); + let verified = twigpine_core::encrypted_manifest::verify_signed_manifest( + body, + &expected_node_did, + &expected_repo, + ) + .expect("reconciliation manifest must verify against the node key"); + assert!( + verified.blobs.iter().any(|b| b.oid == expected_oid), + "manifest must index the resealed blob" + ); + br#"{"id":"RECONCILEMANIFESTTX","timestamp":1710000000000,"version":"1.0.0"}"# + .to_vec() + }) + .create_async() + .await; + let config = ::parse_from([ "twigpine-node-test", "--ipfs-api", &server.url(), + "--irys-url", + &irys_server.url(), ]); - let kp = twigpine_core::identity::Keypair::generate(); let node_did = kp.did(); let node_seed = *kp.to_seed(); let http = reqwest::Client::new(); @@ -2852,6 +2887,7 @@ mod tests { "encrypted recovery must run despite the empty public list" ); m.assert_async().await; + irys_mock.assert_async().await; } /// #218 review (empty-path recovery without path rules): a blob, tree, or diff --git a/crates/twigpine-node/src/test_support.rs b/crates/twigpine-node/src/test_support.rs index 6e476036d..44e99a49b 100644 --- a/crates/twigpine-node/src/test_support.rs +++ b/crates/twigpine-node/src/test_support.rs @@ -24354,11 +24354,38 @@ mod tests { .create_async() .await; + let expected_node_did = state.node_keypair.did().to_string(); + let expected_repo = format!("{}/{}", crate::db::normalize_owner_key(&owner), repo.name); + let expected_oid = secret_oid.clone(); + let mut irys_server = mockito::Server::new_async().await; + let irys_mock = irys_server + .mock("POST", "/upload") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body_from_request(move |req| { + let body: &[u8] = req.body().map(|b| b.as_slice()).unwrap_or(&[]); + let verified = twigpine_core::encrypted_manifest::verify_signed_manifest( + body, + &expected_node_did, + &expected_repo, + ) + .expect("post-push manifest must verify against the node key"); + assert!( + verified.blobs.iter().any(|b| b.oid == expected_oid), + "manifest must index the newly withheld blob" + ); + br#"{"id":"POSTPUSHMANIFESTTX","timestamp":1710000000000,"version":"1.0.0"}"# + .to_vec() + }) + .create_async() + .await; + let guard = admit(&state, &key); coalesce(&state, &key, vec![(tip_a, tip_b)]); // Push A captures are STALE: no rule, public repo. - crate::api::repos::run_encrypt_pin_task_for_test( + crate::api::repos::run_encrypt_pin_task_for_test_with_irys( &state, guard, git_repo.path.clone(), @@ -24369,8 +24396,10 @@ mod tests { vec![], Some(vec![]), true, + irys_server.url(), ) .await; + irys_mock.assert_async().await; assert!( state From 7a1a6817ca899f198585906c6f483f56f5052057 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:56:21 -0600 Subject: [PATCH 07/18] refactor(cli): simplify authenticated manifest recovery Remove duplicate GraphQL handling and redundant merge state while pinning the exact v2 discovery digest, legacy no-fetch behavior, partial-discovery warning, and merge ordering cases that could otherwise pass for the wrong reason. --- crates/twigpine-cli/src/clone.rs | 196 ++++++++++++++++--------------- 1 file changed, 100 insertions(+), 96 deletions(-) diff --git a/crates/twigpine-cli/src/clone.rs b/crates/twigpine-cli/src/clone.rs index f4dc96901..c8c5954ee 100644 --- a/crates/twigpine-cli/src/clone.rs +++ b/crates/twigpine-cli/src/clone.rs @@ -9,6 +9,7 @@ use anyhow::{bail, Context, Result}; use clap::Args; use serde::Deserialize; +use std::collections::HashSet; use std::path::Path; use std::process::Command; @@ -594,6 +595,31 @@ async fn read_protocol_body(resp: reqwest::Response, cap: usize) -> Result Option { + let resp = client + .post(url) + .timeout(timeout) + .json(body) + .send() + .await + .ok()?; + if !resp.status().is_success() { + return None; + } + let bytes = read_protocol_body(resp, GRAPHQL_PAGE_CAP_BYTES) + .await + .ok()?; + serde_json::from_slice(&bytes).ok() +} + /// Arweave transaction ids are exactly 43 base64url characters. Anything else /// is gateway spam and must never reach a request URL (KTD4). fn is_valid_txid(id: &str) -> bool { @@ -687,10 +713,7 @@ const ARWEAVE_LEGACY_PROBE_QUERY: &str = r#"query($repo:String!){transactions(ta /// The legacy v1 writer's tag rule, reproduced for the presence probe only: /// strip characters outside the Irys tag charset and truncate to 128. fn legacy_repo_tag(slug: &str) -> String { - slug.chars() - .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '/' | ':')) - .take(128) - .collect() + twigpine_core::encrypted_manifest::sanitize_tag_value(slug) } /// A parsed page of an Arweave GraphQL `transactions` response: the edge refs @@ -797,7 +820,7 @@ pub(crate) fn height_rank(h: Option) -> (u8, u64) { /// enter merge retention, trigger a `git cat-file`, or trigger an IPFS fetch. fn merge_authenticated( manifests: Vec<(VerifiedManifest, Option)>, - tree_oids: &std::collections::HashSet, + tree_oids: &std::collections::HashMap, ) -> std::collections::HashMap { // oid -> (cid, height_rank, timestamp instant) let mut best: std::collections::HashMap< @@ -810,7 +833,7 @@ fn merge_authenticated( chrono::DateTime::parse_from_rfc3339("1970-01-01T00:00:00Z").unwrap() }); for b in m.blobs { - if !tree_oids.contains(&b.oid) { + if !tree_oids.contains_key(&b.oid) { continue; } let keep_incumbent = match best.get(&b.oid) { @@ -860,8 +883,7 @@ async fn recover_from_arweave( recover_from_arweave_inner( arweave_gateway, ipfs_gateway, - owner, - name, + &canonical_repo_slug(owner, name), dest, keypair, expected_node_did, @@ -890,24 +912,21 @@ impl DiscoveryLimits { } } -#[allow(clippy::too_many_arguments)] async fn recover_from_arweave_inner( arweave_gateway: &str, ipfs_gateway: &str, - owner: &str, - name: &str, + slug: &str, dest: &Path, keypair: &twigpine_core::identity::Keypair, expected_node_did: &str, limits: &DiscoveryLimits, ) -> Result> { - use std::collections::{HashMap, HashSet}; + use std::collections::HashMap; use std::io::Write; use twigpine_core::encrypt::{open_blob, MAX_ENCRYPTED_ENVELOPE_BYTES}; let dest_str = dest.to_str().context("dest path not utf-8")?; - let slug = canonical_repo_slug(owner, name); - let digest = repo_digest(&slug); + let digest = repo_digest(slug); let ag = arweave_gateway.trim_end_matches('/'); let ig = ipfs_gateway.trim_end_matches('/'); // Bound every gateway request: this runs on every clone, so a slow or hung @@ -940,7 +959,6 @@ async fn recover_from_arweave_inner( let mut after: Option = None; let mut seen: HashSet = HashSet::new(); let mut refs: Vec = Vec::new(); - let mut prev_cursor: Option = None; let mut page_num = 0usize; loop { if started.elapsed() >= limits.metadata_budget { @@ -962,21 +980,8 @@ async fn recover_from_arweave_inner( // Any gateway failure (non-2xx, send error, oversized or unparseable // body) ends the loop. let remaining = limits.metadata_budget.saturating_sub(started.elapsed()); - let response = match client - .post(format!("{ag}/graphql")) - .timeout(remaining) - .json(&gql_body) - .send() - .await - { - Ok(r) if r.status().is_success() => { - match read_protocol_body(r, GRAPHQL_PAGE_CAP_BYTES).await { - Ok(bytes) => serde_json::from_slice::(&bytes).ok(), - Err(_) => None, - } - } - _ => None, - }; + let response = + post_graphql_json(&client, format!("{ag}/graphql"), &gql_body, remaining).await; let value = match response { Some(v) => v, None => { @@ -1014,8 +1019,7 @@ async fn recover_from_arweave_inner( Some(true) => match page.end_cursor { // Advance only on a fresh cursor; a missing or repeating cursor is // a degenerate gateway response and must not loop forever. - Some(c) if Some(&c) != prev_cursor.as_ref() => { - prev_cursor = Some(c.clone()); + Some(c) if Some(&c) != after.as_ref() => { after = Some(c); } _ => break, @@ -1072,7 +1076,7 @@ async fn recover_from_arweave_inner( continue; } }; - match verify_signed_manifest(&bytes, expected_node_did, &slug) { + match verify_signed_manifest(&bytes, expected_node_did, slug) { Ok(verified) => manifests.push((verified, r.height)), Err(e) => { warnings.warn_skip_manifest(&r.id, &format!("not a trusted signed manifest: {e}")); @@ -1088,33 +1092,20 @@ async fn recover_from_arweave_inner( if manifests.is_empty() && started.elapsed() < limits.metadata_budget { let probe_body = serde_json::json!({ "query": ARWEAVE_LEGACY_PROBE_QUERY, - "variables": { "repo": legacy_repo_tag(&slug) }, + "variables": { "repo": legacy_repo_tag(slug) }, }); let remaining = limits.metadata_budget.saturating_sub(started.elapsed()); - let legacy_found = match client - .post(format!("{ag}/graphql")) - .timeout(remaining) - .json(&probe_body) - .send() - .await - { - Ok(r) if r.status().is_success() => { - match read_protocol_body(r, GRAPHQL_PAGE_CAP_BYTES).await { - Ok(bytes) => serde_json::from_slice::(&bytes) - .ok() - .and_then(|v| { - v.get("data")? - .get("transactions")? - .get("edges")? - .as_array() - .map(|edges| !edges.is_empty()) - }) - .unwrap_or(false), - Err(_) => false, - } - } - _ => false, - }; + let legacy_found = + post_graphql_json(&client, format!("{ag}/graphql"), &probe_body, remaining) + .await + .and_then(|v| { + v.get("data")? + .get("transactions")? + .get("edges")? + .as_array() + .map(|edges| !edges.is_empty()) + }) + .unwrap_or(false); if legacy_found { emit_warning( "warning: unsigned legacy encrypted-blob manifests exist for this repo but are ignored as unauthenticated; some authorized files may not be recovered", @@ -1136,11 +1127,9 @@ async fn recover_from_arweave_inner( } } } - let tree_oids: HashSet = oid_to_path.keys().cloned().collect(); - // 5. Merge authenticated entries only: height rank first (pending newest), // then the signed timestamp instant, then the larger cid. - let oid_cid = merge_authenticated(manifests, &tree_oids); + let oid_cid = merge_authenticated(manifests, &oid_to_path); // 6. Recover each missing blob the caller can decrypt. let mut recovered = Vec::new(); @@ -1893,12 +1882,12 @@ mod tests { } fn b3_actors() -> B3Actors { - let signer = twigpine_core::identity::Keypair::generate(); - let owner_kp = twigpine_core::identity::Keypair::generate(); + let signer = twigpine_core::identity::Keypair::from_seed(&[11; 32]).unwrap(); + let owner_kp = twigpine_core::identity::Keypair::from_seed(&[12; 32]).unwrap(); B3Actors { owner: owner_kp.did().to_string(), signer, - reader: twigpine_core::identity::Keypair::generate(), + reader: twigpine_core::identity::Keypair::from_seed(&[13; 32]).unwrap(), } } @@ -1937,27 +1926,10 @@ mod tests { } } - fn tree(oids: &[&str]) -> std::collections::HashSet { - oids.iter().map(|s| s.to_string()).collect() - } - - #[test] - fn merge_latest_height_wins_per_oid() { - let lo = vmanifest("2026-06-10T00:00:00Z", "o1", "cidLO"); - let mut two = vmanifest("2026-06-11T00:00:00Z", "o1", "cidHI"); - two.blobs - .push(twigpine_core::encrypted_manifest::EncryptedBlobRef { - oid: "o2".to_string(), - cid: "cid2".to_string(), - }); - let merged = merge_authenticated(vec![(lo, Some(1)), (two, Some(2))], &tree(&["o1", "o2"])); - assert_eq!(merged.get("o1").map(String::as_str), Some("cidHI")); - assert_eq!(merged.get("o2").map(String::as_str), Some("cid2")); - // Order-independence. - let lo2 = vmanifest("2026-06-10T00:00:00Z", "o1", "cidLO"); - let hi2 = vmanifest("2026-06-11T00:00:00Z", "o1", "cidHI"); - let rev = merge_authenticated(vec![(hi2, Some(2)), (lo2, Some(1))], &tree(&["o1"])); - assert_eq!(rev.get("o1").map(String::as_str), Some("cidHI")); + fn tree(oids: &[&str]) -> std::collections::HashMap { + oids.iter() + .map(|s| (s.to_string(), s.to_string())) + .collect() } #[test] @@ -1967,15 +1939,30 @@ mod tests { // is monotonic chain-inclusion metadata, so a correct-but-misconfigured // node clock moving backwards cannot permanently regress recovery. let newer_ts_lo_block = vmanifest("2026-06-11T00:00:00Z", "o1", "cidNEWERTS"); - let older_ts_hi_block = vmanifest("2026-06-10T00:00:00Z", "o1", "cidHIBLOCK"); + let mut older_ts_hi_block = vmanifest("2026-06-10T00:00:00Z", "o1", "cidHIBLOCK"); + older_ts_hi_block + .blobs + .push(twigpine_core::encrypted_manifest::EncryptedBlobRef { + oid: "o2".to_string(), + cid: "cid2".to_string(), + }); let merged = merge_authenticated( vec![ - (newer_ts_lo_block, Some(1)), - (older_ts_hi_block, Some(9999)), + (newer_ts_lo_block.clone(), Some(1)), + (older_ts_hi_block.clone(), Some(9999)), ], - &tree(&["o1"]), + &tree(&["o1", "o2"]), ); assert_eq!(merged.get("o1").map(String::as_str), Some("cidHIBLOCK")); + assert_eq!(merged.get("o2").map(String::as_str), Some("cid2")); + let reverse = merge_authenticated( + vec![ + (older_ts_hi_block.clone(), Some(9999)), + (newer_ts_lo_block.clone(), Some(1)), + ], + &tree(&["o1", "o2"]), + ); + assert_eq!(reverse.get("o1").map(String::as_str), Some("cidHIBLOCK")); } #[test] @@ -1994,10 +1981,10 @@ mod tests { #[test] fn merge_equal_height_breaks_by_timestamp_instant() { - let earlier = vmanifest("2026-06-10T00:00:00Z", "o1", "cidEARLY"); - let later = vmanifest("2026-06-11T00:00:00Z", "o1", "cidLATE"); + let earlier = vmanifest("2026-06-10T00:00:00Z", "o1", "cidZZZ"); + let later = vmanifest("2026-06-11T00:00:00Z", "o1", "cidAAA"); let a = merge_authenticated(vec![(earlier, Some(5)), (later, Some(5))], &tree(&["o1"])); - assert_eq!(a.get("o1").map(String::as_str), Some("cidLATE")); + assert_eq!(a.get("o1").map(String::as_str), Some("cidAAA")); } #[test] @@ -2200,8 +2187,12 @@ mod tests { let txid = valid_txid("txinstall"); let mut server = mockito::Server::new_async().await; + let digest = repo_digest(&canonical_repo_slug(&actors.owner, "myrepo")); let _gql = server .mock("POST", "/graphql") + .match_body(mockito::Matcher::PartialJsonString(format!( + r#"{{"variables":{{"digest":"{digest}"}}}}"# + ))) .with_status(200) .with_header("content-type", "application/json") .with_body(gql_page(&[(txid.as_str(), None)])) @@ -2443,6 +2434,10 @@ mod tests { let reader = Keypair::generate(); let slug = canonical_repo_slug(&actors.owner, "myrepo"); let legacy_tag = legacy_repo_tag(&slug); + assert_eq!( + legacy_tag, + "z6MkfDSNRs2i9S6LZ5vd4RbpZ6754H7R3btDqRTeHhamqvuJ/myrepo" + ); let mut server = mockito::Server::new_async().await; // v2 discovery (carries the digest variable): no candidates. @@ -2468,6 +2463,11 @@ mod tests { .expect(1) .create_async() .await; + let no_raw_fetch = server + .mock("GET", mockito::Matcher::Regex(r"^/raw/.*".into())) + .expect(0) + .create_async() + .await; let paths = recover_from_arweave( &server.url(), @@ -2482,6 +2482,7 @@ mod tests { .unwrap(); assert!(paths.is_empty()); probe.assert_async().await; + no_raw_fetch.assert_async().await; assert!( warnings().contains("unsigned legacy"), "the legacy-presence warning must fire, got: {:?}", @@ -2714,6 +2715,11 @@ mod tests { vec!["secret/b.txt".to_string()], "page-1 blob must still be recovered when page 2 fails" ); + assert!( + warnings().contains("interrupted"), + "mid-pagination failure must surface as partial discovery, got: {:?}", + warnings() + ); } /// A gateway that reports `hasNextPage=true` but never advances the cursor @@ -3135,8 +3141,7 @@ mod tests { let paths = recover_from_arweave_inner( &server.url(), &server.url(), - &actors.owner, - "myrepo", + &canonical_repo_slug(&actors.owner, "myrepo"), &dest, &reader, &actors.signer.did().to_string(), @@ -3189,8 +3194,7 @@ mod tests { let paths = recover_from_arweave_inner( &server.url(), &server.url(), - &actors.owner, - "myrepo", + &canonical_repo_slug(&actors.owner, "myrepo"), &dest, &reader, &actors.signer.did().to_string(), From 5f63c0c6010249295ad1b67531b01bcf362b0c5b Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:04:06 -0600 Subject: [PATCH 08/18] style(cli): satisfy workspace lint gates --- crates/twigpine-cli/src/clone.rs | 8 +++----- crates/twigpine-core/src/encrypted_manifest.rs | 2 +- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/crates/twigpine-cli/src/clone.rs b/crates/twigpine-cli/src/clone.rs index c8c5954ee..6ddccfb30 100644 --- a/crates/twigpine-cli/src/clone.rs +++ b/crates/twigpine-cli/src/clone.rs @@ -823,10 +823,8 @@ fn merge_authenticated( tree_oids: &std::collections::HashMap, ) -> std::collections::HashMap { // oid -> (cid, height_rank, timestamp instant) - let mut best: std::collections::HashMap< - String, - (String, (u8, u64), chrono::DateTime), - > = std::collections::HashMap::new(); + type BestEntry = (String, (u8, u64), chrono::DateTime); + let mut best: std::collections::HashMap = std::collections::HashMap::new(); for (m, height) in manifests { let cand_rank = height_rank(height); let cand_ts = chrono::DateTime::parse_from_rfc3339(&m.timestamp).unwrap_or_else(|_| { @@ -2317,7 +2315,7 @@ mod tests { let bogus_fetch = server .mock("GET", format!("/ipfs/{bogus_cid}").as_str()) .with_status(200) - .with_body(b"bogus".to_vec()) + .with_body(b"bogus") .expect(0) .create_async() .await; diff --git a/crates/twigpine-core/src/encrypted_manifest.rs b/crates/twigpine-core/src/encrypted_manifest.rs index 0e387e03f..2c441152e 100644 --- a/crates/twigpine-core/src/encrypted_manifest.rs +++ b/crates/twigpine-core/src/encrypted_manifest.rs @@ -453,7 +453,7 @@ mod tests { fn owner_must_canonicalize_to_repo_owner() { let kp = keypair(); let owner = kp.did().to_string(); - let wrong_repo = format!("someone-else/repo"); + let wrong_repo = "someone-else/repo".to_string(); assert!(build_signed_manifest( &wrong_repo, &owner, From 0fbc3c7c68043fa87588b2002724f6809fc4b61d Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:11:52 -0600 Subject: [PATCH 09/18] fix(cli): prevent manifest replay and use live pagination Arweave exposes pagination cursors on edges, not PageInfo.endCursor. Recovery now uses the live schema, and signed timestamps outrank replayable inclusion height so copied stale manifests cannot displace newer recovery payloads. The protocol documents the remaining permissionless-tag censorship limit. --- PROTOCOL.md | 17 ++- crates/twigpine-cli/src/clone.rs | 200 +++++++++++++++++++++++-------- 2 files changed, 164 insertions(+), 53 deletions(-) diff --git a/PROTOCOL.md b/PROTOCOL.md index 4ddcf157c..e512a4cbe 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -216,12 +216,21 @@ Authentication happens before merge. Entries naming object ids absent from the cloned tree are discarded before merge retention, local object checks, or gateway fetches. Surviving entries for the same object rank by: -1. block-height rank: a pending anchor is newest, otherwise larger height wins; -2. the signed timestamp compared as an RFC 3339 instant; +1. the signed timestamp compared as an RFC 3339 instant; +2. block-height rank as the equal-timestamp tie-break: a pending anchor is + newest, otherwise larger height wins; 3. the lexicographically larger CID as the final deterministic tie-break. -Height is gateway-reported availability metadata only. It is never evidence of -authenticity. +The signed timestamp must outrank inclusion height because anyone can republish +exact old public manifest bytes into a new transaction. Height is gateway- +reported availability metadata only. It is never evidence of authenticity. + +Discovery tags remain permissionless hints. A publisher can spam matching tag +queries and crowd honest transactions out of the fixed page, transaction, or +time budgets. The caps bound that abuse and require an incomplete-recovery +warning; they do not prove discovery completeness. Closing that censorship hole +requires owner-bound upload ownership or another issuer-bound discovery +mechanism. Public-gateway envelope bodies are capped at 32 MiB of object bytes plus 64 KiB of envelope allowance. A body exactly at the cap is valid; a larger body, diff --git a/crates/twigpine-cli/src/clone.rs b/crates/twigpine-cli/src/clone.rs index 6ddccfb30..2a77e6f4a 100644 --- a/crates/twigpine-cli/src/clone.rs +++ b/crates/twigpine-cli/src/clone.rs @@ -702,7 +702,7 @@ pub(crate) const ARWEAVE_PAGE_SIZE: usize = 100; /// and `block{height}` for the recency ordering. Tags are discovery hints only; /// the signed payload is the authority. The human-readable `Repo` tag is /// diagnostic and is never a v2 discovery key. -const ARWEAVE_DISCOVERY_QUERY: &str = r#"query($digest:String!,$cursor:String){transactions(tags:[{name:"App-Name",values:["twigpine","gitlawb"]},{name:"Schema",values:["gitlawb/encrypted-manifest/v2"]},{name:"Repo-Digest",values:[$digest]}],sort:HEIGHT_DESC,first:100,after:$cursor){pageInfo{hasNextPage endCursor}edges{cursor node{id block{height}}}}}"#; +const ARWEAVE_DISCOVERY_QUERY: &str = r#"query($digest:String!,$cursor:String){transactions(tags:[{name:"App-Name",values:["twigpine","gitlawb"]},{name:"Schema",values:["gitlawb/encrypted-manifest/v2"]},{name:"Repo-Digest",values:[$digest]}],sort:HEIGHT_DESC,first:100,after:$cursor){pageInfo{hasNextPage}edges{cursor node{id block{height}}}}}"#; /// One-page legacy probe: unsigned v1 manifests used the old truncated `Repo` /// tag rule because v1 writers had no digest. This query exists only to tell @@ -772,14 +772,21 @@ pub(crate) fn parse_tx_page(v: &serde_json::Value) -> TxPage { .collect() }) .unwrap_or_default(); + let end_cursor = txns + .and_then(|t| t.get("edges")) + .and_then(|e| e.as_array()) + .and_then(|edges| { + edges + .iter() + .take(ARWEAVE_PAGE_SIZE) + .filter_map(|edge| edge.get("cursor").and_then(|c| c.as_str())) + .last() + .map(String::from) + }); let page_info = txns.and_then(|t| t.get("pageInfo")); let has_next = page_info .and_then(|p| p.get("hasNextPage")) .and_then(|h| h.as_bool()); - let end_cursor = page_info - .and_then(|p| p.get("endCursor")) - .and_then(|c| c.as_str()) - .map(String::from); TxPage { refs, has_next, @@ -797,23 +804,13 @@ pub(crate) fn height_rank(h: Option) -> (u8, u64) { } /// Merge verified per-push manifests into a single `oid -> cid` map, ranked by -/// the composite key `(block height rank, timestamp instant, cid)`: -/// - Arweave block height rank is primary: chain-inclusion metadata is -/// monotonic, so a correct-but-misconfigured node clock moving backwards -/// cannot permanently regress recovery, and a pending (not yet mined) -/// anchor counts as newest. Height is gateway-reported availability -/// metadata; it never enters the authenticity decision, which already -/// happened in `verify_signed_manifest` before anything reached this merge. -/// A hostile gateway can reorder what it shows, but it can already censor -/// newer anchors, so this grants it no new authority; -/// - the signed manifest timestamp breaks equal-height ties, compared as -/// parsed RFC3339 instants rather than strings (offsets and fractional -/// seconds order wrongly as text). Verification already rejected malformed -/// timestamps, so a parse failure here is impossible but ranks lowest -/// rather than panicking; -/// - the lexicographically larger cid is the final deterministic tiebreak so -/// two anchors in the *same* block with the same timestamp still resolve -/// order-independently. +/// the composite key `(timestamp instant, block height rank, cid)`. The signed +/// timestamp is primary because inclusion height is replayable: anyone can copy +/// exact old public bytes into a new Arweave transaction. Timestamp strings +/// compare as parsed RFC3339 instants rather than text. Height breaks equal- +/// timestamp ties (pending newest, then larger height) without entering the +/// authenticity decision, and the lexicographically larger CID is the final +/// deterministic tie-break. /// /// Entries for oids absent from the cloned tree are discarded on insertion: /// a fabricated oid can never become a valid recovered path, so it must not @@ -838,10 +835,10 @@ fn merge_authenticated( // Incumbent wins iff its composite key is >= the candidate's. The // `>=` (not `>`) keeps the incumbent only on a full tie, where the // entries are identical anyway. A strictly-greater candidate key - // (higher block rank, or equal rank + later timestamp instant, or - // equal both + larger cid) replaces it. + // (later signed timestamp instant, or equal timestamp + higher + // block rank, or equal both + larger cid) replaces it. Some((cur_cid, cur_rank, cur_ts)) => { - (*cur_rank, *cur_ts, cur_cid.as_str()) >= (cand_rank, cand_ts, b.cid.as_str()) + (*cur_ts, *cur_rank, cur_cid.as_str()) >= (cand_ts, cand_rank, b.cid.as_str()) } None => false, }; @@ -1125,8 +1122,8 @@ async fn recover_from_arweave_inner( } } } - // 5. Merge authenticated entries only: height rank first (pending newest), - // then the signed timestamp instant, then the larger cid. + // 5. Merge authenticated entries only: signed timestamp first, then height + // rank as the equal-timestamp tie-break, then the larger cid. let oid_cid = merge_authenticated(manifests, &oid_to_path); // 6. Recover each missing blob the caller can decrypt. @@ -1706,10 +1703,16 @@ mod tests { ); } + #[test] + fn discovery_query_uses_edge_cursor_not_pageinfo_endcursor() { + assert!(!ARWEAVE_DISCOVERY_QUERY.contains("endCursor")); + assert!(ARWEAVE_DISCOVERY_QUERY.contains("edges{cursor")); + } + #[test] fn parse_tx_page_extracts_node_ids_and_heights() { let v: serde_json::Value = serde_json::from_str( - r#"{"data":{"transactions":{"pageInfo":{"hasNextPage":true,"endCursor":"C1"},"edges":[{"node":{"id":"TX1","block":{"height":100}}},{"node":{"id":"TX2","block":null}}]}}}"#, + r#"{"data":{"transactions":{"pageInfo":{"hasNextPage":true},"edges":[{"cursor":"C0","node":{"id":"TX1","block":{"height":100}}},{"cursor":"C1","node":{"id":"TX2","block":null}}]}}}"#, ) .unwrap(); let page = parse_tx_page(&v); @@ -1931,11 +1934,10 @@ mod tests { } #[test] - fn merge_height_rank_beats_timestamp() { - // Inverted from the unsigned-v1 rule: a higher block height wins even - // when the lower-height manifest carries the later timestamp. Height - // is monotonic chain-inclusion metadata, so a correct-but-misconfigured - // node clock moving backwards cannot permanently regress recovery. + fn merge_signed_timestamp_beats_replayed_height() { + // A public signed manifest can be copied byte for byte into a new + // Arweave transaction. That replay must not displace a newer signed + // payload merely because the copy has a greater inclusion height. let newer_ts_lo_block = vmanifest("2026-06-11T00:00:00Z", "o1", "cidNEWERTS"); let mut older_ts_hi_block = vmanifest("2026-06-10T00:00:00Z", "o1", "cidHIBLOCK"); older_ts_hi_block @@ -1951,7 +1953,7 @@ mod tests { ], &tree(&["o1", "o2"]), ); - assert_eq!(merged.get("o1").map(String::as_str), Some("cidHIBLOCK")); + assert_eq!(merged.get("o1").map(String::as_str), Some("cidNEWERTS")); assert_eq!(merged.get("o2").map(String::as_str), Some("cid2")); let reverse = merge_authenticated( vec![ @@ -1960,19 +1962,19 @@ mod tests { ], &tree(&["o1", "o2"]), ); - assert_eq!(reverse.get("o1").map(String::as_str), Some("cidHIBLOCK")); + assert_eq!(reverse.get("o1").map(String::as_str), Some("cidNEWERTS")); } #[test] fn merge_pending_anchor_beats_any_mined_anchor() { - // A pending (not yet mined) anchor ranks newest, order-independently, - // even against a far higher mined block. + // At the same signed timestamp, a pending (not yet mined) anchor ranks + // newest, order-independently, even against a far higher mined block. let mined = vmanifest("2026-06-11T00:00:00Z", "o1", "cidMINED"); - let pending = vmanifest("2026-06-10T00:00:00Z", "o1", "cidPENDING"); + let pending = vmanifest("2026-06-11T00:00:00Z", "o1", "cidPENDING"); let a = merge_authenticated(vec![(mined, Some(99)), (pending, None)], &tree(&["o1"])); assert_eq!(a.get("o1").map(String::as_str), Some("cidPENDING")); let mined2 = vmanifest("2026-06-11T00:00:00Z", "o1", "cidMINED"); - let pending2 = vmanifest("2026-06-10T00:00:00Z", "o1", "cidPENDING"); + let pending2 = vmanifest("2026-06-11T00:00:00Z", "o1", "cidPENDING"); let b = merge_authenticated(vec![(pending2, None), (mined2, Some(99))], &tree(&["o1"])); assert_eq!(b.get("o1").map(String::as_str), Some("cidPENDING")); } @@ -2350,6 +2352,106 @@ mod tests { ); } + /// A replayed stale manifest is still correctly signed, so signature + /// verification alone cannot order it away. Its older signed timestamp must + /// lose to the newer payload even when the replay carries a far greater + /// inclusion height. + #[tokio::test] + async fn replayed_stale_signed_manifest_cannot_displace_newer_payload() { + use twigpine_core::encrypt::seal_blob; + + let (_td, dest) = clone_with_missing_secrets(&[ + ( + "public/a.txt", + b"pub +", + ), + ( + "secret/b.txt", + b"SECRET +", + ), + ]); + let oid = oid_of(&dest, "secret/b.txt"); + + let actors = b3_actors(); + let envelope = seal_blob( + b"SECRET +", + &[actors.reader.verifying_key()], + ) + .unwrap(); + let new_cid = test_cid(14); + let stale_cid = test_cid(15); + let tx_new = valid_txid("txnewsign"); + let tx_stale = valid_txid("txstaletx"); + + let mut server = mockito::Server::new_async().await; + let _gql = server + .mock("POST", "/graphql") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(gql_page(&[ + (tx_stale.as_str(), Some(9999)), + (tx_new.as_str(), Some(10)), + ])) + .create_async() + .await; + let stale_body = signed_manifest_json( + &actors.signer, + &actors.owner, + "myrepo", + "2026-06-10T00:00:00Z", + &[(oid.as_str(), stale_cid.as_str())], + ); + let _tx_stale = server + .mock("GET", format!("/raw/{tx_stale}").as_str()) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(stale_body) + .create_async() + .await; + let new_body = signed_manifest_json( + &actors.signer, + &actors.owner, + "myrepo", + "2026-06-11T00:00:00Z", + &[(oid.as_str(), new_cid.as_str())], + ); + let _tx_new = server + .mock("GET", format!("/raw/{tx_new}").as_str()) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(new_body) + .create_async() + .await; + let stale_fetch = server + .mock("GET", format!("/ipfs/{stale_cid}").as_str()) + .expect(0) + .create_async() + .await; + let _blob = server + .mock("GET", format!("/ipfs/{new_cid}").as_str()) + .with_status(200) + .with_body(envelope) + .create_async() + .await; + + let paths = recover_from_arweave( + &server.url(), + &server.url(), + &actors.owner, + "myrepo", + &dest, + &actors.reader, + &actors.signer.did().to_string(), + ) + .await + .unwrap(); + assert_eq!(paths, vec!["secret/b.txt".to_string()]); + stale_fetch.assert_async().await; + } + /// A correctly signed manifest for a DIFFERENT repo must be rejected before /// merge even when the gateway's tags were right: tags are hints, the /// signed payload is the authority. @@ -2555,7 +2657,7 @@ mod tests { let tx_p2 = valid_txid("txpagetwo"); let mut server = mockito::Server::new_async().await; - // Page 1 (cursor null): hasNextPage=true, endCursor C1, an empty-manifest + // Page 1 (cursor null): hasNextPage=true, edge cursor C1, an empty-manifest // anchor that does NOT carry the withheld blob. let _gql_p1 = server .mock("POST", "/graphql") @@ -2565,7 +2667,7 @@ mod tests { .with_status(200) .with_header("content-type", "application/json") .with_body(format!( - r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":true,"endCursor":"C1"}},"edges":[{{"node":{{"id":"{tx_p1}","block":{{"height":10}}}}}}]}}}}}}"# + r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":true}},"edges":[{{"cursor":"C1","node":{{"id":"{tx_p1}","block":{{"height":10}}}}}}]}}}}}}"# )) .create_async() .await; @@ -2578,7 +2680,7 @@ mod tests { .with_status(200) .with_header("content-type", "application/json") .with_body(format!( - r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":false,"endCursor":"C2"}},"edges":[{{"node":{{"id":"{tx_p2}","block":{{"height":20}}}}}}]}}}}}}"# + r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":false}},"edges":[{{"cursor":"C2","node":{{"id":"{tx_p2}","block":{{"height":20}}}}}}]}}}}}}"# )) .create_async() .await; @@ -2670,7 +2772,7 @@ mod tests { .with_status(200) .with_header("content-type", "application/json") .with_body(format!( - r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":true,"endCursor":"C1"}},"edges":[{{"node":{{"id":"{txid}","block":{{"height":20}}}}}}]}}}}}}"# + r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":true}},"edges":[{{"cursor":"C1","node":{{"id":"{txid}","block":{{"height":20}}}}}}]}}}}}}"# )) .create_async() .await; @@ -2721,7 +2823,7 @@ mod tests { } /// A gateway that reports `hasNextPage=true` but never advances the cursor - /// (returns the same `endCursor` every page) must not loop forever: the + /// (returns the same edge cursor every page) must not loop forever: the /// degenerate-cursor guard terminates the loop and recovery returns based on /// what was seen. The test completing at all proves no hang. #[tokio::test] @@ -2739,7 +2841,7 @@ mod tests { let cid = test_cid(9); let txid = valid_txid("txstuck"); - // Every GraphQL POST returns hasNextPage=true with the SAME endCursor. + // Every GraphQL POST returns hasNextPage=true with the SAME edge cursor. // The guard fires on the second page (cursor repeats prev_cursor) and // breaks, so discovery makes exactly two POSTs: page 1 (cursor null) records // STUCK, page 2 (cursor STUCK) sees the repeat and stops. We assert that @@ -2760,7 +2862,7 @@ mod tests { .with_status(200) .with_header("content-type", "application/json") .with_body(format!( - r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":true,"endCursor":"STUCK"}},"edges":[{{"node":{{"id":"{txid}","block":{{"height":20}}}}}}]}}}}}}"# + r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":true}},"edges":[{{"cursor":"STUCK","node":{{"id":"{txid}","block":{{"height":20}}}}}}]}}}}}}"# )) .create_async() .await; @@ -2821,7 +2923,7 @@ mod tests { .with_status(200) .with_header("content-type", "application/json") .with_body(format!( - r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":true,"endCursor":"C1"}},"edges":[{{"node":{{"id":"{txid}","block":{{"height":20}}}}}}]}}}}}}"# + r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":true}},"edges":[{{"cursor":"C1","node":{{"id":"{txid}","block":{{"height":20}}}}}}]}}}}}}"# )) .create_async() .await; @@ -2833,7 +2935,7 @@ mod tests { .with_status(200) .with_header("content-type", "application/json") .with_body(format!( - r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":false,"endCursor":"C2"}},"edges":[{{"node":{{"id":"{txid}","block":{{"height":20}}}}}}]}}}}}}"# + r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":false}},"edges":[{{"cursor":"C2","node":{{"id":"{txid}","block":{{"height":20}}}}}}]}}}}}}"# )) .create_async() .await; @@ -3179,7 +3281,7 @@ mod tests { .with_status(200) .with_header("content-type", "application/json") .with_body(format!( - r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":true,"endCursor":"C1"}},"edges":[{{"node":{{"id":"{txid}","block":{{"height":1}}}}}}]}}}}}}"# + r#"{{"data":{{"transactions":{{"pageInfo":{{"hasNextPage":true}},"edges":[{{"cursor":"C1","node":{{"id":"{txid}","block":{{"height":1}}}}}}]}}}}}}"# )) .create_async() .await; From b88e92791b6f008f5387caf7cf3febba27c2b528 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:14:36 -0600 Subject: [PATCH 10/18] fix(cli): enforce exact arweave transaction ceilings --- crates/twigpine-cli/src/clone.rs | 101 +++++++++++++++++++++++++++++-- 1 file changed, 96 insertions(+), 5 deletions(-) diff --git a/crates/twigpine-cli/src/clone.rs b/crates/twigpine-cli/src/clone.rs index 2a77e6f4a..815117883 100644 --- a/crates/twigpine-cli/src/clone.rs +++ b/crates/twigpine-cli/src/clone.rs @@ -993,17 +993,24 @@ async fn recover_from_arweave_inner( }; let page = parse_tx_page(&value); let full = page.refs.len() >= ARWEAVE_PAGE_SIZE; + let mut cap_hit = false; for r in page.refs { // A malformed tx id is gateway spam and never reaches a request URL. - if !is_valid_txid(&r.id) { + if !is_valid_txid(&r.id) || seen.contains(&r.id) { continue; } - if seen.insert(r.id.clone()) { - refs.push(r); + if refs.len() >= limits.max_tx_ids { + cap_hit = true; + break; } + seen.insert(r.id.clone()); + refs.push(r); } - // Cap checked at the page boundary so a partial page is never half-merged. - if refs.len() >= limits.max_tx_ids { + // The transaction ceiling is exact: never carry a partial overflow page + // into the fetch stage. Reaching the ceiling exactly is complete when + // the gateway says no page follows; an additional unique candidate or a + // promised next page means recovery is knowingly incomplete. + if cap_hit || (refs.len() >= limits.max_tx_ids && page.has_next == Some(true)) { emit_warning(&format!( "warning: Arweave manifest discovery hit the {}-transaction cap; some authorized files may not be recovered", limits.max_tx_ids @@ -3258,6 +3265,90 @@ mod tests { ); } + /// The transaction ceiling is exact even when one page would overflow it: + /// only the first `max_tx_ids` unique valid ids may enter the fetch stage. + #[tokio::test] + async fn discovery_transaction_cap_is_exact_across_a_page_boundary() { + use twigpine_core::identity::Keypair; + + reset_warnings(); + let (_td, dest) = clone_with_missing_secrets(&[ + ( + "public/a.txt", + b"pub +", + ), + ( + "secret/b.txt", + b"SECRET +", + ), + ]); + let reader = Keypair::generate(); + let actors = b3_actors(); + let tx1 = valid_txid("txcapone"); + let tx2 = valid_txid("txcaptwo"); + let tx3 = valid_txid("txcapthree"); + + let mut server = mockito::Server::new_async().await; + let _gql = server + .mock("POST", "/graphql") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(gql_page(&[ + (tx1.as_str(), Some(1)), + (tx2.as_str(), Some(2)), + (tx3.as_str(), Some(3)), + ])) + .create_async() + .await; + let first = server + .mock("GET", format!("/raw/{tx1}").as_str()) + .with_status(200) + .with_body("not a manifest") + .expect(1) + .create_async() + .await; + let second = server + .mock("GET", format!("/raw/{tx2}").as_str()) + .with_status(200) + .with_body("not a manifest") + .expect(1) + .create_async() + .await; + let third = server + .mock("GET", format!("/raw/{tx3}").as_str()) + .expect(0) + .create_async() + .await; + + let limits = DiscoveryLimits { + max_pages: 8, + max_tx_ids: 2, + metadata_budget: std::time::Duration::from_secs(60), + }; + let paths = recover_from_arweave_inner( + &server.url(), + &server.url(), + &canonical_repo_slug(&actors.owner, "myrepo"), + &dest, + &reader, + &actors.signer.did().to_string(), + &limits, + ) + .await + .unwrap(); + assert!(paths.is_empty()); + first.assert_async().await; + second.assert_async().await; + third.assert_async().await; + assert!( + warnings().contains("2-transaction cap"), + "the exact transaction cap must warn, got: {:?}", + warnings() + ); + } + /// Discovery stops at the page cap and warns, even when the gateway keeps /// offering a fresh cursor. #[tokio::test] From 42a2c1b07eff10ad4d26231a9849fb1db926d217 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:15:53 -0600 Subject: [PATCH 11/18] style(cli): satisfy cursor extraction lint --- crates/twigpine-cli/src/clone.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/twigpine-cli/src/clone.rs b/crates/twigpine-cli/src/clone.rs index 815117883..bd53b1076 100644 --- a/crates/twigpine-cli/src/clone.rs +++ b/crates/twigpine-cli/src/clone.rs @@ -780,7 +780,7 @@ pub(crate) fn parse_tx_page(v: &serde_json::Value) -> TxPage { .iter() .take(ARWEAVE_PAGE_SIZE) .filter_map(|edge| edge.get("cursor").and_then(|c| c.as_str())) - .last() + .next_back() .map(String::from) }); let page_info = txns.and_then(|t| t.get("pageInfo")); From 50701fd549898fa3391af5050bf479fdaaf481f3 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:18:28 -0600 Subject: [PATCH 12/18] docs: state arweave edge cursor pagination --- PROTOCOL.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/PROTOCOL.md b/PROTOCOL.md index e512a4cbe..40767b890 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -184,7 +184,9 @@ A client requests Arweave transaction bodies from `/raw/`, not from the manifest-resolving `/` endpoint. Transaction ids are exactly 43 base64url characters before they may appear in a request URL. The CLI discovery query asks for `sort: HEIGHT_DESC` and reads at most 8 pages or -512 transaction ids. Each GraphQL page response is capped at 256 KiB. +exactly at most 512 transaction ids. Pagination uses the cursor on the final +edge; Arweave `pageInfo` supplies `hasNextPage`, not `endCursor`. Each GraphQL +page response is capped at 256 KiB. Discovery plus manifest fetch and verification has a 120 second wall-clock budget. Hitting a count or time budget means recovery is incomplete and must produce a warning. From 01a7b0116235263f0430b45e5455ddc4f94f6d69 Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:36:26 -0600 Subject: [PATCH 13/18] fix(cli): bound verified manifest retention during recovery Replayed Arweave anchors can duplicate valid signed payload bytes without needing a signer. Streaming verified entries into the filtered merge and deduping exact payload copies keeps that replay from multiplying retained manifest entries or repeated verification work. --- crates/twigpine-cli/src/clone.rs | 140 ++++++++++++++++++++----------- 1 file changed, 91 insertions(+), 49 deletions(-) diff --git a/crates/twigpine-cli/src/clone.rs b/crates/twigpine-cli/src/clone.rs index bd53b1076..72ebd5d73 100644 --- a/crates/twigpine-cli/src/clone.rs +++ b/crates/twigpine-cli/src/clone.rs @@ -803,35 +803,46 @@ pub(crate) fn height_rank(h: Option) -> (u8, u64) { } } -/// Merge verified per-push manifests into a single `oid -> cid` map, ranked by -/// the composite key `(timestamp instant, block height rank, cid)`. The signed -/// timestamp is primary because inclusion height is replayable: anyone can copy -/// exact old public bytes into a new Arweave transaction. Timestamp strings -/// compare as parsed RFC3339 instants rather than text. Height breaks equal- -/// timestamp ties (pending newest, then larger height) without entering the -/// authenticity decision, and the lexicographically larger CID is the final -/// deterministic tie-break. -/// +/// Incremental merge retention for verified per-push manifests. Verified +/// entries are filtered and ranked as each manifest verifies, rather than +/// retaining every signed body and parsed entry until a final merge pass. /// Entries for oids absent from the cloned tree are discarded on insertion: /// a fabricated oid can never become a valid recovered path, so it must not /// enter merge retention, trigger a `git cat-file`, or trigger an IPFS fetch. -fn merge_authenticated( - manifests: Vec<(VerifiedManifest, Option)>, - tree_oids: &std::collections::HashMap, -) -> std::collections::HashMap { - // oid -> (cid, height_rank, timestamp instant) - type BestEntry = (String, (u8, u64), chrono::DateTime); - let mut best: std::collections::HashMap = std::collections::HashMap::new(); - for (m, height) in manifests { +// oid -> (cid, height_rank, timestamp instant) +type BestEntry = (String, (u8, u64), chrono::DateTime); + +struct ManifestMerge<'a> { + tree_oids: &'a std::collections::HashMap, + best: std::collections::HashMap, +} + +impl<'a> ManifestMerge<'a> { + fn new(tree_oids: &'a std::collections::HashMap) -> Self { + Self { + tree_oids, + best: std::collections::HashMap::new(), + } + } + + /// Merge one verified manifest, ranked by the composite key `(timestamp + /// instant, block height rank, cid)`. The signed timestamp is primary + /// because inclusion height is replayable: anyone can copy exact old + /// public bytes into a new Arweave transaction. Timestamp strings compare + /// as parsed RFC3339 instants rather than text. Height breaks equal- + /// timestamp ties (pending newest, then larger height) without entering + /// the authenticity decision, and the lexicographically larger CID is the + /// final deterministic tie-break. + fn push(&mut self, m: VerifiedManifest, height: Option) { let cand_rank = height_rank(height); let cand_ts = chrono::DateTime::parse_from_rfc3339(&m.timestamp).unwrap_or_else(|_| { chrono::DateTime::parse_from_rfc3339("1970-01-01T00:00:00Z").unwrap() }); for b in m.blobs { - if !tree_oids.contains_key(&b.oid) { + if !self.tree_oids.contains_key(&b.oid) { continue; } - let keep_incumbent = match best.get(&b.oid) { + let keep_incumbent = match self.best.get(&b.oid) { // Incumbent wins iff its composite key is >= the candidate's. The // `>=` (not `>`) keeps the incumbent only on a full tie, where the // entries are identical anyway. A strictly-greater candidate key @@ -843,13 +854,31 @@ fn merge_authenticated( None => false, }; if !keep_incumbent { - best.insert(b.oid, (b.cid, cand_rank, cand_ts)); + self.best.insert(b.oid, (b.cid, cand_rank, cand_ts)); } } } - best.into_iter() - .map(|(oid, (cid, _, _))| (oid, cid)) - .collect() + + fn finish(self) -> std::collections::HashMap { + self.best + .into_iter() + .map(|(oid, (cid, _, _))| (oid, cid)) + .collect() + } +} + +/// Test-facing batch form of [`ManifestMerge`]. The production recovery path +/// streams manifests into the merge as each one verifies. +#[cfg(test)] +fn merge_authenticated( + manifests: Vec<(VerifiedManifest, Option)>, + tree_oids: &std::collections::HashMap, +) -> std::collections::HashMap { + let mut merge = ManifestMerge::new(tree_oids); + for (m, height) in manifests { + merge.push(m, height); + } + merge.finish() } /// Option B3 fallback recovery, with no dependency on a Twigpine node API. @@ -916,6 +945,7 @@ async fn recover_from_arweave_inner( expected_node_did: &str, limits: &DiscoveryLimits, ) -> Result> { + use sha2::Digest as _; use std::collections::HashMap; use std::io::Write; use twigpine_core::encrypt::{open_blob, MAX_ENCRYPTED_ENVELOPE_BYTES}; @@ -1040,11 +1070,33 @@ async fn recover_from_arweave_inner( } } - // 2. Fetch each manifest body through `/raw/` (the exact bytes, not + // 2. Map oid -> repo-relative path from the cloned tree BEFORE manifest + // verification. The tree oid set is the prefilter that keeps fabricated + // entries out of merge retention, `git cat-file`, and gateway fetches + // entirely, and building it here lets verified entries stream into that + // bounded retention instead of accumulating in an intermediate vector. + let ls = Command::new("git") + .args(["-C", dest_str, "ls-tree", "-r", "HEAD"]) + .output()?; + let mut oid_to_path: HashMap = HashMap::new(); + for line in String::from_utf8_lossy(&ls.stdout).lines() { + if let Some((meta, path)) = line.split_once('\t') { + if let Some(oid) = meta.split_whitespace().nth(2) { + oid_to_path.insert(oid.to_string(), path.to_string()); + } + } + } + + // 3. Fetch each manifest body through `/raw/` (the exact bytes, not // the manifest-resolving endpoint), byte-capped, and verify it against - // the externally anchored node DID BEFORE anything merges. A rejection - // is cheap and bounded; it never fetches or interprets a v1 body. - let mut manifests: Vec<(VerifiedManifest, Option)> = Vec::new(); + // the externally anchored node DID BEFORE it merges. A rejection is + // cheap and bounded; it never fetches or interprets a v1 body. Exact + // replay copies carry identical signed bytes, so dedupe them before + // verification; a re-anchored copy cannot multiply merge retention or + // repeated signature-verification work. + let mut seen_payloads: HashSet<[u8; 32]> = HashSet::new(); + let mut merge = ManifestMerge::new(&oid_to_path); + let mut verified_any = false; for r in refs { if started.elapsed() >= limits.metadata_budget { if !budget_warned { @@ -1078,20 +1130,27 @@ async fn recover_from_arweave_inner( continue; } }; + let payload_hash: [u8; 32] = sha2::Sha256::digest(&bytes).into(); + if !seen_payloads.insert(payload_hash) { + continue; + } match verify_signed_manifest(&bytes, expected_node_did, slug) { - Ok(verified) => manifests.push((verified, r.height)), + Ok(verified) => { + verified_any = true; + merge.push(verified, r.height); + } Err(e) => { warnings.warn_skip_manifest(&r.id, &format!("not a trusted signed manifest: {e}")); } } } - // 3. When no usable signed v2 manifest was found, run one cheap + // 4. When no usable signed v2 manifest was found, run one cheap // metadata-only legacy probe so "unsigned legacy anchors exist but are // not trusted" is said out loud instead of looking like silent absence. // The probe reads one GraphQL page of v1 tags; v1 bodies are never // fetched or used as recovery authority. - if manifests.is_empty() && started.elapsed() < limits.metadata_budget { + if !verified_any && started.elapsed() < limits.metadata_budget { let probe_body = serde_json::json!({ "query": ARWEAVE_LEGACY_PROBE_QUERY, "variables": { "repo": legacy_repo_tag(slug) }, @@ -1115,25 +1174,8 @@ async fn recover_from_arweave_inner( } } - // 4. Map oid -> repo-relative path from the cloned tree BEFORE merging: - // the tree oid set is the prefilter that keeps fabricated entries out - // of merge retention, `git cat-file`, and gateway fetches entirely. - let ls = Command::new("git") - .args(["-C", dest_str, "ls-tree", "-r", "HEAD"]) - .output()?; - let mut oid_to_path: HashMap = HashMap::new(); - for line in String::from_utf8_lossy(&ls.stdout).lines() { - if let Some((meta, path)) = line.split_once('\t') { - if let Some(oid) = meta.split_whitespace().nth(2) { - oid_to_path.insert(oid.to_string(), path.to_string()); - } - } - } - // 5. Merge authenticated entries only: signed timestamp first, then height - // rank as the equal-timestamp tie-break, then the larger cid. - let oid_cid = merge_authenticated(manifests, &oid_to_path); - - // 6. Recover each missing blob the caller can decrypt. + // 5. Recover each missing blob the caller can decrypt. + let oid_cid = merge.finish(); let mut recovered = Vec::new(); for (oid, cid) in oid_cid { // Local presence check. GIT_NO_LAZY_FETCH stops git from making a wasted From 2ba54761f1ec940417cc992a1bc61693a6782d6d Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:26:14 -0600 Subject: [PATCH 14/18] fix(cli): harden arweave recovery feedback fixes --- crates/twigpine-cli/src/clone.rs | 41 +++++++++++++++---- .../twigpine-core/src/encrypted_manifest.rs | 3 ++ docs/LEGACY-NAMES.md | 1 + 3 files changed, 36 insertions(+), 9 deletions(-) diff --git a/crates/twigpine-cli/src/clone.rs b/crates/twigpine-cli/src/clone.rs index 72ebd5d73..de8baf473 100644 --- a/crates/twigpine-cli/src/clone.rs +++ b/crates/twigpine-cli/src/clone.rs @@ -606,7 +606,7 @@ async fn post_graphql_json( ) -> Option { let resp = client .post(url) - .timeout(timeout) + .timeout(timeout.min(std::time::Duration::from_secs(30))) .json(body) .send() .await @@ -1021,6 +1021,18 @@ async fn recover_from_arweave_inner( break; } }; + if value + .get("data") + .and_then(|d| d.get("transactions")) + .is_none() + { + if !refs.is_empty() { + emit_warning( + "warning: Arweave manifest discovery was interrupted by a gateway error; some authorized files may not be recovered", + ); + } + break; + } let page = parse_tx_page(&value); let full = page.refs.len() >= ARWEAVE_PAGE_SIZE; let mut cap_hit = false; @@ -1054,7 +1066,12 @@ async fn recover_from_arweave_inner( Some(c) if Some(&c) != after.as_ref() => { after = Some(c); } - _ => break, + _ => { + emit_warning( + "warning: Arweave gateway promised another page but did not advance the cursor; discovery may be incomplete and some authorized files may not be recovered", + ); + break; + } }, Some(false) => break, // No pageInfo: terminal. A *full* page without it may be a silently @@ -1094,7 +1111,8 @@ async fn recover_from_arweave_inner( // replay copies carry identical signed bytes, so dedupe them before // verification; a re-anchored copy cannot multiply merge retention or // repeated signature-verification work. - let mut seen_payloads: HashSet<[u8; 32]> = HashSet::new(); + let mut verified_payloads: std::collections::HashMap<[u8; 32], Option> = + std::collections::HashMap::new(); let mut merge = ManifestMerge::new(&oid_to_path); let mut verified_any = false; for r in refs { @@ -1109,7 +1127,7 @@ async fn recover_from_arweave_inner( let remaining = limits.metadata_budget.saturating_sub(started.elapsed()); let resp = match client .get(format!("{ag}/raw/{}", r.id)) - .timeout(remaining) + .timeout(remaining.min(std::time::Duration::from_secs(30))) .send() .await { @@ -1131,15 +1149,20 @@ async fn recover_from_arweave_inner( } }; let payload_hash: [u8; 32] = sha2::Sha256::digest(&bytes).into(); - if !seen_payloads.insert(payload_hash) { + if let Some(cached) = verified_payloads.get(&payload_hash) { + if let Some(verified) = cached { + merge.push(verified.clone(), r.height); + } continue; } match verify_signed_manifest(&bytes, expected_node_did, slug) { Ok(verified) => { verified_any = true; + verified_payloads.insert(payload_hash, Some(verified.clone())); merge.push(verified, r.height); } Err(e) => { + verified_payloads.insert(payload_hash, None); warnings.warn_skip_manifest(&r.id, &format!("not a trusted signed manifest: {e}")); } } @@ -3213,12 +3236,11 @@ mod tests { #[test] fn node_env_is_threaded_and_overrides_inherited_values() { let node = "https://node.example.test"; - // An inherited conflicting value must lose to the effective node. - std::env::set_var("GITLAWB_NODE", "http://conflicting-legacy"); + // A conflicting child value must lose to the effective node. let mut cmd = Command::new("env"); + cmd.env("GITLAWB_NODE", "http://conflicting-legacy"); apply_node_env(&mut cmd, Some(node)); let out = cmd.output().unwrap(); - std::env::remove_var("GITLAWB_NODE"); let stdout = String::from_utf8_lossy(&out.stdout); assert!( stdout.contains(&format!("TWIGPINE_NODE={node}")), @@ -3232,10 +3254,11 @@ mod tests { // None leaves the environment untouched for direct local git operations. let mut bare = Command::new("env"); + bare.env("TWIGPINE_NODE", "http://caller-selected"); apply_node_env(&mut bare, None); let out = bare.output().unwrap(); let stdout = String::from_utf8_lossy(&out.stdout); - assert!(!stdout.contains("TWIGPINE_NODE=")); + assert!(stdout.contains("TWIGPINE_NODE=http://caller-selected")); } /// Detailed B3 warnings are capped: at most 20 detail lines reach the diff --git a/crates/twigpine-core/src/encrypted_manifest.rs b/crates/twigpine-core/src/encrypted_manifest.rs index 2c441152e..2e35a20dd 100644 --- a/crates/twigpine-core/src/encrypted_manifest.rs +++ b/crates/twigpine-core/src/encrypted_manifest.rs @@ -143,6 +143,9 @@ fn validate_common( if !seen.insert(blob.oid.to_ascii_lowercase()) { return Err(invalid("duplicate blob oid")); } + if blob.cid.len() > 256 { + return Err(invalid("blob cid exceeds the 256-character bound")); + } let parsed = blob .cid .parse::>() diff --git a/docs/LEGACY-NAMES.md b/docs/LEGACY-NAMES.md index 5222ea1da..0b569305f 100644 --- a/docs/LEGACY-NAMES.md +++ b/docs/LEGACY-NAMES.md @@ -19,6 +19,7 @@ or would invalidate data already stored, and would buy nothing a user can see. | `gitlawb/ref-update/v1` | `CERT_TYPE` in `twigpine-core/src/cert.rs` and `twigpine-attest/src/cert.rs`; the Arweave `Schema` tag written in `twigpine-node/src/arweave.rs` | Signed into every ref-update certificate. Peers refuse a type they do not know, and certificates already signed and anchored carry this one forever. | | `gitlawb/encrypted-manifest/v1` | Permanently stored Arweave artifacts; the CLI legacy-presence probe in `clone.rs` | Unsigned legacy schema of anchored manifests. Existing artifacts remain permanently stored, but current clients never trust them as recovery authority. | | `gitlawb/encrypted-manifest/v2` | `twigpine-core/src/encrypted_manifest.rs`; the Arweave `Schema` tag written in `twigpine-node/src/arweave.rs`; CLI Arweave discovery in `clone.rs` | Current signed schema of encrypted-blob recovery manifests, stored permanently and signed into every artifact. | +| `gitlawb-encrypted-manifest-sig/v2` | `SIGNING_DOMAIN` in `twigpine-core/src/encrypted_manifest.rs` | Signing domain of encrypted-blob recovery manifests. Changing it invalidates every v2 manifest already signed and stored. | | `gitlawb/ref-updates/v1` | `REF_UPDATES_TOPIC` in `twigpine-node/src/p2p/mod.rs` | The gossip topic. A node on another topic hears nothing. | | `/gitlawb/did/` | DHT record key in `twigpine-node/src/p2p/mod.rs` | Key prefix of DHT records other nodes look up. | | `gitlawb/hkdf-salt/webhook-secret`, `gitlawb/webhook-secret/v1` | `twigpine-node/src/state.rs` | Salt and label of the key that seals webhook secrets at rest. Changing either means re-sealing every stored secret. | From 8f183bccf228905b11e924eaecdb2753ebbb222e Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:33:33 -0600 Subject: [PATCH 15/18] fix(cli): bound replayed manifest cache entries --- crates/twigpine-cli/src/clone.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/twigpine-cli/src/clone.rs b/crates/twigpine-cli/src/clone.rs index de8baf473..a3adf2dbc 100644 --- a/crates/twigpine-cli/src/clone.rs +++ b/crates/twigpine-cli/src/clone.rs @@ -1156,8 +1156,9 @@ async fn recover_from_arweave_inner( continue; } match verify_signed_manifest(&bytes, expected_node_did, slug) { - Ok(verified) => { + Ok(mut verified) => { verified_any = true; + verified.blobs.retain(|b| oid_to_path.contains_key(&b.oid)); verified_payloads.insert(payload_hash, Some(verified.clone())); merge.push(verified, r.height); } From 2cf87b663be4308aeadad40c93b5ac5d6e32fd8f Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:11:46 -0600 Subject: [PATCH 16/18] fix(cli): keep the recovery presence probe from lazy-fetching --- crates/twigpine-cli/src/clone.rs | 45 +++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/crates/twigpine-cli/src/clone.rs b/crates/twigpine-cli/src/clone.rs index a3adf2dbc..98c1070dc 100644 --- a/crates/twigpine-cli/src/clone.rs +++ b/crates/twigpine-cli/src/clone.rs @@ -497,9 +497,11 @@ async fn recover_encrypted_blobs( let mut recovered = Vec::new(); for entry in body.blobs { let oid = entry.oid.as_str(); - // Skip if already present locally. + // Skip if already present locally. GIT_NO_LAZY_FETCH keeps the probe from + // asking the promisor for the blob we are about to recover. let mut catfile = Command::new("git"); catfile.args(["-C", dest_str, "cat-file", "-e", oid]); + catfile.env("GIT_NO_LAZY_FETCH", "1"); apply_node_env(&mut catfile, node_env); let present = catfile.status().map(|s| s.success()).unwrap_or(false); if present { @@ -3540,6 +3542,14 @@ mod tests { /// encrypted-blob route can restore it. Returns the tempdir, the clone, and /// the withheld blob's oid. fn clone_missing_secret_blob() -> (TempDir, std::path::PathBuf, String) { + let (td, dest, oid, bare) = clone_with_withheld_secret_blob(); + std::fs::remove_dir_all(&bare).unwrap(); + (td, dest, oid) + } + + /// The same partial clone with the promisor remote left in place, so a lazy + /// fetch of the withheld blob would succeed. Also returns the remote's path. + fn clone_with_withheld_secret_blob() -> (TempDir, std::path::PathBuf, String, String) { let (td, url) = bare_remote(&[("public/a.txt", b"pub\n"), ("secret/b.txt", b"SECRET\n")]); let dest = td.path().join("dest"); let bare = url.strip_prefix("file://").unwrap().to_string(); @@ -3559,8 +3569,7 @@ mod tests { .output() .unwrap(); let oid = String::from_utf8_lossy(&out.stdout).trim().to_string(); - std::fs::remove_dir_all(&bare).unwrap(); - (td, dest, oid) + (td, dest, oid, bare) } /// Mock the node's inventory listing the one withheld blob. The envelope @@ -3715,4 +3724,34 @@ mod tests { assert!(paths.is_empty(), "a 404 envelope is not recoverable"); missing.assert_async().await; } + + /// The presence probe must not lazy-fetch from the promisor: a probe that + /// does would report the withheld blob present and skip the envelope route. + #[tokio::test] + async fn recover_encrypted_blobs_presence_probe_does_not_lazy_fetch() { + use twigpine_core::encrypt::seal_blob; + use twigpine_core::identity::Keypair; + + let (_td, dest, oid, _bare) = clone_with_withheld_secret_blob(); + let reader = Keypair::generate(); + let envelope = seal_blob(b"SECRET\n", &[reader.verifying_key()]).unwrap(); + let mut server = mockito::Server::new_async().await; + let _inv = mock_inventory(&mut server, &oid).await; + let served = server + .mock( + "GET", + format!("/api/v1/repos/alice/myrepo/encrypted-blob/{oid}").as_str(), + ) + .with_status(200) + .with_body(envelope) + .expect(1) + .create_async() + .await; + + let paths = recover_encrypted_blobs(&server.url(), "alice", "myrepo", &dest, &reader) + .await + .unwrap(); + served.assert_async().await; + assert_eq!(paths, vec!["secret/b.txt".to_string()]); + } } From e2e49349ff38b218dad576bf54c6c29165d6035d Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:23:21 -0600 Subject: [PATCH 17/18] fix(cli): report malformed discovery pages and probe legacy anchors when nothing applies --- crates/twigpine-cli/src/clone.rs | 163 ++++++++++++++++++++++++++++--- 1 file changed, 150 insertions(+), 13 deletions(-) diff --git a/crates/twigpine-cli/src/clone.rs b/crates/twigpine-cli/src/clone.rs index 98c1070dc..2b736251c 100644 --- a/crates/twigpine-cli/src/clone.rs +++ b/crates/twigpine-cli/src/clone.rs @@ -1026,6 +1026,8 @@ async fn recover_from_arweave_inner( if value .get("data") .and_then(|d| d.get("transactions")) + .and_then(|t| t.get("edges")) + .and_then(|e| e.as_array()) .is_none() { if !refs.is_empty() { @@ -1159,8 +1161,9 @@ async fn recover_from_arweave_inner( } match verify_signed_manifest(&bytes, expected_node_did, slug) { Ok(mut verified) => { - verified_any = true; verified.blobs.retain(|b| oid_to_path.contains_key(&b.oid)); + // A manifest with nothing in HEAD explains no missing file. + verified_any |= !verified.blobs.is_empty(); verified_payloads.insert(payload_hash, Some(verified.clone())); merge.push(verified, r.height); } @@ -1171,7 +1174,7 @@ async fn recover_from_arweave_inner( } } - // 4. When no usable signed v2 manifest was found, run one cheap + // 4. When no signed v2 manifest applied to HEAD, run one cheap // metadata-only legacy probe so "unsigned legacy anchors exist but are // not trusted" is said out loud instead of looking like silent absence. // The probe reads one GraphQL page of v1 tags; v1 bodies are never @@ -2140,9 +2143,10 @@ mod tests { /// The IPFS fetch used to leave through a bare `_ => continue` on every /// non-success, so a 503 (the truncation status a tuned node makes more likely), /// a 404, and a dead connection all reached the caller as the same silent "blob - /// not recoverable". Two withheld blobs here: the gateway answers 503 for the - /// first and serves the second. The recovered path proves the loop continued; the - /// warning proves the skip was reported and names both the object and the status. + /// not recoverable". Three withheld blobs here: the gateway answers 503 for two + /// and serves one. Candidates are visited in no fixed order, so with two refusals a + /// loop that stops at the first one always misses a request. The warning proves each + /// skip was reported and names both the object and the status. #[tokio::test] async fn recover_from_arweave_reports_a_refusing_gateway_and_continues() { use twigpine_core::encrypt::seal_blob; @@ -2152,15 +2156,18 @@ mod tests { ("public/a.txt", b"pub\n"), ("secret/b.txt", b"SECRET B\n"), ("secret/c.txt", b"SECRET C\n"), + ("secret/d.txt", b"SECRET D\n"), ]); let refused_oid = oid_of(&dest, "secret/b.txt"); let served_oid = oid_of(&dest, "secret/c.txt"); + let also_refused_oid = oid_of(&dest, "secret/d.txt"); let actors = b3_actors(); let envelope = seal_blob(b"SECRET C\n", &[actors.reader.verifying_key()]).unwrap(); let refused_cid = test_cid(1); let served_cid = test_cid(2); + let also_refused_cid = test_cid(4); let txid = valid_txid("txmain"); let mut server = mockito::Server::new_async().await; let _gql = server @@ -2178,6 +2185,7 @@ mod tests { &[ (refused_oid.as_str(), refused_cid.as_str()), (served_oid.as_str(), served_cid.as_str()), + (also_refused_oid.as_str(), also_refused_cid.as_str()), ], ); let _tx = server @@ -2195,6 +2203,12 @@ mod tests { .expect(1) .create_async() .await; + let also_refusal = server + .mock("GET", format!("/ipfs/{also_refused_cid}").as_str()) + .with_status(503) + .expect(1) + .create_async() + .await; let ok = server .mock("GET", format!("/ipfs/{served_cid}").as_str()) .with_status(200) @@ -2216,6 +2230,7 @@ mod tests { .unwrap(); refusal.assert_async().await; + also_refusal.assert_async().await; ok.assert_async().await; assert_eq!( paths, @@ -2225,7 +2240,7 @@ mod tests { let warnings = warnings(); assert!( - warnings.contains(&refused_oid), + warnings.contains(&refused_oid) && warnings.contains(&also_refused_oid), "the skip must name the object it could not fetch, got: {warnings}" ); assert!( @@ -2665,6 +2680,93 @@ mod tests { ); } + /// Runs recovery against one signed v2 manifest naming `secret/b.txt` or an + /// oid absent from HEAD, with a legacy anchor also present. + async fn legacy_probe_with_signed_manifest(applies_to_head: bool, probes: usize) { + use twigpine_core::identity::Keypair; + + reset_warnings(); + let (_td, dest) = clone_with_missing_secrets(&[ + ("public/a.txt", b"pub\n"), + ("secret/b.txt", b"SECRET\n"), + ]); + let oid = if applies_to_head { + oid_of(&dest, "secret/b.txt") + } else { + "0123456789abcdef0123456789abcdef01234567".to_string() + }; + let actors = b3_actors(); + let reader = Keypair::generate(); + let legacy_tag = legacy_repo_tag(&canonical_repo_slug(&actors.owner, "myrepo")); + let cid = test_cid(3); + let txid = valid_txid("txsigned"); + + let mut server = mockito::Server::new_async().await; + let _gql_v2 = server + .mock("POST", "/graphql") + .match_body(mockito::Matcher::PartialJsonString( + r#"{"variables":{"cursor":null}}"#.into(), + )) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(gql_page(&[(txid.as_str(), None)])) + .create_async() + .await; + let probe = server + .mock("POST", "/graphql") + .match_body(mockito::Matcher::PartialJsonString(format!( + r#"{{"variables":{{"repo":"{legacy_tag}"}}}}"# + ))) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"data":{"transactions":{"edges":[{"node":{"id":"legacytx"}}]}}}"#) + .expect(probes) + .create_async() + .await; + let _tx = server + .mock("GET", format!("/raw/{txid}").as_str()) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(signed_manifest_json( + &actors.signer, + &actors.owner, + "myrepo", + "2026-06-11T00:00:00Z", + &[(oid.as_str(), cid.as_str())], + )) + .create_async() + .await; + + recover_from_arweave( + &server.url(), + &server.url(), + &actors.owner, + "myrepo", + &dest, + &reader, + &actors.signer.did().to_string(), + ) + .await + .unwrap(); + probe.assert_async().await; + assert_eq!( + warnings().contains("unsigned legacy"), + probes > 0, + "got: {:?}", + warnings() + ); + } + + #[tokio::test] + async fn recover_from_arweave_probes_legacy_when_no_signed_entry_is_in_head() { + legacy_probe_with_signed_manifest(false, 1).await; + } + + #[tokio::test] + async fn recover_from_arweave_skips_legacy_probe_when_a_signed_entry_is_in_head() { + legacy_probe_with_signed_manifest(true, 0).await; + } + /// A gateway-invented malformed transaction id must never appear in a /// request URL: exactly-43-base64url validation drops it before the fetch. #[tokio::test] @@ -2815,8 +2917,7 @@ mod tests { /// Best-effort on mid-pagination failure: page 1 already yielded a usable /// anchor; page 2 fails. Recovery still installs page 1's blob (partial Ok), /// never aborts the clone. - #[tokio::test] - async fn recover_from_arweave_partial_on_midpagination_failure() { + async fn second_page_response_keeps_page_one(status: usize, page2: &str) -> String { use twigpine_core::encrypt::seal_blob; let (_td, dest) = clone_with_missing_secrets(&[ @@ -2830,6 +2931,7 @@ mod tests { let cid = test_cid(8); let txid = valid_txid("txpartial"); + reset_warnings(); let mut server = mockito::Server::new_async().await; // Page 1 (cursor null): the blob anchor, hasNextPage=true. let manifest_body = signed_manifest_json( @@ -2851,13 +2953,15 @@ mod tests { )) .create_async() .await; - // Page 2 (cursor "C1"): gateway error. + // Page 2 (cursor "C1"): the response under test. let _gql_p2 = server .mock("POST", "/graphql") .match_body(mockito::Matcher::PartialJsonString( r#"{"variables":{"cursor":"C1"}}"#.into(), )) - .with_status(500) + .with_status(status) + .with_header("content-type", "application/json") + .with_body(page2) .create_async() .await; let _tx1 = server @@ -2890,10 +2994,43 @@ mod tests { vec!["secret/b.txt".to_string()], "page-1 blob must still be recovered when page 2 fails" ); + warnings() + } + + #[tokio::test] + async fn recover_from_arweave_partial_on_midpagination_failure() { + let warnings = second_page_response_keeps_page_one(500, "").await; assert!( - warnings().contains("interrupted"), - "mid-pagination failure must surface as partial discovery, got: {:?}", - warnings() + warnings.contains("interrupted"), + "mid-pagination failure must surface as partial discovery, got: {warnings:?}" + ); + } + + /// A 200 whose `transactions` carries no `edges` array is a failed page, not + /// an empty last one. + #[tokio::test] + async fn recover_from_arweave_partial_on_page_without_edges_array() { + for page2 in [ + r#"{"data":{"transactions":{"edges":null}},"errors":[{"message":"x"}]}"#, + r#"{"data":{"transactions":{}}}"#, + r#"{"data":{"transactions":null}}"#, + ] { + let warnings = second_page_response_keeps_page_one(200, page2).await; + assert!( + warnings.contains("interrupted"), + "{page2} must surface as partial discovery, got: {warnings:?}" + ); + } + } + + #[tokio::test] + async fn recover_from_arweave_accepts_an_empty_last_page() { + let warnings = + second_page_response_keeps_page_one(200, r#"{"data":{"transactions":{"edges":[]}}}"#) + .await; + assert!( + !warnings.contains("interrupted"), + "an empty edges array is a complete last page, got: {warnings:?}" ); } From 6624e8488df739d8566651ab768deaef9495cc4c Mon Sep 17 00:00:00 2001 From: beardthelion <56458543+beardthelion@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:36:24 -0600 Subject: [PATCH 18/18] test(core): use hex letters in the oid case normalization test --- crates/twigpine-core/src/encrypted_manifest.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/twigpine-core/src/encrypted_manifest.rs b/crates/twigpine-core/src/encrypted_manifest.rs index 2e35a20dd..41c636e30 100644 --- a/crates/twigpine-core/src/encrypted_manifest.rs +++ b/crates/twigpine-core/src/encrypted_manifest.rs @@ -674,21 +674,21 @@ mod tests { let owner = kp.did().to_string(); let repo = canonical_repo_slug(&owner, "repo"); let upper = vec![EncryptedBlobRef { - oid: oid(1).to_ascii_uppercase(), + oid: oid(0xab).to_ascii_uppercase(), cid: cid_for(1), }]; let body = build_signed_manifest(&repo, &owner, "2026-01-01T00:00:00Z", &upper, &kp).unwrap(); let verified = verify_signed_manifest(&body, &kp.did().to_string(), &repo).unwrap(); - assert_eq!(verified.blobs[0].oid, oid(1)); + assert_eq!(verified.blobs[0].oid, oid(0xab)); let duplicate = vec![ EncryptedBlobRef { - oid: oid(1).to_ascii_uppercase(), + oid: oid(0xab).to_ascii_uppercase(), cid: cid_for(1), }, EncryptedBlobRef { - oid: oid(1), + oid: oid(0xab), cid: cid_for(2), }, ];