Skip to main content

coqui_access_kit/pins/
authorized.rs

1//! A per-user file of pins, in the manner of `~/.ssh/authorized_keys`.
2//!
3//! The file holds one pin per line, `sha256:<hex>` (a certificate's fingerprint) or
4//! `spki-sha256:<hex>` (its public key), then optional whitespace and a comment. Blank lines
5//! and lines starting `#` are ignored; a line that is not a pin is skipped and counted. A file
6//! may hold [`MAX_PIN_LINES`] lines and be [`MAX_FILE_BYTES`] long.
7//!
8//! [`AuthorizedFile`] finds the file by a path template, `{home}/.myapp/authorized_certificates`
9//! say, with `{home}` (the account's `home` attribute), `{name}` and `{id}` filled from the
10//! account a rule already named; it never looks at any other account's file. Who reads the
11//! file is a [`PinFileReader`]: the default, [`DirectReader`], opens it and makes the checks
12//! sshd makes of `authorized_keys`; a consumer whose process cannot read homes supplies a
13//! reader that reads through its own helper, and which makes those checks wherever it has
14//! access. The library checks nothing it cannot see: it renders the path, parses the text a
15//! reader returns, and turns a refusal into "no pins, and why".
16
17use std::fmt;
18use std::path::{Component, Path, PathBuf};
19use std::sync::Arc;
20use std::time::Duration;
21
22use coqui_access::Person;
23use coqui_access::guatiao::FromValue;
24use coqui_access::guatiao::library::ProviderError;
25
26use super::{PinCheck, PinSet, PinSource, pin_matches};
27
28/// The longest file read, in bytes.
29pub const MAX_FILE_BYTES: u64 = 64 * 1024;
30/// The most pin lines a file may hold, counting lines that are not valid pins.
31pub const MAX_PIN_LINES: usize = 1024;
32
33/// What a reader found at a path.
34#[derive(Debug, Clone, PartialEq, Eq)]
35#[non_exhaustive]
36pub enum FileRead {
37    /// The file's text.
38    Text(String),
39    /// There is no file: the account keeps no pins here, which is not a complaint.
40    Missing,
41}
42
43/// Why a reader would not give the file: it counts as no pins and the reason is reported.
44/// The reason never holds a pin.
45#[derive(Debug, Clone, PartialEq, Eq)]
46#[non_exhaustive]
47pub struct ReadFailure(String);
48
49impl ReadFailure {
50    /// A refusal for `reason`.
51    pub fn new(reason: impl Into<String>) -> Self {
52        Self(reason.into())
53    }
54
55    /// The reason.
56    pub fn reason(&self) -> &str {
57        &self.0
58    }
59}
60
61impl fmt::Display for ReadFailure {
62    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
63        formatter.write_str(&self.0)
64    }
65}
66
67impl core::error::Error for ReadFailure {}
68
69/// Reads the pin file of an account.
70///
71/// `account` is the candidate person, with `home` and `uid` among its attributes as its
72/// directory gave them, and `path` the file as the template rendered it: absolute, with no
73/// `..`. The reader makes whatever checks the file deserves where it has access (the owner,
74/// who may write it, its parents, symlinks) and reports their result; the library does not
75/// repeat them. A file that is not there is [`FileRead::Missing`], not a refusal.
76pub trait PinFileReader: Send + Sync {
77    /// The text of `path`, or why it may not be used.
78    fn read(&self, account: &Person, path: &Path) -> Result<FileRead, ReadFailure>;
79}
80
81/// A path template that cannot work. It never quotes the template.
82#[derive(Debug, Clone, PartialEq, Eq)]
83#[non_exhaustive]
84pub struct TemplateError;
85
86impl fmt::Display for TemplateError {
87    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
88        formatter.write_str("a pin file path is text with {home}, {name} and {id} only")
89    }
90}
91
92impl core::error::Error for TemplateError {}
93
94enum Part {
95    Text(String),
96    Home,
97    Name,
98    Id,
99}
100
101/// The pins in a file per user: a [`PinSource`] that reads only the file of the account it
102/// is asked about.
103pub struct AuthorizedFile {
104    template: String,
105    parts: Vec<Part>,
106    reader: Arc<dyn PinFileReader>,
107}
108
109impl fmt::Debug for AuthorizedFile {
110    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
111        formatter
112            .debug_struct("AuthorizedFile")
113            .field("template", &self.template)
114            .finish_non_exhaustive()
115    }
116}
117
118impl AuthorizedFile {
119    /// A source finding the file at `template`, read by [`DirectReader`] until
120    /// [`reader`](AuthorizedFile::reader) says otherwise.
121    ///
122    /// # Errors
123    ///
124    /// For an empty template, or a `{` that is not `{home}`, `{name}` or `{id}`.
125    pub fn new(template: impl Into<String>) -> Result<Self, TemplateError> {
126        let template = template.into();
127        let mut parts = Vec::new();
128        let mut rest = template.as_str();
129        while !rest.is_empty() {
130            match rest.find(['{', '}']) {
131                None => {
132                    parts.push(Part::Text(rest.to_owned()));
133                    break;
134                }
135                Some(at) => {
136                    if at > 0 {
137                        parts.push(Part::Text(rest[..at].to_owned()));
138                    }
139                    let tail = &rest[at..];
140                    let (part, used) = [
141                        ("{home}", Part::Home),
142                        ("{name}", Part::Name),
143                        ("{id}", Part::Id),
144                    ]
145                    .into_iter()
146                    .find(|(word, _)| tail.starts_with(word))
147                    .map(|(word, part)| (part, word.len()))
148                    .ok_or(TemplateError)?;
149                    parts.push(part);
150                    rest = &tail[used..];
151                }
152            }
153        }
154        if parts.is_empty() {
155            return Err(TemplateError);
156        }
157        Ok(Self {
158            template,
159            parts,
160            reader: Arc::new(DirectReader::new()),
161        })
162    }
163
164    /// This source reading files through `reader`. Nothing else touches the file system.
165    #[must_use]
166    pub fn reader(mut self, reader: Arc<dyn PinFileReader>) -> Self {
167        self.reader = reader;
168        self
169    }
170
171    /// The file of `account`, or why there is none to look at.
172    fn path_for(&self, account: &Person) -> Result<PathBuf, String> {
173        let mut path = String::new();
174        for part in &self.parts {
175            match part {
176                Part::Text(text) => path.push_str(text),
177                Part::Home => {
178                    let home = text_attribute(account, "home")
179                        .ok_or("the account has no home directory")?;
180                    if home.is_empty() || home.chars().any(char::is_control) {
181                        return Err("the account's home is not a usable path".to_owned());
182                    }
183                    path.push_str(&home);
184                }
185                Part::Name => path.push_str(&component(&account.name)?),
186                Part::Id => path.push_str(&component(&account.id)?),
187            }
188        }
189        let path = PathBuf::from(path);
190        if !(path.is_absolute() || path.to_string_lossy().starts_with('/')) {
191            return Err("the pin file's path is not absolute".to_owned());
192        }
193        if path
194            .components()
195            .any(|component| matches!(component, Component::ParentDir))
196        {
197            return Err("the pin file's path climbs out with ..".to_owned());
198        }
199        Ok(path)
200    }
201}
202
203/// A name or id as one path component, or why not.
204fn component(value: &str) -> Result<String, String> {
205    let bad = value.is_empty()
206        || value == "."
207        || value == ".."
208        || value
209            .chars()
210            .any(|c| matches!(c, '/' | '\\') || c.is_control());
211    if bad {
212        return Err("the account's name is not safe to put in a path".to_owned());
213    }
214    Ok(value.to_owned())
215}
216
217/// An attribute as text, whether the directory gave it as text or as a number.
218fn text_attribute(account: &Person, name: &str) -> Option<String> {
219    let value = account.attributes.get(name)?;
220    String::from_value(value)
221        .ok()
222        .or_else(|| u64::from_value(value).ok().map(|number| number.to_string()))
223}
224
225impl PinSource for AuthorizedFile {
226    fn check(&self, person: &Person, pins: &PinSet) -> Result<PinCheck, ProviderError> {
227        let path = match self.path_for(person) {
228            Ok(path) => path,
229            Err(reason) => return Ok(PinCheck::Refused(reason)),
230        };
231        let text = match self.reader.read(person, &path) {
232            Ok(FileRead::Text(text)) => text,
233            Ok(FileRead::Missing) => return Ok(PinCheck::Absent),
234            Err(failure) => return Ok(PinCheck::Refused(failure.0)),
235        };
236        Ok(scan(&text, pins))
237    }
238}
239
240/// Whether `text` holds one of `pins`, skipping what is not a pin and saying how much when
241/// nothing is found.
242fn scan(text: &str, pins: &PinSet) -> PinCheck {
243    let (mut lines, mut skipped, mut held) = (0_usize, 0_usize, false);
244    for line in text.lines() {
245        let line = line.trim();
246        if line.is_empty() || line.starts_with('#') {
247            continue;
248        }
249        lines += 1;
250        if lines > MAX_PIN_LINES {
251            return PinCheck::Refused(format!("the file holds more than {MAX_PIN_LINES} lines"));
252        }
253        let pin = line.split_whitespace().next().unwrap_or_default();
254        match pin_matches(pin, pins) {
255            Some(found) => held |= found,
256            None => skipped += 1,
257        }
258    }
259    if held {
260        PinCheck::Holds
261    } else if skipped > 0 {
262        PinCheck::Refused(format!(
263            "{skipped} lines of the file are not pins, and none held"
264        ))
265    } else {
266        PinCheck::Absent
267    }
268}
269
270/// The longest a [`DirectReader`] waits for the file system by default.
271pub const READ_TIMEOUT: Duration = Duration::from_secs(2);
272/// The most reads one [`DirectReader`] lets wait on the file system at once by default, over
273/// every account; one account never has more than one waiting.
274pub const MOST_WAITING: usize = 8;
275
276/// Opens the file itself and makes the checks sshd makes of `authorized_keys`.
277///
278/// On Unix, from the account's real home down, one component at a time:
279///
280/// - the path must lie under the account's `home`; no directory on the way and not the file
281///   may be a symlink, or on another file system than the home;
282/// - the home, every directory below it on the path, and the file must be owned by the
283///   account's uid (its `uid` attribute) or by root and must not be writable by group or
284///   others;
285/// - the file is opened without following a link and without blocking (`O_NOFOLLOW`,
286///   `O_NONBLOCK`), and what is read is the opened file, checked again: a regular file, the
287///   one the walk saw, of at most [`MAX_FILE_BYTES`].
288///
289/// The walk and the read run on a thread the reader waits on for [`timeout`]
290/// (`READ_TIMEOUT` unless set), so a file system that never answers (a network or FUSE mount,
291/// a pipe put where the file should be) costs the caller that long and a refusal. The
292/// thread itself stays stuck until the file system answers. A reader lets one read wait per
293/// account (a hung mount in one person's home stops that person, not the others) and at most
294/// [`max_waiting`](DirectReader::max_waiting) in all, and refuses further reads until some
295/// finish.
296///
297/// There is a gap no portable call closes: a directory above the file may be swapped between
298/// the walk and the open by someone who owns it (only the account, or root) and who is not
299/// the person being signed in. The checks make the account's own writable paths the only
300/// ones that can be abused. Elsewhere than Unix it refuses everything, as those checks have
301/// no meaning there.
302///
303/// [`timeout`]: DirectReader::timeout
304#[derive(Debug, Clone)]
305#[cfg_attr(
306    not(unix),
307    allow(dead_code, reason = "only the Unix reader waits on the file system")
308)]
309pub struct DirectReader {
310    timeout: Duration,
311    most_waiting: usize,
312    waiting: Arc<Waiting>,
313}
314
315/// The accounts that have a read stuck on the file system.
316#[derive(Debug, Default)]
317#[cfg_attr(
318    not(unix),
319    allow(dead_code, reason = "only the Unix reader waits on the file system")
320)]
321struct Waiting {
322    uids: std::sync::Mutex<std::collections::BTreeSet<u32>>,
323}
324
325/// A place among the waiting reads, given back when it is dropped, whether the read
326/// finished, was never started or panicked.
327#[cfg_attr(
328    not(unix),
329    allow(dead_code, reason = "only the Unix reader waits on the file system")
330)]
331struct Place {
332    waiting: Arc<Waiting>,
333    uid: u32,
334}
335
336impl Drop for Place {
337    fn drop(&mut self) {
338        self.waiting
339            .uids
340            .lock()
341            .unwrap_or_else(std::sync::PoisonError::into_inner)
342            .remove(&self.uid);
343    }
344}
345
346impl Default for DirectReader {
347    fn default() -> Self {
348        Self::new()
349    }
350}
351
352impl DirectReader {
353    /// A reader with the default [`READ_TIMEOUT`] and [`MOST_WAITING`].
354    pub fn new() -> Self {
355        Self {
356            timeout: READ_TIMEOUT,
357            most_waiting: MOST_WAITING,
358            waiting: Arc::new(Waiting::default()),
359        }
360    }
361
362    /// How long one read waits on the file system before it is refused.
363    #[must_use]
364    pub fn timeout(mut self, timeout: Duration) -> Self {
365        self.timeout = timeout;
366        self
367    }
368
369    /// How many reads may be stuck on the file system at once before further ones are
370    /// refused without being tried.
371    #[must_use]
372    pub fn max_waiting(mut self, most: usize) -> Self {
373        self.most_waiting = most;
374        self
375    }
376}
377
378impl PinFileReader for DirectReader {
379    fn read(&self, account: &Person, path: &Path) -> Result<FileRead, ReadFailure> {
380        direct(self, account, path)
381    }
382}
383
384#[cfg(not(unix))]
385fn direct(
386    _reader: &DirectReader,
387    _account: &Person,
388    _path: &Path,
389) -> Result<FileRead, ReadFailure> {
390    Err(ReadFailure::new(
391        "per-user pin files are not supported on this platform",
392    ))
393}
394
395#[cfg(unix)]
396fn direct(reader: &DirectReader, account: &Person, path: &Path) -> Result<FileRead, ReadFailure> {
397    let uid: u32 = text_attribute(account, "uid")
398        .and_then(|uid| uid.parse().ok())
399        .ok_or_else(|| {
400            ReadFailure::new("the account has no uid, so a file cannot be trusted as its own")
401        })?;
402    let home = text_attribute(account, "home")
403        .ok_or_else(|| ReadFailure::new("the account has no home directory"))?;
404    let path = path.to_path_buf();
405    bounded(reader, uid, move || walk_and_read(uid, &home, &path))
406}
407
408/// Runs `work` on a thread and waits for it no longer than the reader's timeout. Only one read
409/// per `uid` waits at a time, and no more than the reader's `max_waiting` in all.
410#[cfg(unix)]
411fn bounded<T: Send + 'static>(
412    reader: &DirectReader,
413    uid: u32,
414    work: impl FnOnce() -> Result<T, ReadFailure> + Send + 'static,
415) -> Result<T, ReadFailure> {
416    let place = {
417        let mut uids = reader
418            .waiting
419            .uids
420            .lock()
421            .unwrap_or_else(std::sync::PoisonError::into_inner);
422        if uids.contains(&uid) {
423            return Err(ReadFailure::new(
424                "a pin file read for this account is stuck on the file system",
425            ));
426        }
427        if uids.len() >= reader.most_waiting {
428            return Err(ReadFailure::new(
429                "too many pin file reads are stuck on the file system",
430            ));
431        }
432        uids.insert(uid);
433        Place {
434            waiting: Arc::clone(&reader.waiting),
435            uid,
436        }
437    };
438    let (sender, receiver) = std::sync::mpsc::channel();
439    let started = std::thread::Builder::new()
440        .name("pin-file-read".to_owned())
441        .spawn(move || {
442            // Given back when the work ends, by finishing or by unwinding, and before the
443            // answer is sent: a caller that has its answer may ask for the same account at
444            // once, and must not find the place still taken.
445            let result = {
446                let _place = place;
447                work()
448            };
449            // The caller may have given up; nobody is left to tell.
450            let _ = sender.send(result);
451        });
452    if started.is_err() {
453        return Err(ReadFailure::new("a pin file read could not be started"));
454    }
455    receiver
456        .recv_timeout(reader.timeout)
457        .unwrap_or_else(|_| Err(ReadFailure::new("reading the pin file timed out")))
458}
459
460/// The walk from the home down to the file, and the read of what was opened.
461#[cfg(unix)]
462fn walk_and_read(uid: u32, home: &str, path: &Path) -> Result<FileRead, ReadFailure> {
463    use std::io::Read as _;
464    use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
465
466    let trusted = |meta: &std::fs::Metadata, what: &str| -> Result<(), ReadFailure> {
467        if meta.uid() != uid && meta.uid() != 0 {
468            return Err(ReadFailure::new(format!(
469                "the pin file's {what} is owned by someone else"
470            )));
471        }
472        if meta.mode() & 0o022 != 0 {
473            return Err(ReadFailure::new(format!(
474                "the pin file's {what} is writable by its group or others"
475            )));
476        }
477        Ok(())
478    };
479
480    let real_home = std::fs::canonicalize(home)
481        .map_err(|_| ReadFailure::new("the account's home cannot be resolved"))?;
482    let home_meta = std::fs::metadata(&real_home)
483        .map_err(|_| ReadFailure::new("the account's home cannot be examined"))?;
484    let relative = path
485        .strip_prefix(home)
486        .map_err(|_| ReadFailure::new("the pin file is outside the account's home"))?;
487    trusted(&home_meta, "directories")?;
488
489    let names: Vec<_> = relative.components().collect();
490    if names.is_empty() {
491        return Err(ReadFailure::new("the pin file is the account's home"));
492    }
493    let mut current = real_home;
494    let mut seen = None;
495    for (index, part) in names.iter().enumerate() {
496        let Component::Normal(name) = part else {
497            return Err(ReadFailure::new("the pin file's path is not plain names"));
498        };
499        current.push(name);
500        let meta = match std::fs::symlink_metadata(&current) {
501            Ok(meta) => meta,
502            Err(failure) if failure.kind() == std::io::ErrorKind::NotFound => {
503                return Ok(FileRead::Missing);
504            }
505            Err(_) => return Err(ReadFailure::new("the pin file cannot be examined")),
506        };
507        if meta.file_type().is_symlink() {
508            return Err(ReadFailure::new(
509                "the pin file or a directory above it is a symlink",
510            ));
511        }
512        if meta.dev() != home_meta.dev() {
513            return Err(ReadFailure::new(
514                "the pin file is on another file system than the home",
515            ));
516        }
517        if index + 1 == names.len() {
518            if !meta.is_file() {
519                return Err(ReadFailure::new("the pin file is not a regular file"));
520            }
521            seen = Some(meta);
522        } else {
523            if !meta.is_dir() {
524                return Err(ReadFailure::new(
525                    "a directory above the pin file is not one",
526                ));
527            }
528            trusted(&meta, "directories")?;
529        }
530    }
531    let seen = seen.ok_or_else(|| ReadFailure::new("the pin file cannot be examined"))?;
532
533    // Without following a link and without waiting on a writer, so a pipe put in place after
534    // the walk opens at once and is refused below.
535    let file = std::fs::OpenOptions::new()
536        .read(true)
537        .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
538        .open(&current)
539        .map_err(|_| ReadFailure::new("the pin file cannot be opened"))?;
540    // What was opened, not the name that was walked.
541    let meta = file
542        .metadata()
543        .map_err(|_| ReadFailure::new("the pin file cannot be examined"))?;
544    if !meta.is_file() {
545        return Err(ReadFailure::new("the pin file is not a regular file"));
546    }
547    if meta.dev() != home_meta.dev() || (meta.dev(), meta.ino()) != (seen.dev(), seen.ino()) {
548        return Err(ReadFailure::new(
549            "the pin file changed while it was checked",
550        ));
551    }
552    if meta.len() > MAX_FILE_BYTES {
553        return Err(ReadFailure::new("the pin file is too large"));
554    }
555    trusted(&meta, "file")?;
556
557    let mut text = String::new();
558    file.take(MAX_FILE_BYTES + 1)
559        .read_to_string(&mut text)
560        .map_err(|_| ReadFailure::new("the pin file is not text"))?;
561    if text.len() as u64 > MAX_FILE_BYTES {
562        return Err(ReadFailure::new("the pin file is too large"));
563    }
564    Ok(FileRead::Text(text))
565}
566
567#[cfg(all(test, unix))]
568mod tests {
569    use super::*;
570
571    fn stuck(reader: &DirectReader, uid: u32) -> std::sync::mpsc::Sender<()> {
572        let (release, held) = std::sync::mpsc::channel::<()>();
573        let result = bounded(reader, uid, move || {
574            let _ = held.recv();
575            Ok(())
576        });
577        assert!(result.unwrap_err().reason().contains("timed out"));
578        release
579    }
580
581    fn quick() -> DirectReader {
582        DirectReader::new().timeout(Duration::from_millis(50))
583    }
584
585    fn eventually_reads(reader: &DirectReader, uid: u32) {
586        for _ in 0..200 {
587            if bounded(reader, uid, || Ok(())).is_ok() {
588                return;
589            }
590            std::thread::sleep(Duration::from_millis(10));
591        }
592        panic!("the place was never given back");
593    }
594
595    #[test]
596    fn a_read_that_never_answers_is_refused_after_the_timeout_and_holds_its_account() {
597        let reader = quick();
598        let started = std::time::Instant::now();
599        let release = stuck(&reader, 1000);
600        assert!(started.elapsed() < Duration::from_secs(5));
601        // The stuck read still counts, so a second for that account is refused untried.
602        let refused = bounded(&reader, 1000, || Ok(()));
603        assert!(refused.unwrap_err().reason().contains("stuck"));
604        // Once it finishes, reads go on.
605        release.send(()).unwrap();
606        eventually_reads(&reader, 1000);
607    }
608
609    #[test]
610    fn one_accounts_stuck_read_does_not_stop_another_account() {
611        let reader = quick();
612        let _release = stuck(&reader, 1000);
613        assert_eq!(bounded(&reader, 1001, || Ok(7)).unwrap(), 7);
614    }
615
616    #[test]
617    fn the_overall_cap_is_a_backstop_over_many_accounts() {
618        let reader = quick().max_waiting(2);
619        let _first = stuck(&reader, 1);
620        let _second = stuck(&reader, 2);
621        let refused = bounded(&reader, 3, || Ok(()));
622        assert!(refused.unwrap_err().reason().contains("too many"));
623    }
624
625    #[test]
626    fn a_read_that_panics_gives_its_place_back() {
627        let reader = quick();
628        let result = bounded::<()>(&reader, 1000, || panic!("the worker fails"));
629        assert!(result.is_err());
630        eventually_reads(&reader, 1000);
631    }
632
633    #[test]
634    fn a_read_that_has_answered_has_given_its_place_back() {
635        let reader = quick();
636        for _ in 0..500 {
637            assert_eq!(bounded(&reader, 1, || Ok(1)).unwrap(), 1);
638        }
639    }
640
641    #[test]
642    fn a_read_that_answers_in_time_gives_its_result() {
643        let reader = DirectReader::new();
644        assert_eq!(bounded(&reader, 1, || Ok(7)).unwrap(), 7);
645        let refusal = bounded::<()>(&reader, 1, || Err(ReadFailure::new("no")));
646        assert_eq!(refusal.unwrap_err().reason(), "no");
647    }
648}