1use 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
28pub const MAX_FILE_BYTES: u64 = 64 * 1024;
30pub const MAX_PIN_LINES: usize = 1024;
32
33#[derive(Debug, Clone, PartialEq, Eq)]
35#[non_exhaustive]
36pub enum FileRead {
37 Text(String),
39 Missing,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq)]
46#[non_exhaustive]
47pub struct ReadFailure(String);
48
49impl ReadFailure {
50 pub fn new(reason: impl Into<String>) -> Self {
52 Self(reason.into())
53 }
54
55 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
69pub trait PinFileReader: Send + Sync {
77 fn read(&self, account: &Person, path: &Path) -> Result<FileRead, ReadFailure>;
79}
80
81#[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
101pub 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 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 #[must_use]
166 pub fn reader(mut self, reader: Arc<dyn PinFileReader>) -> Self {
167 self.reader = reader;
168 self
169 }
170
171 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
203fn 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
217fn 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
240fn 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
270pub const READ_TIMEOUT: Duration = Duration::from_secs(2);
272pub const MOST_WAITING: usize = 8;
275
276#[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#[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#[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 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 #[must_use]
364 pub fn timeout(mut self, timeout: Duration) -> Self {
365 self.timeout = timeout;
366 self
367 }
368
369 #[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#[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 let result = {
446 let _place = place;
447 work()
448 };
449 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#[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(¤t) {
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 let file = std::fs::OpenOptions::new()
536 .read(true)
537 .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
538 .open(¤t)
539 .map_err(|_| ReadFailure::new("the pin file cannot be opened"))?;
540 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 let refused = bounded(&reader, 1000, || Ok(()));
603 assert!(refused.unwrap_err().reason().contains("stuck"));
604 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}