Skip to main content

capsule_sdk/
peering.rs

1//! LAN peering: direct device-to-device sync within a single user's own devices
2//! (SSoT: [Peering]).
3//!
4//! Peering is an **accelerator, never a replacement** for server sync: two of a user's
5//! devices on the same network move a freshly-imported asset directly instead of
6//! round-tripping every byte through the server. If no peer answers, discovery fails
7//! silently and the device falls back to ordinary sync — nothing depends on it succeeding.
8//!
9//! This module owns only the two things peering introduces of its own — a LAN **discovery**
10//! mechanism and a **transport** — and borrows everything else:
11//!
12//! - [`discovery`] — the opaque, rotating mDNS advertisement (it must leak neither a user
13//!   handle nor a device name) and the [`Discovery`] seam. The mDNS
14//!   responder is mocked in tests and is where a real pure-Rust responder (`mdns-sd`) plugs
15//!   in; discovery stays deterministic so every rule is a unit test.
16//! - [`channel`] — a mutually-authenticated **TLS 1.3** channel with no CA. The TLS layer
17//!   proves only classical possession; the **hybrid** identity check (that the peer chains to
18//!   the shared User IK exactly as published in the [device directory]) rides *above* the
19//!   channel, before any payload byte, bound to the session via the RFC 5705 TLS exporter.
20//! - [`session`] — the directory anti-rollback floor, the per-source handshake rate limit, and
21//!   the per-request revocation check that quarantines deliveries made after a revocation.
22//! - [`delta`] — "what's missing" is the complement of two content-address sets, reusing the
23//!   sync-cursor model rather than inventing a diff.
24//! - [`transfer`] — the payload is a **delta-scoped [backup artifact]**, fetched with ranged
25//!   `GET` (resumable, idempotent) and ingested through the **same backup restore path**
26//!   (`capsule-core::backup`), with chain-aware forward-vs-stale reconciliation so a peer can
27//!   never resurrect a locally-superseded asset.
28//! - [`delegation`] — upload delegation: a device hands sealed, signed upload bundles to another
29//!   device of the account, which uploads them as an opaque courier; the origin releases its
30//!   original only on custody it checked itself.
31//!
32//! Trust is *identity*, never *content*: the channel authenticates **who** you talk to; every
33//! received asset is still re-verified by restore (ciphertext hash, STREAM tags, `verify_asset`).
34//!
35//! [Peering]: https://docs/design/peering/
36//! [device directory]: https://docs/design/cryptography/keys/#device-directory
37//! [backup artifact]: https://docs/design/backup-recovery/#backup-artifact
38
39pub mod channel;
40pub mod delegation;
41pub mod delta;
42pub mod discovery;
43pub mod session;
44pub mod transfer;
45
46use std::net::IpAddr;
47
48use capsule_core::backup::BackupError;
49use capsule_core::crypto::CryptoError;
50pub use channel::{
51    ArtifactSecret, HandshakeRole, LocalPeer, Message, Offered, Offering, PEERING_PROTOCOL,
52    PEERING_PROTOCOL_MIN, PeerChannel, PeerClient, PeerHello, PinnedTrust, RangeFailure,
53    ServeReport, ServedRange, UpdateDevice, VerifiedPeer, VersionWindow, accept, connect, serve,
54};
55pub use delegation::{
56    DelegateInbox, DelegatedUpload, Delegation, DelegationError, DelegationState,
57    DeleteDisposition, HandOff, HandOffAck, HeldFailure, MemoryInbox, OriginLedger,
58    PERMANENT_UPLOAD_REFUSALS, Quarantine, ReleaseOutcome, RequeueReason, SealedHandOff, Settled,
59    TakenHandOff, TakenHandOffs, VerifiedHandOff, accept_hand_off, accept_hand_off_from,
60    dispose_failure, offer_hand_offs, seal, settle, take_hand_offs, upload_hand_off,
61    verify_hand_off,
62};
63pub use delta::{
64    OFFER_PAGE_CAP, Offer, OfferPage, decode_offer_page, missing_from, offer_bucket,
65    symmetric_difference,
66};
67pub use discovery::{
68    DiscoveredPeer, Discovery, MockDiscovery, OpaqueAdvertisement, RotationEpoch, SERVICE_TYPE,
69    new_boot_id, rotation_epoch,
70};
71pub use session::{
72    DirectoryVersions, HandshakeLimiter, MemoryDirectoryVersions, PeerSession, SharedTrust,
73    TrustSource,
74};
75use thiserror::Error;
76pub use transfer::{
77    ArtifactBlobSource, ChannelBlobSource, DeltaExport, LocalLibrary, PeerRestore,
78    artifact_address, build_delta_artifact, ingest, pull_artifact, pull_over_channel,
79};
80use uuid::Uuid;
81
82use crate::fetch::FetchScope;
83
84/// Everything peering can fail with. Peering is best-effort — a caller treats most of these as
85/// "no peer / fall back to server sync" — but the identity-check variants are load-bearing
86/// security rejections that must never be silently downgraded.
87#[derive(Debug, Error)]
88pub enum PeeringError {
89    /// A TLS handshake, config, or certificate-generation failure.
90    #[error("peering TLS error: {0}")]
91    Tls(String),
92    /// A socket read/write failure on the peering channel.
93    #[error("peering I/O error: {0}")]
94    Io(String),
95    /// The two devices' peering-protocol windows share no version. The channel is torn down
96    /// before any payload byte, and `update` names the device that must update.
97    #[error(
98        "peering protocol windows are disjoint: ours {ours}, peer's {theirs}; update {update:?}"
99    )]
100    VersionDisjoint {
101        /// This device's window.
102        ours: VersionWindow,
103        /// The peer's advertised window.
104        theirs: VersionWindow,
105        /// Which device must update for the windows to meet.
106        update: UpdateDevice,
107    },
108    /// The peer's pinned directory is not signed by the User IK we trust — a foreign identity.
109    #[error("peer directory does not chain to the pinned User IK")]
110    ForeignIdentity,
111    /// The pinned device directory is older than one this device has already verified: a stale
112    /// directory could readmit a revoked device.
113    #[error("pinned device directory version {pinned} is below the verified {highest}")]
114    DirectoryRollback {
115        /// The pinned directory's version.
116        pinned: u64,
117        /// The highest version this device has verified.
118        highest: u64,
119    },
120    /// The peer presented a device directory older than the one this device pins.
121    #[error("peer presented device directory version {theirs}, below ours {ours}")]
122    PeerDirectoryStale {
123        /// The version the peer presented.
124        theirs: u64,
125        /// The version this device pins.
126        ours: u64,
127    },
128    /// The source address exceeded the handshake rate limit.
129    #[error("peering handshake rate limit reached for {0}")]
130    RateLimited(IpAddr),
131    /// The receiver's synchronization scope does not eagerly hold originals, which every backup
132    /// artifact carries; the receiver syncs from the server instead.
133    #[error("receiver scope {0:?} does not take originals over peering")]
134    OutOfScope(FetchScope),
135    /// The peer presented a `device_id` that is absent from our pinned device directory: it is
136    /// not one of this user's enrolled devices.
137    #[error("peer device {0} is not in the pinned device directory")]
138    UnknownDevice(Uuid),
139    /// The peer's directory entry carries a `revoked_at`: a removed device cannot peer.
140    #[error("peer device {0} has been revoked from the device directory")]
141    RevokedDevice(Uuid),
142    /// The peer's hello claims this device's own `device_id`: a hello reflected back at its
143    /// sender, or a device dialing itself. A device never peers with itself.
144    #[error("peer hello claims this device's own id {0}")]
145    SelfPeer(Uuid),
146    /// The application-layer hybrid signature over the channel-binding did not verify under the
147    /// peer's published device key — the peer does not hold the private key it claims.
148    #[error("peer hybrid identity proof failed to verify")]
149    HybridCheckFailed,
150    /// A discovery-layer failure (advertise/browse).
151    #[error("peering discovery error: {0}")]
152    Discovery(String),
153    /// A framing / serialization failure exchanging the handshake hello.
154    #[error("peering codec error: {0}")]
155    Codec(String),
156    /// An underlying cryptographic failure (e.g. a hardware signer refusing to sign the proof).
157    #[error(transparent)]
158    Crypto(#[from] CryptoError),
159    /// A failure opening, verifying, or restoring the transferred backup artifact.
160    #[error(transparent)]
161    Backup(#[from] BackupError),
162    /// The ranged artifact transfer failed (drop budget exhausted, integrity mismatch).
163    #[error("peering transfer failed: {0}")]
164    Transfer(String),
165    /// The peer did not complete a read or write on the channel within its bound: the handshake
166    /// within [`channel::HANDSHAKE_TIMEOUT`], a frame within the channel's I/O timeout.
167    #[error("peering channel timed out: {0}")]
168    Timeout(&'static str),
169    /// The peer answered a request with a refusal. `kind` is the peer's stable name for why
170    /// (one of [`PeeringError::kind`] or [`DelegationError::kind`]); it is the peer's claim,
171    /// reported, never acted on as a fact about this device.
172    #[error("the peer refused the request ({kind}): {message}")]
173    PeerRefused {
174        /// The peer's stable name for the refusal.
175        kind: String,
176        /// The peer's English detail.
177        message: String,
178    },
179    /// The address is not on the local network: peering is LAN-only ([`is_lan`]).
180    #[error("{0} is not a local-network address; peering is LAN-only")]
181    NotLan(IpAddr),
182    /// The account's device directory could not be fetched to authorize a request; the request
183    /// is refused rather than served under trust that may be stale (fail closed).
184    #[error("the device directory is unavailable: {0}")]
185    Directory(String),
186}
187
188impl PeeringError {
189    /// The stable name a `--json` report and a channel refusal carry this error under. One per
190    /// variant; never renamed.
191    #[must_use]
192    pub fn kind(&self) -> &'static str {
193        match self {
194            Self::Tls(_) => "peering_tls",
195            Self::Io(_) => "peering_io",
196            Self::VersionDisjoint { .. } => "version_disjoint",
197            Self::ForeignIdentity => "foreign_identity",
198            Self::DirectoryRollback { .. } => "directory_rollback",
199            Self::PeerDirectoryStale { .. } => "peer_directory_stale",
200            Self::RateLimited(_) => "rate_limited",
201            Self::OutOfScope(_) => "out_of_scope",
202            Self::UnknownDevice(_) => "unknown_device",
203            Self::RevokedDevice(_) => "revoked_device",
204            Self::SelfPeer(_) => "self_peer",
205            Self::HybridCheckFailed => "hybrid_check_failed",
206            Self::Discovery(_) => "discovery",
207            Self::Codec(_) => "codec",
208            Self::Crypto(_) => "crypto",
209            Self::Backup(_) => "backup",
210            Self::Transfer(_) => "transfer",
211            Self::Timeout(_) => "peering_timeout",
212            Self::PeerRefused { .. } => "peer_refused",
213            Self::NotLan(_) => "not_lan",
214            Self::Directory(_) => "directory_unavailable",
215        }
216    }
217}
218
219/// Whether `ip` is on the local network: loopback, an RFC 1918 private or link-local IPv4
220/// address, or an IPv6 unique-local (`fc00::/7`) or link-local (`fe80::/10`) address, including
221/// an IPv4-mapped one of those. Peering dials and admits only these, so a peering channel never
222/// leaves the LAN.
223#[must_use]
224pub fn is_lan(ip: IpAddr) -> bool {
225    match ip {
226        IpAddr::V4(v4) => v4.is_loopback() || v4.is_private() || v4.is_link_local(),
227        IpAddr::V6(v6) => {
228            if let Some(v4) = v6.to_ipv4_mapped() {
229                return is_lan(IpAddr::V4(v4));
230            }
231            let first = v6.segments()[0];
232            v6.is_loopback() || (first & 0xfe00) == 0xfc00 || (first & 0xffc0) == 0xfe80
233        }
234    }
235}
236
237#[cfg(test)]
238mod tests;