1//! The two credentials of the web.2//!3//! spec section 9.1 gives the web one bearer token for TCP and the peer uid for4//! a Unix socket. There are no accounts, no sessions, and no tenancy, so this5//! module holds a token and a set of allowed uids and nothing else. A route6//! that needs a [`Principal`] asks for one; `/healthz` does not.78use std::fmt;9use std::fs;10use std::path::Path;1112usecrate::Headers;1314/// The bytes of a SHA-256-sized bearer token. The deploy file spells it as15/// [`HEX_CHARS`] hex characters; any other length is a startup error, not a16/// panic.17constTOKEN_BYTES: usize = 32;1819/// The token as written in the deploy file: two hex characters per byte.20constHEX_CHARS: usize = TOKEN_BYTES * 2;2122/// The only scheme this server speaks. The single space is part of the23/// spelling, so `Bearer ` and `bearer ` are both refused.24constBEARER: &str = "Bearer ";2526/// Who sent a request. Every route but `/healthz` needs one.27 #[derive(Clone, Copy, PartialEq, Eq, Debug)]28pubenumPrincipal {29/// A TCP request that carried the configured bearer token.30Token,31/// A Unix socket request whose peer process runs as this uid.32PeerUid(u32),33 }3435/// The credentials that this process accepts. An `Auth` with no token is "auth36/// off": every TCP request is `None` and the caller decides (R19). The peer37/// list starts empty; the binary adds the uid that it runs as before it serves.38pubstructAuth {39 token: Option<[u8; TOKEN_BYTES]>,40/// The uids that a Unix socket peer may run as. Empty refuses every uid.41 peers: Vec<u32>,42 }4344implAuth {45/// No token: every request is `None` and the caller decides.46pubfnnew() -> Auth {47Auth {48 token: None,49 peers: Vec::new(),50 }51 }5253/// Reads a token from a file: [`HEX_CHARS`] hex characters and one54/// newline. The deploy file is the only place the token is written, so a55/// short or non-hex file stops the process at startup.56pubfnfrom_token_file(path: &Path) -> Result<Auth, AuthError> {57let text = fs::read_to_string(path).map_err(|e| AuthError::Io(e.to_string()))?;58let token = text.strip_suffix('\n').unwrap_or(&text);59Auth::from_token(token)60 }6162/// From the raw token bytes (the tests use this).63pubfnfrom_token(token: &str) -> Result<Auth, AuthError> {64let bytes = decode_hex(token).ok_or_else(|| {65AuthError::BadToken(format!(66"need {HEX_CHARS} hex characters, got {}",67 token.len()68 ))69 })?;70Ok(Auth {71 token: Some(bytes),72 peers: Vec::new(),73 })74 }7576/// The token is configured.77pubfnis_configured(&self) -> bool {78self.token.is_some()79 }8081/// Adds a uid that a Unix socket peer may run as. The socket owner calls82/// this once at startup; the set is the whole answer to "who is local".83pubfnallow_uid(&mutself, uid: u32) {84if !self.peers.contains(&uid) {85self.peers.push(uid);86 }87 }8889/// Checks the Authorization header of a TCP request. A missing token means90/// auth is off, and this reports `Missing` so that the caller can decide.91pubfncheck_token(&self, headers: &Headers) -> Result<Principal, AuthError> {92let want = self.token.as_ref().ok_or(AuthError::Missing)?;93let value = headers.get("authorization").ok_or(AuthError::Missing)?;94let presented = value.strip_prefix(BEARER).ok_or(AuthError::Scheme)?;95let got = decode_hex(presented).ok_or(AuthError::Bad)?;96ifconstant_time_eq(want, &got) {97Ok(Principal::Token)98 } else {99Err(AuthError::Bad)100 }101 }102103/// Checks the uid of a Unix socket peer. An empty set refuses every uid.104pubfncheck_peer(&self, uid: u32) -> Result<Principal, AuthError> {105ifself.peers.contains(&uid) {106Ok(Principal::PeerUid(uid))107 } else {108Err(AuthError::Bad)109 }110 }111 }112113implDefaultforAuth {114fndefault() -> Auth {115Auth::new()116 }117 }118119/// Compares two tokens of the same size in constant time.120///121/// The fold visits every byte and combines with `|`, so the result depends on122/// all of them and the loop never returns early. The length check may return123/// early because only the decode in [`Auth::check_token`] calls this, and that124/// decode already refuses any input that is not [`TOKEN_BYTES`] long.125fnconstant_time_eq(a: &[u8; TOKEN_BYTES], b: &[u8; TOKEN_BYTES]) -> bool {126letmut diff = 0u8;127for i in0..TOKEN_BYTES {128 diff |= a[i] ^ b[i];129 }130 diff == 0131 }132133/// Decodes [`HEX_CHARS`] hex characters into a token. Anything else is `None`,134/// which the callers turn into an error; the token is never guessed or padded.135fndecode_hex(text: &str) -> Option<[u8; TOKEN_BYTES]> {136let bytes = text.as_bytes();137if bytes.len() != HEX_CHARS {138returnNone;139 }140letmut out = [0u8; TOKEN_BYTES];141for i in0..TOKEN_BYTES {142let high = hex_digit(bytes[i * 2])?;143let low = hex_digit(bytes[i * 2 + 1])?;144 out[i] = (high << 4) | low;145 }146Some(out)147 }148149/// The value of one hex digit, upper or lower case.150fnhex_digit(b: u8) -> Option<u8> {151match b {152 b'0'..=b'9' => Some(b - b'0'),153 b'a'..=b'f' => Some(b - b'a' + 10),154 b'A'..=b'F' => Some(b - b'A' + 10),155 _ => None,156 }157 }158159/// The reason a request has no [`Principal`].160 #[derive(Clone, PartialEq, Eq, Debug)]161pubenumAuthError {162/// No Authorization header, or no token is configured. The caller treats163/// the second case as auth off.164Missing,165/// The Authorization header does not start with [`BEARER`].166Scheme,167/// The presented token is not the configured one.168Bad,169/// The token file is not [`HEX_CHARS`] hex characters and one newline.170BadToken(String),171/// The token file could not be read.172Io(String),173 }174175impl fmt::DisplayforAuthError {176fnfmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {177matchself {178AuthError::Missing => write!(f, "no authorization"),179AuthError::Scheme => write!(f, "not a Bearer token"),180AuthError::Bad => write!(f, "bad credentials"),181AuthError::BadToken(why) => write!(f, "bad token file: {why}"),182AuthError::Io(why) => write!(f, "io: {why}"),183 }184 }185 }186187impl std::error::ErrorforAuthError {}