1use 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#[derive(Debug, Clone)]
26pub struct KeyFile {
27 path: PathBuf,
28 cached: Arc<Mutex<Option<Cached>>>,
30}
31
32#[derive(Debug)]
33struct Cached {
34 stamp: Stamp,
35 verifier: JwtVerifier,
36}
37
38type Stamp = (SystemTime, u64);
40
41impl KeyFile {
42 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 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 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
105fn stamp(path: &Path) -> Option<Stamp> {
107 let meta = std::fs::metadata(path).ok()?;
108 Some((meta.modified().ok()?, meta.len()))
109}