Skip to main content

iroh_live_relay/
keys.rs

1//! The JWT keys of iroh clients, read again when their file changes.
2
3use std::{
4    path::{Path, PathBuf},
5    sync::{Arc, Mutex},
6    time::SystemTime,
7};
8
9use iroh::EndpointId;
10use moq_ext_access::policy::{Decision, JwtVerifier, PeerRequest, Rejection, TokenVerifier};
11use tracing::{info, warn};
12
13use crate::Error;
14
15/// A [`TokenVerifier`] of JWTs with the keys in a file, read again when the file changes.
16///
17/// The file holds a JWK or a JWK set, as `--auth-key` takes it. Before each
18/// token the verifier compares the file's modification time and size with
19/// the ones it last read, as moq-auth's reference policy does for browsers,
20/// so a rotated or revoked key takes effect for the next session without a
21/// restart. A file that is gone or no longer holds a key rejects every token
22/// until it is fixed. Sessions already admitted keep their authorization.
23///
24/// Wrap it in a [`Verify`](moq_ext_access::policy::Verify) to use it as a policy.
25#[derive(Debug, Clone)]
26pub struct KeyFile {
27    path: PathBuf,
28    /// The keys as last read, with the stamp of the file they were read from.
29    cached: Arc<Mutex<Option<Cached>>>,
30}
31
32#[derive(Debug)]
33struct Cached {
34    stamp: Stamp,
35    verifier: JwtVerifier,
36}
37
38/// What identifies a version of the file: its modification time and size.
39type Stamp = (SystemTime, u64);
40
41impl KeyFile {
42    /// Reads the keys in `path`, which is read again whenever it changes.
43    ///
44    /// # Errors
45    ///
46    /// Fails with [`Error::Keys`] if the file holds neither a JWK nor a JWK set.
47    pub fn load(path: impl Into<PathBuf>) -> Result<Self, Error> {
48        let path = path.into();
49        let stamp = stamp(&path);
50        let (keys, _) = crate::load_keys(&path)?;
51        let cached = stamp.map(|stamp| Cached {
52            stamp,
53            verifier: JwtVerifier::new(keys),
54        });
55        Ok(Self {
56            path,
57            cached: Arc::new(Mutex::new(cached)),
58        })
59    }
60
61    /// Returns the verifier of the keys the file holds now.
62    fn current(&self) -> Result<JwtVerifier, Rejection> {
63        let unreadable = || {
64            Rejection::new("the relay cannot read its JWT keys")
65                .with_code(moq_net::Error::Unauthorized)
66        };
67        let mut cached = self.cached.lock().expect("poisoned");
68        // Stamped before reading, so a write that races the read is caught at the next token.
69        let Some(stamp) = stamp(&self.path) else {
70            warn!(path = %self.path.display(), "the JWT key file is gone, refusing tokens");
71            *cached = None;
72            return Err(unreadable());
73        };
74        if let Some(cached) = cached.as_ref().filter(|cached| cached.stamp == stamp) {
75            return Ok(cached.verifier.clone());
76        }
77        match crate::load_keys(&self.path) {
78            Ok((keys, _)) => {
79                info!(path = %self.path.display(), "read the changed JWT key file");
80                let verifier = JwtVerifier::new(keys);
81                *cached = Some(Cached {
82                    stamp,
83                    verifier: verifier.clone(),
84                });
85                Ok(verifier)
86            }
87            Err(err) => {
88                warn!(
89                    error = format_args!("{err:#}"),
90                    "the JWT key file holds no key, refusing tokens"
91                );
92                *cached = None;
93                Err(unreadable())
94            }
95        }
96    }
97}
98
99impl TokenVerifier<EndpointId> for KeyFile {
100    fn verify(&self, token: &str, request: &PeerRequest<EndpointId>) -> Decision {
101        self.current()?.verify(token, request)
102    }
103}
104
105/// Returns the stamp of the file at `path`, or `None` if it cannot be read.
106fn stamp(path: &Path) -> Option<Stamp> {
107    let meta = std::fs::metadata(path).ok()?;
108    Some((meta.modified().ok()?, meta.len()))
109}