Skip to main content

moq_ext_access/
policy.rs

1//! Admission and authorization of sessions, decided by a [`Policy`].
2//!
3//! A node asks its policy when a session opens, in either direction, and
4//! again later (see [`Event`]). The answer is a [`Decision`]. The building
5//! blocks compose:
6//!
7//! - [`Open`] and [`Closed`] admit or reject everyone.
8//! - [`from_fn`] decides with a synchronous closure.
9//! - [`Policy::filter`] narrows a policy by a predicate.
10//! - [`Queue`] hands each decision to the application.
11//! - [`Verify`] decides with a [`TokenVerifier`] when the peer presents a
12//!   token, and with a fallback policy when it does not.
13//!
14//! # Examples
15//!
16//! Admit everyone to subscribe, except one peer:
17//!
18//! ```
19//! use moq_ext_access::{
20//!     Grant,
21//!     policy::{self, Policy},
22//! };
23//!
24//! let policy = policy::Open(Grant::subscribe_only())
25//!     .filter(|request: &policy::PeerRequest<String>| request.peer() != "mallory");
26//! # drop(policy);
27//! ```
28
29use std::{
30    fmt,
31    future::Future,
32    pin::Pin,
33    sync::Arc,
34    time::{Duration, SystemTime},
35};
36
37use n0_future::future;
38
39#[cfg(feature = "jwt")]
40pub use self::jwt::JwtVerifier;
41#[cfg(feature = "rcan")]
42pub use self::rcan::{MAX_LINK_BYTES, MAX_LINKS, MoqCapability, RcanVerifier, encode_chain};
43pub use self::{
44    queue::{Pending, Queue},
45    verify::{TokenVerifier, Verify},
46};
47use crate::{Direction, Grant, PeerId, SessionRequest};
48
49#[cfg(feature = "jwt")]
50mod jwt;
51mod queue;
52#[cfg(feature = "rcan")]
53mod rcan;
54mod verify;
55
56/// A peer's request for a session, as a policy sees it.
57#[derive(Debug, Clone)]
58pub struct PeerRequest<P: PeerId> {
59    peer: P,
60    request: SessionRequest,
61    direction: Direction,
62    event: Event,
63}
64
65impl<P: PeerId> PeerRequest<P> {
66    /// Creates a request of `peer` for a session it opened, as a node asks its policy.
67    #[must_use]
68    pub fn new(peer: P, request: SessionRequest, event: Event) -> Self {
69        Self {
70            peer,
71            request,
72            direction: Direction::Accepted,
73            event,
74        }
75    }
76
77    /// Returns this request with `direction` saying which side opens the session.
78    ///
79    /// For a session this node dials, the request is the one the node sends.
80    #[must_use]
81    pub fn with_direction(mut self, direction: Direction) -> Self {
82        self.direction = direction;
83        self
84    }
85
86    /// Returns the peer, as the transport authenticated it.
87    #[must_use]
88    pub fn peer(&self) -> &P {
89        &self.peer
90    }
91
92    /// Returns which side opened the session.
93    #[must_use]
94    pub fn direction(&self) -> Direction {
95        self.direction
96    }
97
98    /// Returns why the node asks.
99    #[must_use]
100    pub fn event(&self) -> Event {
101        self.event
102    }
103
104    /// Returns the path the session requested, without its query.
105    #[must_use]
106    pub fn path(&self) -> &str {
107        self.request.path()
108    }
109
110    /// Returns a query parameter of the session's request.
111    #[must_use]
112    pub fn query(&self, key: &str) -> Option<&str> {
113        self.request.query(key)
114    }
115
116    /// Returns the token the peer presented, as [`SessionRequest::token`] does.
117    #[must_use]
118    pub fn token(&self) -> Option<&str> {
119        self.request.token()
120    }
121}
122
123/// Why a node asks its policy.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum Event {
126    /// A session opens.
127    Connect,
128    /// A live session is decided again, because its authorization expired or the application asked.
129    Reauthorize,
130}
131
132/// A policy's answer: the session's rights, or a rejection that closes it.
133pub type Decision = Result<Authorization, Rejection>;
134
135/// What an admitted session may do, and until when.
136#[derive(Debug, Clone, Default, PartialEq, Eq)]
137pub struct Authorization {
138    /// What the peer may subscribe to and publish.
139    pub grant: Grant,
140    /// When the node decides again, such as when a token expires.
141    pub expires: Option<SystemTime>,
142}
143
144impl From<Grant> for Authorization {
145    fn from(grant: Grant) -> Self {
146        Self {
147            grant,
148            ..Default::default()
149        }
150    }
151}
152
153/// Why a policy rejected a session.
154///
155/// The peer sees [`code`](Self::code), and [`reason`](Self::reason) stays local.
156#[derive(Debug, Clone)]
157pub struct Rejection {
158    code: moq_net::Error,
159    reason: String,
160}
161
162impl Rejection {
163    /// Creates a rejection that closes the session with [`moq_net::Error::Unauthorized`].
164    #[must_use]
165    pub fn new(reason: impl Into<String>) -> Self {
166        Self {
167            code: moq_net::Error::Unauthorized,
168            reason: reason.into(),
169        }
170    }
171
172    /// Returns this rejection with another close code, such as [`moq_net::Error::App`].
173    #[must_use]
174    pub fn with_code(mut self, code: moq_net::Error) -> Self {
175        self.code = code;
176        self
177    }
178
179    /// Returns the code the session closes with.
180    #[must_use]
181    pub fn code(&self) -> &moq_net::Error {
182        &self.code
183    }
184
185    /// Returns why the policy rejected the session.
186    #[must_use]
187    pub fn reason(&self) -> &str {
188        &self.reason
189    }
190}
191
192impl fmt::Display for Rejection {
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        write!(f, "{} ({})", self.reason, self.code)
195    }
196}
197
198impl std::error::Error for Rejection {}
199
200/// A rule that decides whether a peer may hold a session, and with which rights.
201///
202/// Implement it with `async fn decide`.
203pub trait Policy<P: PeerId>: fmt::Debug + Send + Sync + 'static {
204    /// Decides whether the peer may hold a session, and with which rights.
205    ///
206    /// A node drops the future on its decide timeout and when it shuts down,
207    /// so an implementation must tolerate cancellation at any await.
208    fn decide(&self, request: &PeerRequest<P>) -> impl Future<Output = Decision> + Send;
209
210    /// Returns a policy that rejects the peers `admit` refuses, and asks this one otherwise.
211    ///
212    /// The predicate is not watched: when the state it reads changes, tell
213    /// the node to decide again.
214    fn filter<F>(self, admit: F) -> Filter<Self, F>
215    where
216        Self: Sized,
217        F: Fn(&PeerRequest<P>) -> bool + Send + Sync + 'static,
218    {
219        Filter { inner: self, admit }
220    }
221}
222
223/// A [`Policy`] with its type erased, as a node stores it.
224///
225/// `Arc<dyn DynPolicy<P>>` implements [`Policy`]. Implement [`Policy`], not
226/// this trait.
227pub trait DynPolicy<P: PeerId>: fmt::Debug + Send + Sync + 'static {
228    /// Decides as [`Policy::decide`] does, with a boxed future.
229    fn decide<'a>(
230        &'a self,
231        request: &'a PeerRequest<P>,
232    ) -> Pin<Box<dyn Future<Output = Decision> + Send + 'a>>;
233}
234
235impl<P: PeerId, T: Policy<P>> DynPolicy<P> for T {
236    fn decide<'a>(
237        &'a self,
238        request: &'a PeerRequest<P>,
239    ) -> Pin<Box<dyn Future<Output = Decision> + Send + 'a>> {
240        Box::pin(Policy::decide(self, request))
241    }
242}
243
244impl<P: PeerId> Policy<P> for Arc<dyn DynPolicy<P>> {
245    async fn decide(&self, request: &PeerRequest<P>) -> Decision {
246        DynPolicy::decide(&**self, request).await
247    }
248}
249
250/// A policy that admits everyone with one grant.
251///
252/// A node's default policy is `Open(Grant::subscribe_only())`.
253#[derive(Debug, Clone, PartialEq, Eq)]
254pub struct Open(pub Grant);
255
256impl<P: PeerId> Policy<P> for Open {
257    fn decide(&self, _request: &PeerRequest<P>) -> impl Future<Output = Decision> + Send {
258        future::ready(Ok(self.0.clone().into()))
259    }
260}
261
262/// A policy that rejects everyone.
263#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
264pub struct Closed;
265
266impl<P: PeerId> Policy<P> for Closed {
267    fn decide(&self, _request: &PeerRequest<P>) -> impl Future<Output = Decision> + Send {
268        future::ready(Err(Rejection::new("closed")))
269    }
270}
271
272/// Returns a policy that decides with the synchronous closure `decide`.
273///
274/// # Examples
275///
276/// ```
277/// use moq_ext_access::{
278///     Grant,
279///     policy::{self, PeerRequest, Rejection},
280/// };
281///
282/// let policy = policy::from_fn(|request: &PeerRequest<String>| {
283///     if request.token() == Some("secret") {
284///         Ok(Grant::everything().into())
285///     } else {
286///         Err(Rejection::new("no valid token"))
287///     }
288/// });
289/// # drop(policy);
290/// ```
291#[must_use]
292pub fn from_fn<P, F>(decide: F) -> FromFn<F>
293where
294    P: PeerId,
295    F: Fn(&PeerRequest<P>) -> Decision + Send + Sync + 'static,
296{
297    FromFn(decide)
298}
299
300/// A policy that decides with a closure, built by [`from_fn`].
301#[derive(Clone)]
302pub struct FromFn<F>(F);
303
304impl<F> fmt::Debug for FromFn<F> {
305    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306        f.write_str("FromFn(..)")
307    }
308}
309
310impl<P, F> Policy<P> for FromFn<F>
311where
312    P: PeerId,
313    F: Fn(&PeerRequest<P>) -> Decision + Send + Sync + 'static,
314{
315    fn decide(&self, request: &PeerRequest<P>) -> impl Future<Output = Decision> + Send {
316        future::ready((self.0)(request))
317    }
318}
319
320/// A policy that rejects the peers a predicate refuses, built by [`Policy::filter`].
321#[derive(Clone)]
322pub struct Filter<T, F> {
323    inner: T,
324    admit: F,
325}
326
327impl<T: fmt::Debug, F> fmt::Debug for Filter<T, F> {
328    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329        f.debug_struct("Filter")
330            .field("inner", &self.inner)
331            .finish_non_exhaustive()
332    }
333}
334
335impl<P, T, F> Policy<P> for Filter<T, F>
336where
337    P: PeerId,
338    T: Policy<P>,
339    F: Fn(&PeerRequest<P>) -> bool + Send + Sync + 'static,
340{
341    async fn decide(&self, request: &PeerRequest<P>) -> Decision {
342        if !(self.admit)(request) {
343            return Err(Rejection::new("filtered"));
344        }
345        self.inner.decide(request).await
346    }
347}
348
349/// Asks `policy` about `request` within `timeout`, as a node does before it admits a session.
350///
351/// A policy that takes longer is a rejection with
352/// [`moq_net::Error::Timeout`].
353///
354/// Needs a tokio runtime with time enabled. Dropping the future drops the
355/// policy's.
356pub async fn decide_within<P: PeerId>(
357    policy: &dyn DynPolicy<P>,
358    request: &PeerRequest<P>,
359    timeout: Duration,
360) -> Decision {
361    n0_future::time::timeout(timeout, policy.decide(request))
362        .await
363        .unwrap_or_else(|_| Err(too_slow()))
364}
365
366/// Returns the rejection of a policy that did not decide in time.
367fn too_slow() -> Rejection {
368    Rejection::new("the policy did not decide in time").with_code(moq_net::Error::Timeout)
369}
370
371#[cfg(test)]
372mod tests;