Skip to main content

sapphire_framework_server/api_keys/
mod.rs

1//! The served workspace's API keys (#364): the HTTP layer's verifier.
2//!
3//! The keys live in the workspace (`<root>/.<app>/api_keys/`, see
4//! [`sapphire_framework_keys::store_dir`]), so they sync with it and no bridge is asked.
5
6mod import;
7
8pub use import::{IMPORTED_MARKER, ImportReport, import_external_devices};
9
10use std::path::PathBuf;
11use std::sync::{Arc, Mutex};
12use std::time::Duration;
13
14use sapphire_framework_keys::{
15    Authenticated, KeyProfiles, KeyVerifier, Verdict, Verifier, fill_missing_profiles, store_dir,
16};
17use sapphire_workspace::AppContext;
18
19use crate::selection::SelectionFile;
20
21/// Checks tokens against the keys of the workspace this application serves.
22///
23/// It finds the served root in the application's selection file (`workspace.toml`, which
24/// the server rewrites on a switch), parsing it again only when its text changed — not its
25/// modification time, which two writes within one tick share — and keeps one
26/// [`KeyVerifier`] — and so one cache — per root. With no workspace
27/// served, every token is refused. A key's profile gives its [`Access`]
28/// ([`KeyProfiles::standard`] unless [`profiles`](Self::profiles) says otherwise); a key
29/// of a profile the application does not offer is [`Verdict::Forbidden`].
30///
31/// [`Access`]: sapphire_framework_keys::Access
32pub struct WorkspaceKeyVerifier {
33    app: String,
34    file: SelectionFile,
35    ttl: Option<Duration>,
36    profiles: KeyProfiles,
37    state: Mutex<State>,
38}
39
40#[derive(Default)]
41struct State {
42    /// The selection file's text when last parsed (`None` inside: no file); `None` before
43    /// the first.
44    text: Option<Option<String>>,
45    root: Option<PathBuf>,
46    verifier: Option<Arc<KeyVerifier>>,
47}
48
49impl WorkspaceKeyVerifier {
50    /// The verifier for `ctx`'s application, on its own selection file.
51    pub fn for_app(ctx: &'static AppContext) -> WorkspaceKeyVerifier {
52        WorkspaceKeyVerifier::at(ctx.app_name, SelectionFile::for_app(ctx))
53    }
54
55    /// The verifier for `app_name`, on the selection file `file`.
56    pub fn at(app_name: &str, file: SelectionFile) -> WorkspaceKeyVerifier {
57        WorkspaceKeyVerifier {
58            app: app_name.to_owned(),
59            file,
60            ttl: None,
61            profiles: KeyProfiles::standard(),
62            state: Mutex::new(State::default()),
63        }
64    }
65
66    /// The application's own profiles, instead of the framework's three.
67    pub fn profiles(mut self, profiles: KeyProfiles) -> WorkspaceKeyVerifier {
68        self.profiles = profiles;
69        self
70    }
71
72    /// Trust a success for `ttl` instead of corundum's default.
73    pub fn cache_ttl(mut self, ttl: Duration) -> WorkspaceKeyVerifier {
74        self.ttl = Some(ttl);
75        self
76    }
77
78    /// The verifier for the root served now, if one is.
79    fn current(&self) -> Option<Arc<KeyVerifier>> {
80        // The file is a few lines; reading it is cheaper than being wrong about a switch.
81        let text = match std::fs::read_to_string(self.file.path()) {
82            Ok(text) => Some(text),
83            Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
84            Err(err) => {
85                tracing::warn!("could not read the served workspace: {err}");
86                return None;
87            }
88        };
89        let mut state = self.state.lock().expect("key verifier state");
90        if state.text.as_ref() != Some(&text) {
91            state.text = Some(text);
92            // The same text is not parsed (nor warned about) again.
93            let root = match self.file.load(&self.app) {
94                Ok(selection) => selection.map(|s| s.root),
95                Err(err) => {
96                    tracing::warn!("could not read the served workspace: {err}");
97                    None
98                }
99            };
100            if root != state.root {
101                state.verifier = root.as_deref().map(|root| {
102                    let dir = store_dir(&self.app, root);
103                    // Keys from before profiles, which corundum would skip.
104                    if let Err(err) = fill_missing_profiles(&dir) {
105                        tracing::warn!("could not give the API keys a profile: {err}");
106                    }
107                    let verifier = KeyVerifier::new(&dir);
108                    Arc::new(match self.ttl {
109                        Some(ttl) => verifier.cache_ttl(ttl),
110                        None => verifier,
111                    })
112                });
113                state.root = root;
114            }
115        }
116        state.verifier.clone()
117    }
118}
119
120/// Import the workgroup's external devices into the workspace at `root`, once per host
121/// (see [`import_external_devices`]). Failures are logged and retried at the next start.
122pub(crate) fn import_once(ctx: &AppContext, root: &std::path::Path) {
123    let bridge_dir = match std::env::var_os("SAPPHIRE_BRIDGE_DIR").filter(|v| !v.is_empty()) {
124        Some(dir) => PathBuf::from(dir),
125        None => match sapphire_workspace::dirs::data_dir() {
126            Some(dir) => dir.join(sapphire_ipc::BRIDGE_DIR_NAME),
127            None => return,
128        },
129    };
130    match import_external_devices(ctx.app_name, ctx.data_dir(), &bridge_dir, root) {
131        Ok(ImportReport { imported: 0, .. }) => {}
132        Ok(report) => tracing::info!(
133            imported = report.imported,
134            "the workgroup's external devices are now this workspace's API keys; the workgroup's ledger is no longer read: manage them with `api-key`"
135        ),
136        Err(err) => tracing::warn!("could not import the external devices: {err}"),
137    }
138}
139
140#[async_trait::async_trait]
141impl Verifier for WorkspaceKeyVerifier {
142    async fn verify(&self, token: &str) -> Verdict {
143        let Some(verifier) = self.current() else {
144            return Verdict::Refused;
145        };
146        let token = token.to_owned();
147        // A miss reads the store's files.
148        match tokio::task::spawn_blocking(move || verifier.verify(&token)).await {
149            Ok(corundum_framework_keys::Verdict::Accepted(key)) => {
150                match self.profiles.access(&key.profile) {
151                    Some(access) => Verdict::Accepted(Authenticated {
152                        id: key.id,
153                        name: key.name,
154                        profile: key.profile,
155                        access,
156                    }),
157                    None => Verdict::Forbidden,
158                }
159            }
160            Ok(corundum_framework_keys::Verdict::Refused) => Verdict::Refused,
161            Err(err) => {
162                tracing::error!("the key check did not finish: {err}");
163                Verdict::Refused
164            }
165        }
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172    use crate::selection::Selection;
173    use sapphire_framework_keys::open_store;
174
175    const APP: &str = "sapphire-keytest";
176
177    fn rw() -> sapphire_framework_keys::ProfileId {
178        sapphire_framework_keys::ProfileId::new(sapphire_framework_keys::READ_WRITE).unwrap()
179    }
180
181    struct Host {
182        _tmp: tempfile::TempDir,
183        file: SelectionFile,
184        a: PathBuf,
185        b: PathBuf,
186    }
187
188    fn host() -> Host {
189        let tmp = tempfile::tempdir().unwrap();
190        let a = tmp.path().join("a");
191        let b = tmp.path().join("b");
192        std::fs::create_dir_all(&a).unwrap();
193        std::fs::create_dir_all(&b).unwrap();
194        let file = SelectionFile::at(tmp.path().join("config").join("workspace.toml"));
195        Host {
196            _tmp: tmp,
197            file,
198            a,
199            b,
200        }
201    }
202
203    fn select(file: &SelectionFile, root: &std::path::Path) {
204        // A switch lands in a later instant than the read before it, as a real one does.
205        std::thread::sleep(Duration::from_millis(20));
206        file.save(&Selection {
207            root: root.to_owned(),
208            sync: false,
209        })
210        .unwrap();
211    }
212
213    fn accepted(v: Verdict) -> Option<String> {
214        match v {
215            Verdict::Accepted(who) => Some(who.name),
216            Verdict::Forbidden | Verdict::Refused => None,
217        }
218    }
219
220    #[tokio::test]
221    async fn the_access_is_the_profile_s() {
222        let h = host();
223        select(&h.file, &h.a);
224        let read_only = sapphire_framework_keys::ProfileId::new("read-only").unwrap();
225        let (_, token) = open_store(APP, &h.a)
226            .unwrap()
227            .add("p", None, read_only)
228            .unwrap();
229        let v = WorkspaceKeyVerifier::at(APP, h.file.clone());
230        let Verdict::Accepted(who) = v.verify(token.expose()).await else {
231            panic!("refused");
232        };
233        assert_eq!(who.profile.as_str(), "read-only");
234        assert_eq!(who.access, sapphire_framework_keys::Access::Read);
235    }
236
237    #[tokio::test]
238    async fn a_key_of_a_profile_the_app_does_not_offer_is_forbidden() {
239        let h = host();
240        select(&h.file, &h.a);
241        let gone = sapphire_framework_keys::ProfileId::new("room-gone").unwrap();
242        let (_, token) = open_store(APP, &h.a).unwrap().add("p", None, gone).unwrap();
243        let v = WorkspaceKeyVerifier::at(APP, h.file.clone());
244        assert_eq!(v.verify(token.expose()).await, Verdict::Forbidden);
245    }
246
247    #[tokio::test]
248    async fn an_app_s_own_profiles_decide() {
249        let h = host();
250        select(&h.file, &h.a);
251        let room = sapphire_framework_keys::ProfileId::new("room-1").unwrap();
252        let (_, token) = open_store(APP, &h.a).unwrap().add("p", None, room).unwrap();
253        let v = WorkspaceKeyVerifier::at(APP, h.file.clone()).profiles(
254            sapphire_framework_keys::KeyProfiles::new(Vec::new, |id| {
255                (id.as_str() == "room-1").then_some(sapphire_framework_keys::Access::Write)
256            }),
257        );
258        let Verdict::Accepted(who) = v.verify(token.expose()).await else {
259            panic!("refused");
260        };
261        assert_eq!(who.access, sapphire_framework_keys::Access::Write);
262    }
263
264    // A key file from before profiles, synced into the served workspace: read-only.
265    #[tokio::test]
266    async fn a_key_without_a_profile_is_read_only() {
267        let h = host();
268        let (key, token) = open_store(APP, &h.a).unwrap().add("p", None, rw()).unwrap();
269        let file = store_dir(APP, &h.a).join(format!("{}.toml", key.id));
270        let text = std::fs::read_to_string(&file).unwrap();
271        let old: String = text
272            .lines()
273            .filter(|l| !l.starts_with("profile"))
274            .map(|l| format!("{l}\n"))
275            .collect();
276        std::fs::write(&file, old).unwrap();
277        select(&h.file, &h.a);
278        let v = WorkspaceKeyVerifier::at(APP, h.file.clone());
279        let Verdict::Accepted(who) = v.verify(token.expose()).await else {
280            panic!("refused");
281        };
282        assert_eq!(who.access, sapphire_framework_keys::Access::Read);
283    }
284
285    #[tokio::test]
286    async fn key_in_workspace_is_accepted() {
287        let h = host();
288        select(&h.file, &h.a);
289        let (_, token) = open_store(APP, &h.a).unwrap().add("p", None, rw()).unwrap();
290        let v = WorkspaceKeyVerifier::at(APP, h.file.clone());
291        assert_eq!(
292            accepted(v.verify(token.expose()).await).as_deref(),
293            Some("p")
294        );
295        assert_eq!(accepted(v.verify("sapphire-ak-wrong").await), None);
296    }
297
298    #[tokio::test]
299    async fn retire_takes_effect_after_ttl() {
300        let h = host();
301        select(&h.file, &h.a);
302        let mut store = open_store(APP, &h.a).unwrap();
303        let (_, token) = store.add("p", None, rw()).unwrap();
304        let v = WorkspaceKeyVerifier::at(APP, h.file.clone()).cache_ttl(Duration::from_millis(300));
305        assert!(accepted(v.verify(token.expose()).await).is_some());
306        store.retire("p").unwrap();
307        tokio::time::sleep(Duration::from_millis(500)).await;
308        assert_eq!(accepted(v.verify(token.expose()).await), None);
309    }
310
311    #[tokio::test]
312    async fn copied_key_file_is_accepted() {
313        let h = host();
314        select(&h.file, &h.a);
315        let v = WorkspaceKeyVerifier::at(APP, h.file.clone());
316        // Made on another host's copy of the workspace, then synced here.
317        let elsewhere = tempfile::tempdir().unwrap();
318        let (key, token) = open_store(APP, elsewhere.path())
319            .unwrap()
320            .add("p", None, rw())
321            .unwrap();
322        let name = format!("{}.toml", key.id);
323        std::fs::create_dir_all(store_dir(APP, &h.a)).unwrap();
324        std::fs::copy(
325            store_dir(APP, elsewhere.path()).join(&name),
326            store_dir(APP, &h.a).join(&name),
327        )
328        .unwrap();
329        assert!(accepted(v.verify(token.expose()).await).is_some());
330    }
331
332    #[tokio::test]
333    async fn switch_changes_the_keys() {
334        let h = host();
335        let (_, in_a) = open_store(APP, &h.a).unwrap().add("a", None, rw()).unwrap();
336        let (_, in_b) = open_store(APP, &h.b).unwrap().add("b", None, rw()).unwrap();
337        select(&h.file, &h.a);
338        let v = WorkspaceKeyVerifier::at(APP, h.file.clone());
339        assert!(accepted(v.verify(in_a.expose()).await).is_some());
340        select(&h.file, &h.b);
341        assert_eq!(
342            accepted(v.verify(in_a.expose()).await),
343            None,
344            "the old workspace's key"
345        );
346        assert!(accepted(v.verify(in_b.expose()).await).is_some());
347    }
348
349    #[tokio::test]
350    async fn missing_root_refuses() {
351        let h = host();
352        let (_, token) = open_store(APP, &h.a).unwrap().add("p", None, rw()).unwrap();
353        select(&h.file, &h.a);
354        std::fs::remove_dir_all(&h.a).unwrap();
355        let v = WorkspaceKeyVerifier::at(APP, h.file.clone());
356        assert_eq!(accepted(v.verify(token.expose()).await), None);
357        assert!(
358            !h.a.exists(),
359            "the verifier must not recreate the workspace"
360        );
361    }
362
363    #[tokio::test]
364    async fn no_selection_refuses() {
365        let h = host();
366        let (_, token) = open_store(APP, &h.a).unwrap().add("p", None, rw()).unwrap();
367        h.file.clear().unwrap();
368        let v = WorkspaceKeyVerifier::at(APP, h.file.clone());
369        assert_eq!(accepted(v.verify(token.expose()).await), None);
370    }
371
372    #[tokio::test]
373    async fn a_switch_in_the_same_tick_is_seen() {
374        let h = host();
375        let (_, in_a) = open_store(APP, &h.a).unwrap().add("a", None, rw()).unwrap();
376        let (_, in_b) = open_store(APP, &h.b).unwrap().add("b", None, rw()).unwrap();
377        let save = |root: &std::path::Path| {
378            h.file
379                .save(&Selection {
380                    root: root.to_owned(),
381                    sync: false,
382                })
383                .unwrap()
384        };
385        save(&h.a);
386        let v = WorkspaceKeyVerifier::at(APP, h.file.clone());
387        assert!(accepted(v.verify(in_a.expose()).await).is_some());
388        let tick = std::fs::metadata(h.file.path())
389            .unwrap()
390            .modified()
391            .unwrap();
392        // Rewritten within the file system's timestamp tick (1 s on some): same mtime.
393        save(&h.b);
394        std::fs::File::options()
395            .write(true)
396            .open(h.file.path())
397            .unwrap()
398            .set_modified(tick)
399            .unwrap();
400        assert_eq!(
401            accepted(v.verify(in_a.expose()).await),
402            None,
403            "the old workspace's key"
404        );
405        assert!(accepted(v.verify(in_b.expose()).await).is_some());
406    }
407}