1use 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#[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 #[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 #[must_use]
81 pub fn with_direction(mut self, direction: Direction) -> Self {
82 self.direction = direction;
83 self
84 }
85
86 #[must_use]
88 pub fn peer(&self) -> &P {
89 &self.peer
90 }
91
92 #[must_use]
94 pub fn direction(&self) -> Direction {
95 self.direction
96 }
97
98 #[must_use]
100 pub fn event(&self) -> Event {
101 self.event
102 }
103
104 #[must_use]
106 pub fn path(&self) -> &str {
107 self.request.path()
108 }
109
110 #[must_use]
112 pub fn query(&self, key: &str) -> Option<&str> {
113 self.request.query(key)
114 }
115
116 #[must_use]
118 pub fn token(&self) -> Option<&str> {
119 self.request.token()
120 }
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum Event {
126 Connect,
128 Reauthorize,
130}
131
132pub type Decision = Result<Authorization, Rejection>;
134
135#[derive(Debug, Clone, Default, PartialEq, Eq)]
137pub struct Authorization {
138 pub grant: Grant,
140 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#[derive(Debug, Clone)]
157pub struct Rejection {
158 code: moq_net::Error,
159 reason: String,
160}
161
162impl Rejection {
163 #[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 #[must_use]
174 pub fn with_code(mut self, code: moq_net::Error) -> Self {
175 self.code = code;
176 self
177 }
178
179 #[must_use]
181 pub fn code(&self) -> &moq_net::Error {
182 &self.code
183 }
184
185 #[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
200pub trait Policy<P: PeerId>: fmt::Debug + Send + Sync + 'static {
204 fn decide(&self, request: &PeerRequest<P>) -> impl Future<Output = Decision> + Send;
209
210 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
223pub trait DynPolicy<P: PeerId>: fmt::Debug + Send + Sync + 'static {
228 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#[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#[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#[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#[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#[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
349pub 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
366fn 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;