use axum::{
Json,
body::Bytes,
extract::{FromRequestParts, Path, RawQuery, State},
http::{HeaderMap, Request, StatusCode, header, request::Parts},
middleware::Next,
response::{IntoResponse, Response},
};
use crate::core::{Access, Grant, Role};
use crate::model::{AuthServerInfo, ObjectId, ObjectType, Problem, Target};
use crate::schema::{self, PayloadGroup, Policy};
use super::{
ApiError, AppState,
auth::{Scope, bearer_from_header},
etag::Cached,
notify::Fanout,
store::Page,
};
pub mod broker;
pub mod events;
pub mod notifiers;
pub mod programs;
pub mod reports;
pub mod resources;
pub mod subscriptions;
pub mod vens;
#[derive(Debug)]
pub struct Ctx {
pub principal: super::auth::Principal,
anonymous_allowed: bool,
state: AppState,
role: tokio::sync::OnceCell<Role>,
}
impl Ctx {
pub fn is_business_logic(&self) -> bool {
self.principal.is_business_logic()
}
pub async fn role(&self) -> Role {
self.role
.get_or_init(|| async {
match (&self.principal.client_id, self.is_business_logic()) {
(_, true) => Role::BusinessLogic,
(Some(client_id), false) => {
let grant = self
.state
.storage
.grant_for(client_id)
.await
.unwrap_or_else(|e| {
tracing::error!(
error = %e, %client_id,
"grant lookup failed; denying targets"
);
Grant::empty()
});
Role::Ven {
client_id: client_id.clone(),
grant,
}
}
(None, false) => Role::Anonymous,
}
})
.await
.clone()
}
pub fn require(&self, scope: Scope) -> Result<(), ApiError> {
if self.principal.scopes.contains(scope) {
Ok(())
} else {
Err(ApiError::MissingScope(scope))
}
}
pub fn require_read(&self) -> Result<(), ApiError> {
if self.principal.scopes.contains_any(&[
Scope::ReadAll,
Scope::ReadBl,
Scope::ReadTargets,
Scope::ReadVenObjects,
]) {
return Ok(());
}
if self.principal.client_id.is_none() && self.anonymous_allowed {
return Ok(());
}
Err(ApiError::MissingScope(Scope::ReadTargets))
}
pub fn client_id(&self) -> Result<&crate::model::ClientId, ApiError> {
self.principal.client_id.as_ref().ok_or_else(|| {
ApiError::Forbidden("this operation requires an identified client".into())
})
}
pub async fn list_access(&self, requested: Vec<Target>) -> Access {
Access::list(self.role().await, requested)
}
pub async fn id_access(&self) -> Access {
Access::by_id(self.role().await)
}
pub fn owned_access(&self, requested: Vec<Target>) -> Access {
let role = match &self.principal.client_id {
_ if self.is_business_logic() => Role::BusinessLogic,
Some(client_id) => Role::Ven {
client_id: client_id.clone(),
grant: Grant::empty(),
},
None => Role::Anonymous,
};
Access::list(role, requested)
}
pub fn owned_id_access(&self) -> Access {
let mut access = self.owned_access(Vec::new());
access = Access::by_id(access.role().clone());
access
}
}
impl FromRequestParts<AppState> for Ctx {
type Rejection = ApiError;
async fn from_request_parts(
parts: &mut Parts,
state: &AppState,
) -> Result<Self, Self::Rejection> {
let bearer = parts
.headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok());
let principal = state
.authenticator
.authenticate(bearer_from_header(bearer))
.await?;
Ok(Ctx {
principal,
anonymous_allowed: state.authenticator.allows_anonymous(),
state: state.clone(),
role: tokio::sync::OnceCell::new(),
})
}
}
#[derive(Debug, Default, Clone)]
pub struct Params(Vec<(String, String)>);
impl Params {
pub fn parse(raw: Option<&str>) -> Self {
let Some(raw) = raw else {
return Self::default();
};
Self(
url::form_urlencoded::parse(raw.as_bytes())
.map(|(k, v)| (k.into_owned(), v.into_owned()))
.collect(),
)
}
pub fn first(&self, key: &str) -> Option<&str> {
self.0
.iter()
.find(|(k, _)| k == key)
.map(|(_, v)| v.as_str())
}
pub fn all(&self, key: &str) -> Vec<&str> {
self.0
.iter()
.filter(|(k, _)| k == key)
.flat_map(|(_, v)| v.split(','))
.map(str::trim)
.filter(|s| !s.is_empty())
.collect()
}
pub fn parse_one<T>(&self, key: &str) -> Result<Option<T>, ApiError>
where
T: core::str::FromStr,
T::Err: core::fmt::Display,
{
self.first(key)
.map(|v| {
v.parse::<T>()
.map_err(|e| ApiError::BadRequest(format!("invalid {key}: {e}")))
})
.transpose()
}
pub fn targets(&self) -> Result<Vec<Target>, ApiError> {
self.all("targets")
.into_iter()
.map(|t| {
Target::new(t).map_err(|e| ApiError::BadRequest(format!("invalid target: {e}")))
})
.collect()
}
pub fn page(&self) -> Result<Page, ApiError> {
let skip = self.parse_one::<i64>("skip")?.unwrap_or(0);
if skip < 0 {
return Err(ApiError::BadRequest("skip must not be negative".into()));
}
let limit = self
.parse_one::<i64>("limit")?
.unwrap_or(Page::MAX_LIMIT as i64);
if !(0..=Page::MAX_LIMIT as i64).contains(&limit) {
return Err(ApiError::BadRequest(format!(
"limit must be between 0 and {}",
Page::MAX_LIMIT
)));
}
Ok(Page {
skip: skip as usize,
limit: limit as usize,
})
}
pub fn active(&self) -> Result<Option<bool>, ApiError> {
self.parse_one::<bool>("active")
}
pub fn object_types(&self) -> Result<Vec<ObjectType>, ApiError> {
self.all("objects")
.into_iter()
.map(|o| {
o.parse::<ObjectType>()
.map_err(|_| ApiError::BadRequest(format!("unknown object type {o:?}")))
})
.collect()
}
}
pub fn params(raw: &Option<String>) -> Params {
Params::parse(raw.as_deref())
}
pub const JSON_MEDIA_TYPES: &str = "application/json or application/*+json";
pub const TOKEN_MEDIA_TYPES: &str = "application/x-www-form-urlencoded or application/json";
fn is_json_media_type(value: &str) -> bool {
let essence = value.split(';').next().unwrap_or("").trim();
essence.eq_ignore_ascii_case("application/json")
|| essence.split_once('/').is_some_and(|(_, sub)| {
sub.len() > 5 && sub[sub.len() - 5..].eq_ignore_ascii_case("+json")
})
}
fn require_media_type(
headers: &HeaderMap,
accepted: &'static str,
admits: fn(&str) -> bool,
) -> Result<(), ApiError> {
let Some(value) = headers.get(header::CONTENT_TYPE) else {
return Ok(());
};
let Ok(value) = value.to_str() else {
return Err(ApiError::UnsupportedMediaType(format!(
"the Content-Type header is not valid text; this endpoint reads {accepted}"
)));
};
if value.trim().is_empty() || admits(value) {
return Ok(());
}
Err(ApiError::UnsupportedMediaType(format!(
"a {value:?} body cannot be read by this endpoint, which reads {accepted}"
)))
}
pub fn require_token_media_type(headers: &HeaderMap) -> Result<(), ApiError> {
require_media_type(headers, TOKEN_MEDIA_TYPES, |value| {
let essence = value.split(';').next().unwrap_or("").trim();
essence.eq_ignore_ascii_case("application/x-www-form-urlencoded")
|| is_json_media_type(value)
})
}
#[derive(Debug, Clone)]
pub struct JsonBody(Bytes);
impl JsonBody {
pub fn parse<T: serde::de::DeserializeOwned>(&self) -> Result<T, ApiError> {
parse_body(&self.0)
}
pub fn bytes(&self) -> &Bytes {
&self.0
}
}
impl<S: Send + Sync> axum::extract::FromRequest<S> for JsonBody {
type Rejection = ApiError;
async fn from_request(
request: Request<axum::body::Body>,
state: &S,
) -> Result<Self, Self::Rejection> {
require_media_type(request.headers(), JSON_MEDIA_TYPES, is_json_media_type)?;
Bytes::from_request(request, state).await.map(Self).map_err(
|e| match e.status() {
StatusCode::PAYLOAD_TOO_LARGE => ApiError::PayloadTooLarge(
"the request body exceeds this VTN's limit".to_string(),
),
_ => ApiError::BadRequest(format!("the request body could not be read: {e}")),
},
)
}
}
pub fn parse_body<T: serde::de::DeserializeOwned>(bytes: &Bytes) -> Result<T, ApiError> {
if bytes.is_empty() {
return Err(ApiError::BadRequest("a request body is required".into()));
}
serde_json::from_slice(bytes)
.map_err(|e| ApiError::BadRequest(format!("malformed request body: {e}")))
}
pub fn check_attributes(
state: &AppState,
attributes: Option<&Vec<crate::model::ValuesMap>>,
group: PayloadGroup,
) -> Result<(), ApiError> {
match attributes {
Some(values) => check_payloads(state, values, group),
None => Ok(()),
}
}
pub fn check_payloads(
state: &AppState,
payloads: &[crate::model::ValuesMap],
group: PayloadGroup,
) -> Result<(), ApiError> {
if state.config.payload_policy == Policy::Off {
return Ok(());
}
let violations = schema::validate_all(payloads, group);
if violations.is_empty() {
return Ok(());
}
match state.config.payload_policy {
Policy::Strict => Err(ApiError::InvalidPayload(violations)),
_ => {
for v in &violations {
tracing::warn!(violation = %v, "payload does not match its enumeration");
}
Ok(())
}
}
}
pub fn ok<T: serde::Serialize>(
state: &AppState,
headers: &HeaderMap,
value: &T,
) -> Result<Response, ApiError> {
Ok(Cached::json(value, headers, state.config.http_caching)
.map_err(|e| ApiError::Internal(e.to_string()))?
.into_response())
}
pub fn created<T: serde::Serialize>(value: &T) -> Result<Response, ApiError> {
Ok((StatusCode::CREATED, Json(value)).into_response())
}
pub fn hide_targets<T, F, S>(access: &Access, items: &mut [T], get: F, set: S)
where
F: Fn(&T) -> &[Target],
S: Fn(&mut T, Vec<Target>),
{
for item in items {
if let Some(visible) = access.visible_targets(get(item)) {
set(item, visible);
}
}
}
pub fn require_visible<T, F, S>(
access: &Access,
mut item: T,
object_type: ObjectType,
id: &ObjectId,
get: F,
set: S,
) -> Result<T, ApiError>
where
F: Fn(&T) -> &[Target],
S: Fn(&mut T, Vec<Target>),
{
match access.visible_targets(get(&item)) {
Some(visible) => {
set(&mut item, visible);
Ok(item)
}
None => Err(ApiError::NotFound {
object_type,
id: id.clone(),
}),
}
}
pub fn require_owner(
access: &Access,
owner: Option<&crate::model::ClientId>,
object_type: ObjectType,
id: &ObjectId,
) -> Result<(), ApiError> {
if access.owns(owner) {
Ok(())
} else {
Err(ApiError::NotFound {
object_type,
id: id.clone(),
})
}
}
pub async fn fanout(state: &AppState, object_type: ObjectType) -> Fanout {
snapshot(state, object_type, Gate::Targeted).await
}
pub async fn fanout_owned(
state: &AppState,
object_type: ObjectType,
owner: Option<&crate::model::ClientId>,
) -> Fanout {
debug_assert!(
matches!(
object_type,
ObjectType::Ven | ObjectType::Resource | ObjectType::Report | ObjectType::Subscription
),
"{object_type} is gated by targeting, not by ownership; use `fanout`"
);
snapshot(state, object_type, Gate::Owned(owner)).await
}
#[derive(Debug, Clone, Copy)]
enum Gate<'a> {
Targeted,
Owned(Option<&'a crate::model::ClientId>),
}
async fn snapshot(state: &AppState, object_type: ObjectType, gate: Gate<'_>) -> Fanout {
let subscriptions = match state.storage.subscribers(object_type.announces()).await {
Ok(s) => s,
Err(e) => {
tracing::error!(error = %e, "could not load subscriptions for notification");
Vec::new()
}
};
let topics = state
.config
.mqtt
.is_some()
.then(|| super::notify::Topics::new(state.config.mqtt_topic_prefix.clone()));
let now = state.clock.now();
let subscriptions = match state.storage.subscriber_health().await {
Ok(health) if !health.is_empty() => {
let cut_off: Vec<&ObjectId> = health
.iter()
.filter(|h| h.is_cut_off(now))
.map(|h| &h.subscription_id)
.collect();
subscriptions
.into_iter()
.filter(|s| {
let suppressed = cut_off.contains(&&s.subscription.id);
if suppressed {
tracing::debug!(
subscription = %s.subscription.id,
"subscriber is cut off; not queueing"
);
}
!suppressed
})
.collect()
}
Ok(_) => subscriptions,
Err(e) => {
tracing::error!(error = %e, "could not read subscriber health; not suppressing anyone");
subscriptions
}
};
if subscriptions.is_empty() && topics.is_none() {
return Fanout::none();
}
let grants = match gate {
Gate::Targeted => state.storage.all_grants().await.unwrap_or_default(),
Gate::Owned(None) => Vec::new(),
Gate::Owned(Some(client_id)) => match state.storage.get_ven_by_client(client_id).await {
Ok(Some(ven)) => vec![(ven.id, ven.client_id, Grant::empty())],
Ok(None) => Vec::new(),
Err(e) => {
tracing::error!(error = %e, %client_id, "could not resolve the owner's VEN");
Vec::new()
}
},
};
let by_client: std::collections::BTreeMap<_, _> = grants
.iter()
.map(|(_, client_id, grant)| (client_id.clone(), grant.clone()))
.collect();
let subscribers = subscriptions
.into_iter()
.map(|subscriber| {
let role = if subscriber.owner.is_business_logic() {
Role::BusinessLogic
} else {
Role::Ven {
client_id: subscriber.subscription.client_id.clone(),
grant: by_client
.get(&subscriber.subscription.client_id)
.cloned()
.unwrap_or_else(Grant::empty),
}
};
(subscriber.subscription, role)
})
.collect();
Fanout::new(subscribers, grants, topics, now)
}
pub async fn health(State(state): State<AppState>) -> Response {
if !state.storage.healthy().await {
return ApiError::Storage(super::store::StorageError::Unavailable(
"backend not reachable".into(),
))
.into_response();
}
let gauges = super::metrics::gauges(&state).await;
(
StatusCode::OK,
[(axum::http::header::CONTENT_TYPE, "application/json")],
serde_json::json!({
"status": "ok",
"outbox": gauges.outbox,
"subscribersCutOff": gauges.subscribers_cut_off,
"reports": gauges.reports,
})
.to_string(),
)
.into_response()
}
pub async fn admin_outbox(
State(state): State<AppState>,
ctx: Ctx,
headers: HeaderMap,
RawQuery(raw): RawQuery,
) -> Result<Response, ApiError> {
ctx.require(Scope::ReadAll)?;
let page = params(&raw).page()?;
let entries = state.storage.dead_letters(page.limit.max(1)).await?;
ok(&state, &headers, &entries)
}
pub async fn admin_subscribers(
State(state): State<AppState>,
ctx: Ctx,
headers: HeaderMap,
) -> Result<Response, ApiError> {
ctx.require(Scope::ReadAll)?;
let health = state.storage.subscriber_health().await?;
ok(&state, &headers, &health)
}
pub async fn admin_outbox_retry(
State(state): State<AppState>,
ctx: Ctx,
) -> Result<Response, ApiError> {
ctx.require(Scope::WriteSubscriptions)?;
if !ctx.is_business_logic() {
return Err(ApiError::Forbidden(
"the notification queue is business logic's".into(),
));
}
let revived = state.storage.revive_dead(state.clock.now()).await?;
let restored = state.storage.clear_subscriber_health().await?;
tracing::info!(
revived,
restored,
"abandoned notifications made due again and every cut-off subscriber restored"
);
Ok((
StatusCode::OK,
[(header::CONTENT_TYPE, "application/json")],
serde_json::json!({ "revived": revived, "subscribersRestored": restored }).to_string(),
)
.into_response())
}
pub async fn auth_server(State(state): State<AppState>) -> Json<AuthServerInfo> {
Json(AuthServerInfo {
token_url: state.authenticator.token_url(),
})
}
pub async fn auth_token(
State(state): State<AppState>,
headers: HeaderMap,
body: Bytes,
) -> Response {
no_store(auth_token_inner(state, headers, body).await)
}
fn no_store(mut response: Response) -> Response {
response.headers_mut().insert(
header::CACHE_CONTROL,
axum::http::HeaderValue::from_static("no-store"),
);
response
}
async fn auth_token_inner(state: AppState, headers: HeaderMap, body: Bytes) -> Response {
if !state.authenticator.issues_tokens() {
return ApiError::NotImplemented(super::auth::TokenError::NotIssuing.to_string())
.into_response();
}
if let Err(e) = require_token_media_type(&headers) {
return e.into_response();
}
let Some(request) = parse_credentials(&body) else {
return oauth_error(crate::model::OAuthError::new(
crate::model::OAuthErrorKind::InvalidRequest,
"expected grant_type, client_id and client_secret",
));
};
match state.authenticator.issue_token(&request).await {
Ok(token) => (StatusCode::OK, Json(token)).into_response(),
Err(super::auth::TokenError::NotIssuing) => {
ApiError::NotImplemented(super::auth::TokenError::NotIssuing.to_string())
.into_response()
}
Err(super::auth::TokenError::Refused(e)) => oauth_error(e),
Err(e @ super::auth::TokenError::Unavailable(_)) => {
ApiError::Unavailable(e.to_string()).into_response()
}
}
}
fn oauth_error(error: crate::model::OAuthError) -> Response {
(StatusCode::BAD_REQUEST, Json(error)).into_response()
}
fn parse_credentials(body: &Bytes) -> Option<crate::model::ClientCredentialRequest> {
if let Ok(request) = serde_json::from_slice::<crate::model::ClientCredentialRequest>(body) {
return Some(request);
}
let form = Params::parse(Some(core::str::from_utf8(body).ok()?));
Some(crate::model::ClientCredentialRequest {
grant_type: form.first("grant_type")?.to_string(),
client_id: form.first("client_id")?.to_string(),
client_secret: form.first("client_secret")?.to_string(),
scope: form.first("scope").map(str::to_string),
})
}
pub async fn not_found() -> ApiError {
ApiError::NoSuchRoute
}
pub const REQUEST_ID_HEADER: &str = "x-request-id";
fn layer_problem(status: StatusCode) -> (&'static str, &'static str) {
match status {
StatusCode::METHOD_NOT_ALLOWED => (
"method-not-allowed",
"this method is not defined for this resource",
),
StatusCode::PAYLOAD_TOO_LARGE => (
"payload-too-large",
"the request body exceeds this VTN's limit",
),
StatusCode::GATEWAY_TIMEOUT => (
"timeout",
"the VTN took too long to answer and gave up on this request",
),
StatusCode::UNSUPPORTED_MEDIA_TYPE => (
"unsupported-media-type",
"this endpoint cannot read a body of that media type",
),
_ => ("error", "the request could not be completed"),
}
}
pub async fn problem_responses(request: Request<axum::body::Body>, next: Next) -> Response {
let request_id = request
.headers()
.get(REQUEST_ID_HEADER)
.and_then(|v| v.to_str().ok())
.map(str::to_string);
let response = next.run(request).await;
let status = response.status();
let content_type = response
.headers()
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.map(str::to_string);
let is_problem = content_type
.as_deref()
.is_some_and(|v| v.starts_with("application/problem+json"));
let is_json = content_type
.as_deref()
.is_some_and(|v| v.starts_with("application/json"));
if (status.is_client_error() || status.is_server_error()) && !is_problem && !is_json {
let (slug, detail) = layer_problem(status);
let title = status.canonical_reason().unwrap_or("Error");
let mut problem = Problem::new(status.as_u16(), slug, title).with_detail(detail);
if let Some(id) = request_id {
problem = problem.with_instance(id);
}
let (mut parts, _) = response.into_parts();
parts.headers.remove(header::CONTENT_LENGTH);
parts.headers.insert(
header::CONTENT_TYPE,
axum::http::HeaderValue::from_static("application/problem+json"),
);
let body = serde_json::to_vec(&problem).unwrap_or_default();
return Response::from_parts(parts, axum::body::Body::from(body));
}
let Some(id) = request_id else {
return response;
};
if !is_problem {
return response;
}
let (parts, body) = response.into_parts();
let Ok(bytes) = axum::body::to_bytes(body, 64 * 1024).await else {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
};
let Ok(problem) = serde_json::from_slice::<Problem>(&bytes) else {
return Response::from_parts(parts, axum::body::Body::from(bytes));
};
let Ok(body) = serde_json::to_vec(&problem.with_instance(id)) else {
return Response::from_parts(parts, axum::body::Body::from(bytes));
};
let mut parts = parts;
parts.headers.remove(header::CONTENT_LENGTH);
Response::from_parts(parts, axum::body::Body::from(body))
}
pub type ListArgs = (State<AppState>, Ctx, HeaderMap, RawQuery);
pub type ItemArgs = (State<AppState>, Ctx, HeaderMap, Path<String>, RawQuery);
pub fn parse_id(raw: &str) -> Result<ObjectId, ApiError> {
ObjectId::new(raw).map_err(|e| ApiError::BadRequest(format!("invalid object id: {e}")))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn layer_problems_mint_published_types() {
use crate::model::problem::problem_type;
for status in [
StatusCode::METHOD_NOT_ALLOWED,
StatusCode::PAYLOAD_TOO_LARGE,
StatusCode::GATEWAY_TIMEOUT,
StatusCode::UNSUPPORTED_MEDIA_TYPE,
StatusCode::BAD_GATEWAY,
] {
let (slug, _) = layer_problem(status);
assert!(
problem_type(slug).is_some(),
"{slug} is minted but not published; add it to PROBLEMS and the registry page"
);
}
}
#[test]
fn repeated_and_comma_separated_lists_both_parse() {
let a = Params::parse(Some("targets=x&targets=y"));
assert_eq!(a.all("targets"), vec!["x", "y"]);
let b = Params::parse(Some("targets=x,y"));
assert_eq!(b.all("targets"), vec!["x", "y"]);
}
#[test]
fn percent_encoding_is_decoded() {
let p = Params::parse(Some("programName=Time%20of%20Use"));
assert_eq!(p.first("programName"), Some("Time of Use"));
}
#[test]
fn pagination_is_bounded_by_the_schema() {
assert_eq!(
Params::parse(Some("limit=10&skip=5")).page().unwrap(),
Page { skip: 5, limit: 10 }
);
assert!(Params::parse(Some("limit=51")).page().is_err());
assert!(Params::parse(Some("skip=-1")).page().is_err());
assert!(Params::parse(Some("limit=abc")).page().is_err());
assert_eq!(Params::parse(None).page().unwrap(), Page::default());
}
#[test]
fn invalid_targets_are_rejected_at_the_edge() {
let long = "t".repeat(129);
assert!(
Params::parse(Some(&format!("targets={long}")))
.targets()
.is_err()
);
}
#[test]
fn empty_target_entries_are_dropped() {
let p = Params::parse(Some("targets=a,,b"));
assert_eq!(p.targets().unwrap().len(), 2);
}
#[test]
fn an_empty_body_is_a_clear_error() {
let err = parse_body::<crate::model::ProgramRequest>(&Bytes::new()).unwrap_err();
assert!(matches!(err, ApiError::BadRequest(_)));
}
}