1use std::path::Path;
20use std::sync::Arc;
21
22use crate::login_page::{self, SessionStore, LOGIN_PATH, LOGOUT_PATH};
23
24#[derive(Debug, Clone)]
26pub enum AuthPolicy {
27 Session {
32 user: String,
33 pass: String,
34 store: Arc<SessionStore>,
35 },
36 ApiKey { key: String },
39}
40
41#[derive(Debug, Clone)]
45pub struct AuthConfig {
46 pub policy: AuthPolicy,
47 pub realm: String,
48}
49
50pub const DEFAULT_REALM: &str = "KROT Protected Tunnel";
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Outcome {
57 Ok,
58 Missing,
59 BadCreds,
60}
61
62#[derive(Debug, Clone)]
65pub enum SessionAction {
66 Forward,
68 ServeLoginPage {
71 next: String,
72 error: Option<&'static str>,
73 },
74 Redirect {
77 location: String,
78 set_cookie: Option<String>,
79 },
80}
81
82impl AuthPolicy {
83 #[must_use]
86 pub fn check_api_key(&self, headers: &[httparse::Header<'_>]) -> Outcome {
87 match self {
88 Self::ApiKey { key } => check_api_key(key, headers),
89 Self::Session { .. } => {
90 debug_assert!(false, "check_api_key called on Session policy");
91 Outcome::BadCreds
92 }
93 }
94 }
95
96 #[must_use]
100 pub fn decide_session(
101 &self,
102 method: &str,
103 path: &str,
104 headers: &[httparse::Header<'_>],
105 body: &[u8],
106 ) -> SessionAction {
107 match self {
108 Self::Session { user, pass, store } => {
109 decide_session_inner(user, pass, store, method, path, headers, body)
110 }
111 Self::ApiKey { .. } => {
112 debug_assert!(false, "decide_session called on ApiKey policy");
113 SessionAction::Redirect {
114 location: "/".to_string(),
115 set_cookie: None,
116 }
117 }
118 }
119 }
120}
121
122fn decide_session_inner(
123 user: &str,
124 pass: &str,
125 store: &SessionStore,
126 method: &str,
127 path: &str,
128 headers: &[httparse::Header<'_>],
129 body: &[u8],
130) -> SessionAction {
131 let (path_only, query) = match path.split_once('?') {
132 Some((p, q)) => (p, Some(q)),
133 None => (path, None),
134 };
135
136 if path_only == LOGOUT_PATH {
138 if let Some(tok) = current_session_token(headers) {
139 store.invalidate(tok);
140 }
141 return SessionAction::Redirect {
142 location: "/".to_string(),
143 set_cookie: Some(login_page::session_clear_cookie()),
144 };
145 }
146
147 if path_only == LOGIN_PATH && method.eq_ignore_ascii_case("POST") {
149 let body_str = std::str::from_utf8(body).unwrap_or("");
150 let form = login_page::parse_login_form(body_str);
151 let ok = form.user.as_deref() == Some(user)
152 && constant_time_eq(
153 form.pass.as_deref().unwrap_or("").as_bytes(),
154 pass.as_bytes(),
155 );
156 let next = form
157 .next
158 .as_deref()
159 .map_or_else(|| "/".to_string(), login_page::safe_next);
160 if ok {
161 let token = store.create();
162 return SessionAction::Redirect {
163 location: next,
164 set_cookie: Some(login_page::session_set_cookie(&token)),
165 };
166 }
167 return SessionAction::ServeLoginPage {
168 next,
169 error: Some("Invalid username or password."),
170 };
171 }
172
173 if path_only == LOGIN_PATH {
175 let next = query
176 .and_then(|q| q.split('&').find_map(|pair| pair.strip_prefix("next=")))
177 .map(login_page::form_decode)
178 .as_deref()
179 .map_or_else(|| "/".to_string(), login_page::safe_next);
180 return SessionAction::ServeLoginPage { next, error: None };
181 }
182
183 if let Some(tok) = current_session_token(headers) {
185 if store.validate_and_refresh(tok) {
186 return SessionAction::Forward;
187 }
188 }
189 SessionAction::Redirect {
190 location: format!("{LOGIN_PATH}?next={}", percent_encode_path(path)),
191 set_cookie: None,
192 }
193}
194
195fn current_session_token<'a>(headers: &'a [httparse::Header<'_>]) -> Option<&'a str> {
196 for h in headers {
197 if h.name.eq_ignore_ascii_case("cookie") {
198 if let Ok(value) = std::str::from_utf8(h.value) {
199 if let Some(tok) = login_page::extract_session_cookie(value) {
200 return Some(tok);
201 }
202 }
203 }
204 }
205 None
206}
207
208fn percent_encode_path(s: &str) -> String {
212 let mut out = String::with_capacity(s.len());
213 for b in s.bytes() {
214 match b {
215 b'A'..=b'Z'
216 | b'a'..=b'z'
217 | b'0'..=b'9'
218 | b'-'
219 | b'_'
220 | b'.'
221 | b'~'
222 | b'/'
223 | b':'
224 | b'@'
225 | b','
226 | b';'
227 | b'=' => {
228 out.push(b as char);
229 }
230 _ => {
231 out.push('%');
232 out.push(hex_upper(b >> 4));
233 out.push(hex_upper(b & 0x0f));
234 }
235 }
236 }
237 out
238}
239
240const fn hex_upper(n: u8) -> char {
241 match n {
242 0..=9 => (b'0' + n) as char,
243 _ => (b'A' + n - 10) as char,
244 }
245}
246
247fn check_api_key(key: &str, headers: &[httparse::Header<'_>]) -> Outcome {
248 let mut saw_header = false;
249 for h in headers {
250 if h.name.eq_ignore_ascii_case("x-api-key") {
251 saw_header = true;
252 let Ok(value) = std::str::from_utf8(h.value) else {
253 return Outcome::BadCreds;
254 };
255 if constant_time_eq(value.trim().as_bytes(), key.as_bytes()) {
256 return Outcome::Ok;
257 }
258 }
259 if h.name.eq_ignore_ascii_case("authorization") {
260 saw_header = true;
261 let Ok(value) = std::str::from_utf8(h.value) else {
262 return Outcome::BadCreds;
263 };
264 let Some(rest) = strip_scheme_ci(value.trim(), "bearer") else {
265 continue;
266 };
267 if constant_time_eq(rest.trim().as_bytes(), key.as_bytes()) {
268 return Outcome::Ok;
269 }
270 }
271 }
272 if saw_header {
273 Outcome::BadCreds
274 } else {
275 Outcome::Missing
276 }
277}
278
279fn strip_scheme_ci<'a>(value: &'a str, scheme: &str) -> Option<&'a str> {
280 if value.len() <= scheme.len() {
281 return None;
282 }
283 let (head, tail) = value.split_at(scheme.len());
284 if !head.eq_ignore_ascii_case(scheme) {
285 return None;
286 }
287 if !tail.starts_with(char::is_whitespace) {
288 return None;
289 }
290 Some(tail)
291}
292
293fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
294 if a.len() != b.len() {
295 return false;
296 }
297 let mut acc: u8 = 0;
298 for (x, y) in a.iter().zip(b.iter()) {
299 acc |= x ^ y;
300 }
301 acc == 0
302}
303
304#[must_use]
307pub fn api_key_reject_response() -> Vec<u8> {
308 let body = b"Forbidden";
309 let head = format!(
310 "HTTP/1.1 403 Forbidden\r\n\
311 Content-Type: text/plain\r\n\
312 Content-Length: {}\r\n\
313 Connection: close\r\n\r\n",
314 body.len(),
315 );
316 let mut out = head.into_bytes();
317 out.extend_from_slice(body);
318 out
319}
320
321#[must_use]
326pub const fn looks_like_tls(first_byte: u8) -> bool {
327 first_byte == 0x16
328}
329
330pub fn session_from_userpass(
333 s: &str,
334 store: Arc<SessionStore>,
335) -> Result<AuthPolicy, AuthConfigError> {
336 let (user, pass) = s.split_once(':').ok_or(AuthConfigError::MissingColon)?;
337 if user.is_empty() {
338 return Err(AuthConfigError::EmptyUser);
339 }
340 Ok(AuthPolicy::Session {
341 user: user.to_string(),
342 pass: pass.to_string(),
343 store,
344 })
345}
346
347#[must_use]
349pub fn api_key_from_str(s: &str) -> AuthPolicy {
350 AuthPolicy::ApiKey {
351 key: s.trim().to_string(),
352 }
353}
354
355pub fn read_env(var: &str) -> Result<String, AuthConfigError> {
356 let value = std::env::var(var).map_err(|_| AuthConfigError::EnvUnset(var.to_string()))?;
357 if value.is_empty() {
358 return Err(AuthConfigError::EnvUnset(var.to_string()));
359 }
360 Ok(value)
361}
362
363pub fn read_file(path: &Path) -> Result<String, AuthConfigError> {
364 let raw = std::fs::read_to_string(path)
365 .map_err(|e| AuthConfigError::FileRead(path.display().to_string(), e.to_string()))?;
366 let trimmed = raw.trim_end_matches(['\r', '\n']).to_string();
367 if trimmed.is_empty() {
368 return Err(AuthConfigError::FileEmpty(path.display().to_string()));
369 }
370 Ok(trimmed)
371}
372
373#[derive(Debug, thiserror::Error)]
374pub enum AuthConfigError {
375 #[error("--auth value missing the `:` separator")]
376 MissingColon,
377 #[error("--auth username is empty")]
378 EmptyUser,
379 #[error("env var `{0}` is unset or empty")]
380 EnvUnset(String),
381 #[error("cannot read `{0}`: {1}")]
382 FileRead(String, String),
383 #[error("file `{0}` is empty")]
384 FileEmpty(String),
385}
386
387#[cfg(test)]
388mod tests {
389 use super::*;
390
391 fn header<'a>(name: &'a str, value: &'a [u8]) -> httparse::Header<'a> {
392 httparse::Header { name, value }
393 }
394
395 fn session_policy() -> AuthPolicy {
396 AuthPolicy::Session {
397 user: "alice".into(),
398 pass: "s3cret".into(),
399 store: SessionStore::new(),
400 }
401 }
402
403 #[test]
404 fn session_from_userpass_parses() {
405 let store = SessionStore::new();
406 let AuthPolicy::Session { user, pass, .. } =
407 session_from_userpass("alice:s3cret", store).unwrap()
408 else {
409 panic!("expected Session");
410 };
411 assert_eq!(user, "alice");
412 assert_eq!(pass, "s3cret");
413 }
414
415 #[test]
416 fn session_from_userpass_requires_colon() {
417 assert!(matches!(
418 session_from_userpass("noColonHere", SessionStore::new()),
419 Err(AuthConfigError::MissingColon),
420 ));
421 }
422
423 #[test]
424 fn session_from_userpass_rejects_empty_user() {
425 assert!(matches!(
426 session_from_userpass(":passonly", SessionStore::new()),
427 Err(AuthConfigError::EmptyUser),
428 ));
429 }
430
431 #[test]
432 fn session_missing_cookie_redirects_to_login() {
433 let policy = session_policy();
434 let action = policy.decide_session("GET", "/dashboard", &[], b"");
435 let SessionAction::Redirect {
436 location,
437 set_cookie,
438 } = action
439 else {
440 panic!("expected Redirect, got {action:?}");
441 };
442 assert_eq!(set_cookie, None);
443 assert!(location.starts_with("/__krot/login?next="));
444 assert!(location.contains("%2Fdashboard") || location.contains("/dashboard"));
445 }
446
447 #[test]
448 fn session_valid_cookie_forwards() {
449 let policy = session_policy();
450 let AuthPolicy::Session { ref store, .. } = policy else {
451 unreachable!()
452 };
453 let token = store.create();
454 let cookie = format!("__krot_session={token}");
455 let hs = [header("Cookie", cookie.as_bytes())];
456 let action = policy.decide_session("GET", "/dashboard", &hs, b"");
457 assert!(matches!(action, SessionAction::Forward), "{action:?}");
458 }
459
460 #[test]
461 fn session_login_get_serves_page() {
462 let policy = session_policy();
463 let action = policy.decide_session("GET", "/__krot/login", &[], b"");
464 let SessionAction::ServeLoginPage { next, error } = action else {
465 panic!("expected ServeLoginPage");
466 };
467 assert_eq!(next, "/");
468 assert!(error.is_none());
469 }
470
471 #[test]
472 fn session_login_get_honours_next_query() {
473 let policy = session_policy();
474 let action = policy.decide_session("GET", "/__krot/login?next=%2Fdash", &[], b"");
475 let SessionAction::ServeLoginPage { next, .. } = action else {
476 panic!("expected ServeLoginPage");
477 };
478 assert_eq!(next, "/dash");
479 }
480
481 #[test]
482 fn session_login_post_correct_creds_sets_cookie() {
483 let policy = session_policy();
484 let body = b"user=alice&pass=s3cret&next=%2Fhome";
485 let action = policy.decide_session("POST", "/__krot/login", &[], body);
486 let SessionAction::Redirect {
487 location,
488 set_cookie,
489 } = action
490 else {
491 panic!("expected Redirect");
492 };
493 assert_eq!(location, "/home");
494 let sc = set_cookie.expect("cookie");
495 assert!(sc.contains("__krot_session="));
496 assert!(sc.contains("HttpOnly"));
497 }
498
499 #[test]
500 fn session_login_post_wrong_creds_shows_error() {
501 let policy = session_policy();
502 let body = b"user=alice&pass=wrong&next=%2F";
503 let action = policy.decide_session("POST", "/__krot/login", &[], body);
504 let SessionAction::ServeLoginPage { error, .. } = action else {
505 panic!("expected ServeLoginPage");
506 };
507 assert!(error.is_some());
508 }
509
510 #[test]
511 fn session_logout_clears_cookie() {
512 let policy = session_policy();
513 let AuthPolicy::Session { ref store, .. } = policy else {
514 unreachable!()
515 };
516 let token = store.create();
517 let cookie = format!("__krot_session={token}");
518 let hs = [header("Cookie", cookie.as_bytes())];
519 let action = policy.decide_session("GET", "/__krot/logout", &hs, b"");
520 let SessionAction::Redirect {
521 location,
522 set_cookie,
523 } = action
524 else {
525 panic!("expected Redirect");
526 };
527 assert_eq!(location, "/");
528 let sc = set_cookie.expect("clear cookie");
529 assert!(sc.contains("Max-Age=0"));
530 assert!(!store.validate_and_refresh(&token));
531 }
532
533 #[test]
534 fn session_expired_cookie_redirects() {
535 let policy = session_policy();
536 let hs = [header("Cookie", b"__krot_session=nope")];
537 let action = policy.decide_session("GET", "/x", &hs, b"");
538 assert!(matches!(action, SessionAction::Redirect { .. }));
539 }
540
541 #[test]
544 fn api_key_accepts_x_api_key() {
545 let p = AuthPolicy::ApiKey {
546 key: "sk_live_42".into(),
547 };
548 let hs = [header("X-API-Key", b"sk_live_42")];
549 assert_eq!(p.check_api_key(&hs), Outcome::Ok);
550 }
551
552 #[test]
553 fn api_key_accepts_bearer() {
554 let p = AuthPolicy::ApiKey {
555 key: "sk_live_42".into(),
556 };
557 let hs = [header("Authorization", b"Bearer sk_live_42")];
558 assert_eq!(p.check_api_key(&hs), Outcome::Ok);
559 }
560
561 #[test]
562 fn api_key_rejects_wrong() {
563 let p = AuthPolicy::ApiKey {
564 key: "sk_live_42".into(),
565 };
566 let hs = [header("X-API-Key", b"nope")];
567 assert_eq!(p.check_api_key(&hs), Outcome::BadCreds);
568 }
569
570 #[test]
571 fn api_key_missing_returns_missing() {
572 let p = AuthPolicy::ApiKey {
573 key: "sk_live_42".into(),
574 };
575 let hs = [header("Host", b"example")];
576 assert_eq!(p.check_api_key(&hs), Outcome::Missing);
577 }
578
579 #[test]
580 fn api_key_reject_shape() {
581 let bytes = api_key_reject_response();
582 let head = std::str::from_utf8(&bytes).unwrap();
583 assert!(head.starts_with("HTTP/1.1 403 Forbidden\r\n"));
584 assert!(!head.contains("WWW-Authenticate"));
585 assert!(head.ends_with("Forbidden"));
586 }
587
588 #[test]
589 fn tls_heuristic() {
590 assert!(looks_like_tls(0x16));
591 assert!(!looks_like_tls(b'G'));
592 assert!(!looks_like_tls(b'P'));
593 }
594
595 #[test]
596 fn constant_time_eq_correctness() {
597 assert!(constant_time_eq(b"same", b"same"));
598 assert!(!constant_time_eq(b"same", b"diff"));
599 assert!(!constant_time_eq(b"a", b"ab"));
600 assert!(constant_time_eq(b"", b""));
601 }
602
603 #[test]
604 fn read_file_trims_trailing_newlines() {
605 use std::io::Write as _;
606 let dir = tempfile::TempDir::new().unwrap();
607 let path = dir.path().join("secret");
608 let mut f = std::fs::File::create(&path).unwrap();
609 f.write_all(b"hunter2\n\n").unwrap();
610 assert_eq!(read_file(&path).unwrap(), "hunter2");
611 }
612
613 #[test]
614 fn read_file_rejects_empty() {
615 let dir = tempfile::TempDir::new().unwrap();
616 let path = dir.path().join("empty");
617 std::fs::write(&path, b"").unwrap();
618 assert!(matches!(
619 read_file(&path),
620 Err(AuthConfigError::FileEmpty(_))
621 ));
622 }
623
624 proptest::proptest! {
625 #[test]
626 fn api_key_check_never_panics(
627 name in ".{0,64}",
628 value in proptest::collection::vec(proptest::prelude::any::<u8>(), 0..1024),
629 ) {
630 let policy = AuthPolicy::ApiKey { key: "sk".into() };
631 let hs = [httparse::Header { name: &name, value: &value }];
632 let _ = policy.check_api_key(&hs);
633 }
634
635 #[test]
636 fn decide_session_never_panics(
637 method in "[A-Z]{0,10}",
638 path in ".{0,256}",
639 cookie in ".{0,256}",
640 body in proptest::collection::vec(proptest::prelude::any::<u8>(), 0..2048),
641 ) {
642 let policy = AuthPolicy::Session {
643 user: "u".into(),
644 pass: "p".into(),
645 store: SessionStore::new(),
646 };
647 let hs = [httparse::Header { name: "Cookie", value: cookie.as_bytes() }];
648 let _ = policy.decide_session(&method, &path, &hs, &body);
649 }
650
651 #[test]
652 fn session_from_userpass_never_panics(s in ".{0,256}") {
653 let _ = session_from_userpass(&s, SessionStore::new());
654 }
655 }
656}