swarm-authelia-bridge: authorize a request before parsing its body
The handler took `Json<BridgeRequest>`, which axum runs before the handler
body. A caller with no token and a malformed body got axum's rejection
(415/400/422), whose text is serde's ("unknown variant ..., expected one of
..."), and not the one generic 401 an unauthenticated caller is meant to see.
Take the body as bytes, authorize, then parse. A caller that is let in and
sends a body that doesn't parse gets a 400 with the parse error, as before in
substance. The request's content type is no longer checked.
This commit is contained in:
parent
4a7df3f804
commit
56cc8a86ec
3 changed files with 152 additions and 11 deletions
1
Cargo.lock
generated
1
Cargo.lock
generated
|
|
@ -5423,6 +5423,7 @@ dependencies = [
|
|||
"swarm-authelia-bridge-sock",
|
||||
"swarm-secret-client",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
|
|
|
|||
|
|
@ -25,5 +25,9 @@ swarm-secret-client.workspace = true
|
|||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
# `oneshot`, to send a request through the router.
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@ mod store;
|
|||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use axum::body::Bytes;
|
||||
use axum::extract::State;
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
|
|
@ -123,9 +124,7 @@ async fn main() -> Result<()> {
|
|||
write_lock: tokio::sync::Mutex::new(()),
|
||||
});
|
||||
|
||||
let app = Router::new()
|
||||
.route("/requests", post(handle_request))
|
||||
.with_state(Arc::clone(&state));
|
||||
let app = router(Arc::clone(&state));
|
||||
|
||||
let listener = bind_socket(&socket)?;
|
||||
tracing::info!(socket = %socket.display(), "swarm-authelia-bridge listening");
|
||||
|
|
@ -176,15 +175,69 @@ fn bind_socket(path: &std::path::Path) -> Result<tokio::net::UnixListener> {
|
|||
/// verbatim (JSON), not a per-operation REST route. That is what let the
|
||||
/// second operation arrive as a match arm rather than as another route
|
||||
/// with its own extractor and its own copy of the authorize call.
|
||||
async fn handle_request(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(req): Json<BridgeRequest>,
|
||||
) -> Response {
|
||||
if let Err(resp) = authorize(&state, &headers).await {
|
||||
return resp;
|
||||
///
|
||||
/// Only an authorized caller gets here, because [`require_controller`] wraps
|
||||
/// the router. The body is taken as bytes and parsed here, not by a `Json`
|
||||
/// extractor: the answer to one that does not parse is the `400` of
|
||||
/// [`unreadable`], which carries serde's own text and is for the controller
|
||||
/// alone.
|
||||
async fn handle_request(State(state): State<Arc<AppState>>, body: Bytes) -> Response {
|
||||
match serde_json::from_slice(&body) {
|
||||
Ok(req) => respond(&state.config, &state.write_lock, req).await,
|
||||
Err(e) => unreadable(&e),
|
||||
}
|
||||
respond(&state.config, &state.write_lock, req).await
|
||||
}
|
||||
|
||||
/// The routes the bridge serves. Every one goes through [`protect`] in
|
||||
/// [`router`], so adding a route here is all it takes to have it guarded.
|
||||
fn routes() -> Router<Arc<AppState>> {
|
||||
Router::new().route("/requests", post(handle_request))
|
||||
}
|
||||
|
||||
/// `routes` behind [`require_controller`], then given `state`. The layer is
|
||||
/// applied to the finished set, here, and not in the caller's chain of
|
||||
/// `.route`s: axum's `Router::layer` wraps only the routes added before it, so
|
||||
/// a route chained on after the layer would be served without a token. Routes
|
||||
/// belong in [`routes`]; [`router`] adds none to what this returns.
|
||||
fn protect(routes: Router<Arc<AppState>>, state: Arc<AppState>) -> Router {
|
||||
routes
|
||||
.layer(axum::middleware::from_fn_with_state(
|
||||
Arc::clone(&state),
|
||||
require_controller,
|
||||
))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
/// The router: [`routes`], behind [`require_controller`], so no handler's
|
||||
/// extractor reads a body before the caller is let in.
|
||||
fn router(state: Arc<AppState>) -> Router {
|
||||
protect(routes(), state)
|
||||
}
|
||||
|
||||
/// Middleware: let the request through only when [`authorize`] does, and
|
||||
/// answer its refusal otherwise.
|
||||
async fn require_controller(
|
||||
State(state): State<Arc<AppState>>,
|
||||
request: axum::extract::Request,
|
||||
next: axum::middleware::Next,
|
||||
) -> Response {
|
||||
match authorize(&state, request.headers()).await {
|
||||
Ok(()) => next.run(request).await,
|
||||
Err(refusal) => refusal,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `400` answering a body that does not parse as a [`BridgeRequest`].
|
||||
/// Only reached by a caller [`authorize`] let in, so serde's text in the
|
||||
/// answer goes to the controller and to nobody else.
|
||||
fn unreadable(e: &serde_json::Error) -> Response {
|
||||
(
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(BridgeResponse::Error {
|
||||
message: format!("unreadable request: {e}"),
|
||||
}),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// Everything after authentication: the operation itself. Takes the config
|
||||
|
|
@ -492,9 +545,17 @@ async fn generate_password(bin: &std::path::Path) -> Result<String> {
|
|||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::Router;
|
||||
use axum::body::Bytes;
|
||||
use axum::extract::State;
|
||||
use axum::response::Response;
|
||||
use axum::routing::post;
|
||||
|
||||
use super::{
|
||||
BridgeRequest, Config, Refusal, StatusCode, bind_socket, classify, handle,
|
||||
introspect::Verdict, respond,
|
||||
AppState, BridgeRequest, Config, Refusal, StatusCode, bind_socket, classify, handle,
|
||||
handle_request, introspect::Verdict, protect, respond, router, routes,
|
||||
};
|
||||
|
||||
const CONTROLLER: &str = "swarm-controller";
|
||||
|
|
@ -622,6 +683,81 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
/// A state with no authelia to reach: a request is refused before
|
||||
/// anything calls it, or the test fails by trying.
|
||||
fn state_without_authelia() -> Arc<AppState> {
|
||||
Arc::new(AppState {
|
||||
config: config_with_one_operator(),
|
||||
http: reqwest::Client::new(),
|
||||
write_lock: tokio::sync::Mutex::new(()),
|
||||
})
|
||||
}
|
||||
|
||||
/// POST `body` to `path` on `app`, with no token.
|
||||
async fn post_tokenless(app: Router, path: &str, body: &'static str) -> Response {
|
||||
use tower::ServiceExt as _;
|
||||
app.oneshot(
|
||||
axum::http::Request::post(path)
|
||||
.body(axum::body::Body::from(body))
|
||||
.expect("a request"),
|
||||
)
|
||||
.await
|
||||
.expect("a router answers")
|
||||
}
|
||||
|
||||
/// A caller with no token gets the one generic refusal whatever its body
|
||||
/// is: serde's text about an unknown variant or a missing field is for an
|
||||
/// authenticated caller only. The request goes through the real router, so
|
||||
/// the layer is what is under test.
|
||||
#[tokio::test]
|
||||
async fn a_tokenless_request_is_refused_before_its_body_is_read() {
|
||||
for body in [
|
||||
"not json at all",
|
||||
"\"DropTable\"",
|
||||
"{\"EnsureAgentIdentity\":{}}",
|
||||
"",
|
||||
] {
|
||||
let resp = post_tokenless(router(state_without_authelia()), "/requests", body).await;
|
||||
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED, "body {body:?}");
|
||||
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
|
||||
.await
|
||||
.expect("body");
|
||||
let text = String::from_utf8(bytes.to_vec()).expect("utf-8");
|
||||
assert!(text.contains(Refusal::Caller.message()), "{text}");
|
||||
for serde_text in ["expected", "unknown variant", "missing field", "EOF"] {
|
||||
assert!(!text.contains(serde_text), "{serde_text} leaked: {text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`protect`] guards whatever set it is given: a second route, handed to it
|
||||
/// as [`router`] hands it the real ones, is refused without a token too.
|
||||
#[tokio::test]
|
||||
async fn a_route_given_to_protect_is_refused_without_a_token() {
|
||||
let routes = routes().route("/other", post(|| async { StatusCode::OK }));
|
||||
let resp = post_tokenless(protect(routes, state_without_authelia()), "/other", "").await;
|
||||
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
/// What an authorized caller gets, driven at the handler (a real
|
||||
/// authorization needs authelia): a body that parses is answered by the
|
||||
/// operation, and one that does not is a `400` carrying the parse error.
|
||||
#[tokio::test]
|
||||
async fn after_authorization_a_body_is_answered_or_refused_as_a_bad_request() {
|
||||
let state = state_without_authelia();
|
||||
let ask = |body: &'static str| handle_request(State(Arc::clone(&state)), Bytes::from(body));
|
||||
|
||||
assert_eq!(ask(r#""ListOperators""#).await.status(), StatusCode::OK);
|
||||
for body in ["not json", "\"DropTable\"", ""] {
|
||||
assert_eq!(
|
||||
ask(body).await.status(),
|
||||
StatusCode::BAD_REQUEST,
|
||||
"body {body:?}"
|
||||
);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(state.config.users_file.parent().unwrap());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_socket_replaces_a_stale_one_and_is_group_only() {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
|
|
|
|||
Loading…
Reference in a new issue