Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / infra / agents / agentd / src / auth.rs

auth.rs215 lines · 6.8 KiBRaw
1//! Session auth: argon2 password verification, random session tokens,
2//! in-memory login rate limiting.
3//!
4//! The session cookie holds a 32-byte random token (base64url). Only the
5//! SHA-256 hash of the token is stored in SQLite.
6
7use std::collections::HashMap;
8use std::sync::{Arc, Mutex};
9use std::time::{Duration, Instant};
10
11use argon2::{Argon2, PasswordHash, PasswordVerifier};
12use rand::RngCore;
13use sha2::{Digest, Sha256};
14
15use crate::models::now_unix;
16use crate::store::Store;
17
18pub const SESSION_COOKIE: &str = "agentd_session";
19/// 7-day session lifetime, in seconds.
20pub const SESSION_TTL_SECS: i64 = 7 * 24 * 3600;
21
22#[derive(Clone)]
23pub struct Auth {
24 pub store: Store,
25 password_hash: String,
26 limiter: Arc<Mutex<LoginLimiter>>,
27}
28
29impl Auth {
30 pub fn new(store: Store, password_hash: String) -> Auth {
31 Auth {
32 store,
33 password_hash,
34 limiter: Arc::new(Mutex::new(LoginLimiter::default())),
35 }
36 }
37
38 /// Verify a password against the configured argon2 PHC hash.
39 /// Returns `false` (not an error) on mismatch so callers can 401/429.
40 pub fn verify_password(&self, password: &str) -> bool {
41 let parsed = match PasswordHash::new(&self.password_hash) {
42 Ok(h) => h,
43 Err(_) => return false,
44 };
45 Argon2::default()
46 .verify_password(password.as_bytes(), &parsed)
47 .is_ok()
48 }
49
50 /// Rate-limit check for a login attempt from `ip`. Returns `Some(retry
51 /// after)` when the attempt must be rejected with 429.
52 pub fn login_gate(&self, ip: &str) -> Option<Duration> {
53 self.limiter
54 .lock()
55 .map(|mut l| l.check(ip))
56 .unwrap_or(None)
57 }
58
59 pub fn login_failed(&self, ip: &str) {
60 if let Ok(mut l) = self.limiter.lock() {
61 l.failed(ip);
62 }
63 }
64
65 pub fn login_ok(&self, ip: &str) {
66 if let Ok(mut l) = self.limiter.lock() {
67 l.succeeded(ip);
68 }
69 }
70
71 /// Issue a session: random token + stored hash. Returns the raw token
72 /// (goes into the cookie only).
73 pub fn issue_session(&self) -> Result<String, String> {
74 let mut bytes = [0u8; 32];
75 rand::rng().fill_bytes(&mut bytes);
76 let token = base64url(&bytes);
77 let hash = token_sha_hex(&token);
78 let exp = now_unix() + SESSION_TTL_SECS;
79 self.store.put_session(&hash, exp)?;
80 Ok(token)
81 }
82
83 pub fn check_token(&self, token: &str) -> bool {
84 if token.is_empty() || token.len() > 256 {
85 return false;
86 }
87 let hash = token_sha_hex(token);
88 self.store
89 .session_valid(&hash, now_unix())
90 .unwrap_or(false)
91 }
92
93 pub fn revoke_token(&self, token: &str) {
94 let hash = token_sha_hex(token);
95 let _ = self.store.delete_session(&hash);
96 }
97}
98
99pub fn token_sha_hex(token: &str) -> String {
100 let digest = Sha256::digest(token.as_bytes());
101 hex_encode(&digest)
102}
103
104pub fn hex_encode(bytes: &[u8]) -> String {
105 const HEX: &[u8; 16] = b"0123456789abcdef";
106 let mut s = String::with_capacity(bytes.len() * 2);
107 for b in bytes {
108 s.push(HEX[(b >> 4) as usize] as char);
109 s.push(HEX[(b & 0xf) as usize] as char);
110 }
111 s
112}
113
114fn base64url(bytes: &[u8]) -> String {
115 const ALPH: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
116 let mut s = String::with_capacity((bytes.len() * 4).div_ceil(3));
117 let mut i = 0;
118 while i + 3 <= bytes.len() {
119 let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8) | bytes[i + 2] as u32;
120 s.push(ALPH[((n >> 18) & 63) as usize] as char);
121 s.push(ALPH[((n >> 12) & 63) as usize] as char);
122 s.push(ALPH[((n >> 6) & 63) as usize] as char);
123 s.push(ALPH[(n & 63) as usize] as char);
124 i += 3;
125 }
126 let rem = bytes.len() - i;
127 if rem == 1 {
128 let n = (bytes[i] as u32) << 16;
129 s.push(ALPH[((n >> 18) & 63) as usize] as char);
130 s.push(ALPH[((n >> 12) & 63) as usize] as char);
131 } else if rem == 2 {
132 let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8);
133 s.push(ALPH[((n >> 18) & 63) as usize] as char);
134 s.push(ALPH[((n >> 12) & 63) as usize] as char);
135 s.push(ALPH[((n >> 6) & 63) as usize] as char);
136 }
137 s
138}
139
140/// In-memory exponential-backoff login limiter: per-IP backoff on failures
141/// (1s, 2s, 4s, … capped at 5 min) plus a global cap of 60 attempts/min
142/// across all IPs.
143#[derive(Default)]
144struct LoginLimiter {
145 per_ip: HashMap<String, (u32, Instant)>,
146 global: Vec<Instant>,
147}
148
149impl LoginLimiter {
150 const MAX_BACKOFF: Duration = Duration::from_secs(300);
151 const GLOBAL_CAP: usize = 60;
152
153 fn check(&mut self, ip: &str) -> Option<Duration> {
154 let now = Instant::now();
155 self.global.retain(|t| now.duration_since(*t) < Duration::from_secs(60));
156 if self.global.len() >= Self::GLOBAL_CAP {
157 return Some(Duration::from_secs(30));
158 }
159 if let Some((fails, last)) = self.per_ip.get(ip) {
160 if *fails > 0 {
161 let shift = (*fails - 1).min(8);
162 let backoff = Duration::from_secs(1 << shift).min(Self::MAX_BACKOFF);
163 let elapsed = now.duration_since(*last);
164 if elapsed < backoff {
165 return Some(backoff - elapsed);
166 }
167 }
168 }
169 None
170 }
171
172 fn failed(&mut self, ip: &str) {
173 let now = Instant::now();
174 self.global.push(now);
175 let e = self.per_ip.entry(ip.to_string()).or_insert((0, now));
176 e.0 = e.0.saturating_add(1);
177 e.1 = now;
178 }
179
180 fn succeeded(&mut self, ip: &str) {
181 self.per_ip.remove(ip);
182 }
183}
184
185/// Client IP for rate limiting: first hop of `X-Forwarded-For` (set by
186/// Caddy), else the peer socket address.
187pub fn client_ip(forwarded_for: Option<&str>, peer: Option<std::net::SocketAddr>) -> String {
188 if let Some(ff) = forwarded_for {
189 let first = ff.split(',').next().unwrap_or("").trim();
190 if !first.is_empty() {
191 return first.to_string();
192 }
193 }
194 peer.map(|p| p.ip().to_string()).unwrap_or_else(|| "unknown".to_string())
195}
196
197/// Parse the session token out of a `Cookie` header value.
198pub fn session_token_from_cookie(header: &str) -> Option<String> {
199 for part in header.split(';') {
200 let part = part.trim();
201 if let Some(v) = part.strip_prefix(&format!("{SESSION_COOKIE}=")) {
202 let v = v.trim().trim_matches('"').to_string();
203 if !v.is_empty() {
204 return Some(v);
205 }
206 }
207 }
208 None
209}
210
211/// Strict `Origin` check for state-changing routes: the header must be
212/// present and exactly equal the configured public origin.
213pub fn origin_allowed(origin: Option<&str>, public_origin: &str) -> bool {
214 matches!(origin, Some(o) if o == public_origin)
215}