mirror of
https://github.com/pcvolkmer/mv64e-rest-to-kafka-gateway
synced 2025-09-13 09:12:51 +00:00
test: ensure authorization check is done first
This will ensure authorization check will be done before any other checks.
This commit is contained in:
51
src/main.rs
51
src/main.rs
@@ -1,17 +1,16 @@
|
|||||||
use axum::body::Body;
|
use axum::body::Body;
|
||||||
use axum::http::header::{AUTHORIZATION, CONTENT_TYPE, WWW_AUTHENTICATE};
|
use axum::http::header::WWW_AUTHENTICATE;
|
||||||
use axum::http::{HeaderValue, Request, StatusCode};
|
use axum::http::StatusCode;
|
||||||
use axum::middleware::{from_fn, Next};
|
|
||||||
use axum::response::{IntoResponse, Response};
|
use axum::response::{IntoResponse, Response};
|
||||||
use clap::Parser;
|
|
||||||
use rdkafka::producer::FutureProducer;
|
use rdkafka::producer::FutureProducer;
|
||||||
use rdkafka::ClientConfig;
|
use rdkafka::ClientConfig;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::sync::{Arc, LazyLock};
|
use std::sync::{Arc, LazyLock};
|
||||||
use tower_http::trace::TraceLayer;
|
|
||||||
|
#[cfg(not(test))]
|
||||||
|
use clap::Parser;
|
||||||
|
|
||||||
use crate::cli::Cli;
|
use crate::cli::Cli;
|
||||||
use crate::routes::routes;
|
|
||||||
use crate::sender::DefaultMtbFileSender;
|
use crate::sender::DefaultMtbFileSender;
|
||||||
use crate::AppResponse::{Accepted, Unauthorized, UnsupportedContentType};
|
use crate::AppResponse::{Accepted, Unauthorized, UnsupportedContentType};
|
||||||
|
|
||||||
@@ -55,6 +54,7 @@ impl IntoResponse for AppResponse<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(not(test))]
|
||||||
static CONFIG: LazyLock<Cli> = LazyLock::new(Cli::parse);
|
static CONFIG: LazyLock<Cli> = LazyLock::new(Cli::parse);
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
@@ -81,14 +81,10 @@ async fn main() -> Result<(), ()> {
|
|||||||
|
|
||||||
let sender = Arc::new(DefaultMtbFileSender::new(&CONFIG.topic, producer));
|
let sender = Arc::new(DefaultMtbFileSender::new(&CONFIG.topic, producer));
|
||||||
|
|
||||||
let routes = routes(sender)
|
|
||||||
.layer(from_fn(check_basic_auth))
|
|
||||||
.layer(TraceLayer::new_for_http());
|
|
||||||
|
|
||||||
match tokio::net::TcpListener::bind(&CONFIG.listen).await {
|
match tokio::net::TcpListener::bind(&CONFIG.listen).await {
|
||||||
Ok(listener) => {
|
Ok(listener) => {
|
||||||
log::info!("Starting application listening on '{}'", CONFIG.listen);
|
log::info!("Starting application listening on '{}'", CONFIG.listen);
|
||||||
if let Err(err) = axum::serve(listener, routes).await {
|
if let Err(err) = axum::serve(listener, routes::routes(sender)).await {
|
||||||
log::error!("Error starting application: {err}");
|
log::error!("Error starting application: {err}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -98,30 +94,15 @@ async fn main() -> Result<(), ()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn check_content_type_header(request: Request<Body>, next: Next) -> Response {
|
// Test Configuration
|
||||||
match request
|
#[cfg(test)]
|
||||||
.headers()
|
static CONFIG: LazyLock<Cli> = LazyLock::new(|| Cli {
|
||||||
.get(CONTENT_TYPE)
|
bootstrap_server: "localhost:9094".to_string(),
|
||||||
.map(HeaderValue::as_bytes)
|
topic: "test-topic".to_string(),
|
||||||
{
|
// Basic dG9rZW46dmVyeS1zZWNyZXQ=
|
||||||
Some(
|
token: "$2y$05$LIIFF4Rbi3iRVA4UIqxzPeTJ0NOn/cV2hDnSKFftAMzbEZRa42xSG".to_string(),
|
||||||
b"application/json"
|
listen: "0.0.0.0:3000".to_string(),
|
||||||
| b"application/json; charset=utf-8"
|
});
|
||||||
| b"application/vnd.dnpm.v2.mtb+json",
|
|
||||||
) => next.run(request).await,
|
|
||||||
_ => UnsupportedContentType.into_response(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn check_basic_auth(request: Request<Body>, next: Next) -> Response {
|
|
||||||
if let Some(Ok(auth_header)) = request.headers().get(AUTHORIZATION).map(|x| x.to_str()) {
|
|
||||||
if auth::check_basic_auth(auth_header, &CONFIG.token) {
|
|
||||||
return next.run(request).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
log::warn!("Invalid authentication used");
|
|
||||||
Unauthorized.into_response()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
128
src/routes.rs
128
src/routes.rs
@@ -1,12 +1,16 @@
|
|||||||
use crate::check_content_type_header;
|
|
||||||
use crate::sender::DynMtbFileSender;
|
use crate::sender::DynMtbFileSender;
|
||||||
use crate::AppResponse::{Accepted, InternalServerError};
|
use crate::AppResponse::{Accepted, InternalServerError, Unauthorized, UnsupportedContentType};
|
||||||
|
use crate::{auth, CONFIG};
|
||||||
|
use axum::body::Body;
|
||||||
use axum::extract::Path;
|
use axum::extract::Path;
|
||||||
use axum::middleware::from_fn;
|
use axum::http::header::{AUTHORIZATION, CONTENT_TYPE};
|
||||||
|
use axum::http::{HeaderValue, Request};
|
||||||
|
use axum::middleware::{from_fn, Next};
|
||||||
use axum::response::{IntoResponse, Response};
|
use axum::response::{IntoResponse, Response};
|
||||||
use axum::routing::{delete, post};
|
use axum::routing::{delete, post};
|
||||||
use axum::{Extension, Json, Router};
|
use axum::{Extension, Json, Router};
|
||||||
use mv64e_mtb_dto::Mtb;
|
use mv64e_mtb_dto::Mtb;
|
||||||
|
use tower_http::trace::TraceLayer;
|
||||||
|
|
||||||
pub async fn handle_delete(
|
pub async fn handle_delete(
|
||||||
Path(patient_id): Path<String>,
|
Path(patient_id): Path<String>,
|
||||||
@@ -38,6 +42,33 @@ pub fn routes(sender: DynMtbFileSender) -> Router {
|
|||||||
)
|
)
|
||||||
.layer(Extension(sender))
|
.layer(Extension(sender))
|
||||||
.layer(from_fn(check_content_type_header))
|
.layer(from_fn(check_content_type_header))
|
||||||
|
.layer(from_fn(check_basic_auth))
|
||||||
|
.layer(TraceLayer::new_for_http())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn check_basic_auth(request: Request<Body>, next: Next) -> Response {
|
||||||
|
if let Some(Ok(auth_header)) = request.headers().get(AUTHORIZATION).map(|x| x.to_str()) {
|
||||||
|
if auth::check_basic_auth(auth_header, &CONFIG.token) {
|
||||||
|
return next.run(request).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
log::warn!("Invalid authentication used");
|
||||||
|
Unauthorized.into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn check_content_type_header(request: Request<Body>, next: Next) -> Response {
|
||||||
|
match request
|
||||||
|
.headers()
|
||||||
|
.get(CONTENT_TYPE)
|
||||||
|
.map(HeaderValue::as_bytes)
|
||||||
|
{
|
||||||
|
Some(
|
||||||
|
b"application/json"
|
||||||
|
| b"application/json; charset=utf-8"
|
||||||
|
| b"application/vnd.dnpm.v2.mtb+json",
|
||||||
|
) => next.run(request).await,
|
||||||
|
_ => UnsupportedContentType.into_response(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -68,6 +99,7 @@ mod tests {
|
|||||||
Request::builder()
|
Request::builder()
|
||||||
.method(Method::POST)
|
.method(Method::POST)
|
||||||
.uri("/mtb/etl/patient-record")
|
.uri("/mtb/etl/patient-record")
|
||||||
|
.header(AUTHORIZATION, "Basic dG9rZW46dmVyeS1zZWNyZXQ=")
|
||||||
.header(CONTENT_TYPE, "application/json")
|
.header(CONTENT_TYPE, "application/json")
|
||||||
.body(body)
|
.body(body)
|
||||||
.expect("request built"),
|
.expect("request built"),
|
||||||
@@ -98,6 +130,7 @@ mod tests {
|
|||||||
Request::builder()
|
Request::builder()
|
||||||
.method(Method::DELETE)
|
.method(Method::DELETE)
|
||||||
.uri("/mtb/etl/patient-record/fae56ea7-24a7-4556-82fb-2b5dde71bb4d")
|
.uri("/mtb/etl/patient-record/fae56ea7-24a7-4556-82fb-2b5dde71bb4d")
|
||||||
|
.header(AUTHORIZATION, "Basic dG9rZW46dmVyeS1zZWNyZXQ=")
|
||||||
.header(CONTENT_TYPE, "application/json")
|
.header(CONTENT_TYPE, "application/json")
|
||||||
.body(Body::empty())
|
.body(Body::empty())
|
||||||
.expect("request built"),
|
.expect("request built"),
|
||||||
@@ -126,6 +159,7 @@ mod tests {
|
|||||||
Request::builder()
|
Request::builder()
|
||||||
.method(Method::POST)
|
.method(Method::POST)
|
||||||
.uri("/mtb/etl/patient-record")
|
.uri("/mtb/etl/patient-record")
|
||||||
|
.header(AUTHORIZATION, "Basic dG9rZW46dmVyeS1zZWNyZXQ=")
|
||||||
.header(CONTENT_TYPE, "application/vnd.dnpm.v2.mtb+json")
|
.header(CONTENT_TYPE, "application/vnd.dnpm.v2.mtb+json")
|
||||||
.body(body)
|
.body(body)
|
||||||
.expect("request built"),
|
.expect("request built"),
|
||||||
@@ -154,6 +188,7 @@ mod tests {
|
|||||||
Request::builder()
|
Request::builder()
|
||||||
.method(Method::POST)
|
.method(Method::POST)
|
||||||
.uri("/mtb/etl/patient-record")
|
.uri("/mtb/etl/patient-record")
|
||||||
|
.header(AUTHORIZATION, "Basic dG9rZW46dmVyeS1zZWNyZXQ=")
|
||||||
.header(CONTENT_TYPE, "application/xml")
|
.header(CONTENT_TYPE, "application/xml")
|
||||||
.body(body)
|
.body(body)
|
||||||
.expect("request built"),
|
.expect("request built"),
|
||||||
@@ -163,4 +198,91 @@ mod tests {
|
|||||||
|
|
||||||
assert_eq!(response.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
|
assert_eq!(response.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
#[allow(clippy::expect_used)]
|
||||||
|
async fn should_respond_bad_request_if_not_parsable() {
|
||||||
|
let mut sender_mock = MockMtbFileSender::new();
|
||||||
|
|
||||||
|
sender_mock
|
||||||
|
.expect_send()
|
||||||
|
.withf(|mtb| mtb.patient.id.eq("fae56ea7-24a7-4556-82fb-2b5dde71bb4d"))
|
||||||
|
.return_once(move |_| Ok(String::new()));
|
||||||
|
|
||||||
|
let router = routes(Arc::new(sender_mock) as DynMtbFileSender);
|
||||||
|
let body = Body::from("Das ist kein JSON!");
|
||||||
|
|
||||||
|
let response = router
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/mtb/etl/patient-record")
|
||||||
|
.header(AUTHORIZATION, "Basic dG9rZW46dmVyeS1zZWNyZXQ=")
|
||||||
|
.header(CONTENT_TYPE, "application/json")
|
||||||
|
.body(body)
|
||||||
|
.expect("request built"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
#[allow(clippy::expect_used)]
|
||||||
|
async fn should_respond_bad_request_if_not_processable() {
|
||||||
|
let mut sender_mock = MockMtbFileSender::new();
|
||||||
|
|
||||||
|
sender_mock
|
||||||
|
.expect_send()
|
||||||
|
.withf(|mtb| mtb.patient.id.eq("fae56ea7-24a7-4556-82fb-2b5dde71bb4d"))
|
||||||
|
.return_once(move |_| Ok(String::new()));
|
||||||
|
|
||||||
|
let router = routes(Arc::new(sender_mock) as DynMtbFileSender);
|
||||||
|
let body = Body::from("{}");
|
||||||
|
|
||||||
|
let response = router
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/mtb/etl/patient-record")
|
||||||
|
.header(AUTHORIZATION, "Basic dG9rZW46dmVyeS1zZWNyZXQ=")
|
||||||
|
.header(CONTENT_TYPE, "application/json")
|
||||||
|
.body(body)
|
||||||
|
.expect("request built"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
#[allow(clippy::expect_used)]
|
||||||
|
async fn should_check_authorization_first() {
|
||||||
|
let mut sender_mock = MockMtbFileSender::new();
|
||||||
|
|
||||||
|
sender_mock
|
||||||
|
.expect_send()
|
||||||
|
.withf(|mtb| mtb.patient.id.eq("fae56ea7-24a7-4556-82fb-2b5dde71bb4d"))
|
||||||
|
.return_once(move |_| Ok(String::new()));
|
||||||
|
|
||||||
|
let router = routes(Arc::new(sender_mock) as DynMtbFileSender);
|
||||||
|
let body = Body::from("<test>Das ist ein Test</test>");
|
||||||
|
|
||||||
|
let response = router
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.method(Method::POST)
|
||||||
|
.uri("/mtb/etl/patient-record")
|
||||||
|
// No Auth header!
|
||||||
|
.header(CONTENT_TYPE, "application/xml")
|
||||||
|
.body(body)
|
||||||
|
.expect("request built"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user