crates/edge/server/src/auth.rs 6.3 KiB 187 lines Raw
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.7 8 use std::fmt;9 use std::fs;10 use std::path::Path;11 12 use crate::Headers;13 14 /// 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.17 const TOKEN_BYTES: usize = 32;18 19 /// The token as written in the deploy file: two hex characters per byte.20 const HEX_CHARS: usize = TOKEN_BYTES * 2;21 22 /// The only scheme this server speaks. The single space is part of the23 /// spelling, so `Bearer  ` and `bearer ` are both refused.24 const BEARER: &str = "Bearer ";25 26 /// Who sent a request. Every route but `/healthz` needs one.27 #[derive(Clone, Copy, PartialEq, Eq, Debug)]28 pub enum Principal {29     /// A TCP request that carried the configured bearer token.30     Token,31     /// A Unix socket request whose peer process runs as this uid.32     PeerUid(u32),33 }34 35 /// 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.38 pub struct Auth {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 }43 44 impl Auth {45     /// No token: every request is `None` and the caller decides.46     pub fn new() -> Auth {47         Auth {48             token: None,49             peers: Vec::new(),50         }51     }52 53     /// 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.56     pub fn from_token_file(path: &Path) -> Result<Auth, AuthError> {57         let text = fs::read_to_string(path).map_err(|e| AuthError::Io(e.to_string()))?;58         let token = text.strip_suffix('\n').unwrap_or(&text);59         Auth::from_token(token)60     }61 62     /// From the raw token bytes (the tests use this).63     pub fn from_token(token: &str) -> Result<Auth, AuthError> {64         let bytes = decode_hex(token).ok_or_else(|| {65             AuthError::BadToken(format!(66                 "need {HEX_CHARS} hex characters, got {}",67                 token.len()68             ))69         })?;70         Ok(Auth {71             token: Some(bytes),72             peers: Vec::new(),73         })74     }75 76     /// The token is configured.77     pub fn is_configured(&self) -> bool {78         self.token.is_some()79     }80 81     /// 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".83     pub fn allow_uid(&mut self, uid: u32) {84         if !self.peers.contains(&uid) {85             self.peers.push(uid);86         }87     }88 89     /// 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.91     pub fn check_token(&self, headers: &Headers) -> Result<Principal, AuthError> {92         let want = self.token.as_ref().ok_or(AuthError::Missing)?;93         let value = headers.get("authorization").ok_or(AuthError::Missing)?;94         let presented = value.strip_prefix(BEARER).ok_or(AuthError::Scheme)?;95         let got = decode_hex(presented).ok_or(AuthError::Bad)?;96         if constant_time_eq(want, &got) {97             Ok(Principal::Token)98         } else {99             Err(AuthError::Bad)100         }101     }102 103     /// Checks the uid of a Unix socket peer. An empty set refuses every uid.104     pub fn check_peer(&self, uid: u32) -> Result<Principal, AuthError> {105         if self.peers.contains(&uid) {106             Ok(Principal::PeerUid(uid))107         } else {108             Err(AuthError::Bad)109         }110     }111 }112 113 impl Default for Auth {114     fn default() -> Auth {115         Auth::new()116     }117 }118 119 /// 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.125 fn constant_time_eq(a: &[u8; TOKEN_BYTES], b: &[u8; TOKEN_BYTES]) -> bool {126     let mut diff = 0u8;127     for i in 0..TOKEN_BYTES {128         diff |= a[i] ^ b[i];129     }130     diff == 0131 }132 133 /// 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.135 fn decode_hex(text: &str) -> Option<[u8; TOKEN_BYTES]> {136     let bytes = text.as_bytes();137     if bytes.len() != HEX_CHARS {138         return None;139     }140     let mut out = [0u8; TOKEN_BYTES];141     for i in 0..TOKEN_BYTES {142         let high = hex_digit(bytes[i * 2])?;143         let low = hex_digit(bytes[i * 2 + 1])?;144         out[i] = (high << 4) | low;145     }146     Some(out)147 }148 149 /// The value of one hex digit, upper or lower case.150 fn hex_digit(b: u8) -> Option<u8> {151     match 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 }158 159 /// The reason a request has no [`Principal`].160 #[derive(Clone, PartialEq, Eq, Debug)]161 pub enum AuthError {162     /// No Authorization header, or no token is configured. The caller treats163     /// the second case as auth off.164     Missing,165     /// The Authorization header does not start with [`BEARER`].166     Scheme,167     /// The presented token is not the configured one.168     Bad,169     /// The token file is not [`HEX_CHARS`] hex characters and one newline.170     BadToken(String),171     /// The token file could not be read.172     Io(String),173 }174 175 impl fmt::Display for AuthError {176     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {177         match self {178             AuthError::Missing => write!(f, "no authorization"),179             AuthError::Scheme => write!(f, "not a Bearer token"),180             AuthError::Bad => write!(f, "bad credentials"),181             AuthError::BadToken(why) => write!(f, "bad token file: {why}"),182             AuthError::Io(why) => write!(f, "io: {why}"),183         }184     }185 }186 187 impl std::error::Error for AuthError {}