use std::collections::BTreeSet;
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use axum::body::Bytes;
use axum::error_handling::HandleErrorLayer;
use axum::extract::{DefaultBodyLimit, State};
use axum::http::{header, HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::post;
use axum::Router;
use serde::Serialize;
use serde_json::Value;
use tower::limit::ConcurrencyLimitLayer;
use tower::timeout::TimeoutLayer;
use tower::ServiceBuilder;
use trust_tasks_rs::{
consume_dispatched_answer, discovery::DiscoveryRegistry, erase_verifier,
specs::trust_task_discovery::v0_4 as discovery, AnswerOutcome, AsyncDispatcher, ConsumeChecks,
DynProofVerifier, ErrorPayload, ErrorResponse, FreshnessPolicy, InMemoryReplayGuard, Payload,
PayloadPolicy, PayloadValidator, ProofPolicy, ProofVerifier, RejectReason, ReplayGuard,
ReplayPolicy, RequestPayload, ResolvedParties, TransportHandler, TrustTask,
};
use uuid::Uuid;
use crate::auth::{AsyncAuth, BearerAuth};
mod superseded_discovery;
use crate::handler::HttpsHandler;
use crate::status::status_for_code;
pub const MAX_BODY_BYTES: usize = 256 * 1024;
pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
pub const DEFAULT_MAX_CONCURRENT_REQUESTS: usize = 512;
#[derive(Debug, Clone)]
pub struct RequestContext {
pub authenticated_sender: Option<String>,
pub local: Option<String>,
pub resolved: ResolvedParties,
}
type Answer = Result<Option<Value>, ErrorResponse>;
type Routes = AsyncDispatcher<RequestContext, Answer>;
type HandlerFuture = Pin<Box<dyn Future<Output = Result<Option<Value>, RejectReason>> + Send>>;
struct ServerState {
local_vid: Option<String>,
auth: Box<dyn AsyncAuth>,
routes: Routes,
verifier: Option<Arc<dyn DynProofVerifier>>,
payload_validator: Option<Box<dyn PayloadValidator + Send + Sync>>,
require_attribution: bool,
allowed_did_methods: Option<BTreeSet<String>>,
replay_guard: Option<Arc<dyn ReplayGuard>>,
freshness: FreshnessPolicy,
default_document_bound: usize,
}
enum DidMethodPolicy {
Default,
Only(BTreeSet<String>),
Any,
}
pub const DEFAULT_ALLOWED_DID_METHODS: &[&str] = &["key"];
pub struct HttpsServerBuilder {
local_vid: Option<String>,
auth: Option<Box<dyn AsyncAuth>>,
routes: Routes,
largest_declared_bound: usize,
max_body_bytes: Option<usize>,
verifier: Option<Arc<dyn DynProofVerifier>>,
payload_validator: Option<Box<dyn PayloadValidator + Send + Sync>>,
require_attribution: bool,
did_methods: DidMethodPolicy,
replay_protection: bool,
replay_guard: Option<Arc<dyn ReplayGuard>>,
freshness: FreshnessPolicy,
public_discovery: Arc<AtomicBool>,
applied_freshness: Arc<OnceLock<FreshnessPolicy>>,
request_timeout: Option<Duration>,
max_concurrent_requests: Option<usize>,
}
impl HttpsServerBuilder {
pub fn local_vid(mut self, vid: impl Into<String>) -> Self {
self.local_vid = Some(vid.into());
self
}
pub fn with_auth(mut self, auth: impl AsyncAuth) -> Self {
self.auth = Some(Box::new(auth));
self
}
pub fn with_verifier<V>(mut self, verifier: V) -> Self
where
V: ProofVerifier + Send + Sync + 'static,
{
self.verifier = Some(erase_verifier(verifier));
self
}
pub fn with_payload_validator<W>(mut self, validator: W) -> Self
where
W: PayloadValidator + Send + Sync + 'static,
{
self.payload_validator = Some(Box::new(validator));
self
}
pub fn max_body_bytes(mut self, limit: usize) -> Self {
self.max_body_bytes = Some(limit);
self
}
pub fn on<P, F>(self, handler: F) -> Self
where
P: RequestPayload + Send + 'static,
P::Response: Serialize + 'static,
F: Fn(&TrustTask<P>, &RequestContext) -> Result<P::Response, RejectReason>
+ Send
+ Sync
+ 'static,
{
self.on_sync(handler, true)
}
pub(crate) fn on_sync<P, F>(self, handler: F, may_block: bool) -> Self
where
P: RequestPayload + Send + 'static,
P::Response: Serialize + 'static,
F: Fn(&TrustTask<P>, &RequestContext) -> Result<P::Response, RejectReason>
+ Send
+ Sync
+ 'static,
{
let handler = Arc::new(handler);
self.register::<P>(move |req, ctx| {
let handler = Arc::clone(&handler);
Box::pin(async move {
let response = run_sync(may_block, || handler(&req, &ctx))?;
respond(&req, response).map(Some)
})
})
}
pub fn on_async<P, F, Fut>(self, handler: F) -> Self
where
P: RequestPayload + Send + 'static,
P::Response: Serialize + 'static,
F: Fn(TrustTask<P>, RequestContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<P::Response, RejectReason>> + Send + 'static,
{
self.register::<P>(move |req, ctx| {
let head = head_of(&req);
let answer = handler(req, ctx);
Box::pin(async move {
let response = answer.await?;
respond(&head, response).map(Some)
})
})
}
pub fn on_ack<P, F>(self, handler: F) -> Self
where
P: Payload + Send + 'static,
F: Fn(&TrustTask<P>, &RequestContext) -> Result<(), RejectReason> + Send + Sync + 'static,
{
let handler = Arc::new(handler);
self.register::<P>(move |req, ctx| {
let handler = Arc::clone(&handler);
Box::pin(async move {
run_sync(true, || handler(&req, &ctx))?;
Ok(None)
})
})
}
pub fn on_ack_async<P, F, Fut>(self, handler: F) -> Self
where
P: Payload + Send + 'static,
F: Fn(TrustTask<P>, RequestContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), RejectReason>> + Send + 'static,
{
self.register::<P>(move |req, ctx| {
let answer = handler(req, ctx);
Box::pin(async move {
answer.await?;
Ok(None)
})
})
}
fn register<P>(
mut self,
handler: impl Fn(TrustTask<P>, RequestContext) -> HandlerFuture + Send + Sync + 'static,
) -> Self
where
P: Payload + Send + 'static,
{
if let Some(bound) = P::MAX_DOCUMENT_BYTES {
self.largest_declared_bound = self.largest_declared_bound.max(bound);
}
let routes = std::mem::take(&mut self.routes);
self.routes = routes.on_async::<P, _, _>(move |req: TrustTask<P>, ctx: RequestContext| {
let head = head_of(&req);
let transport = HttpsHandler::new(ctx.local.clone(), ctx.authenticated_sender.clone());
let answer = handler(req, ctx);
async move {
answer
.await
.map_err(|reason| routed_error(&transport, &head, reason))
}
});
self
}
pub fn require_attribution(mut self, require: bool) -> Self {
self.require_attribution = require;
self
}
pub fn replay_protection(mut self, keep_record: bool) -> Self {
self.replay_protection = keep_record;
self
}
pub fn with_replay_guard<G>(mut self, guard: G) -> Self
where
G: ReplayGuard + 'static,
{
self.replay_guard = Some(Arc::new(guard));
self
}
pub fn freshness(mut self, policy: FreshnessPolicy) -> Self {
self.freshness = policy;
self
}
pub fn allowed_did_methods<I, S>(mut self, methods: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.did_methods = DidMethodPolicy::Only(methods.into_iter().map(Into::into).collect());
self
}
pub fn allow_any_did_method(mut self) -> Self {
self.did_methods = DidMethodPolicy::Any;
self
}
pub fn public_discovery(self) -> Self {
self.public_discovery.store(true, Ordering::Relaxed);
self
}
pub fn request_timeout(mut self, timeout: Duration) -> Self {
self.request_timeout = Some(timeout);
self
}
pub fn max_concurrent_requests(mut self, limit: usize) -> Self {
self.max_concurrent_requests = Some(limit);
self
}
pub fn with_discovery(self, registry: DiscoveryRegistry) -> Self {
self.install_discovery(registry, false)
}
pub fn enable_discovery(self) -> Self {
let mut registry: DiscoveryRegistry = self.routes.registered_uris().into_iter().collect();
registry.register_payload::<discovery::Payload>();
superseded_discovery::register(&mut registry);
self.install_discovery(registry, true)
}
fn install_discovery(self, registry: DiscoveryRegistry, advertise_freshness: bool) -> Self {
let public = Arc::clone(&self.public_discovery);
let applied_freshness = Arc::clone(&self.applied_freshness);
let this = self;
let this = this.with_superseded_discovery(registry.clone(), advertise_freshness);
this.on_sync::<discovery::Payload, _>(
move |req, ctx| {
refuse_unauthenticated_discovery(&public, ctx.authenticated_sender.is_none())?;
Ok(match applied_freshness.get() {
Some(policy) if advertise_freshness => registry
.clone()
.acceptance_window_from(policy)
.respond_to_v0_4(&req.payload),
_ => registry.respond_to_v0_4(&req.payload),
})
},
false,
)
}
pub fn build(self) -> HttpsServer {
let auth = self.auth.unwrap_or_else(|| Box::new(BearerAuth::new()));
let _ = self.applied_freshness.set(self.freshness);
let allowed_did_methods = match self.did_methods {
DidMethodPolicy::Only(methods) => Some(methods),
DidMethodPolicy::Any => None,
DidMethodPolicy::Default => self.verifier.is_some().then(|| {
DEFAULT_ALLOWED_DID_METHODS
.iter()
.map(|m| (*m).to_string())
.collect()
}),
};
let body_limit = self
.max_body_bytes
.unwrap_or_else(|| MAX_BODY_BYTES.max(self.largest_declared_bound));
HttpsServer {
state: Arc::new(ServerState {
local_vid: self.local_vid,
auth,
routes: self.routes,
verifier: self.verifier,
payload_validator: self.payload_validator,
require_attribution: self.require_attribution,
allowed_did_methods,
replay_guard: self.replay_protection.then(|| {
self.replay_guard
.unwrap_or_else(|| Arc::new(InMemoryReplayGuard::default()))
}),
freshness: self.freshness,
default_document_bound: self.max_body_bytes.unwrap_or(MAX_BODY_BYTES),
}),
body_limit,
request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQUEST_TIMEOUT),
max_concurrent_requests: self
.max_concurrent_requests
.unwrap_or(DEFAULT_MAX_CONCURRENT_REQUESTS),
}
}
}
pub struct HttpsServer {
state: Arc<ServerState>,
body_limit: usize,
request_timeout: Duration,
max_concurrent_requests: usize,
}
impl HttpsServer {
pub fn builder() -> HttpsServerBuilder {
HttpsServerBuilder {
local_vid: None,
auth: None,
routes: AsyncDispatcher::new(),
largest_declared_bound: 0,
max_body_bytes: None,
verifier: None,
payload_validator: None,
require_attribution: true,
did_methods: DidMethodPolicy::Default,
replay_protection: true,
replay_guard: None,
freshness: FreshnessPolicy::consequential(),
public_discovery: Arc::new(AtomicBool::new(false)),
applied_freshness: Arc::new(OnceLock::new()),
request_timeout: None,
max_concurrent_requests: None,
}
}
pub fn body_limit(&self) -> usize {
self.body_limit
}
pub fn into_router(self) -> Router {
let timeout = self.request_timeout;
let concurrency = self.max_concurrent_requests;
Router::new()
.route("/trust-tasks", post(dispatch_handler))
.layer(DefaultBodyLimit::max(self.body_limit))
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(|err: tower::BoxError| async move {
if err.is::<tower::timeout::error::Elapsed>() {
StatusCode::REQUEST_TIMEOUT
} else {
StatusCode::INTERNAL_SERVER_ERROR
}
}))
.layer(ConcurrencyLimitLayer::new(concurrency))
.layer(TimeoutLayer::new(timeout)),
)
.with_state(self.state)
}
pub async fn serve(self, addr: impl tokio::net::ToSocketAddrs) -> std::io::Result<()> {
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, self.into_router()).await
}
}
async fn dispatch_handler(
State(state): State<Arc<ServerState>>,
headers: HeaderMap,
body: Bytes,
) -> Response {
if !is_json_content_type(&headers) {
return StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response();
}
let doc: TrustTask<Value> = match serde_json::from_slice(&body) {
Ok(d) => d,
Err(e) => {
return error_response(free_standing_error(RejectReason::malformed_from_serde(&e)))
}
};
let received: Value = match serde_json::from_slice(&body) {
Ok(v) => v,
Err(e) => {
return error_response(free_standing_error(RejectReason::malformed_from_serde(&e)))
}
};
let peer_vid = match extract_bearer(&headers) {
Some(token) => state.auth.resolve_async(token).await,
None => None,
};
let transport = HttpsHandler::new(state.local_vid.clone(), peer_vid);
let replay = match &state.replay_guard {
Some(guard) => ReplayPolicy::Guard(guard.as_ref()),
None => ReplayPolicy::NotConsequential,
};
let mut checks = ConsumeChecks {
freshness: state.freshness,
replay,
..ConsumeChecks::not_consequential()
}
.require_attribution(state.require_attribution)
.with_received_bytes(body.len(), Some(state.default_document_bound));
checks.proof_did_methods = state.allowed_did_methods.clone();
let proof_policy: ProofPolicy<'_, dyn DynProofVerifier> = match &state.verifier {
Some(verifier) => ProofPolicy::VerifyReceived(verifier.as_ref(), &received),
None => ProofPolicy::RejectIfPresentReceived(&received),
};
let payload_policy: PayloadPolicy<'_, dyn PayloadValidator + Send + Sync> =
match &state.payload_validator {
Some(validator) => PayloadPolicy::Validate(validator.as_ref()),
None => PayloadPolicy::AcceptUnvalidated,
};
let authenticated_sender = transport.peer().map(str::to_string);
let local = transport.local().map(str::to_string);
let outcome = consume_dispatched_answer(
&transport,
proof_policy,
payload_policy,
checks,
&state.routes,
doc,
state.local_vid.as_deref().unwrap_or(""),
chrono::Utc::now(),
new_id,
|resolved| RequestContext {
authenticated_sender,
local,
resolved,
},
)
.await;
match outcome {
AnswerOutcome::Handled(Some(body)) => success_response(body),
AnswerOutcome::Handled(None) => StatusCode::NO_CONTENT.into_response(),
AnswerOutcome::Rejected(error) => error_response(error),
AnswerOutcome::Suppressed => error_response(suppressed_error_response()),
AnswerOutcome::Duplicate {
prior_response: Some(prior),
..
} => replayed_response(prior),
AnswerOutcome::Duplicate {
in_flight: true, ..
} => StatusCode::ACCEPTED.into_response(),
AnswerOutcome::Duplicate { .. } => StatusCode::NO_CONTENT.into_response(),
}
}
fn run_sync<T>(may_block: bool, handler: impl FnOnce() -> T) -> T {
if may_block {
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
if runtime.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread {
return tokio::task::block_in_place(handler);
}
}
}
handler()
}
fn respond<P, R: Serialize>(request: &TrustTask<P>, payload: R) -> Result<Value, RejectReason> {
serde_json::to_value(request.respond_with(new_id(), payload)).map_err(|_| {
RejectReason::InternalError {
reason: "the response could not be serialised".to_string(),
}
})
}
fn head_of<P>(doc: &TrustTask<P>) -> TrustTask<()> {
TrustTask {
id: doc.id.clone(),
thread_id: doc.thread_id.clone(),
parent_thread_id: doc.parent_thread_id.clone(),
ceremony: doc.ceremony.clone(),
type_uri: doc.type_uri.clone(),
issuer: doc.issuer.clone(),
recipient: doc.recipient.clone(),
issued_at: doc.issued_at,
expires_at: doc.expires_at,
payload: (),
context: doc.context.clone(),
proof: doc.proof.clone(),
extra: doc.extra.clone(),
}
}
fn routed_error(
transport: &HttpsHandler,
request: &TrustTask<()>,
reason: RejectReason,
) -> ErrorResponse {
transport
.reject(request, new_id(), reason)
.unwrap_or_else(suppressed_error_response)
}
fn new_id() -> String {
format!("urn:uuid:{}", Uuid::new_v4())
}
fn is_json_content_type(headers: &HeaderMap) -> bool {
let Some(value) = headers
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
else {
return false;
};
let media_type = value.split(';').next().unwrap_or("").trim();
media_type.eq_ignore_ascii_case("application/json")
}
fn extract_bearer(headers: &HeaderMap) -> Option<&str> {
let value = headers.get(header::AUTHORIZATION)?.to_str().ok()?;
let token = value
.strip_prefix("Bearer ")
.or_else(|| value.strip_prefix("bearer "))?;
Some(token.trim())
}
fn success_response(body: Value) -> Response {
let bytes = serde_json::to_vec(&body).expect("serialise success body");
(
StatusCode::OK,
[(header::CONTENT_TYPE, "application/json")],
bytes,
)
.into_response()
}
fn replayed_response(prior: Value) -> Response {
let is_error = prior
.get("type")
.and_then(Value::as_str)
.and_then(|t| t.parse::<trust_tasks_rs::TypeUri>().ok())
.is_some_and(|t| {
t.for_routing() == trust_tasks_rs::trust_task_error_type_uri().for_routing()
});
if is_error {
if let Ok(error) = serde_json::from_value::<ErrorResponse>(prior.clone()) {
return error_response(error);
}
}
success_response(prior)
}
fn error_response(error_doc: ErrorResponse) -> Response {
let status = status_for_code(&error_doc.payload.code);
let status = StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
let body = serde_json::to_vec(&error_doc).expect("serialise error response");
(status, [(header::CONTENT_TYPE, "application/json")], body).into_response()
}
fn free_standing_error(reason: RejectReason) -> ErrorResponse {
let mut doc = TrustTask::new(
new_id(),
trust_tasks_rs::trust_task_error_type_uri(),
ErrorPayload::from(reason),
);
doc.issued_at = Some(trust_tasks_rs::issued_at_now());
doc
}
fn suppressed_error_response() -> ErrorResponse {
free_standing_error(RejectReason::MalformedRequest {
reason: String::new(),
})
}
fn refuse_unauthenticated_discovery(
public: &AtomicBool,
unauthenticated: bool,
) -> Result<(), RejectReason> {
if !public.load(Ordering::Relaxed) && unauthenticated {
return Err(RejectReason::PermissionDenied {
reason: "discovery requires an authenticated sender".into(),
});
}
Ok(())
}