1use std::collections::HashMap;
19use std::fmt;
20use std::net::SocketAddr;
21use std::sync::{Mutex, PoisonError};
22use std::time::{Duration, Instant};
23
24use openmoat_core::Taint;
25use zeroize::Zeroizing;
26
27pub const MIN_TOKEN_LEN: usize = 32;
29
30const MAX_SESSION_LEN: usize = 128;
32
33pub struct Credential {
35 session: String,
36 token: Zeroizing<Vec<u8>>,
37}
38
39impl fmt::Debug for Credential {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 f.debug_struct("Credential")
43 .field("session", &self.session)
44 .finish_non_exhaustive()
45 }
46}
47
48#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
50#[non_exhaustive]
51pub enum CredentialError {
52 #[error("a session id is 1 to 128 ASCII letters, digits, `.`, `_` or `-`")]
55 Session,
56 #[error("a session token is at least 32 ASCII letters, digits, `.`, `_` or `-`")]
58 Token,
59}
60
61fn plain(bytes: &[u8]) -> bool {
63 bytes
64 .iter()
65 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
66}
67
68impl Credential {
69 pub fn new(session: &str, token: &[u8]) -> Result<Self, CredentialError> {
71 if session.is_empty() || session.len() > MAX_SESSION_LEN || !plain(session.as_bytes()) {
72 return Err(CredentialError::Session);
73 }
74 if token.len() < MIN_TOKEN_LEN || !plain(token) {
75 return Err(CredentialError::Token);
76 }
77 Ok(Self {
78 session: session.to_owned(),
79 token: Zeroizing::new(token.to_vec()),
80 })
81 }
82
83 #[must_use]
85 pub fn session(&self) -> &str {
86 &self.session
87 }
88
89 #[must_use]
92 pub fn proxy_url(&self, addr: SocketAddr) -> Zeroizing<String> {
93 let token = String::from_utf8_lossy(&self.token);
94 Zeroizing::new(format!("http://{}:{token}@{addr}", self.session))
95 }
96}
97
98pub trait Verify: Send + Sync {
101 fn verify(&self, user: &[u8], password: &[u8]) -> Option<String>;
105}
106
107pub trait TaintLookup: Send + Sync {
110 fn taint(&self, session: &str) -> Result<Taint, String>;
113
114 fn version(&self) -> Option<i64> {
120 None
121 }
122}
123
124#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
127#[non_exhaustive]
128pub enum AuthError {
129 #[error("this proxy serves sessions only: the request carries no session credential")]
131 Missing,
132 #[error("the session credential is malformed")]
134 Malformed,
135 #[error("the session credential is not valid")]
137 Invalid,
138}
139
140type Looked = (Instant, Option<i64>, Taint);
142
143const MAX_RECENT: usize = 1024;
145
146const RECENT_IDLE: Duration = Duration::from_mins(10);
148
149pub struct Sessions<'a> {
151 credentials: Vec<Credential>,
152 issued: Option<&'a dyn Verify>,
153 without_credential: bool,
157 taint: &'a dyn TaintLookup,
158 recent: Mutex<HashMap<String, Looked>>,
162}
163
164impl fmt::Debug for Sessions<'_> {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 f.debug_struct("Sessions")
167 .field("credentials", &self.credentials)
168 .field("issued", &self.issued.is_some())
169 .field("without_credential", &self.without_credential)
170 .finish_non_exhaustive()
171 }
172}
173
174impl<'a> Sessions<'a> {
175 #[must_use]
177 pub fn new(credentials: Vec<Credential>, taint: &'a dyn TaintLookup) -> Self {
178 Self {
179 credentials,
180 issued: None,
181 without_credential: false,
182 taint,
183 recent: Mutex::new(HashMap::new()),
184 }
185 }
186
187 #[must_use]
190 pub fn issued(issued: &'a dyn Verify, taint: &'a dyn TaintLookup) -> Self {
191 Self {
192 issued: Some(issued),
193 ..Self::new(Vec::new(), taint)
194 }
195 }
196
197 #[must_use]
201 pub fn serving_without_credential(mut self) -> Self {
202 self.without_credential = true;
203 self
204 }
205
206 #[must_use]
208 pub fn serves_without_credential(&self) -> bool {
209 self.without_credential
210 }
211
212 pub fn verify<T: AsRef<[u8]>>(&self, headers: &[T]) -> Result<String, AuthError> {
216 let value = match headers {
217 [] => return Err(AuthError::Missing),
218 [one] => one.as_ref(),
219 _ => return Err(AuthError::Malformed),
220 };
221 let decoded = basic(value).ok_or(AuthError::Malformed)?;
222 let colon = decoded
223 .iter()
224 .position(|b| *b == b':')
225 .ok_or(AuthError::Malformed)?;
226 let (session, token) = (&decoded[..colon], &decoded[colon + 1..]);
227 let mut found = None;
228 for credential in &self.credentials {
229 let id = constant_time_eq(credential.session.as_bytes(), session);
230 let secret = constant_time_eq(&credential.token, token);
231 if id & secret {
232 found = Some(credential.session.clone());
233 }
234 }
235 if found.is_none()
236 && let Some(issued) = self.issued
237 {
238 found = issued.verify(session, token);
239 }
240 found.ok_or(AuthError::Invalid)
241 }
242
243 pub fn taint(&self, session: &str) -> Result<Taint, String> {
245 let version = self.taint.version();
247 let taint = self.taint.taint(session)?;
248 let mut recent = self.recent.lock().unwrap_or_else(PoisonError::into_inner);
249 if recent.len() >= MAX_RECENT {
252 recent.retain(|_, (at, _, _)| at.elapsed() < RECENT_IDLE);
253 }
254 recent.insert(session.to_owned(), (Instant::now(), version, taint.clone()));
255 Ok(taint)
256 }
257
258 pub fn taint_within(&self, session: &str, max_age: Duration) -> Result<Taint, String> {
265 let version = self.taint.version();
266 {
267 let recent = self.recent.lock().unwrap_or_else(PoisonError::into_inner);
268 if let Some((at, seen, taint)) = recent.get(session)
269 && at.elapsed() < max_age
270 && version.is_some()
271 && *seen == version
272 {
273 return Ok(taint.clone());
274 }
275 }
276 self.taint(session)
277 }
278}
279
280fn basic(value: &[u8]) -> Option<Zeroizing<Vec<u8>>> {
283 let value = value.trim_ascii();
284 let space = value.iter().position(u8::is_ascii_whitespace)?;
285 let (scheme, rest) = value.split_at(space);
286 if !scheme.eq_ignore_ascii_case(b"basic") {
287 return None;
288 }
289 base64(rest.trim_ascii())
290}
291
292#[must_use]
294pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
295 if a.len() != b.len() {
296 return false;
297 }
298 let diff = a
299 .iter()
300 .zip(b)
301 .fold(0u8, |acc, (x, y)| acc | std::hint::black_box(x ^ y));
302 std::hint::black_box(diff) == 0
303}
304
305#[must_use]
308pub fn base64(input: &[u8]) -> Option<Zeroizing<Vec<u8>>> {
309 let data = input
310 .strip_suffix(b"==")
311 .or_else(|| input.strip_suffix(b"="))
312 .unwrap_or(input);
313 let padded = data.len() != input.len();
314 if data.is_empty() || data.len() % 4 == 1 || (padded && !input.len().is_multiple_of(4)) {
315 return None;
316 }
317 let mut out = Zeroizing::new(Vec::with_capacity(data.len() / 4 * 3 + 2));
318 let mut acc: u32 = 0;
319 let mut bits = 0u32;
320 for &c in data {
321 let v = match c {
322 b'A'..=b'Z' => c - b'A',
323 b'a'..=b'z' => c - b'a' + 26,
324 b'0'..=b'9' => c - b'0' + 52,
325 b'+' => 62,
326 b'/' => 63,
327 _ => return None,
328 };
329 acc = (acc << 6) | u32::from(v);
330 bits += 6;
331 if bits >= 8 {
332 bits -= 8;
333 out.push(u8::try_from((acc >> bits) & 0xff).ok()?);
334 acc &= (1 << bits) - 1;
335 }
336 }
337 Some(out)
338}
339
340#[cfg(test)]
341pub(crate) mod tests;