1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
/*
This file is part of gnix (https://codeberg.org/metamuffin/gnix)
which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
Copyright (C) 2025 metamuffin <metamuffin.org>
*/
use crate::{
config::DynNode,
error::ServiceError,
modules::{Node, NodeContext, NodeKind, NodeRequest, NodeResponse},
};
use base64::Engine;
use futures::Future;
use http_body_util::{combinators::BoxBody, BodyExt};
use hyper::{
header::{HeaderValue, AUTHORIZATION, WWW_AUTHENTICATE},
Response, StatusCode,
};
use log::debug;
use serde::Deserialize;
use serde_yml::Value;
use std::{pin::Pin, sync::Arc};
use super::Credentials;
pub struct HttpBasicAuthKind;
impl NodeKind for HttpBasicAuthKind {
fn name(&self) -> &'static str {
"http_basic_auth"
}
fn instanciate(&self, config: Value) -> anyhow::Result<Arc<dyn Node>> {
Ok(Arc::new(serde_yml::from_value::<HttpBasicAuth>(config)?))
}
}
#[derive(Deserialize)]
pub struct HttpBasicAuth {
realm: String,
users: Credentials,
next: DynNode,
}
impl Node for HttpBasicAuth {
fn handle<'a>(
&'a self,
context: &'a mut NodeContext,
request: NodeRequest,
) -> Pin<Box<dyn Future<Output = Result<NodeResponse, ServiceError>> + Send + Sync + 'a>> {
Box::pin(async move {
if let Some(auth) = request.headers().get(AUTHORIZATION) {
let k = auth
.as_bytes()
.strip_prefix(b"Basic ")
.ok_or(ServiceError::BadAuth)?;
let k = base64::engine::general_purpose::STANDARD.decode(k)?;
let k = String::from_utf8(k)?;
let (username, password) = k.split_once(":").ok_or(ServiceError::BadAuth)?;
if self.users.authentificate(username, password) {
debug!("valid auth");
return self.next.handle(context, request).await;
} else {
debug!("invalid auth");
}
}
debug!("unauthorized; sending auth challenge");
let mut r = Response::new(BoxBody::<_, ServiceError>::new(
String::new().map_err(|_| unreachable!()),
));
*r.status_mut() = StatusCode::UNAUTHORIZED;
r.headers_mut().insert(
WWW_AUTHENTICATE,
HeaderValue::from_str(&format!("Basic realm=\"{}\"", self.realm)).unwrap(),
);
Ok(r)
})
}
}
|