1use 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
16pub const MAX_LINKS: usize = 8;
18
19pub const MAX_LINK_BYTES: usize = 2 * 1024;
21
22const PREFIX: &str = "rcan1:";
26
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(into = "Wire", try_from = "Wire")]
41pub struct MoqCapability {
42 pub root: String,
44 pub publish: Prefixes,
46 pub subscribe: Prefixes,
48}
49
50impl MoqCapability {
51 #[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 #[must_use]
63 pub fn with_publish(mut self, publish: impl Into<Prefixes>) -> Self {
64 self.publish = publish.into();
65 self
66 }
67
68 #[must_use]
70 pub fn with_subscribe(mut self, subscribe: impl Into<Prefixes>) -> Self {
71 self.subscribe = subscribe.into();
72 self
73 }
74
75 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#[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 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
147fn 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
160fn 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 if head.contains('*') {
173 return Err(InvalidPrefix::Wildcard(text.to_owned()));
174 }
175 head.parse()
176}
177
178#[derive(Debug, Clone)]
217pub struct RcanVerifier {
218 principal: VerifyingKey,
219 root: String,
220}
221
222impl RcanVerifier {
223 #[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 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 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
286fn 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#[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
316fn 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
349fn 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;