kumo_server_common/http_server/
auth.rs1use crate::acct::{log_authn, AuthnAuditRecord};
2use crate::authn_authz::{
3 ACLQueryDisposition, AccessControlList, AuthInfo, Identity, IdentityContext, Resource,
4};
5use crate::http_server::AppState;
6use async_trait::async_trait;
7use axum::extract::{FromRequestParts, Request, State};
8use axum::http::{StatusCode, Uri};
9use axum::middleware::Next;
10use axum::response::{IntoResponse, Response};
11use config::{declare_event, load_config, SerdeWrappedValue};
12use kumo_chrono_helper::{DateTime, Instant};
13use serde::{Deserialize, Serialize};
14use std::net::{IpAddr, SocketAddr};
15use tokio::time::Duration;
16
17lruttl::declare_cache! {
18static AUTH_CACHE: LruCacheWithTtl<AuthKind, Result<AuthKindResult, String>>::new("http_server_auth", 128);
20}
21
22declare_event! {
23static HTTP_AUTH_BASIC: Single("http_server_validate_auth_basic",
24 username: String,
25 password: Option<String>
26) -> SerdeWrappedValue<AuthKindResult>;
27}
28
29declare_event! {
30static HTTP_AUTH_BEARER: Single("http_server_validate_auth_bearer",
31 token: String
32) -> SerdeWrappedValue<AuthKindResult>;
33}
34
35#[derive(Debug, Clone, Hash, Eq, PartialEq)]
39enum AuthKind {
40 TrustedIp(IpAddr),
41 Basic {
42 user: String,
43 password: Option<String>,
44 },
45 Bearer {
46 token: String,
47 },
48}
49
50#[derive(Deserialize, Serialize, Clone, Debug)]
51#[serde(untagged)]
52pub enum AuthKindResult {
53 Bool(bool),
54 AuthInfo(AuthInfo),
55}
56
57impl Default for AuthKindResult {
58 fn default() -> Self {
59 Self::Bool(false)
60 }
61}
62
63impl AuthKind {
64 pub fn from_header(authorization: &str) -> Option<Self> {
65 let (kind, contents) = authorization.split_once(' ')?;
66 match kind {
67 "Basic" => {
68 let decoded = data_encoding::BASE64.decode(contents.as_bytes()).ok()?;
69 let decoded = String::from_utf8(decoded).ok()?;
70 let (user, password) = if let Some((id, password)) = decoded.split_once(':') {
71 (id.to_string(), Some(password.to_string()))
72 } else {
73 (decoded.to_string(), None)
74 };
75 Some(Self::Basic { user, password })
76 }
77 "Bearer" => Some(Self::Bearer {
78 token: contents.to_string(),
79 }),
80 _ => None,
81 }
82 }
83
84 async fn check_authentication_impl(&self) -> anyhow::Result<AuthKindResult> {
85 let mut config = load_config().await?;
86 let result = match self {
87 Self::TrustedIp(_) => AuthKindResult::Bool(true),
88 Self::Basic { user, password } => {
89 config
90 .async_call_callback(&HTTP_AUTH_BASIC, (user.to_string(), password.clone()))
91 .await?
92 .0
93 }
94 Self::Bearer { token } => {
95 config
96 .async_call_callback(&HTTP_AUTH_BEARER, token.to_string())
97 .await?
98 .0
99 }
100 };
101 config.put();
102 Ok(result)
103 }
104
105 async fn lookup_cache(&self) -> Option<Result<AuthKindResult, String>> {
106 AUTH_CACHE.get(self)
107 }
108
109 pub async fn check_authentication(&self) -> anyhow::Result<AuthKindResult> {
110 match self.lookup_cache().await {
111 Some(res) => res.map_err(|err| anyhow::anyhow!("{err}")),
112 None => {
113 let res = self
114 .check_authentication_impl()
115 .await
116 .map_err(|err| format!("{err:#}"));
117
118 let expiration = Instant::now().saturating_add(Duration::from_secs(60));
119 let res = AUTH_CACHE.insert(self.clone(), res, expiration).await;
120
121 res.map_err(|err| anyhow::anyhow!("{err}"))
122 }
123 }
124 }
125}
126
127pub async fn auth_middleware(
128 State(state): State<AppState>,
129 mut request: Request,
130 next: Next,
131) -> Response {
132 let mut auth_info = AuthInfo::default();
133 let mut auth_kind = None;
134
135 if let Some(remote_addr) = request
137 .extensions()
138 .get::<axum::extract::ConnectInfo<SocketAddr>>()
139 .map(|ci| ci.0)
140 {
141 let ip = remote_addr.ip();
142
143 auth_info.set_peer_address(Some(ip));
147
148 if state.is_trusted_host(ip) {
152 auth_kind.replace(AuthKind::TrustedIp(ip));
153 auth_info.add_group("kumomta:http-listener-trusted-ip");
154 }
155 }
156
157 if let Some(authorization) = request.headers().get(axum::http::header::AUTHORIZATION) {
159 match authorization.to_str() {
160 Err(_) => {
161 return (StatusCode::BAD_REQUEST, "Malformed Authorization header").into_response()
162 }
163 Ok(authorization) => match AuthKind::from_header(authorization) {
164 None => {
165 return (
166 StatusCode::BAD_REQUEST,
167 "Malformed or unsupported Authorization header",
168 )
169 .into_response()
170 }
171 Some(kind) => {
172 let mut attempted_identity = match &kind {
173 AuthKind::Basic { user, .. } => Identity {
174 identity: user.to_string(),
175 context: IdentityContext::HttpBasicAuth,
176 },
177 AuthKind::Bearer { .. } => Identity {
178 identity: String::new(),
179 context: IdentityContext::BearerToken,
180 },
181 AuthKind::TrustedIp(_) => {
182 unreachable!();
183 }
184 };
185 match kind.check_authentication().await {
186 Ok(AuthKindResult::Bool(true)) => {
187 auth_info.add_identity(attempted_identity.clone());
189 log_authn(AuthnAuditRecord {
190 attempted_identity,
191 success: true,
192 auth_info: auth_info.clone(),
193 timestamp: DateTime::now(),
194 })
195 .await
196 .ok();
197 auth_kind.replace(kind);
198 }
199 Ok(AuthKindResult::Bool(false)) => {
200 let reason = format!(
201 "{:?} Authentication Failed for {}",
202 attempted_identity.context, attempted_identity.identity
203 );
204 log_authn(AuthnAuditRecord {
205 attempted_identity,
206 success: false,
207 auth_info,
208 timestamp: DateTime::now(),
209 })
210 .await
211 .ok();
212 return (StatusCode::UNAUTHORIZED, reason).into_response();
213 }
214 Ok(AuthKindResult::AuthInfo(info)) => {
215 if attempted_identity.identity.is_empty() {
216 if let Some(ident) = info.identities.first() {
223 attempted_identity = ident.clone();
224 }
225 }
226
227 auth_info.merge_from(info);
229
230 log_authn(AuthnAuditRecord {
231 attempted_identity,
232 success: true,
233 auth_info: auth_info.clone(),
234 timestamp: DateTime::now(),
235 })
236 .await
237 .ok();
238 auth_kind.replace(kind);
239 }
240 Err(err) => {
241 tracing::error!("Error validating {kind:?}: {err:#}");
242 return (StatusCode::INTERNAL_SERVER_ERROR, "try again later")
243 .into_response();
244 }
245 }
246 }
247 },
248 }
249 }
250
251 if let Some(kind) = auth_kind.take() {
253 request.extensions_mut().insert(kind);
254 }
255 request.extensions_mut().insert(auth_info.clone());
256
257 match HttpEndpointResource::new(state.local_addr, request.uri()) {
259 Ok(mut resource) => {
260 let resource_id = resource.ident.to_string();
261 let method = request.method().to_string();
262 match AccessControlList::query_resource_access(&mut resource, &auth_info, &method).await
263 {
264 Ok(result) => match result {
265 ACLQueryDisposition::Allow { .. } => {}
266 ACLQueryDisposition::Deny { .. } => {
267 return (
270 StatusCode::UNAUTHORIZED,
271 format!("{auth_info} denied {method} on {resource_id}"),
272 )
273 .into_response();
274 }
275 ACLQueryDisposition::DenyByDefault => {
276 return (
281 StatusCode::UNAUTHORIZED,
282 format!("{auth_info} not permitted {method} on {resource_id}"),
283 )
284 .into_response();
285 }
286 },
287 Err(err) => {
288 tracing::error!("Error querying ACL: {err:#}");
289 return (StatusCode::INTERNAL_SERVER_ERROR, "try again later").into_response();
290 }
291 }
292 }
293 Err(err) => {
294 tracing::error!("Error building HttpEndpointResource: {err:#}");
295 return (StatusCode::BAD_REQUEST, "malformed URI?").into_response();
296 }
297 }
298
299 next.run(request).await
301}
302
303#[derive(Clone)]
304pub struct HttpEndpointResource {
305 ident: String,
306 iter: std::vec::IntoIter<String>,
307}
308
309const MAX_ACL_PATH_LEN: usize = 256;
311const MAX_ACL_PATH_COMPONENTS: usize = 10;
312
313impl HttpEndpointResource {
314 pub fn new(local_addr: SocketAddr, uri: &Uri) -> anyhow::Result<Self> {
315 let mut path: String = uri.path().to_string();
316 path.truncate(MAX_ACL_PATH_LEN);
317 let mut path_components: Vec<_> =
318 path[1..].splitn(MAX_ACL_PATH_COMPONENTS + 1, '/').collect();
319 path_components.truncate(MAX_ACL_PATH_COMPONENTS);
320
321 let mut resources_with_host_and_port = vec![];
322 let mut resources_with_path_only = vec![];
323
324 while !path_components.is_empty() {
325 let path = path_components.join("/");
326
327 resources_with_host_and_port.push(format!("http_listener/{local_addr}/{path}"));
328 resources_with_path_only.push(format!("http_listener/*/{path}"));
329
330 path_components.pop();
331 }
332 resources_with_host_and_port.push(format!("http_listener/{local_addr}"));
333
334 let mut resources = resources_with_host_and_port;
335 resources.append(&mut resources_with_path_only);
336 resources.push("http_listener".to_string());
337
338 let ident = resources[0].clone();
339
340 Ok(Self {
341 ident,
342 iter: resources.into_iter(),
343 })
344 }
345}
346
347#[async_trait]
348impl Resource for HttpEndpointResource {
349 fn resource_id(&self) -> &str {
350 &self.ident
351 }
352
353 async fn next_resource_id(&mut self) -> Option<String> {
354 self.iter.next()
355 }
356}
357
358#[cfg(test)]
359#[test]
360fn test_http_endpoint_resource_expansion() {
361 let res = HttpEndpointResource::new(
362 "127.0.0.1:8080".parse().unwrap(),
363 &Uri::from_static("https://user:pass@example.com:8080/foo/bar/baz"),
364 )
365 .unwrap();
366
367 assert_eq!(
368 res.iter.collect::<Vec<String>>(),
369 [
370 "http_listener/127.0.0.1:8080/foo/bar/baz",
371 "http_listener/127.0.0.1:8080/foo/bar",
372 "http_listener/127.0.0.1:8080/foo",
373 "http_listener/127.0.0.1:8080",
374 "http_listener/*/foo/bar/baz",
375 "http_listener/*/foo/bar",
376 "http_listener/*/foo",
377 "http_listener"
378 ]
379 .into_iter()
380 .map(Into::into)
381 .collect::<Vec<String>>(),
382 );
383}
384
385impl<B> FromRequestParts<B> for AuthKind
386where
387 B: Send + Sync,
388{
389 type Rejection = (StatusCode, &'static str);
390
391 async fn from_request_parts(
392 parts: &mut axum::http::request::Parts,
393 _: &B,
394 ) -> Result<Self, Self::Rejection> {
395 let kind = parts
396 .extensions
397 .get::<AuthKind>()
398 .ok_or((StatusCode::UNAUTHORIZED, "Unauthorized"))?;
399
400 Ok(kind.clone())
401 }
402}