Skip to main content

moq_ext_access/policy/
rcan.rs

1//! A token verifier for rcan capability chains, bound to the peer's key.
2
3use std::{
4    borrow::Borrow,
5    time::{Duration, SystemTime},
6};
7
8use ed25519_dalek::VerifyingKey;
9use moq_net::{InvalidPrefix, Prefix, Prefixes};
10use rcan::{Authorizer, Capability, Expires, Rcan};
11use serde::{Deserialize, Serialize};
12
13use super::{Authorization, Decision, PeerRequest, Rejection, TokenVerifier};
14use crate::{Grant, PeerId};
15
16/// The most links a capability chain may have.
17pub const MAX_LINKS: usize = 8;
18
19/// The most bytes one encoded link of a capability chain may take.
20pub const MAX_LINK_BYTES: usize = 2 * 1024;
21
22/// The prefix of an encoded capability chain.
23///
24/// The `1` names rcan's version-1 token format, which this crate reads.
25const PREFIX: &str = "rcan1:";
26
27/// What a holder may do at a moq node: publish and subscribe under a root.
28///
29/// The prefixes are relative to [`root`](Self::root), as in a moq-auth JWT,
30/// and each covers its path and every path beneath it. One capability permits
31/// another when its paths cover the other's.
32///
33/// On the wire each prefix is spelled as the subtree pattern it covers,
34/// `foo/**` or `**`, which verifiers from before prefixes read the same way.
35/// A chain from such a verifier's era whose members are literal paths, such
36/// as `bob/cam` or `""`, does not verify: rcan checks a link's signature over
37/// the capability written again, and a literal is now written as its
38/// subtree. Such a chain must be issued again.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(into = "Wire", try_from = "Wire")]
41pub struct MoqCapability {
42    /// The path the prefixes are relative to.
43    pub root: String,
44    /// The paths the holder may publish, relative to the root.
45    pub publish: Prefixes,
46    /// The paths the holder may subscribe to, relative to the root.
47    pub subscribe: Prefixes,
48}
49
50impl MoqCapability {
51    /// Returns a capability under `root` that grants nothing yet.
52    #[must_use]
53    pub fn new(root: impl Into<String>) -> Self {
54        Self {
55            root: root.into(),
56            publish: Prefixes::new(),
57            subscribe: Prefixes::new(),
58        }
59    }
60
61    /// Returns this capability with `publish` as the paths the holder may publish.
62    #[must_use]
63    pub fn with_publish(mut self, publish: impl Into<Prefixes>) -> Self {
64        self.publish = publish.into();
65        self
66    }
67
68    /// Returns this capability with `subscribe` as the paths the holder may subscribe to.
69    #[must_use]
70    pub fn with_subscribe(mut self, subscribe: impl Into<Prefixes>) -> Self {
71        self.subscribe = subscribe.into();
72        self
73    }
74
75    /// Returns the grant this capability gives, with absolute prefixes.
76    fn grant(&self) -> Result<Grant, InvalidPrefix> {
77        Ok(Grant {
78            subscribe: self.subscribe.rooted(&self.root)?,
79            publish: self.publish.rooted(&self.root)?,
80        })
81    }
82}
83
84impl Capability for MoqCapability {
85    fn permits(&self, other: &Self) -> bool {
86        match (self.grant(), other.grant()) {
87            (Ok(mine), Ok(theirs)) => {
88                mine.publish.covers(&theirs.publish) && mine.subscribe.covers(&theirs.subscribe)
89            }
90            _ => false,
91        }
92    }
93}
94
95/// The wire form of a [`MoqCapability`].
96///
97/// An enum, so a later kind of capability, such as one to serve paths to a
98/// set of peers, can join without breaking the tokens issued before it.
99#[derive(Clone, Serialize, Deserialize)]
100enum Wire {
101    Access {
102        root: String,
103        publish: Vec<String>,
104        subscribe: Vec<String>,
105    },
106}
107
108impl From<MoqCapability> for Wire {
109    /// Spells each prefix as the subtree pattern it covers, `foo/**` or `**`.
110    ///
111    /// Verifiers that read members as patterns then grant the same subtree,
112    /// and rcan checks a link's signature over the payload written again, so
113    /// a chain must read back to the bytes it was signed as.
114    fn from(capability: MoqCapability) -> Self {
115        let strings = |prefixes: &Prefixes| prefixes.iter().map(written_prefix).collect();
116        Self::Access {
117            publish: strings(&capability.publish),
118            subscribe: strings(&capability.subscribe),
119            root: capability.root,
120        }
121    }
122}
123
124impl TryFrom<Wire> for MoqCapability {
125    type Error = InvalidPrefix;
126
127    fn try_from(wire: Wire) -> Result<Self, Self::Error> {
128        let Wire::Access {
129            root,
130            publish,
131            subscribe,
132        } = wire;
133        let prefixes = |strings: Vec<String>| {
134            strings
135                .iter()
136                .map(|text| wire_prefix(text))
137                .collect::<Result<Prefixes, _>>()
138        };
139        Ok(Self {
140            root,
141            publish: prefixes(publish)?,
142            subscribe: prefixes(subscribe)?,
143        })
144    }
145}
146
147/// Spells a prefix as the subtree pattern it covers in a capability's wire form.
148///
149/// The empty prefix is `**`, and any other is `foo/**`, except a prefix
150/// already as deep as a path may be, which can have nothing beneath it and is
151/// written as is. [`wire_prefix`] reads each spelling back to the same prefix.
152fn written_prefix(prefix: &Prefix) -> String {
153    match prefix.as_str() {
154        "" => "**".to_owned(),
155        text if moq_net::path::parts(text).count() == moq_net::Path::MAX_PARTS => text.to_owned(),
156        text => format!("{text}/**"),
157    }
158}
159
160/// Parses a prefix of a capability's wire form.
161///
162/// A subtree is spelled `foo/**`, and every path `**`. Those read as the
163/// prefixes `foo` and the empty prefix. Any other wildcard is refused,
164/// including `/**`, which names no subtree. Other text parses as a prefix.
165fn wire_prefix(text: &str) -> Result<Prefix, InvalidPrefix> {
166    let head = match text.strip_suffix("/**") {
167        Some(head) if !head.is_empty() => head,
168        _ if text == "**" => "",
169        _ => text,
170    };
171    // A wildcard left in the head names something other than one subtree.
172    if head.contains('*') {
173        return Err(InvalidPrefix::Wildcard(text.to_owned()));
174    }
175    head.parse()
176}
177
178/// A [`TokenVerifier`] of rcan capability chains that a principal issued.
179///
180/// The principal is the key whose space the verifier shares, such as a
181/// node's own key or an app's account key. A chain starts with a
182/// [`MoqCapability`] the principal issued and may delegate it, narrowing
183/// it, up to [`MAX_LINKS`] links. Its last link must name the peer that
184/// presents it, as the transport authenticated it, so a stolen chain is
185/// useless without the peer's key.
186///
187/// A valid chain admits the peer with the last link's capability, which must
188/// lie within the verifier's root. The authorization expires with the
189/// earliest link: rcan's `valid_until` names the last second a link is
190/// valid, so the authorization expires one second after it.
191///
192/// The peer id must borrow as its 32-byte ed25519 public key, as iroh's
193/// `EndpointId` does.
194///
195/// # Examples
196///
197/// ```
198/// use ed25519_dalek::SigningKey;
199/// use moq_ext_access::policy::{MoqCapability, RcanVerifier, encode_chain};
200/// use rcan::{Expires, Rcan};
201///
202/// let alice = SigningKey::from_bytes(&[1; 32]);
203/// let device = SigningKey::from_bytes(&[2; 32]);
204/// let capability =
205///     MoqCapability::new("spaces/alice").with_publish("device".parse::<moq_net::Prefix>()?);
206/// let link = Rcan::issuing_builder(&alice, device.verifying_key(), capability)
207///     .sign(Expires::valid_for(std::time::Duration::from_secs(3600)));
208/// // The device presents this as its token:
209/// let token = encode_chain(&[link]);
210///
211/// // The node that shares alice's space verifies it:
212/// let verifier = RcanVerifier::new(alice.verifying_key(), "spaces/alice");
213/// # drop((token, verifier));
214/// # Ok::<_, moq_net::InvalidPrefix>(())
215/// ```
216#[derive(Debug, Clone)]
217pub struct RcanVerifier {
218    principal: VerifyingKey,
219    root: String,
220}
221
222impl RcanVerifier {
223    /// Creates a verifier for the chains `principal` issued under `root`.
224    #[must_use]
225    pub fn new(principal: VerifyingKey, root: impl Into<String>) -> Self {
226        Self {
227            principal,
228            root: root.into(),
229        }
230    }
231}
232
233impl<P> TokenVerifier<P> for RcanVerifier
234where
235    P: PeerId + Borrow<[u8; 32]>,
236{
237    fn verify(&self, token: &str, request: &PeerRequest<P>) -> Decision {
238        let invoker = VerifyingKey::from_bytes(request.peer().borrow())
239            .map_err(|_| Rejection::new("the peer id is not an ed25519 key"))?;
240        let chain = decode_chain(token)?;
241        let leaf = chain
242            .last()
243            .ok_or_else(|| Rejection::new("the capability chain is empty"))?
244            .capability()
245            .clone();
246        if !within(&leaf.root, &self.root) {
247            return Err(Rejection::new(format!(
248                "the capability's root {:?} is outside {:?}",
249                leaf.root, self.root
250            )));
251        }
252        let proofs: Vec<&Rcan<MoqCapability>> = chain.iter().collect();
253        if let Err(err) =
254            Authorizer::new(self.principal).check_invocation_from(invoker, leaf.clone(), &proofs)
255        {
256            // rcan fails an expired link like any other. Only a chain that
257            // runs from the principal to the invoker counts as expired, so a
258            // forged or foreign chain never picks its own rejection code.
259            let now = SystemTime::now();
260            if chain.iter().any(|link| !link.expires().is_valid_at(now))
261                && runs_between(&chain, &self.principal, &invoker)
262            {
263                return Err(Rejection::new("a link of the capability chain expired")
264                    .with_code(moq_net::Error::Expired));
265            }
266            return Err(Rejection::new(format!("invalid capability chain: {err:#}")));
267        }
268        let grant = leaf
269            .grant()
270            .map_err(|err| Rejection::new(format!("invalid capability: {err}")))?;
271        let expires = chain
272            .iter()
273            .filter_map(|link| match link.expires() {
274                Expires::Never => None,
275                // Valid through the whole second it names. A time beyond the
276                // clock's range is never, and the other links still bound it.
277                Expires::At(secs) => {
278                    SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(secs.saturating_add(1)))
279                }
280            })
281            .min();
282        Ok(Authorization { grant, expires })
283    }
284}
285
286/// Reports whether `chain` delegates `principal`'s capability link by link to `invoker`.
287fn runs_between(
288    chain: &[Rcan<MoqCapability>],
289    principal: &VerifyingKey,
290    invoker: &VerifyingKey,
291) -> bool {
292    let mut issuer = principal;
293    for link in chain {
294        if link.issuer() != issuer || link.capability_issuer() != principal {
295            return false;
296        }
297        issuer = link.audience();
298    }
299    issuer == invoker
300}
301
302/// Encodes a capability chain as a token, first link first.
303///
304/// The token is `rcan1:` and the lowercase, unpadded base32 of the postcard
305/// encoding of the links. A peer presents it as its session token, and a
306/// [`RcanVerifier`] reads it.
307#[must_use]
308pub fn encode_chain(chain: &[Rcan<MoqCapability>]) -> String {
309    let bytes = postcard::to_stdvec(chain).expect("encoding into a vec cannot fail");
310    let encoded = data_encoding::BASE32_NOPAD
311        .encode(&bytes)
312        .to_ascii_lowercase();
313    format!("{PREFIX}{encoded}")
314}
315
316/// Decodes a token from [`encode_chain`], within the size limits.
317///
318/// Decoding checks each link's signature.
319fn decode_chain(token: &str) -> Result<Vec<Rcan<MoqCapability>>, Rejection> {
320    let encoded = token
321        .strip_prefix(PREFIX)
322        .ok_or_else(|| Rejection::new("not an rcan capability chain"))?;
323    let limit = data_encoding::BASE32_NOPAD.encode_len(MAX_LINKS * MAX_LINK_BYTES);
324    if encoded.len() > limit {
325        return Err(Rejection::new("the capability chain is too large"));
326    }
327    let bytes = data_encoding::BASE32_NOPAD_NOCASE
328        .decode(encoded.as_bytes())
329        .map_err(|err| Rejection::new(format!("the capability chain is not base32: {err}")))?;
330    let chain: Vec<Rcan<MoqCapability>> = postcard::from_bytes(&bytes)
331        .map_err(|err| Rejection::new(format!("invalid capability chain: {err}")))?;
332    if chain.len() > MAX_LINKS {
333        return Err(Rejection::new(format!(
334            "the capability chain has {} links, more than {MAX_LINKS}",
335            chain.len()
336        )));
337    }
338    if chain
339        .iter()
340        .any(|link| link.encode().len() > MAX_LINK_BYTES)
341    {
342        return Err(Rejection::new(
343            "a link of the capability chain is too large",
344        ));
345    }
346    Ok(chain)
347}
348
349/// Reports whether `path` is `root` or lies below it, segment by segment.
350fn within(path: &str, root: &str) -> bool {
351    let (path, root) = (path.trim_matches('/'), root.trim_matches('/'));
352    root.is_empty()
353        || path == root
354        || path
355            .strip_prefix(root)
356            .is_some_and(|rest| rest.starts_with('/'))
357}
358
359#[cfg(test)]
360mod tests;