1use std::error::Error;
4use std::fmt;
5use std::io::{self, Read};
6use std::path::Path;
7
8use zeroize::Zeroizing;
9
10use crate::BearerCredential;
11
12#[cfg(any(target_os = "linux", target_os = "macos"))]
13use std::fs::{File, OpenOptions};
14#[cfg(any(target_os = "linux", target_os = "macos"))]
15use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
16
17const BEARER_PRESENTATION_BYTES: usize = 43;
18const PROC_STATUS_MAX_BYTES: usize = 65_536;
19#[cfg(target_os = "linux")]
20const PROC_STATUS_PATH: &str = "/proc/self/status";
21#[cfg(any(test, not(target_os = "macos")))]
22const LINUX_O_NOFOLLOW: i32 = 0o00400000;
23#[cfg(any(test, not(target_os = "macos")))]
24const LINUX_O_NONBLOCK: i32 = 0o00004000;
25#[cfg(any(test, target_os = "macos"))]
26const MACOS_O_NOFOLLOW: i32 = 0x0100;
27#[cfg(any(test, target_os = "macos"))]
28const MACOS_O_NONBLOCK: i32 = 0x0004;
29
30#[cfg(target_os = "macos")]
31const O_NOFOLLOW: i32 = MACOS_O_NOFOLLOW;
32#[cfg(not(target_os = "macos"))]
33const O_NOFOLLOW: i32 = LINUX_O_NOFOLLOW;
34
35#[cfg(target_os = "macos")]
36const O_NONBLOCK: i32 = MACOS_O_NONBLOCK;
37#[cfg(not(target_os = "macos"))]
38const O_NONBLOCK: i32 = LINUX_O_NONBLOCK;
39
40const PROTECTED_OPEN_FLAGS: i32 = O_NOFOLLOW | O_NONBLOCK;
41
42#[derive(Clone, Copy, Eq, PartialEq)]
44pub enum BearerCredentialFileError {
45 UnsupportedPlatform,
47 ProtectedFileRejected,
49 InvalidPresentation,
51}
52
53impl fmt::Debug for BearerCredentialFileError {
54 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
55 formatter.write_str(match self {
56 Self::UnsupportedPlatform => "UnsupportedPlatform",
57 Self::ProtectedFileRejected => "ProtectedFileRejected",
58 Self::InvalidPresentation => "InvalidPresentation",
59 })
60 }
61}
62
63impl fmt::Display for BearerCredentialFileError {
64 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
65 formatter.write_str(match self {
66 Self::UnsupportedPlatform => {
67 "protected bearer credential files are unsupported on this platform"
68 }
69 Self::ProtectedFileRejected => "protected bearer credential file was rejected",
70 Self::InvalidPresentation => "bearer credential presentation is invalid",
71 })
72 }
73}
74
75impl Error for BearerCredentialFileError {}
76
77pub fn load_protected_bearer_credential(
82 path: &Path,
83) -> Result<BearerCredential, BearerCredentialFileError> {
84 load_protected_bearer_credential_diagnosed(path).map_err(|failure| failure.kind())
85}
86
87pub fn load_protected_bearer_credential_diagnosed(
90 path: &Path,
91) -> Result<BearerCredential, BearerCredentialFileFailure> {
92 #[cfg(target_os = "linux")]
93 {
94 load_with_diagnostics(&LinuxPlatform, path)
95 }
96 #[cfg(target_os = "macos")]
97 {
98 load_with_diagnostics(&MacOsPlatform, path)
99 }
100 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
101 {
102 let _ = path;
103 Err(BearerCredentialFileFailure::new(
104 BearerCredentialFileCause::UnsupportedPlatform,
105 ))
106 }
107}
108
109#[derive(Clone, Copy, Debug, Eq, PartialEq)]
111pub enum BearerCredentialFileCause {
112 UnsupportedPlatform,
114 NotFound,
116 ReadDenied,
118 NotRegular,
120 WrongOwner,
122 Permissions,
124 FileChanged,
126 InvalidLength,
128 InvalidPresentation,
130 EffectiveUserUnavailable,
132 Unavailable,
134}
135impl BearerCredentialFileCause {
136 #[must_use]
138 pub const fn as_str(self) -> &'static str {
139 match self {
140 Self::UnsupportedPlatform => "unsupported_platform",
141 Self::NotFound => "not_found",
142 Self::ReadDenied => "read_denied",
143 Self::NotRegular => "not_regular",
144 Self::WrongOwner => "wrong_owner",
145 Self::Permissions => "permissions",
146 Self::FileChanged => "file_changed",
147 Self::InvalidLength => "invalid_length",
148 Self::InvalidPresentation => "invalid_presentation",
149 Self::EffectiveUserUnavailable => "effective_user_unavailable",
150 Self::Unavailable => "unavailable",
151 }
152 }
153 #[must_use]
155 pub const fn expected(self) -> &'static str {
156 match self {
157 Self::UnsupportedPlatform => "supported protected-file platform",
158 Self::NotFound => "selected credential file exists",
159 Self::ReadDenied => "selected credential file is readable by its owner",
160 Self::NotRegular => "regular file without a final symlink",
161 Self::WrongOwner => "file owned by the current effective user",
162 Self::Permissions => "no group or other file access",
163 Self::FileChanged => "unchanged device and inode during protected open",
164 Self::InvalidLength => "exact 43-byte capability token without trailing newline",
165 Self::InvalidPresentation => "valid canonical bearer presentation",
166 Self::EffectiveUserUnavailable => "one bounded canonical effective-user observation",
167 Self::Unavailable => "available protected-file metadata and read operations",
168 }
169 }
170 #[must_use]
172 pub const fn fix(self) -> &'static str {
173 match self {
174 Self::UnsupportedPlatform => "use a supported Unix protected-file deployment",
175 Self::NotFound => "restore the selected protected credential file",
176 Self::ReadDenied => "restore owner read access to the selected credential file",
177 Self::NotRegular => "select an owned regular credential file without a final symlink",
178 Self::WrongOwner => "use a private credential file owned by the current effective user",
179 Self::Permissions => "set credential file mode to 0600",
180 Self::FileChanged => "retry after restoring stable protected credential-file custody",
181 Self::InvalidLength | Self::InvalidPresentation => {
182 "retain the exact issued capability token without a trailing newline; never print it"
183 }
184 Self::EffectiveUserUnavailable => {
185 "restore the platform effective-user source; do not bypass ownership checks"
186 }
187 Self::Unavailable => "restore protected-file availability and retry",
188 }
189 }
190}
191
192#[derive(Clone, Copy, Debug, Eq, PartialEq)]
194pub struct BearerCredentialFileFailure {
195 kind: BearerCredentialFileError,
196 cause: BearerCredentialFileCause,
197}
198impl BearerCredentialFileFailure {
199 const fn new(cause: BearerCredentialFileCause) -> Self {
200 let kind = match cause {
201 BearerCredentialFileCause::UnsupportedPlatform => {
202 BearerCredentialFileError::UnsupportedPlatform
203 }
204 BearerCredentialFileCause::InvalidPresentation => {
205 BearerCredentialFileError::InvalidPresentation
206 }
207 _ => BearerCredentialFileError::ProtectedFileRejected,
208 };
209 Self { kind, cause }
210 }
211 #[must_use]
213 pub const fn kind(self) -> BearerCredentialFileError {
214 self.kind
215 }
216 #[must_use]
218 pub const fn cause(self) -> BearerCredentialFileCause {
219 self.cause
220 }
221}
222impl fmt::Display for BearerCredentialFileFailure {
223 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224 write!(
225 f,
226 "protected bearer credential rejected: {}",
227 self.cause.as_str()
228 )
229 }
230}
231impl Error for BearerCredentialFileFailure {}
232
233fn io_failure(error: io::Error) -> BearerCredentialFileFailure {
234 BearerCredentialFileFailure::new(match error.kind() {
235 io::ErrorKind::NotFound => BearerCredentialFileCause::NotFound,
236 io::ErrorKind::PermissionDenied => BearerCredentialFileCause::ReadDenied,
237 _ => BearerCredentialFileCause::Unavailable,
238 })
239}
240
241#[derive(Clone, Copy)]
242struct FileMetadata {
243 is_regular: bool,
244 uid: u32,
245 mode: u32,
246 device: u64,
247 inode: u64,
248}
249
250trait ProtectedFilePlatform {
251 type ProcStatusReader: Read;
252 type OpenedFile: Read;
253
254 fn open_proc_status(&self) -> io::Result<Self::ProcStatusReader>;
255 fn symlink_metadata(&self, path: &Path) -> io::Result<FileMetadata>;
256 fn open_file(&self, path: &Path, flags: i32) -> io::Result<Self::OpenedFile>;
257 fn opened_metadata(&self, file: &Self::OpenedFile) -> io::Result<FileMetadata>;
258}
259
260#[cfg(target_os = "linux")]
261struct LinuxPlatform;
262
263#[cfg(target_os = "linux")]
264impl ProtectedFilePlatform for LinuxPlatform {
265 type ProcStatusReader = File;
266 type OpenedFile = File;
267
268 fn open_proc_status(&self) -> io::Result<Self::ProcStatusReader> {
269 File::open(PROC_STATUS_PATH)
270 }
271
272 fn symlink_metadata(&self, path: &Path) -> io::Result<FileMetadata> {
273 std::fs::symlink_metadata(path).map(metadata_snapshot)
274 }
275
276 fn open_file(&self, path: &Path, flags: i32) -> io::Result<Self::OpenedFile> {
277 OpenOptions::new().read(true).custom_flags(flags).open(path)
278 }
279
280 fn opened_metadata(&self, file: &Self::OpenedFile) -> io::Result<FileMetadata> {
281 file.metadata().map(metadata_snapshot)
282 }
283}
284
285#[cfg(target_os = "macos")]
286struct MacOsPlatform;
287
288#[cfg(target_os = "macos")]
289impl ProtectedFilePlatform for MacOsPlatform {
290 type ProcStatusReader = io::Cursor<Vec<u8>>;
291 type OpenedFile = File;
292
293 fn open_proc_status(&self) -> io::Result<Self::ProcStatusReader> {
294 let uid = macos_effective_uid()?;
295 Ok(io::Cursor::new(
296 format!("Uid:\t{uid}\t{uid}\t{uid}\t{uid}\n").into_bytes(),
297 ))
298 }
299
300 fn symlink_metadata(&self, path: &Path) -> io::Result<FileMetadata> {
301 std::fs::symlink_metadata(path).map(metadata_snapshot)
302 }
303
304 fn open_file(&self, path: &Path, flags: i32) -> io::Result<Self::OpenedFile> {
305 OpenOptions::new().read(true).custom_flags(flags).open(path)
306 }
307
308 fn opened_metadata(&self, file: &Self::OpenedFile) -> io::Result<FileMetadata> {
309 file.metadata().map(metadata_snapshot)
310 }
311}
312
313#[cfg(target_os = "macos")]
314fn macos_effective_uid() -> io::Result<u32> {
315 use std::process::Command;
316 use std::sync::OnceLock;
317
318 static CACHED_EUID: OnceLock<u32> = OnceLock::new();
319 if let Some(uid) = CACHED_EUID.get() {
320 return Ok(*uid);
321 }
322 let output = Command::new("/usr/bin/id").arg("-u").output()?;
323 if !output.status.success() {
324 return Err(io::Error::other("id -u failed"));
325 }
326 let trimmed = std::str::from_utf8(&output.stdout)
327 .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "id -u non-utf8"))?
328 .trim();
329 let uid = trimmed
330 .parse::<u32>()
331 .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "id -u invalid u32"))?;
332 let _ = CACHED_EUID.set(uid);
333 Ok(uid)
334}
335
336#[cfg(any(target_os = "linux", target_os = "macos"))]
337fn metadata_snapshot(metadata: std::fs::Metadata) -> FileMetadata {
338 FileMetadata {
339 is_regular: metadata.is_file(),
340 uid: metadata.uid(),
341 mode: metadata.mode(),
342 device: metadata.dev(),
343 inode: metadata.ino(),
344 }
345}
346
347#[cfg(test)]
348fn load_with<P: ProtectedFilePlatform>(
349 platform: &P,
350 path: &Path,
351) -> Result<BearerCredential, BearerCredentialFileError> {
352 load_with_diagnostics(platform, path).map_err(|failure| failure.kind())
353}
354fn load_with_diagnostics<P: ProtectedFilePlatform>(
355 platform: &P,
356 path: &Path,
357) -> Result<BearerCredential, BearerCredentialFileFailure> {
358 use BearerCredentialFileCause as Cause;
359 let effective_uid = read_effective_uid(platform)?;
360 let before = platform.symlink_metadata(path).map_err(io_failure)?;
361 if !before.is_regular {
362 return Err(BearerCredentialFileFailure::new(Cause::NotRegular));
363 }
364 let mut file = platform
365 .open_file(path, PROTECTED_OPEN_FLAGS)
366 .map_err(io_failure)?;
367 let opened = platform.opened_metadata(&file).map_err(io_failure)?;
368 if !opened.is_regular {
369 return Err(BearerCredentialFileFailure::new(Cause::NotRegular));
370 }
371 if opened.uid != effective_uid {
372 return Err(BearerCredentialFileFailure::new(Cause::WrongOwner));
373 }
374 if opened.mode & 0o077 != 0 {
375 return Err(BearerCredentialFileFailure::new(Cause::Permissions));
376 }
377 if (opened.device, opened.inode) != (before.device, before.inode) {
378 return Err(BearerCredentialFileFailure::new(Cause::FileChanged));
379 }
380 let mut presentation = Zeroizing::new(Vec::with_capacity(BEARER_PRESENTATION_BYTES + 1));
381 file.by_ref()
382 .take((BEARER_PRESENTATION_BYTES + 1) as u64)
383 .read_to_end(&mut presentation)
384 .map_err(io_failure)?;
385 if presentation.len() != BEARER_PRESENTATION_BYTES {
386 return Err(BearerCredentialFileFailure::new(Cause::InvalidLength));
387 }
388 let presentation = std::str::from_utf8(&presentation)
389 .map_err(|_| BearerCredentialFileFailure::new(Cause::InvalidPresentation))?;
390 BearerCredential::new(presentation)
391 .map_err(|_| BearerCredentialFileFailure::new(Cause::InvalidPresentation))
392}
393fn read_effective_uid<P: ProtectedFilePlatform>(
394 platform: &P,
395) -> Result<u32, BearerCredentialFileFailure> {
396 let unavailable =
397 || BearerCredentialFileFailure::new(BearerCredentialFileCause::EffectiveUserUnavailable);
398 let mut status = platform.open_proc_status().map_err(|_| unavailable())?;
399 let mut bytes = Vec::with_capacity(8 * 1024);
400 status
401 .by_ref()
402 .take((PROC_STATUS_MAX_BYTES + 1) as u64)
403 .read_to_end(&mut bytes)
404 .map_err(|_| unavailable())?;
405 if bytes.len() > PROC_STATUS_MAX_BYTES {
406 return Err(unavailable());
407 }
408 parse_effective_uid(&bytes).ok_or_else(unavailable)
409}
410
411fn parse_effective_uid(status: &[u8]) -> Option<u32> {
412 let mut effective_uid = None;
413 for line in status.split(|byte| *byte == b'\n') {
414 let Some(fields) = line.strip_prefix(b"Uid:") else {
415 continue;
416 };
417 if effective_uid.is_some() {
418 return None;
419 }
420 effective_uid = Some(parse_uid_fields(fields)?[1]);
421 }
422 effective_uid
423}
424
425fn parse_uid_fields(fields: &[u8]) -> Option<[u32; 4]> {
426 let mut cursor = 0;
427 require_separator(fields, &mut cursor)?;
428 let mut values = [0_u32; 4];
429 for (index, value) in values.iter_mut().enumerate() {
430 if index != 0 {
431 require_separator(fields, &mut cursor)?;
432 }
433 let start = cursor;
434 while fields.get(cursor).is_some_and(u8::is_ascii_digit) {
435 cursor += 1;
436 }
437 *value = parse_canonical_u32(&fields[start..cursor])?;
438 }
439 (cursor == fields.len()).then_some(values)
440}
441
442fn require_separator(fields: &[u8], cursor: &mut usize) -> Option<()> {
443 let start = *cursor;
444 while fields
445 .get(*cursor)
446 .is_some_and(|byte| matches!(byte, b' ' | b'\t'))
447 {
448 *cursor += 1;
449 }
450 (*cursor != start).then_some(())
451}
452
453fn parse_canonical_u32(bytes: &[u8]) -> Option<u32> {
454 if bytes.is_empty() || (bytes.len() > 1 && bytes[0] == b'0') {
455 return None;
456 }
457 bytes.iter().try_fold(0_u32, |value, byte| {
458 byte.is_ascii_digit()
459 .then_some(*byte - b'0')
460 .and_then(|digit| value.checked_mul(10)?.checked_add(u32::from(digit)))
461 })
462}
463
464#[cfg(test)]
465mod tests {
466 use std::cell::Cell;
467
468 use super::*;
469
470 const TOKEN: &[u8] = b"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8";
471 const TEST_PATH: &str = "/not-opened-by-test-platform";
472 const EFFECTIVE_UID: u32 = 1_234;
473
474 struct InjectedReader {
475 bytes: Vec<u8>,
476 position: usize,
477 fail_at: Option<usize>,
478 }
479
480 impl InjectedReader {
481 fn new(bytes: Vec<u8>, fail_at: Option<usize>) -> Self {
482 Self {
483 bytes,
484 position: 0,
485 fail_at,
486 }
487 }
488 }
489
490 impl Read for InjectedReader {
491 fn read(&mut self, output: &mut [u8]) -> io::Result<usize> {
492 if self.fail_at == Some(self.position) {
493 return Err(io::Error::other("injected read failure"));
494 }
495 if self.position == self.bytes.len() || output.is_empty() {
496 return Ok(0);
497 }
498
499 let readable_end = self
500 .fail_at
501 .unwrap_or(self.bytes.len())
502 .min(self.bytes.len());
503 let count = output.len().min(readable_end.saturating_sub(self.position));
504 if count == 0 {
505 return Err(io::Error::other("injected read failure"));
506 }
507 output[..count].copy_from_slice(&self.bytes[self.position..self.position + count]);
508 self.position += count;
509 Ok(count)
510 }
511 }
512
513 struct TestPlatform {
514 proc_status: io::Result<Vec<u8>>,
515 proc_status_fail_at: Option<usize>,
516 before: io::Result<FileMetadata>,
517 opened: io::Result<FileMetadata>,
518 bytes: io::Result<Vec<u8>>,
519 bytes_fail_at: Option<usize>,
520 flags: Cell<Option<i32>>,
521 metadata_reads: Cell<u32>,
522 }
523
524 impl TestPlatform {
525 fn valid() -> Self {
526 let metadata = FileMetadata {
527 is_regular: true,
528 uid: EFFECTIVE_UID,
529 mode: 0o100600,
530 device: 11,
531 inode: 17,
532 };
533 Self {
534 proc_status: Ok(b"Name:\triffdb\nUid:\t1234\t1234 1234\t1234\n".to_vec()),
535 proc_status_fail_at: None,
536 before: Ok(metadata),
537 opened: Ok(metadata),
538 bytes: Ok(TOKEN.to_vec()),
539 bytes_fail_at: None,
540 flags: Cell::new(None),
541 metadata_reads: Cell::new(0),
542 }
543 }
544 }
545
546 impl ProtectedFilePlatform for TestPlatform {
547 type ProcStatusReader = InjectedReader;
548 type OpenedFile = InjectedReader;
549
550 fn open_proc_status(&self) -> io::Result<Self::ProcStatusReader> {
551 self.proc_status
552 .as_ref()
553 .map(|bytes| InjectedReader::new(bytes.clone(), self.proc_status_fail_at))
554 .map_err(|error| io::Error::new(error.kind(), "injected"))
555 }
556
557 fn symlink_metadata(&self, _path: &Path) -> io::Result<FileMetadata> {
558 self.metadata_reads.set(self.metadata_reads.get() + 1);
559 self.before
560 .as_ref()
561 .copied()
562 .map_err(|error| io::Error::new(error.kind(), "injected"))
563 }
564
565 fn open_file(&self, _path: &Path, flags: i32) -> io::Result<Self::OpenedFile> {
566 self.flags.set(Some(flags));
567 self.bytes
568 .as_ref()
569 .map(|bytes| InjectedReader::new(bytes.clone(), self.bytes_fail_at))
570 .map_err(|error| io::Error::new(error.kind(), "injected"))
571 }
572
573 fn opened_metadata(&self, _file: &Self::OpenedFile) -> io::Result<FileMetadata> {
574 self.opened
575 .as_ref()
576 .copied()
577 .map_err(|error| io::Error::new(error.kind(), "injected"))
578 }
579 }
580
581 #[test]
582 fn exact_linux_bounds_flags_and_presentation_are_frozen() {
583 assert_eq!(PROC_STATUS_MAX_BYTES, 65_536);
584 assert_eq!(BEARER_PRESENTATION_BYTES, 43);
585 assert_eq!(LINUX_O_NOFOLLOW, 0o00400000);
586 assert_eq!(LINUX_O_NONBLOCK, 0o00004000);
587 assert_eq!(LINUX_O_NOFOLLOW | LINUX_O_NONBLOCK, 0o00404000);
588 assert_eq!(MACOS_O_NOFOLLOW, 0x0100);
589 assert_eq!(MACOS_O_NONBLOCK, 0x0004);
590 assert_eq!(MACOS_O_NOFOLLOW | MACOS_O_NONBLOCK, 0x0104);
591 assert_eq!(PROTECTED_OPEN_FLAGS, O_NOFOLLOW | O_NONBLOCK);
592
593 let platform = TestPlatform::valid();
594 let loaded = load_with(&platform, Path::new(TEST_PATH)).expect("credential");
595 let expected = BearerCredential::new(std::str::from_utf8(TOKEN).expect("ASCII"))
596 .expect("expected credential");
597 assert!(loaded.has_same_presentation(&expected));
598 assert_eq!(platform.flags.get(), Some(PROTECTED_OPEN_FLAGS));
599 }
600
601 #[test]
602 fn effective_uid_requires_one_canonical_four_field_line() {
603 assert_eq!(
604 parse_effective_uid(b"Name:\triffdb\nUid:\t1 4294967295\t3 4\n"),
605 Some(u32::MAX)
606 );
607 assert_eq!(parse_effective_uid(b"Uid: 0\t0 0\t0"), Some(0));
608 for malformed in [
609 b"Name:\triffdb\n".as_slice(),
610 b"Uid:\t1 2 3 4\nUid:\t1 2 3 4\n",
611 b"Uid:1 2 3 4\n",
612 b"Uid:\t1 2 3\n",
613 b"Uid:\t1 2 3 4 5\n",
614 b"Uid:\t01 2 3 4\n",
615 b"Uid:\t1 +2 3 4\n",
616 b"Uid:\t1 4294967296 3 4\n",
617 b"Uid:\t1 2 3 4 \n",
618 b"Uid:\t1 2 3 4\r\n",
619 ] {
620 assert_eq!(parse_effective_uid(malformed), None);
621 }
622 }
623
624 #[test]
625 fn proc_status_must_reach_eof_within_the_exact_bound() {
626 let mut exact = b"Uid:\t1234\t1234\t1234\t1234\n".to_vec();
627 exact.resize(PROC_STATUS_MAX_BYTES, b'x');
628 let mut platform = TestPlatform::valid();
629 platform.proc_status = Ok(exact);
630 assert!(load_with(&platform, Path::new(TEST_PATH)).is_ok());
631
632 let mut over = b"Uid:\t1234\t1234\t1234\t1234\n".to_vec();
633 over.resize(PROC_STATUS_MAX_BYTES + 1, b'x');
634 let mut platform = TestPlatform::valid();
635 platform.proc_status = Ok(over);
636 assert_eq!(
637 load_with(&platform, Path::new(TEST_PATH)).err(),
638 Some(BearerCredentialFileError::ProtectedFileRejected)
639 );
640 }
641
642 #[test]
643 fn proc_status_failures_stop_before_the_credential_open() {
644 let canonical = b"Uid:\t1234\t1234\t1234\t1234\n";
645 for fail_at in [0, canonical.len() / 2, canonical.len()] {
646 let mut platform = TestPlatform::valid();
647 platform.proc_status = Ok(canonical.to_vec());
648 platform.proc_status_fail_at = Some(fail_at);
649 assert_eq!(
650 load_with(&platform, Path::new(TEST_PATH)).err(),
651 Some(BearerCredentialFileError::ProtectedFileRejected)
652 );
653 assert_eq!(platform.flags.get(), None);
654 }
655
656 let mut unavailable = TestPlatform::valid();
657 unavailable.proc_status = Err(io::Error::new(
658 io::ErrorKind::NotFound,
659 "secret proc failure canary",
660 ));
661 assert_eq!(
662 load_with(&unavailable, Path::new(TEST_PATH)).err(),
663 Some(BearerCredentialFileError::ProtectedFileRejected)
664 );
665 assert_eq!(unavailable.flags.get(), None);
666
667 for malformed in [
668 b"Name:\triffdb\n".as_slice(),
669 b"Uid:\t1 2 3 4\nUid:\t1 2 3 4\n",
670 b"Uid:\t1 4294967296 3 4\n",
671 ] {
672 let mut platform = TestPlatform::valid();
673 platform.proc_status = Ok(malformed.to_vec());
674 assert_eq!(
675 load_with(&platform, Path::new(TEST_PATH)).err(),
676 Some(BearerCredentialFileError::ProtectedFileRejected)
677 );
678 assert_eq!(platform.flags.get(), None);
679 }
680 }
681
682 #[test]
683 fn path_open_handle_owner_mode_and_identity_failures_are_closed() {
684 let mutations: [fn(&mut TestPlatform); 8] = [
685 |platform| platform.before = Err(io::Error::other("pre-open metadata failure")),
686 |platform| platform.before.as_mut().expect("metadata").is_regular = false,
687 |platform| platform.bytes = Err(io::Error::other("open failure")),
688 |platform| platform.opened = Err(io::Error::other("opened metadata failure")),
689 |platform| platform.opened.as_mut().expect("metadata").is_regular = false,
690 |platform| platform.opened.as_mut().expect("metadata").uid += 1,
691 |platform| platform.opened.as_mut().expect("metadata").device += 1,
692 |platform| platform.opened.as_mut().expect("metadata").inode += 1,
693 ];
694 for mutate in mutations {
695 let mut platform = TestPlatform::valid();
696 mutate(&mut platform);
697 assert_eq!(
698 load_with(&platform, Path::new(TEST_PATH)).err(),
699 Some(BearerCredentialFileError::ProtectedFileRejected)
700 );
701 }
702
703 let mut preopen_nonregular = TestPlatform::valid();
704 preopen_nonregular
705 .before
706 .as_mut()
707 .expect("metadata")
708 .is_regular = false;
709 assert_eq!(
710 load_with(&preopen_nonregular, Path::new(TEST_PATH)).err(),
711 Some(BearerCredentialFileError::ProtectedFileRejected)
712 );
713 assert_eq!(preopen_nonregular.flags.get(), None);
714
715 for forbidden_bit in [0o001, 0o002, 0o004, 0o010, 0o020, 0o040] {
716 let mut platform = TestPlatform::valid();
717 platform.opened.as_mut().expect("metadata").mode |= forbidden_bit;
718 assert_eq!(
719 load_with(&platform, Path::new(TEST_PATH)).err(),
720 Some(BearerCredentialFileError::ProtectedFileRejected),
721 "mode bit {forbidden_bit:#05o} must reject"
722 );
723 }
724 }
725
726 #[test]
727 fn symlink_and_replacement_races_fail_before_a_credential_is_returned() {
728 let mut raced_to_symlink = TestPlatform::valid();
729 raced_to_symlink.bytes = Err(io::Error::other("O_NOFOLLOW raced symlink"));
730 assert_eq!(
731 load_with(&raced_to_symlink, Path::new(TEST_PATH)).err(),
732 Some(BearerCredentialFileError::ProtectedFileRejected)
733 );
734 assert_eq!(raced_to_symlink.flags.get(), Some(O_NOFOLLOW | O_NONBLOCK));
735
736 for replace in [
737 |metadata: &mut FileMetadata| metadata.device += 1,
738 |metadata: &mut FileMetadata| metadata.inode += 1,
739 |metadata: &mut FileMetadata| metadata.is_regular = false,
740 ] {
741 let mut platform = TestPlatform::valid();
742 replace(platform.opened.as_mut().expect("opened metadata"));
743 assert_eq!(
744 load_with(&platform, Path::new(TEST_PATH)).err(),
745 Some(BearerCredentialFileError::ProtectedFileRejected)
746 );
747 }
748 }
749
750 #[test]
751 fn credential_requires_exactly_43_bytes_and_a_confirmed_final_eof() {
752 for bytes in [TOKEN[..42].to_vec(), [TOKEN, b"A"].concat()] {
753 let mut platform = TestPlatform::valid();
754 platform.bytes = Ok(bytes);
755 assert_eq!(
756 load_with(&platform, Path::new(TEST_PATH)).err(),
757 Some(BearerCredentialFileError::ProtectedFileRejected)
758 );
759 }
760
761 for fail_at in [0, BEARER_PRESENTATION_BYTES / 2, BEARER_PRESENTATION_BYTES] {
762 let mut platform = TestPlatform::valid();
763 platform.bytes_fail_at = Some(fail_at);
764 assert_eq!(
765 load_with(&platform, Path::new(TEST_PATH)).err(),
766 Some(BearerCredentialFileError::ProtectedFileRejected),
767 "read failure at byte {fail_at} must reject"
768 );
769 }
770 }
771
772 #[test]
773 fn every_invalid_alphabet_byte_rejects_at_every_presentation_position() {
774 for position in 0..BEARER_PRESENTATION_BYTES {
775 for byte in u8::MIN..=u8::MAX {
776 if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_') {
777 continue;
778 }
779 let mut bytes = TOKEN.to_vec();
780 bytes[position] = byte;
781 let mut platform = TestPlatform::valid();
782 platform.bytes = Ok(bytes);
783 assert_eq!(
784 load_with(&platform, Path::new(TEST_PATH)).err(),
785 Some(BearerCredentialFileError::InvalidPresentation),
786 "byte {byte:#04x} at position {position} must reject"
787 );
788 }
789 }
790 }
791
792 #[test]
793 fn presentation_valid_noncanonical_token_is_left_for_server_rejection() {
794 let noncanonical = vec![b'A'; BEARER_PRESENTATION_BYTES];
795 let mut platform = TestPlatform::valid();
796 platform.bytes = Ok(noncanonical.clone());
797 let loaded = load_with(&platform, Path::new(TEST_PATH))
798 .expect("presentation-only validation accepts URL-safe alphabet text");
799 let expected =
800 BearerCredential::new(std::str::from_utf8(&noncanonical).expect("ASCII presentation"))
801 .expect("same presentation is accepted by the metadata boundary");
802 assert!(loaded.has_same_presentation(&expected));
803 }
804
805 #[test]
806 fn public_errors_are_fixed_and_redacted() {
807 let canary = "credential-file-secret-canary";
808 for error in [
809 BearerCredentialFileError::UnsupportedPlatform,
810 BearerCredentialFileError::ProtectedFileRejected,
811 BearerCredentialFileError::InvalidPresentation,
812 ] {
813 assert!(!format!("{error:?}").contains(canary));
814 assert!(!error.to_string().contains(canary));
815 assert!(Error::source(&error).is_none());
816 }
817 }
818 #[test]
820 fn protected_bearer_diagnostics_preserve_original_checks_without_restat() {
821 use BearerCredentialFileCause as Cause;
822 let mut cases = Vec::new();
823 let mut p = TestPlatform::valid();
824 p.before = Err(io::ErrorKind::NotFound.into());
825 cases.push((p, Cause::NotFound));
826 let mut p = TestPlatform::valid();
827 p.before.as_mut().unwrap().is_regular = false;
828 cases.push((p, Cause::NotRegular));
829 let mut p = TestPlatform::valid();
830 p.opened.as_mut().unwrap().uid += 1;
831 cases.push((p, Cause::WrongOwner));
832 let mut p = TestPlatform::valid();
833 p.opened.as_mut().unwrap().mode = 0o100644;
834 cases.push((p, Cause::Permissions));
835 let mut p = TestPlatform::valid();
836 p.opened.as_mut().unwrap().inode += 1;
837 cases.push((p, Cause::FileChanged));
838 let mut p = TestPlatform::valid();
839 p.bytes = Ok(vec![b'A'; 44]);
840 cases.push((p, Cause::InvalidLength));
841 let mut p = TestPlatform::valid();
842 p.bytes = Ok(vec![b'!'; 43]);
843 cases.push((p, Cause::InvalidPresentation));
844 for (platform, cause) in cases {
845 let failure = load_with_diagnostics(&platform, Path::new(TEST_PATH))
846 .err()
847 .unwrap();
848 assert_eq!(failure.cause(), cause);
849 assert_eq!(
850 platform.metadata_reads.get(),
851 1,
852 "the reported cause is from the original procedure"
853 );
854 assert_eq!(
855 load_with(&platform, Path::new(TEST_PATH)).err(),
856 Some(failure.kind()),
857 "the legacy classification is unchanged"
858 );
859 let rendered = format!("{failure:?} {failure}");
860 assert!(!rendered.contains(TEST_PATH));
861 assert!(!rendered.contains(std::str::from_utf8(TOKEN).unwrap()));
862 }
863 let mut platform = TestPlatform::valid();
864 platform.proc_status = Ok(b"invalid".to_vec());
865 assert_eq!(
866 load_with_diagnostics(&platform, Path::new(TEST_PATH))
867 .err()
868 .unwrap()
869 .cause(),
870 Cause::EffectiveUserUnavailable
871 );
872 assert_eq!(platform.metadata_reads.get(), 0);
873 }
874}