1use crate::error::ServerError;
8use std::fs;
9use std::path::Path;
10
11pub const BASIC_REALM: &str = "arks";
13
14#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct BasicCredential {
17 pub username: String,
18 pub password: String,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct BasicAuthConfig {
24 pub credentials: Vec<BasicCredential>,
25 pub realm: String,
26}
27
28impl BasicAuthConfig {
29 pub fn single(user: impl Into<String>, pass: impl Into<String>) -> Self {
30 Self {
31 credentials: vec![BasicCredential {
32 username: user.into(),
33 password: pass.into(),
34 }],
35 realm: BASIC_REALM.into(),
36 }
37 }
38
39 pub fn parse_user_pass(spec: &str) -> Result<Self, ServerError> {
41 let (user, pass) = split_user_pass(spec)?;
42 Ok(Self::single(user, pass))
43 }
44
45 pub fn from_file(path: impl AsRef<Path>) -> Result<Self, ServerError> {
48 let text = fs::read_to_string(path.as_ref())
49 .map_err(|e| ServerError::Msg(format!("basic-auth file: {e}")))?;
50 let mut credentials = Vec::new();
51 for (idx, line) in text.lines().enumerate() {
52 let line = line.trim();
53 if line.is_empty() || line.starts_with('#') {
54 continue;
55 }
56 let (user, pass) = split_user_pass(line)
57 .map_err(|e| ServerError::Msg(format!("basic-auth file line {}: {e}", idx + 1)))?;
58 credentials.push(BasicCredential {
59 username: user,
60 password: pass,
61 });
62 }
63 if credentials.is_empty() {
64 return Err(ServerError::Msg(
65 "basic-auth file has no credentials".into(),
66 ));
67 }
68 Ok(Self {
69 credentials,
70 realm: BASIC_REALM.into(),
71 })
72 }
73
74 pub fn challenge_header(&self) -> String {
75 format!("Basic realm=\"{}\"", self.realm.replace('"', ""))
76 }
77
78 pub fn check_authorization(&self, authorization: Option<&str>) -> bool {
80 self.authorized_user(authorization).is_some()
81 }
82
83 pub fn authorized_user(&self, authorization: Option<&str>) -> Option<String> {
85 let raw = authorization.map(str::trim).filter(|s| !s.is_empty())?;
86 let rest = raw
87 .strip_prefix("Basic ")
88 .or_else(|| raw.strip_prefix("basic "))?;
89 let decoded = base64_decode(rest.trim().as_bytes()).ok()?;
90 let pair = String::from_utf8(decoded).ok()?;
91 let (user, pass) = pair.split_once(':')?;
92 self.credentials
93 .iter()
94 .any(|c| {
95 constant_eq(c.username.as_bytes(), user.as_bytes())
96 && constant_eq(c.password.as_bytes(), pass.as_bytes())
97 })
98 .then(|| user.to_string())
99 }
100}
101
102fn split_user_pass(spec: &str) -> Result<(String, String), ServerError> {
103 let spec = spec.trim();
104 let Some((user, pass)) = spec.split_once(':') else {
105 return Err(ServerError::Msg(
106 "basic-auth needs user:pass (colon-separated)".into(),
107 ));
108 };
109 if user.is_empty() {
110 return Err(ServerError::Msg("basic-auth username empty".into()));
111 }
112 Ok((user.to_string(), pass.to_string()))
113}
114
115fn constant_eq(a: &[u8], b: &[u8]) -> bool {
116 if a.len() != b.len() {
117 let mut acc = 1u8;
119 let n = a.len().max(b.len());
120 for i in 0..n {
121 let x = a.get(i).copied().unwrap_or(0);
122 let y = b.get(i).copied().unwrap_or(0);
123 acc |= x ^ y;
124 }
125 return false && acc == 0;
126 }
127 let mut acc = 0u8;
128 for (x, y) in a.iter().zip(b.iter()) {
129 acc |= x ^ y;
130 }
131 acc == 0
132}
133
134fn base64_decode(input: &[u8]) -> Result<Vec<u8>, ()> {
135 fn val(c: u8) -> Result<u8, ()> {
136 match c {
137 b'A'..=b'Z' => Ok(c - b'A'),
138 b'a'..=b'z' => Ok(c - b'a' + 26),
139 b'0'..=b'9' => Ok(c - b'0' + 52),
140 b'+' => Ok(62),
141 b'/' => Ok(63),
142 _ => Err(()),
143 }
144 }
145 let mut cleaned = Vec::with_capacity(input.len());
146 for &c in input {
147 if !c.is_ascii_whitespace() {
148 cleaned.push(c);
149 }
150 }
151 if cleaned.is_empty() || cleaned.len() % 4 != 0 {
152 return Err(());
153 }
154 let mut out = Vec::with_capacity(cleaned.len() / 4 * 3);
155 for chunk in cleaned.chunks_exact(4) {
156 let pad = chunk.iter().filter(|&&c| c == b'=').count();
157 if pad > 2 {
158 return Err(());
159 }
160 let b0 = val(chunk[0])?;
161 let b1 = val(chunk[1])?;
162 let b2 = if chunk[2] == b'=' { 0 } else { val(chunk[2])? };
163 let b3 = if chunk[3] == b'=' { 0 } else { val(chunk[3])? };
164 let n =
165 (u32::from(b0) << 18) | (u32::from(b1) << 12) | (u32::from(b2) << 6) | u32::from(b3);
166 out.push(((n >> 16) & 0xff) as u8);
167 if pad < 2 {
168 out.push(((n >> 8) & 0xff) as u8);
169 }
170 if pad < 1 {
171 out.push((n & 0xff) as u8);
172 }
173 }
174 Ok(out)
175}
176
177pub fn base64_encode(data: &[u8]) -> String {
179 const T: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
180 let mut out = String::new();
181 let mut i = 0;
182 while i + 3 <= data.len() {
183 let n = (u32::from(data[i]) << 16) | (u32::from(data[i + 1]) << 8) | u32::from(data[i + 2]);
184 out.push(T[((n >> 18) & 63) as usize] as char);
185 out.push(T[((n >> 12) & 63) as usize] as char);
186 out.push(T[((n >> 6) & 63) as usize] as char);
187 out.push(T[(n & 63) as usize] as char);
188 i += 3;
189 }
190 let rem = data.len() - i;
191 if rem == 1 {
192 let n = u32::from(data[i]) << 16;
193 out.push(T[((n >> 18) & 63) as usize] as char);
194 out.push(T[((n >> 12) & 63) as usize] as char);
195 out.push('=');
196 out.push('=');
197 } else if rem == 2 {
198 let n = (u32::from(data[i]) << 16) | (u32::from(data[i + 1]) << 8);
199 out.push(T[((n >> 18) & 63) as usize] as char);
200 out.push(T[((n >> 12) & 63) as usize] as char);
201 out.push(T[((n >> 6) & 63) as usize] as char);
202 out.push('=');
203 }
204 out
205}
206
207pub fn basic_authorization_header(user: &str, pass: &str) -> String {
208 format!(
209 "Basic {}",
210 base64_encode(format!("{user}:{pass}").as_bytes())
211 )
212}
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217
218 #[test]
219 fn accepts_valid_basic() {
220 let cfg = BasicAuthConfig::single("alice", "s3cret");
221 let hdr = basic_authorization_header("alice", "s3cret");
222 assert!(cfg.check_authorization(Some(&hdr)));
223 }
224
225 #[test]
226 fn rejects_missing_and_wrong() {
227 let cfg = BasicAuthConfig::single("alice", "s3cret");
228 assert!(!cfg.check_authorization(None));
229 assert!(!cfg.check_authorization(Some("")));
230 assert!(!cfg.check_authorization(Some("Bearer x")));
231 assert!(!cfg.check_authorization(Some(&basic_authorization_header("alice", "nope"))));
232 assert!(!cfg.check_authorization(Some(&basic_authorization_header("bob", "s3cret"))));
233 }
234
235 #[test]
236 fn password_may_contain_colon() {
237 let cfg = BasicAuthConfig::parse_user_pass("u:p:ass").unwrap();
238 assert!(cfg.check_authorization(Some(&basic_authorization_header("u", "p:ass"))));
239 }
240
241 #[test]
242 fn roundtrip_base64() {
243 let raw = b"user:pass-word!";
244 let enc = base64_encode(raw);
245 assert_eq!(base64_decode(enc.as_bytes()).unwrap(), raw);
246 }
247}