use axum::{
Json,
extract::State,
response::{IntoResponse, Response},
};
use serde::{Deserialize, Serialize};
use crate::model::{ClientId, ObjectType};
use super::super::{AppState, auth::bearer_from_header};
#[derive(Debug, Clone, Deserialize)]
pub struct AuthRequest {
#[serde(default)]
pub username: String,
#[serde(default)]
pub password: String,
#[serde(default, rename = "clientid")]
pub client_id: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct AclRequest {
#[serde(default)]
pub username: String,
#[serde(default)]
pub action: String,
#[serde(default)]
pub topic: String,
#[serde(default, rename = "clientid")]
pub client_id: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Decision {
pub result: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
impl Decision {
pub fn allow() -> Self {
Self {
result: "allow",
reason: None,
}
}
pub fn deny(reason: impl Into<String>) -> Self {
Self {
result: "deny",
reason: Some(reason.into()),
}
}
}
impl IntoResponse for Decision {
fn into_response(self) -> Response {
(axum::http::StatusCode::OK, Json(self)).into_response()
}
}
pub async fn authenticate(State(state): State<AppState>, body: axum::body::Bytes) -> Response {
let Ok(request) = serde_json::from_slice::<AuthRequest>(&body) else {
return Decision::deny("unreadable authentication request").into_response();
};
decide_auth(&state, &request).await.into_response()
}
pub async fn authorize(State(state): State<AppState>, body: axum::body::Bytes) -> Response {
let Ok(request) = serde_json::from_slice::<AclRequest>(&body) else {
return Decision::deny("unreadable authorization request").into_response();
};
decide_acl(&state, &request).await.into_response()
}
fn broker_configured(state: &AppState) -> Result<(), Decision> {
if state.config.mqtt.is_some() {
Ok(())
} else {
Err(Decision::deny("this VTN offers no MQTT notifier"))
}
}
async fn decide_auth(state: &AppState, request: &AuthRequest) -> Decision {
if let Err(denied) = broker_configured(state) {
return denied;
}
let principal = match state
.authenticator
.authenticate(bearer_from_header(Some(&request.password)).or(Some(request.password.trim())))
.await
{
Ok(principal) => principal,
Err(e) => return Decision::deny(e.to_string()),
};
let Some(client_id) = principal.client_id else {
return Decision::deny("this credential identifies no client");
};
if client_id.as_str() != request.username {
return Decision::deny(format!(
"the MQTT username must be the credential's clientID ({client_id})"
));
}
Decision::allow()
}
async fn decide_acl(state: &AppState, request: &AclRequest) -> Decision {
if let Err(denied) = broker_configured(state) {
return denied;
}
let Ok(username) = ClientId::new(&request.username) else {
return Decision::deny("the MQTT username is not a valid clientID");
};
if !request.action.eq_ignore_ascii_case("subscribe") {
let is_publisher = state
.config
.mqtt_publisher_client
.as_ref()
.is_some_and(|id| *id == username);
let prefix = state.config.mqtt_topic_prefix.trim_end_matches('/');
let under_prefix = prefix.is_empty() || request.topic.starts_with(&format!("{prefix}/"));
return match (is_publisher, under_prefix) {
(true, true) => Decision::allow(),
(true, false) => Decision::deny(
"the VTN's publisher may only publish under this VTN's own topic prefix",
),
(false, _) => Decision::deny("only the VTN publishes to these topics"),
};
}
match ven_scope(&state.config.mqtt_topic_prefix, &request.topic) {
Some(ven_id) => {
let Ok(id) = crate::model::ObjectId::new(&ven_id) else {
return Decision::deny("the topic names no valid venID");
};
match state.storage.get_ven(&id).await {
Ok(ven) if ven.client_id == username => Decision::allow(),
Ok(_) => Decision::deny("that VEN belongs to another client"),
Err(_) => Decision::deny("no such VEN"),
}
}
None => {
if state.config.mqtt_business_logic_clients.contains(&username) {
Decision::allow()
} else {
Decision::deny(
"collection-wide topics carry every object's full target set and are business \
logic's",
)
}
}
}
}
fn ven_scope(prefix: &str, topic: &str) -> Option<String> {
let prefix = prefix.trim_end_matches('/');
let rest = if prefix.is_empty() {
topic
} else {
topic.strip_prefix(prefix)?.strip_prefix('/')?
};
let parts: Vec<&str> = rest.split('/').collect();
let ven_id = match parts.as_slice() {
[collection, ven_id, _operation] if *collection == ObjectType::Ven.collection() => ven_id,
[collection, "vens", ven_id, _operation]
if ObjectType::ALL
.iter()
.any(|t| t.collection() == *collection) =>
{
ven_id
}
_ => return None,
};
if ven_id.contains('+') || ven_id.contains('#') || ven_id.is_empty() {
return None;
}
Some((*ven_id).to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_ven_scoped_topic_yields_its_ven() {
assert_eq!(
ven_scope("openadr3", "openadr3/events/vens/ven-1/create").as_deref(),
Some("ven-1")
);
assert_eq!(
ven_scope("openadr3", "openadr3/events/vens/ven-1/+").as_deref(),
Some("ven-1")
);
assert_eq!(
ven_scope("openadr3", "openadr3/resources/vens/ven-1/update").as_deref(),
Some("ven-1")
);
assert_eq!(
ven_scope("openadr3", "openadr3/vens/ven-1/update").as_deref(),
Some("ven-1")
);
assert_eq!(
ven_scope("", "events/vens/ven-1/create").as_deref(),
Some("ven-1")
);
}
#[test]
fn a_collection_topic_is_not_ven_scoped() {
assert_eq!(ven_scope("openadr3", "openadr3/events/create"), None);
assert_eq!(ven_scope("openadr3", "openadr3/events/+"), None);
assert_eq!(
ven_scope("openadr3", "openadr3/events/programs/prg-1/create"),
None
);
assert_eq!(
ven_scope("openadr3", "other/events/vens/ven-1/create"),
None
);
assert_eq!(ven_scope("openadr3", "openadr3/vens/create"), None);
assert_eq!(ven_scope("openadr3", "openadr3/vens/+"), None);
}
#[test]
fn a_wildcard_where_the_ven_id_belongs_is_not_a_ven_scope() {
assert_eq!(ven_scope("openadr3", "openadr3/events/vens/+/create"), None);
assert_eq!(ven_scope("openadr3", "openadr3/events/vens/#"), None);
assert_eq!(
ven_scope("openadr3", "openadr3/events/vens/ven-1/create/extra"),
None
);
}
}