iroh_live_node/claim.rs
1//! Ticket claims: widening a peer's grant to the one path a ticket names.
2
3use std::{
4 str::FromStr,
5 sync::{Arc, Weak},
6};
7
8use iroh::EndpointId;
9use moq_net::Path;
10use n0_error::e;
11use tracing::debug;
12
13use crate::{Error, Node, node::Shared, publish::check_path, state::ClaimRefused};
14
15/// A claim on one path of one peer, held for as long as it widens the peer's grant.
16///
17/// Created by [`Node::claim_path`]. Dropping the last claim on a path narrows
18/// the peer's sessions again. Not `Clone`: share it in an `Arc`.
19#[derive(derive_more::Debug)]
20#[debug("PathClaim({}, {})", peer.fmt_short(), path)]
21pub struct PathClaim {
22 peer: EndpointId,
23 path: Path,
24 /// `None` for a claim on the node's own paths, which widens nothing.
25 #[debug(skip)]
26 shared: Option<Weak<Shared>>,
27}
28
29impl PathClaim {
30 /// Returns the peer the claim is for.
31 #[must_use]
32 pub fn peer(&self) -> EndpointId {
33 self.peer
34 }
35
36 /// Returns the claimed path.
37 #[must_use]
38 pub fn path(&self) -> &Path {
39 &self.path
40 }
41}
42
43impl Drop for PathClaim {
44 fn drop(&mut self) {
45 let Some(shared) = self.shared.as_ref().and_then(Weak::upgrade) else {
46 return;
47 };
48 // A panic elsewhere may have poisoned the lock. Do not panic again.
49 if let Ok(mut state) = shared.state.lock() {
50 state.release_path(&self.peer, &self.path);
51 debug!(peer = %self.peer.fmt_short(), path = %self.path, "ticket claim released");
52 }
53 }
54}
55
56/// Reports whether `peer` owns `path` by the generic rule.
57///
58/// Exactly one segment is the peer's id in its canonical 64-hex spelling, and
59/// no other segment parses as an endpoint id. So a claimed path names its
60/// publisher and no other peer. A path beneath it that names a second id
61/// belongs to no one by this rule.
62pub(crate) fn owns_by_id(peer: &EndpointId, path: &Path) -> bool {
63 let own = peer.to_string();
64 let mut named = 0;
65 for part in path.parts() {
66 if part == own {
67 named += 1;
68 } else if EndpointId::from_str(part).is_ok() {
69 return false;
70 }
71 }
72 named == 1
73}
74
75impl Node {
76 /// Widens what `peer` may publish on this node to `path`, for as long as the claim lives.
77 ///
78 /// moq grants are prefixes, so the claim covers every path beneath `path`
79 /// too. This is how a ticket subscribe reads a path the node's grant would not
80 /// let the peer publish. The claim is added on top of each session's
81 /// grant, on every session with the peer, including ones that
82 /// start later. Dropping the last claim on a path narrows the grant again,
83 /// and moq then ends what local readers read at the path from the peer.
84 ///
85 /// A live session applies the wider grant a moment after this returns, so
86 /// a read of the path that starts at once may still be refused.
87 ///
88 /// A claim on a path of this node's own id is a no-op. A claim on a
89 /// path the peer owns is recorded even while the peer's authorization
90 /// (see [`authorization_for`](Self::authorization_for)) already lets it
91 /// publish there: it widens nothing then, and keeps the path if a
92 /// re-decide narrows the authorization. A path the peer does not own but its authorization
93 /// covers is a no-op claim.
94 ///
95 /// Otherwise the peer has to own the path: the
96 /// [`Layout::owner`](crate::layout::Layout::owner) of
97 /// [`NodeConfig::layout`](crate::NodeConfig::layout) decides if it is
98 /// set. Otherwise exactly one segment of the path is the peer's endpoint
99 /// id, and no other segment parses as one. The claimed path itself then
100 /// belongs to the peer. The paths beneath it that the claim also covers
101 /// belong to the peer or to no one, provided the layout's ownership
102 /// carries down to sub-paths, as [`Layout`](crate::layout::Layout)
103 /// requires. Hop pinning and the route table rely on that.
104 ///
105 /// # Errors
106 ///
107 /// Fails with [`Error::NotOwner`] if the peer neither owns the path nor
108 /// may publish there, [`Error::TooManyClaims`] if the peer already holds
109 /// 64 claimed paths or 16 KiB of them, and [`Error::ShutDown`] once the
110 /// node has shut down.
111 pub fn claim_path(&self, peer: EndpointId, path: &Path) -> Result<PathClaim, Error> {
112 if self.shared.shutdown.is_cancelled() {
113 return Err(e!(Error::ShutDown));
114 }
115 check_path(path)?;
116 // Only the authorization the peer already holds counts here: the
117 // policy is async, and a claim must not wait for it.
118 let granted = || {
119 self.authorization_for(peer)
120 .is_some_and(|authorization| authorization.grant.allows_publish(path.as_str()))
121 };
122 let unrecorded = || PathClaim {
123 peer,
124 path: path.clone(),
125 shared: None,
126 };
127 if peer == self.shared.id {
128 return Ok(unrecorded());
129 }
130 let owned = match &self.shared.layout {
131 Some(layout) => layout.owner(path.as_str()) == Some(peer),
132 None => owns_by_id(&peer, path),
133 };
134 if !owned {
135 // The authorization alone allows the path, so there is nothing to keep.
136 if granted() {
137 return Ok(unrecorded());
138 }
139 return Err(e!(Error::NotOwner {
140 path: path.clone(),
141 peer
142 }));
143 }
144 self.shared
145 .state
146 .lock()
147 .expect("poisoned")
148 .claim_path(peer, path)
149 .map_err(|refused| match refused {
150 ClaimRefused::Closed => e!(Error::ShutDown),
151 ClaimRefused::TooMany => e!(Error::TooManyClaims { peer }),
152 })?;
153 debug!(peer = %peer.fmt_short(), %path, "ticket path claimed");
154 Ok(PathClaim {
155 peer,
156 path: path.clone(),
157 shared: Some(Arc::downgrade(&self.shared)),
158 })
159 }
160}
161
162#[cfg(test)]
163mod tests {
164 use iroh::SecretKey;
165
166 use super::*;
167
168 fn path(path: &str) -> Path {
169 Path::new(path).expect("a path")
170 }
171
172 #[test]
173 fn a_path_naming_the_peer_once_is_its_own() {
174 let peer = SecretKey::generate().public();
175 assert!(owns_by_id(&peer, &path(&format!("live/{peer}/cam"))));
176 assert!(owns_by_id(&peer, &path(&format!("{peer}"))));
177 assert!(owns_by_id(&peer, &path(&format!("a/b/{peer}"))));
178 }
179
180 #[test]
181 fn a_path_naming_another_peer_or_none_is_not_its_own() {
182 let (peer, other) = (
183 SecretKey::generate().public(),
184 SecretKey::generate().public(),
185 );
186 assert!(!owns_by_id(&peer, &path("live/cam")));
187 assert!(!owns_by_id(&peer, &path(&format!("live/{other}/cam"))));
188 assert!(!owns_by_id(&peer, &path(&format!("live/{peer}/{other}"))));
189 assert!(!owns_by_id(&peer, &path(&format!("live/{peer}/{peer}"))));
190 }
191
192 #[test]
193 fn only_the_canonical_spelling_of_the_id_counts() {
194 let peer = SecretKey::generate().public();
195 let upper = peer.to_string().to_ascii_uppercase();
196 assert!(!owns_by_id(&peer, &path(&format!("live/{upper}/cam"))));
197 }
198}