Skip to main content

tilo_dialogs/
chosen.rs

1//! The files a person chose for an app in the system file chooser, outside any workspace.
2//!
3//! Choosing a file in the session shell's chooser is the person's consent, and it gives the app
4//! that asked exactly what was chosen: the file to read for an Open, the file to write (created if
5//! it is new) for a Save, the folder and everything under it for a folder. Nothing else.
6//!
7//! A sandboxed app is handed the descriptor the chooser opened with the person's rights, and a
8//! reference that names the choice again (`/run/tilo/chosen/records/<token>/<name>`): an opaque
9//! path, never a host path the app could use itself. Reopening resolves the reference through this
10//! table, and answers nothing for a choice that is gone.
11//!
12//! The table is the session's one for everything it keeps of a choice, and it is kept as a record
13//! of the device it runs on ([`Store`], bound by the session to the device's own records): read
14//! and written through the same settings action as the device's other records, which only its
15//! person reaches, rather than living in a private file of this session. A choice inside a
16//! workspace is not here: it is a grant on the file's tree node, written through the workspace's
17//! own policy.
18
19use std::collections::{BTreeMap, HashMap};
20use std::ffi::{OsStr, OsString};
21use std::path::{Component, Path, PathBuf};
22use std::sync::atomic::{AtomicU64, Ordering};
23use std::sync::{Arc, OnceLock, RwLock};
24
25/// Where a chosen item is named from on every device: the app reaches nothing of it but the
26/// descriptor the chooser hands, and this path names the choice again later.
27pub const CHOSEN_ROOT: &str = "/run/tilo/chosen";
28
29/// The path segment device-record choices live under, below [`CHOSEN_ROOT`].
30const RECORDS: &str = "records";
31
32/// The device record the table is kept as, through [`Store`].
33pub const RECORD: &str = "chosen.files";
34
35/// One choice, as the device's record keeps it.
36#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
37pub struct Kept {
38    pub workspace: String,
39    pub app: String,
40    pub kind: String,
41    pub host: PathBuf,
42}
43
44/// Where the device keeps the table: its own records, read when the session starts and written as
45/// each choice is made.
46pub trait Store: Send + Sync {
47    /// What the record held when this session started.
48    fn load(&self) -> Vec<Kept>;
49    /// Keep `kept` as the record from now on.
50    fn keep(&self, kept: Vec<Kept>);
51    /// Follow the record from now on, handing `changed` what it holds each time the record changes
52    /// elsewhere: what another of the person's tools writes reaches the table as it lands. Whether
53    /// the record can be followed.
54    fn follow(&self, _changed: Arc<dyn Fn(Vec<Kept>) + Send + Sync>) -> bool {
55        false
56    }
57}
58
59/// The key a choice is made under: the workspace the app runs in and its package id, so the same
60/// app in another workspace sees none of it and no app reaches another's choices.
61#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
62pub struct AppKey {
63    workspace: String,
64    app: String,
65}
66
67impl AppKey {
68    /// The key for `app` running in `workspace`, or `None` when either is not a name the entries
69    /// can carry as one path component (a workspace id is letters, digits and `-`; a package id
70    /// adds `.` and `_`, and does not start with `.`).
71    #[must_use]
72    pub fn new(workspace: &str, app: &str) -> Option<Self> {
73        (is_workspace(workspace) && is_app(app)).then(|| Self {
74            workspace: workspace.to_owned(),
75            app: app.to_owned(),
76        })
77    }
78
79    #[must_use]
80    pub fn workspace(&self) -> &str {
81        &self.workspace
82    }
83
84    #[must_use]
85    pub fn app(&self) -> &str {
86        &self.app
87    }
88}
89
90pub(crate) fn is_workspace(name: &str) -> bool {
91    !name.is_empty()
92        && name.len() <= 64
93        && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
94}
95
96pub(crate) fn is_app(name: &str) -> bool {
97    !name.is_empty()
98        && name.len() <= 255
99        && !name.starts_with('.')
100        && name
101            .bytes()
102            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'))
103}
104
105/// What a choice allows the app.
106#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
107pub enum Kind {
108    Read,
109    /// One file to write, created if it does not exist yet: a Save. Its save sibling
110    /// (`.<name>.tilo-save`) may be written and renamed over it, so a save replaces the file whole
111    /// or not at all.
112    Save,
113    Folder {
114        write: bool,
115    },
116}
117
118impl Kind {
119    fn of_tag(tag: &str) -> Option<Self> {
120        Some(match tag {
121            "read" => Self::Read,
122            "save" => Self::Save,
123            "folder" => Self::Folder { write: false },
124            "folder-write" => Self::Folder { write: true },
125            _ => return None,
126        })
127    }
128
129    fn tag(self) -> &'static str {
130        match self {
131            Self::Read => "read",
132            Self::Save => "save",
133            Self::Folder { write: false } => "folder",
134            Self::Folder { write: true } => "folder-write",
135        }
136    }
137
138    /// Whether the app may change what the choice names.
139    #[must_use]
140    pub fn writes(self) -> bool {
141        matches!(self, Self::Save | Self::Folder { write: true })
142    }
143}
144
145/// One chosen file or folder of the host, behind a choice.
146#[derive(Clone, Debug, PartialEq, Eq)]
147pub struct Document {
148    /// The chosen file or folder on the host, resolved when it was chosen. For a [`Kind::Save`] of
149    /// a new file, the resolved folder joined with the chosen name.
150    pub host: PathBuf,
151    pub kind: Kind,
152}
153
154impl Document {
155    #[must_use]
156    pub fn name(&self) -> &OsStr {
157        self.host
158            .file_name()
159            .unwrap_or_else(|| OsStr::new("document"))
160    }
161
162    /// Where a save writes before its bytes replace the file.
163    #[must_use]
164    pub fn save_sibling(&self) -> Option<OsString> {
165        (self.kind == Kind::Save).then(|| {
166            let mut sibling = OsString::from(".");
167            sibling.push(self.name());
168            sibling.push(".tilo-save");
169            sibling
170        })
171    }
172}
173
174/// One choice, as a host hands it to the chooser and to the app.
175#[derive(Clone, Debug)]
176pub struct Chosen {
177    /// The path the app reaches it by: what names it again, never a host path.
178    pub reference: PathBuf,
179    /// Its name there.
180    pub name: String,
181    /// The host file or folder it is.
182    pub host: PathBuf,
183    /// What the person's choice allows.
184    pub kind: Kind,
185    /// Where a save writes before its bytes replace the file; `None` for anything but a save.
186    pub save_sibling: Option<OsString>,
187}
188
189#[derive(Debug)]
190pub enum GrantError {
191    /// What was chosen is not what the chooser asked for (a folder for a file, a missing file for
192    /// an Open, a symbolic link for a Save).
193    NotThatKind,
194    /// What was chosen could not be resolved on the host.
195    Io(std::io::Error),
196}
197
198impl std::fmt::Display for GrantError {
199    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200        match self {
201            Self::NotThatKind => f.write_str("the chosen item is not what was asked for"),
202            Self::Io(error) => write!(f, "the chosen item cannot be reached: {error}"),
203        }
204    }
205}
206
207impl std::error::Error for GrantError {}
208
209/// What one app in one workspace was given, and the order it was chosen in.
210#[derive(Default, PartialEq)]
211struct View {
212    documents: BTreeMap<String, Document>,
213    recent: Vec<String>,
214}
215
216impl View {
217    fn choose(&mut self, token: String, document: Document) -> bool {
218        if self.recent.first() == Some(&token) {
219            return false;
220        }
221        self.recent.retain(|kept| *kept != token);
222        self.recent.insert(0, token.clone());
223        self.documents.insert(token, document);
224        true
225    }
226
227    /// Add `document` behind those already in the view, as reading a kept table (newest first)
228    /// does.
229    fn keep_older(&mut self, token: String, document: Document) {
230        if let Some(held) = self.documents.get_mut(&token) {
231            *held = document;
232            return;
233        }
234        self.documents.insert(token.clone(), document);
235        self.recent.push(token);
236    }
237
238    fn by_recency(&self) -> impl Iterator<Item = (&String, &Document)> {
239        self.recent
240            .iter()
241            .filter_map(|token| self.documents.get_key_value(token))
242    }
243}
244
245type Views = HashMap<AppKey, View>;
246
247/// The files people chose for their apps outside any workspace, as this session reaches them.
248#[derive(Clone, Default)]
249pub struct ChosenTable {
250    views: Arc<RwLock<Views>>,
251    store: Arc<OnceLock<Arc<dyn Store>>>,
252    /// How often what the table holds changed: what a reader compares to tell whether any choice
253    /// moved since it last read.
254    revision: Arc<AtomicU64>,
255}
256
257impl ChosenTable {
258    #[must_use]
259    pub fn new() -> Self {
260        Self::default()
261    }
262
263    /// How often what the table holds changed. A number that moves each time a choice is made,
264    /// taken back, or read from the device's record.
265    #[must_use]
266    pub fn revision(&self) -> u64 {
267        self.revision.load(Ordering::Acquire)
268    }
269
270    fn changed(&self) {
271        self.revision.fetch_add(1, Ordering::AcqRel);
272    }
273
274    /// Keep the table as the device's record `store` holds, reading what it held now and following
275    /// it from then on, so a choice another of the person's tools makes reaches the table as it
276    /// lands.
277    ///
278    /// The read runs on a thread of its own, so a session starts without waiting on its records;
279    /// what was chosen earlier is there before any choice needs to know it.
280    pub fn bind(&self, store: Arc<dyn Store>) {
281        if self.store.set(store).is_err() {
282            return;
283        }
284        let table = self.clone();
285        let loaded = std::thread::Builder::new()
286            .name("tilo-chosen-load".into())
287            .spawn(move || {
288                table.load();
289                table.follow();
290            });
291        if let Err(error) = loaded {
292            tracing::warn!(%error, "the files people chose earlier are not read");
293        }
294    }
295
296    /// Follow the record the table is kept as from now on: each reading of it replaces what the
297    /// table holds.
298    fn follow(&self) {
299        let Some(store) = self.store.get().cloned() else {
300            return;
301        };
302        let table = self.clone();
303        // A store that cannot follow its record reads it when the table is bound only.
304        store.follow(Arc::new(move |kept| table.replace(kept)));
305    }
306
307    fn load(&self) {
308        let Some(store) = self.store.get().cloned() else {
309            return;
310        };
311        self.replace(store.load());
312    }
313
314    /// Hold `kept` as the table from now on, as the device's record keeps it, and say the table
315    /// changed where it did.
316    fn replace(&self, kept: Vec<Kept>) {
317        let mut views: Views = HashMap::new();
318        for kept in kept {
319            let (Some(key), Some(kind)) = (
320                AppKey::new(&kept.workspace, &kept.app),
321                Kind::of_tag(&kept.kind),
322            ) else {
323                continue;
324            };
325            let Ok(host) = resolve_choice(&kept.host, kind) else {
326                continue;
327            };
328            let document = Document { host, kind };
329            let token = token(&key, &document);
330            views.entry(key).or_default().keep_older(token, document);
331        }
332        let changed = self.views.write().is_ok_and(|mut held| {
333            if *held == views {
334                return false;
335            }
336            *held = views;
337            true
338        });
339        if changed {
340            self.changed();
341        }
342    }
343
344    fn keep(&self) {
345        let Some(store) = self.store.get() else {
346            return;
347        };
348        let Some(snapshot) = self.views.read().ok().map(|views| {
349            views
350                .iter()
351                .flat_map(|(key, view)| {
352                    view.by_recency().map(|(_, document)| Kept {
353                        workspace: key.workspace.clone(),
354                        app: key.app.clone(),
355                        kind: document.kind.tag().to_owned(),
356                        host: document.host.clone(),
357                    })
358                })
359                .collect::<Vec<_>>()
360        }) else {
361            return;
362        };
363        store.keep(snapshot);
364    }
365
366    /// Give `key` the item the person chose at `chosen`, as `kind`, and answer the choice the app
367    /// is handed. Choosing the same item again answers the same reference, so a recent file
368    /// reopens where it was, and makes it the most recent.
369    ///
370    /// # Errors
371    ///
372    /// [`GrantError::NotThatKind`] when `chosen` is not what `kind` needs; [`GrantError::Io`] when
373    /// it cannot be resolved.
374    pub fn grant(&self, key: &AppKey, chosen: &Path, kind: Kind) -> Result<Chosen, GrantError> {
375        let host = resolve_choice(chosen, kind)?;
376        let document = Document { host, kind };
377        let token = token(key, &document);
378        let changed = self.views.write().is_ok_and(|mut views| {
379            views
380                .entry(key.clone())
381                .or_default()
382                .choose(token.clone(), document.clone())
383        });
384        if changed {
385            self.keep();
386            self.changed();
387        }
388        Ok(entry(&token, document))
389    }
390
391    /// The document `token` names for `key`.
392    #[must_use]
393    pub fn document(&self, key: &AppKey, token: &str) -> Option<Document> {
394        self.views
395            .read()
396            .ok()?
397            .get(key)
398            .and_then(|view| view.documents.get(token).cloned())
399    }
400
401    /// The choice `reference` names for `key`, if it is one the person gave that app.
402    ///
403    /// The answer names the choice's own reference whatever `reference` asked for: a caller
404    /// checking what it may reach strips the reference from this one, and so refuses anything
405    /// that is not a plain name beneath a chosen folder.
406    #[must_use]
407    pub fn looked_up(&self, key: &AppKey, reference: &Path) -> Option<Chosen> {
408        let (token, _) = split_reference(reference)?;
409        let document = self.document(key, &token)?;
410        Some(entry(&token, document))
411    }
412
413    /// What was chosen for `key`, most recent first.
414    #[must_use]
415    pub fn entries(&self, key: &AppKey) -> Vec<Chosen> {
416        self.views
417            .read()
418            .ok()
419            .and_then(|views| {
420                views.get(key).map(|view| {
421                    view.by_recency()
422                        .map(|(token, document)| entry(token, document.clone()))
423                        .collect()
424                })
425            })
426            .unwrap_or_default()
427    }
428
429    /// What was chosen for `key` on the host, most recent first.
430    #[must_use]
431    pub fn chosen(&self, key: &AppKey) -> Vec<PathBuf> {
432        self.views
433            .read()
434            .ok()
435            .and_then(|views| {
436                views
437                    .get(key)
438                    .map(|view| view.by_recency().map(|(_, d)| d.host.clone()).collect())
439            })
440            .unwrap_or_default()
441    }
442
443    #[must_use]
444    pub fn tokens(&self, key: &AppKey) -> Vec<String> {
445        self.views
446            .read()
447            .ok()
448            .and_then(|views| {
449                views
450                    .get(key)
451                    .map(|view| view.documents.keys().cloned().collect())
452            })
453            .unwrap_or_default()
454    }
455
456    /// Forget everything chosen for `key`.
457    pub fn revoke(&self, key: &AppKey) {
458        let removed = self
459            .views
460            .write()
461            .is_ok_and(|mut views| views.remove(key).is_some());
462        if removed {
463            self.keep();
464            self.changed();
465        }
466    }
467
468    /// Every choice the table holds, by the app it was made for, most recent first within an app:
469    /// what a view lists of the files people chose outside any workspace.
470    #[must_use]
471    pub fn all(&self) -> Vec<(AppKey, String, Chosen)> {
472        self.views
473            .read()
474            .ok()
475            .map(|views| {
476                views
477                    .iter()
478                    .flat_map(|(key, view)| {
479                        view.by_recency().map(move |(token, document)| {
480                            (key.clone(), token.clone(), entry(token, document.clone()))
481                        })
482                    })
483                    .collect()
484            })
485            .unwrap_or_default()
486    }
487
488    /// Forget the one choice `token` of `key`, keeping the rest. Whether it was there: the device's
489    /// record is written again without it.
490    pub fn forget(&self, key: &AppKey, token: &str) -> bool {
491        let removed = self.views.write().is_ok_and(|mut views| {
492            let Some(view) = views.get_mut(key) else {
493                return false;
494            };
495            let removed = view.documents.remove(token).is_some();
496            if removed {
497                view.recent.retain(|held| held != token);
498                if view.documents.is_empty() {
499                    views.remove(key);
500                }
501            }
502            removed
503        });
504        if removed {
505            self.keep();
506            self.changed();
507        }
508        removed
509    }
510}
511
512/// One choice, from the token the table keeps it under.
513fn entry(token: &str, document: Document) -> Chosen {
514    let name = document.name().to_string_lossy().into_owned();
515    let reference = Path::new(CHOSEN_ROOT).join(RECORDS).join(token).join(&name);
516    Chosen {
517        reference,
518        name,
519        save_sibling: document.save_sibling(),
520        host: document.host,
521        kind: document.kind,
522    }
523}
524
525fn resolve_choice(chosen: &Path, kind: Kind) -> Result<PathBuf, GrantError> {
526    match kind {
527        Kind::Read => {
528            let host = chosen.canonicalize().map_err(GrantError::Io)?;
529            let meta = std::fs::metadata(&host).map_err(GrantError::Io)?;
530            if meta.is_file() {
531                Ok(host)
532            } else {
533                Err(GrantError::NotThatKind)
534            }
535        }
536        Kind::Folder { .. } => {
537            let host = chosen.canonicalize().map_err(GrantError::Io)?;
538            if std::fs::metadata(&host).map_err(GrantError::Io)?.is_dir() {
539                Ok(host)
540            } else {
541                Err(GrantError::NotThatKind)
542            }
543        }
544        Kind::Save => {
545            let name = plain_name(chosen).ok_or(GrantError::NotThatKind)?;
546            let parent = chosen
547                .parent()
548                .filter(|parent| !parent.as_os_str().is_empty())
549                .ok_or(GrantError::NotThatKind)?
550                .canonicalize()
551                .map_err(GrantError::Io)?;
552            if !std::fs::metadata(&parent).map_err(GrantError::Io)?.is_dir() {
553                return Err(GrantError::NotThatKind);
554            }
555            let host = parent.join(name);
556            match std::fs::symlink_metadata(&host) {
557                Ok(meta) if meta.is_file() => Ok(host),
558                Ok(_) => Err(GrantError::NotThatKind),
559                Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(host),
560                Err(error) => Err(GrantError::Io(error)),
561            }
562        }
563    }
564}
565
566fn plain_name(path: &Path) -> Option<&OsStr> {
567    match path.components().next_back()? {
568        Component::Normal(name) => Some(name),
569        _ => None,
570    }
571}
572
573/// A choice's token: the same for the same choice by the same app in the same workspace, and
574/// unguessable from outside without knowing all three.
575fn token(key: &AppKey, document: &Document) -> String {
576    let mut hasher = blake3::Hasher::new();
577    hasher.update(b"tilo-chosen/1\0");
578    hasher.update(key.workspace.as_bytes());
579    hasher.update(b"\0");
580    hasher.update(key.app.as_bytes());
581    hasher.update(b"\0");
582    hasher.update(document.kind.tag().as_bytes());
583    hasher.update(b"\0");
584    hasher.update(document.host.as_os_str().as_encoded_bytes());
585    let hex = hasher.finalize().to_hex();
586    hex.chars().take(24).collect()
587}
588
589/// The token a reference names and the path beneath it.
590#[must_use]
591pub fn split_reference(path: &Path) -> Option<(String, PathBuf)> {
592    let rest = path.strip_prefix(CHOSEN_ROOT).ok()?;
593    let mut components = rest.components();
594    let Component::Normal(first) = components.next()? else {
595        return None;
596    };
597    if first != RECORDS {
598        return None;
599    }
600    let Component::Normal(token) = components.next()? else {
601        return None;
602    };
603    let inner: PathBuf = components.collect();
604    let token = token.to_str()?.to_owned();
605    Some((token, inner))
606}
607
608/// The table the session and its portal share: one for every app this session serves, bound to the
609/// device's records once the session has them.
610#[must_use]
611pub fn chosen_table() -> Arc<ChosenTable> {
612    static TABLE: OnceLock<Arc<ChosenTable>> = OnceLock::new();
613    Arc::clone(TABLE.get_or_init(|| Arc::new(ChosenTable::new())))
614}
615
616/// Keep the shared table as the device's record `store` holds.
617pub fn bind_store(store: Arc<dyn Store>) {
618    chosen_table().bind(store);
619}
620
621#[cfg(test)]
622mod tests {
623    use std::sync::Mutex;
624
625    use super::*;
626
627    fn key() -> AppKey {
628        AppKey::new("5ba25f73-87c5-447f-a5a6-880dc4249a81", "so.tilo.totp").unwrap()
629    }
630
631    /// A store kept in this process, as the device's record keeps it.
632    #[derive(Default)]
633    struct Held(Mutex<Vec<Kept>>);
634
635    impl Store for Held {
636        fn load(&self) -> Vec<Kept> {
637            self.0.lock().unwrap().clone()
638        }
639
640        fn keep(&self, kept: Vec<Kept>) {
641            *self.0.lock().unwrap() = kept;
642        }
643    }
644
645    fn wait_for(table: &ChosenTable, key: &AppKey, tokens: usize) {
646        tilo_test_env::wait_until("the kept table is read", || {
647            table.tokens(key).len() == tokens
648        });
649    }
650
651    #[test]
652    fn keys_carry_only_names_one_path_component_can_hold() {
653        assert!(AppKey::new("workspace-1", "so.tilo.files").is_some());
654        for (workspace, app) in [
655            ("", "so.tilo.files"),
656            ("../x", "so.tilo.files"),
657            ("workspace", ".."),
658            ("workspace", "a/b"),
659            ("workspace", ".hidden"),
660        ] {
661            assert!(
662                AppKey::new(workspace, app).is_none(),
663                "{workspace:?} {app:?}"
664            );
665        }
666    }
667
668    #[test]
669    fn a_choice_answers_a_stable_reference_in_the_chosen_root() {
670        let dir = tempfile::tempdir().unwrap();
671        let file = dir.path().join("report.pdf");
672        std::fs::write(&file, b"pdf").unwrap();
673        let table = ChosenTable::new();
674        let chosen = table.grant(&key(), &file, Kind::Read).unwrap();
675        assert_eq!(
676            table.grant(&key(), &file, Kind::Read).unwrap().reference,
677            chosen.reference
678        );
679        assert_eq!(table.entries(&key())[0].reference, chosen.reference);
680        assert!(chosen.reference.starts_with(CHOSEN_ROOT));
681        assert_eq!(chosen.name, "report.pdf");
682        assert_eq!(
683            table.looked_up(&key(), &chosen.reference).unwrap().host,
684            file.canonicalize().unwrap()
685        );
686        let other = AppKey::new("other-workspace", "so.tilo.totp").unwrap();
687        assert!(table.looked_up(&other, &chosen.reference).is_none());
688        assert_ne!(
689            table.grant(&other, &file, Kind::Read).unwrap().reference,
690            chosen.reference
691        );
692        assert!(
693            table
694                .looked_up(
695                    &key(),
696                    Path::new("/run/tilo/chosen/records/nope/report.pdf")
697                )
698                .is_none()
699        );
700    }
701
702    #[test]
703    fn a_kept_table_reopens_a_choice_where_it_was_and_forgets_what_is_gone() {
704        let dir = tempfile::tempdir().unwrap();
705        let kept = dir.path().join("kept.pdf");
706        let gone = dir.path().join("gone.pdf");
707        std::fs::write(&kept, b"kept").unwrap();
708        std::fs::write(&gone, b"gone").unwrap();
709        let store = Arc::new(Held::default());
710        let table = ChosenTable::new();
711        table.bind(store.clone());
712        let reference = table.grant(&key(), &kept, Kind::Read).unwrap().reference;
713        table.grant(&key(), &gone, Kind::Read).unwrap();
714        std::fs::remove_file(&gone).unwrap();
715
716        let next = ChosenTable::new();
717        next.bind(store);
718        wait_for(&next, &key(), 1);
719        assert!(
720            next.looked_up(&key(), &reference).is_some(),
721            "what was kept is served once the record is read"
722        );
723    }
724
725    #[test]
726    fn recent_lists_choices_newest_first_and_keeps_the_order() {
727        let dir = tempfile::tempdir().unwrap();
728        let [a, b, c] = ["a.txt", "b.txt", "c.txt"].map(|name| {
729            let path = dir.path().join(name);
730            std::fs::write(&path, name).unwrap();
731            path.canonicalize().unwrap()
732        });
733        let table = ChosenTable::new();
734        for path in [&a, &b, &c, &a] {
735            table.grant(&key(), path, Kind::Read).unwrap();
736        }
737        assert_eq!(
738            table.chosen(&key()),
739            [a, c, b],
740            "choosing again makes it the newest"
741        );
742        let other = AppKey::new("other-workspace", "so.tilo.totp").unwrap();
743        assert!(table.chosen(&other).is_empty(), "each app has its own");
744    }
745
746    #[test]
747    fn a_choice_must_be_what_the_chooser_asked_for() {
748        let dir = tempfile::tempdir().unwrap();
749        let table = ChosenTable::new();
750        assert!(matches!(
751            table.grant(&key(), dir.path(), Kind::Read),
752            Err(GrantError::NotThatKind)
753        ));
754        let file = dir.path().join("a.txt");
755        std::fs::write(&file, b"a").unwrap();
756        assert!(matches!(
757            table.grant(&key(), &file, Kind::Folder { write: false }),
758            Err(GrantError::NotThatKind)
759        ));
760        assert!(
761            table
762                .grant(&key(), &dir.path().join("new.txt"), Kind::Save)
763                .is_ok()
764        );
765        assert!(matches!(
766            table.grant(&key(), &dir.path().join("missing.txt"), Kind::Read),
767            Err(GrantError::Io(_))
768        ));
769    }
770}