Skip to main content

capsule_sdk/peering/
session.rs

1//! What a peering session enforces after the handshake, and what guards the handshake itself.
2//!
3//! - [`DirectoryVersions`] is the persisted anti-rollback floor: the highest `directory_version`
4//!   this device has verified. Persistence is local state, so it lives behind this seam;
5//!   [`MemoryDirectoryVersions`] is the in-process adapter.
6//! - [`HandshakeLimiter`] caps handshake attempts per source address, so the LAN cannot probe a
7//!   device for membership. Time is passed in, so every rule is a deterministic unit test.
8//! - [`PeerSession`] re-checks the peer's revocation on **every request**, not only at the
9//!   handshake, and remembers what the peer delivered and when, so everything delivered after
10//!   its revocation took effect can be quarantined.
11//! - [`TrustSource`] is where the serving side reads the trust each request is checked against;
12//!   [`SharedTrust`] is the in-process adapter a refreshing owner replaces.
13
14use std::collections::{HashMap, VecDeque};
15use std::net::IpAddr;
16use std::sync::atomic::{AtomicU64, Ordering};
17use std::sync::{Mutex, PoisonError, RwLock};
18use std::time::{Duration, Instant};
19
20use jiff::Timestamp;
21use uuid::Uuid;
22
23use super::PeeringError;
24use super::channel::{PinnedTrust, VerifiedPeer, admit_device, admit_directory};
25
26/// The persisted anti-rollback floor: the highest device-directory version this device has
27/// verified. Implementations must be monotonic — [`record`](Self::record) never lowers it — and
28/// durable across restarts, or a reboot readmits a stale directory.
29pub trait DirectoryVersions: Send + Sync {
30    /// The highest version recorded so far (`0` when none).
31    fn highest(&self) -> Result<u64, PeeringError>;
32
33    /// Record that `version` verified; the floor becomes `max(floor, version)`.
34    fn record(&self, version: u64) -> Result<(), PeeringError>;
35}
36
37/// An in-memory [`DirectoryVersions`]: monotonic for the life of the process.
38#[derive(Debug, Default)]
39pub struct MemoryDirectoryVersions(AtomicU64);
40
41impl MemoryDirectoryVersions {
42    /// A floor starting at `version` — what a device restores from its persisted value.
43    #[must_use]
44    pub fn starting_at(version: u64) -> Self {
45        Self(AtomicU64::new(version))
46    }
47}
48
49impl DirectoryVersions for MemoryDirectoryVersions {
50    fn highest(&self) -> Result<u64, PeeringError> {
51        Ok(self.0.load(Ordering::Acquire))
52    }
53
54    fn record(&self, version: u64) -> Result<(), PeeringError> {
55        self.0.fetch_max(version, Ordering::AcqRel);
56        Ok(())
57    }
58}
59
60/// Handshake attempts admitted per source address within one window, by default.
61pub const DEFAULT_HANDSHAKES_PER_WINDOW: usize = 8;
62
63/// The default rate-limit window.
64pub const DEFAULT_HANDSHAKE_WINDOW: Duration = Duration::from_secs(60);
65
66/// The most source addresses the limiter tracks at once, bounding its memory. When a new source
67/// finds the table full, idle sources are pruned, and if it is still full of live ones the
68/// least recently active source is evicted: a full table never refuses a new source.
69pub const MAX_TRACKED_SOURCES: usize = 1024;
70
71/// A sliding-window handshake rate limit per source address.
72#[derive(Debug)]
73pub struct HandshakeLimiter {
74    max_attempts: usize,
75    window: Duration,
76    attempts: Mutex<HashMap<IpAddr, VecDeque<Instant>>>,
77}
78
79impl Default for HandshakeLimiter {
80    fn default() -> Self {
81        Self::new(DEFAULT_HANDSHAKES_PER_WINDOW, DEFAULT_HANDSHAKE_WINDOW)
82    }
83}
84
85impl HandshakeLimiter {
86    /// Admit at most `max_attempts` handshakes per source address in any `window`.
87    #[must_use]
88    pub fn new(max_attempts: usize, window: Duration) -> Self {
89        Self {
90            max_attempts,
91            window,
92            attempts: Mutex::new(HashMap::new()),
93        }
94    }
95
96    /// Whether a handshake from `source` at `now` is admitted. An admitted attempt counts against
97    /// the window; a refused one does not extend it. The table never holds more than
98    /// [`MAX_TRACKED_SOURCES`] sources: when a new source finds it full, idle sources are pruned,
99    /// and if it is still full of live ones the source whose latest attempt is oldest is evicted
100    /// (its budget is forgotten), so no flood of addresses can lock a new peer out. A poisoned
101    /// lock refuses (fail closed).
102    pub fn admit(&self, source: IpAddr, now: Instant) -> bool {
103        let Ok(mut attempts) = self.attempts.lock() else {
104            return false;
105        };
106        let window = self.window;
107        let live = |at: &Instant| now.saturating_duration_since(*at) < window;
108        if !attempts.contains_key(&source) && attempts.len() >= MAX_TRACKED_SOURCES {
109            attempts.retain(|_, seen| seen.iter().any(live));
110            let stalest = (attempts.len() >= MAX_TRACKED_SOURCES)
111                .then(|| {
112                    attempts
113                        .iter()
114                        .min_by_key(|(_, seen)| seen.back().copied())
115                        .map(|(evicted, _)| *evicted)
116                })
117                .flatten();
118            if let Some(evicted) = stalest {
119                attempts.remove(&evicted);
120                tracing::debug!(
121                    %source,
122                    %evicted,
123                    "handshake limiter full of live sources; evicted the least recently active"
124                );
125            }
126        }
127        let seen = attempts.entry(source).or_default();
128        while seen.front().is_some_and(|at| !live(at)) {
129            seen.pop_front();
130        }
131        if seen.len() >= self.max_attempts {
132            tracing::debug!(%source, attempts = seen.len(), "handshake attempt over the limit");
133            return false;
134        }
135        seen.push_back(now);
136        true
137    }
138
139    /// How many sources the table tracks — the bound tests assert.
140    #[cfg(test)]
141    pub(crate) fn tracked(&self) -> usize {
142        self.attempts.lock().map_or(0, |attempts| attempts.len())
143    }
144}
145
146/// Where the serving side of a channel reads the trust it authorizes **each request** against:
147/// the account's directory as this device pins it **now**, so a peer revoked mid-session is
148/// refused at its next request. An implementation that cannot produce current trust returns an
149/// error, and the request is refused (fail closed) rather than served under trust that may be
150/// stale.
151pub trait TrustSource: Send + Sync {
152    /// The trust pinned now.
153    fn current(
154        &self,
155    ) -> impl std::future::Future<Output = Result<PinnedTrust, PeeringError>> + Send;
156}
157
158/// Trust that never changes for the life of the session.
159impl TrustSource for PinnedTrust {
160    async fn current(&self) -> Result<PinnedTrust, PeeringError> {
161        Ok(self.clone())
162    }
163}
164
165/// Trust held in memory that its owner replaces as the directory refreshes: a session reading it
166/// sees each replacement at its next request.
167#[derive(Debug)]
168pub struct SharedTrust(RwLock<PinnedTrust>);
169
170impl SharedTrust {
171    /// Start from `trust`.
172    #[must_use]
173    pub fn new(trust: PinnedTrust) -> Self {
174        Self(RwLock::new(trust))
175    }
176
177    /// Replace the trust every later request is authorized against.
178    pub fn replace(&self, trust: PinnedTrust) {
179        *self.0.write().unwrap_or_else(PoisonError::into_inner) = trust;
180    }
181}
182
183impl TrustSource for SharedTrust {
184    async fn current(&self) -> Result<PinnedTrust, PeeringError> {
185        Ok(self
186            .0
187            .read()
188            .unwrap_or_else(PoisonError::into_inner)
189            .clone())
190    }
191}
192
193/// One established peering session, as the serving side tracks it: the verified peer, whether
194/// it has been cut off, and what it delivered when.
195#[derive(Debug)]
196pub struct PeerSession {
197    peer: Uuid,
198    cut_off: bool,
199    deliveries: Vec<(Uuid, Timestamp)>,
200}
201
202impl PeerSession {
203    /// A session with the peer the handshake verified.
204    #[must_use]
205    pub fn new(peer: &VerifiedPeer) -> Self {
206        Self {
207            peer: peer.device_id,
208            cut_off: false,
209            deliveries: Vec::new(),
210        }
211    }
212
213    /// The peer's directory device id.
214    #[must_use]
215    pub fn peer(&self) -> Uuid {
216        self.peer
217    }
218
219    /// Authorize the peer's next request against the trust pinned **now**: the directory must
220    /// still chain to the IK without rolling back, and the peer must still be enrolled and
221    /// un-revoked. A refusal cuts the session off for good, so a later request is refused even if
222    /// a caller retries with older trust.
223    pub fn authorize(
224        &mut self,
225        trust: &PinnedTrust,
226        versions: &dyn DirectoryVersions,
227    ) -> Result<(), PeeringError> {
228        if self.cut_off {
229            return Err(PeeringError::RevokedDevice(self.peer));
230        }
231        let verdict = admit_directory(trust, versions).and_then(|()| {
232            admit_device(trust, self.peer)?;
233            Ok(())
234        });
235        if let Err(error) = &verdict {
236            tracing::warn!(peer = %self.peer, %error, "peer request refused; session cut off");
237            self.cut_off = true;
238        }
239        verdict
240    }
241
242    /// Record that the peer delivered `asset` at `received_at`.
243    pub fn record_delivery(&mut self, asset: Uuid, received_at: Timestamp) {
244        self.deliveries.push((asset, received_at));
245    }
246
247    /// The assets this peer delivered at or after its revocation took effect under `trust` —
248    /// everything to quarantine. Empty while the peer is un-revoked. A peer absent from the
249    /// directory, or revoked at a time that does not parse, has every delivery quarantined
250    /// (fail closed).
251    #[must_use]
252    pub fn quarantined_deliveries(&self, trust: &PinnedTrust) -> Vec<Uuid> {
253        let effective = match trust.directory.device(&self.peer) {
254            Some(entry) => match entry.revoked_at.as_deref() {
255                None => return Vec::new(),
256                Some(at) => at.parse::<Timestamp>().ok(),
257            },
258            None => None,
259        };
260        let quarantined: Vec<Uuid> = self
261            .deliveries
262            .iter()
263            .filter(|(_, at)| effective.is_none_or(|revoked| *at >= revoked))
264            .map(|(asset, _)| *asset)
265            .collect();
266        tracing::info!(
267            peer = %self.peer,
268            quarantined = quarantined.len(),
269            "quarantining deliveries made after the peer's revocation"
270        );
271        quarantined
272    }
273}