Skip to main content

moq_ext_access/policy/
jwt.rs

1//! A token verifier for JWTs, the tokens moq-relay reads.
2
3use std::{fmt, sync::Arc, time::SystemTime};
4
5use moq_auth::KeySet;
6
7use super::{Authorization, Decision, PeerRequest, Rejection, TokenVerifier};
8use crate::{Grant, PeerId};
9
10/// A [`TokenVerifier`] of JWTs, which checks them with a moq-auth [`KeySet`] as moq-relay does.
11///
12/// A valid token admits the peer with the publish and subscribe prefixes its
13/// claims grant at the requested path, and its `exp` claim becomes the
14/// authorization's expiry. A token whose root does not overlap the requested
15/// path is a rejection.
16///
17/// A JWT is a bearer token: whoever holds it may use it. When the peer has
18/// an iroh key, prefer a capability chain bound to that key, which a thief
19/// cannot use.
20///
21/// # Examples
22///
23/// ```
24/// use moq_ext_access::policy::{JwtVerifier, Verify};
25///
26/// let keys = moq_auth::KeySet::default();
27/// let policy = Verify::new(JwtVerifier::new(keys));
28/// # drop(policy);
29/// ```
30#[derive(Clone)]
31pub struct JwtVerifier {
32    keys: Arc<KeySet>,
33}
34
35impl fmt::Debug for JwtVerifier {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        f.debug_struct("JwtVerifier")
38            .field("keys", &self.keys.keys.len())
39            .finish()
40    }
41}
42
43impl JwtVerifier {
44    /// Creates a verifier that accepts tokens signed by a key in `keys`.
45    #[must_use]
46    pub fn new(keys: KeySet) -> Self {
47        Self {
48            keys: Arc::new(keys),
49        }
50    }
51
52    /// Verifies `token` and returns what it grants at `path`, as moq-relay reads it.
53    ///
54    /// The grant's prefixes are relative to `path`, and it expires with the
55    /// token.
56    ///
57    /// # Errors
58    ///
59    /// Fails with the moq-auth error if no key verifies the token, the token
60    /// expired, or its root does not overlap `path`.
61    pub fn verify_grant(
62        &self,
63        token: &str,
64        path: &str,
65    ) -> Result<moq_auth::Grant, moq_auth::Error> {
66        let claims = self.keys.verify(token)?;
67        let permissions = claims.authorize(path)?;
68        let mut grant = moq_auth::Grant::new(permissions.publish, permissions.subscribe);
69        grant.expires = claims.expires;
70        Ok(grant)
71    }
72}
73
74impl<P: PeerId> TokenVerifier<P> for JwtVerifier {
75    fn verify(&self, token: &str, request: &PeerRequest<P>) -> Decision {
76        let path = request.path();
77        let grant = self.verify_grant(token, path).map_err(rejection)?;
78        // The prefixes are relative to the requested path, and a grant names
79        // absolute paths.
80        let absolute = |prefixes: moq_auth::Prefixes| {
81            prefixes
82                .rooted(path)
83                .map_err(|err| Rejection::new(format!("invalid token path: {err}")))
84        };
85        Ok(Authorization {
86            grant: Grant {
87                subscribe: absolute(grant.subscribe.path)?,
88                publish: absolute(grant.publish.path)?,
89            },
90            expires: grant.expires.map(SystemTime::from),
91        })
92    }
93}
94
95/// Returns the rejection for a token moq-auth refuses.
96fn rejection(err: moq_auth::Error) -> Rejection {
97    let code = match err {
98        moq_auth::Error::TokenExpired => moq_net::Error::Expired,
99        _ => moq_net::Error::Unauthorized,
100    };
101    Rejection::new(format!("invalid token: {err}")).with_code(code)
102}
103
104#[cfg(test)]
105mod tests {
106    use std::time::Duration;
107
108    use moq_auth::{Algorithm, Claims, Key};
109
110    use super::*;
111    use crate::{SessionRequest, policy::Event};
112
113    fn keys() -> KeySet {
114        let key = Key::generate(Algorithm::HS256, None).expect("a key");
115        KeySet {
116            keys: vec![Arc::new(key)],
117        }
118    }
119
120    /// Returns claims under `spaces/alice` that let the holder publish under `bob/`.
121    fn claims() -> Claims {
122        Claims::default()
123            .with_root("spaces/alice")
124            .with_publish(["bob".parse().expect("a prefix")])
125            .with_subscribe([moq_auth::Prefix::all()])
126    }
127
128    fn sign(keys: &KeySet, claims: &Claims) -> String {
129        keys.sign(claims).expect("signed")
130    }
131
132    fn request(path: &str) -> PeerRequest<String> {
133        PeerRequest::new("bob".to_owned(), SessionRequest::new(path), Event::Connect)
134    }
135
136    fn verify(verifier: &JwtVerifier, token: &str, path: &str) -> Decision {
137        TokenVerifier::<String>::verify(verifier, token, &request(path))
138    }
139
140    #[test]
141    fn a_valid_token_admits_with_its_prefixes() {
142        let keys = keys();
143        let verifier = JwtVerifier::new(keys.clone());
144        let token = sign(&keys, &claims());
145        for path in ["/spaces/alice", "/", "/spaces/alice/bob"] {
146            let grant = verify(&verifier, &token, path).expect("admitted").grant;
147            assert!(grant.allows_publish("spaces/alice/bob/cam"), "at {path}");
148            assert!(!grant.allows_publish("spaces/alice/carol/cam"), "at {path}");
149            assert!(grant.allows_subscribe("spaces/alice/bob/cam"), "at {path}");
150            assert!(!grant.allows_subscribe("spaces/eve/cam"), "at {path}");
151        }
152    }
153
154    #[test]
155    fn a_token_for_another_root_rejects() {
156        let keys = keys();
157        let verifier = JwtVerifier::new(keys.clone());
158        let token = sign(&keys, &claims());
159        let rejection = verify(&verifier, &token, "/spaces/eve").expect_err("rejected");
160        assert!(matches!(rejection.code(), moq_net::Error::Unauthorized));
161    }
162
163    #[test]
164    fn an_expired_token_rejects() {
165        let keys = keys();
166        let verifier = JwtVerifier::new(keys.clone());
167        let mut claims = claims();
168        claims.expires = Some(
169            (SystemTime::now() - Duration::from_secs(60))
170                .try_into()
171                .expect("after 1970"),
172        );
173        let rejection = verify(&verifier, &sign(&keys, &claims), "/").expect_err("rejected");
174        assert!(
175            matches!(rejection.code(), moq_net::Error::Expired),
176            "{rejection}"
177        );
178    }
179
180    #[test]
181    fn a_token_signed_by_another_key_rejects() {
182        let verifier = JwtVerifier::new(keys());
183        let token = sign(&keys(), &claims());
184        let rejection = verify(&verifier, &token, "/").expect_err("rejected");
185        assert!(matches!(rejection.code(), moq_net::Error::Unauthorized));
186    }
187
188    #[test]
189    fn the_exp_claim_becomes_the_expiry() {
190        let keys = keys();
191        let verifier = JwtVerifier::new(keys.clone());
192        let expires = SystemTime::now() + Duration::from_secs(3600);
193        let mut claims = claims();
194        claims.expires = Some(expires.try_into().expect("after 1970"));
195        let authorization = verify(&verifier, &sign(&keys, &claims), "/").expect("admitted");
196        let got = authorization.expires.expect("an expiry");
197        // `exp` has whole seconds on the wire.
198        let gap = got
199            .duration_since(expires)
200            .unwrap_or_else(|err| err.duration());
201        assert!(gap < Duration::from_secs(1), "{got:?} vs {expires:?}");
202        let no_exp = verify(&verifier, &sign(&keys, &self::claims()), "/").expect("admitted");
203        assert_eq!(no_exp.expires, None);
204    }
205
206    #[test]
207    fn a_malformed_token_rejects_as_unauthorized() {
208        let verifier = JwtVerifier::new(keys());
209        for token in ["", "not-a-jwt", "a.b.c", "rcan1:aaaa"] {
210            let rejection = verify(&verifier, token, "/").expect_err(token);
211            assert!(
212                matches!(rejection.code(), moq_net::Error::Unauthorized),
213                "{token}: {rejection}"
214            );
215            assert!(
216                rejection.reason().starts_with("invalid token"),
217                "{rejection}"
218            );
219        }
220    }
221
222    #[test]
223    fn verify_grant_keeps_the_patterns_relative_to_the_path() {
224        let keys = keys();
225        let verifier = JwtVerifier::new(keys.clone());
226        let token = sign(&keys, &claims());
227        let grant = verifier
228            .verify_grant(&token, "spaces/alice")
229            .expect("admitted");
230        assert!(grant.publish.path.matches("bob/cam"));
231        assert!(!grant.publish.path.matches("spaces/alice/bob/cam"));
232        assert_eq!(grant.expires, None);
233        verifier
234            .verify_grant(&token, "spaces/eve")
235            .expect_err("another root");
236        verifier
237            .verify_grant("garbage", "spaces/alice")
238            .expect_err("not a token");
239    }
240
241    /// Signs a token whose claims are `payload`, a JSON object, as written.
242    ///
243    /// Returns the token and a key set that verifies it. moq-auth only signs
244    /// claims it would read back, so a token spelled as an earlier release
245    /// wrote it is signed here with an Ed25519 key.
246    #[cfg(feature = "rcan")]
247    fn sign_raw(payload: &str) -> (KeySet, String) {
248        use data_encoding::BASE64URL_NOPAD;
249        use ed25519_dalek::{Signer, SigningKey};
250        use moq_auth::{EllipticCurve, Jwk, KeyMaterial};
251
252        let signer = SigningKey::from_bytes(&[7; 32]);
253        let material = KeyMaterial::OKP {
254            curve: EllipticCurve::Ed25519,
255            x: signer.verifying_key().to_bytes().to_vec(),
256            d: Some(signer.to_bytes().to_vec()),
257        };
258        let key = Jwk::new(Algorithm::EdDSA, material)
259            .import()
260            .expect("a key");
261        let header = BASE64URL_NOPAD.encode(br#"{"alg":"EdDSA","typ":"JWT"}"#);
262        let body = BASE64URL_NOPAD.encode(payload.as_bytes());
263        let signed = format!("{header}.{body}");
264        let signature = BASE64URL_NOPAD.encode(&signer.sign(signed.as_bytes()).to_bytes());
265        let keys = KeySet {
266            keys: vec![Arc::new(key)],
267        };
268        (keys, format!("{signed}.{signature}"))
269    }
270
271    #[cfg(feature = "rcan")]
272    #[test]
273    fn a_subtree_claim_grants_its_subtree_and_another_wildcard_rejects() {
274        let (keys, token) = sign_raw(r#"{"root":"spaces/alice","publish":["bob/**"]}"#);
275        let grant = verify(&JwtVerifier::new(keys), &token, "/spaces/alice")
276            .expect("admitted")
277            .grant;
278        assert!(grant.allows_publish("spaces/alice/bob"));
279        assert!(grant.allows_publish("spaces/alice/bob/cam"));
280        assert!(!grant.allows_publish("spaces/alice/bobby"));
281
282        let (keys, token) = sign_raw(r#"{"root":"spaces/alice","publish":["*/cam"]}"#);
283        let rejection =
284            verify(&JwtVerifier::new(keys), &token, "/spaces/alice").expect_err("rejected");
285        assert!(
286            matches!(rejection.code(), moq_net::Error::Unauthorized),
287            "{rejection}"
288        );
289    }
290}