use std::sync::Arc;
use std::time::Duration;
use reqwest::{header, Client, ClientBuilder, Url};
use serde::de::DeserializeOwned;
use serde_json::Value;
use thiserror::Error;
use trust_tasks_rs::{
erase_verifier, DynProofVerifier, ErrorResponse, Payload, ProofVerifier, RequestPayload,
TransportHandler, TrustTask, TypeUri,
};
use crate::handler::HttpsHandler;
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
pub const DEFAULT_MAX_RESPONSE_BYTES: usize = 256 * 1024;
const MAX_ERROR_BODY_BYTES: usize = 512;
const MAX_REDIRECTS: usize = 5;
#[derive(Default)]
pub struct HttpsClientBuilder {
server_url: Option<String>,
server_vid: Option<String>,
my_vid: Option<String>,
my_token: Option<String>,
strip_redundant_in_band: bool,
timeout: Option<Duration>,
connect_timeout: Option<Duration>,
response_verifier: Option<Arc<dyn DynProofVerifier>>,
max_response_bytes: Option<usize>,
allow_insecure_http: bool,
follow_redirects: bool,
}
impl HttpsClientBuilder {
pub fn server_url(mut self, url: impl Into<String>) -> Self {
self.server_url = Some(url.into());
self
}
pub fn server_vid(mut self, vid: impl Into<String>) -> Self {
self.server_vid = Some(vid.into());
self
}
pub fn my_vid(mut self, vid: impl Into<String>) -> Self {
self.my_vid = Some(vid.into());
self
}
pub fn my_token(mut self, token: impl Into<String>) -> Self {
self.my_token = Some(token.into());
self
}
pub fn strip_redundant_in_band(mut self, strip: bool) -> Self {
self.strip_redundant_in_band = strip;
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
pub fn connect_timeout(mut self, timeout: Duration) -> Self {
self.connect_timeout = Some(timeout);
self
}
pub fn max_response_bytes(mut self, limit: usize) -> Self {
self.max_response_bytes = Some(limit);
self
}
pub fn allow_insecure_http(mut self, allow: bool) -> Self {
self.allow_insecure_http = allow;
self
}
pub fn follow_redirects(mut self, follow: bool) -> Self {
self.follow_redirects = follow;
self
}
pub fn with_response_verifier<V>(mut self, verifier: V) -> Self
where
V: ProofVerifier + Send + Sync + 'static,
{
self.response_verifier = Some(erase_verifier(verifier));
self
}
pub fn build(self) -> Result<HttpsClient, ClientError> {
let server_url = self
.server_url
.ok_or_else(|| ClientError::Config("server_url is required".into()))?;
let base: Url = format!("{}/trust-tasks", server_url.trim_end_matches('/'))
.parse()
.map_err(|e| ClientError::Config(format!("server_url is not a valid URL: {e}")))?;
let https = match base.scheme() {
"https" => true,
"http" if is_loopback(&base) => false,
"http" if self.my_token.is_some() => {
return Err(ClientError::Config(
"server_url is plain http: a bearer token is only sent over https \
(or to a loopback host)"
.into(),
))
}
"http" if self.allow_insecure_http => false,
"http" => {
return Err(ClientError::Config(
"server_url is plain http: use https, or allow_insecure_http(true)".into(),
))
}
other => {
return Err(ClientError::Config(format!(
"server_url scheme {other:?} is not https"
)))
}
};
let redirects = if self.follow_redirects {
reqwest::redirect::Policy::custom(|attempt| {
let same_origin = attempt
.previous()
.first()
.is_some_and(|first| first.origin() == attempt.url().origin());
if attempt.previous().len() > MAX_REDIRECTS {
attempt.error("too many redirects")
} else if same_origin {
attempt.follow()
} else {
attempt.stop()
}
})
} else {
reqwest::redirect::Policy::none()
};
let http = ClientBuilder::new()
.timeout(self.timeout.unwrap_or(DEFAULT_TIMEOUT))
.connect_timeout(self.connect_timeout.unwrap_or(DEFAULT_CONNECT_TIMEOUT))
.redirect(redirects)
.https_only(https)
.build()
.map_err(|e| ClientError::Config(e.to_string()))?;
Ok(HttpsClient {
http,
endpoint: base,
server_vid: self.server_vid,
my_vid: self.my_vid,
my_token: self.my_token,
strip_redundant_in_band: self.strip_redundant_in_band,
response_verifier: self.response_verifier,
max_response_bytes: self
.max_response_bytes
.unwrap_or(DEFAULT_MAX_RESPONSE_BYTES),
})
}
}
fn is_loopback(url: &Url) -> bool {
match url.host_str() {
None => false,
Some(host) => {
let host = host.trim_start_matches('[').trim_end_matches(']');
host.eq_ignore_ascii_case("localhost")
|| host.to_ascii_lowercase().ends_with(".localhost")
|| host
.parse::<std::net::IpAddr>()
.is_ok_and(|ip| ip.is_loopback())
}
}
}
async fn read_capped(mut resp: reqwest::Response, limit: usize) -> Result<Vec<u8>, ClientError> {
if resp
.content_length()
.is_some_and(|declared| declared > limit as u64)
{
return Err(ClientError::ResponseTooLarge { limit });
}
let mut body = Vec::new();
while let Some(chunk) = resp.chunk().await? {
if body.len() + chunk.len() > limit {
return Err(ClientError::ResponseTooLarge { limit });
}
body.extend_from_slice(&chunk);
}
Ok(body)
}
fn error_body_excerpt(body: &[u8]) -> String {
let text = String::from_utf8_lossy(body);
if text.len() <= MAX_ERROR_BODY_BYTES {
return text.into_owned();
}
let mut end = MAX_ERROR_BODY_BYTES;
while !text.is_char_boundary(end) {
end -= 1;
}
text[..end].to_string()
}
fn decode_error(e: serde_json::Error) -> ClientError {
ClientError::ResponseDecode(format!(
"{:?} error at line {} column {}",
e.classify(),
e.line(),
e.column()
))
}
pub struct HttpsClient {
http: Client,
endpoint: Url,
server_vid: Option<String>,
my_vid: Option<String>,
my_token: Option<String>,
strip_redundant_in_band: bool,
response_verifier: Option<Arc<dyn DynProofVerifier>>,
max_response_bytes: usize,
}
impl HttpsClient {
pub fn builder() -> HttpsClientBuilder {
HttpsClientBuilder::default()
}
pub async fn send<Req>(
&self,
mut request: TrustTask<Req>,
) -> Result<TrustTask<Req::Response>, ClientError>
where
Req: RequestPayload + serde::Serialize,
Req::Response: DeserializeOwned,
{
if request.issuer.is_none() {
request.issuer = self.my_vid.clone();
}
if request.recipient.is_none() {
request.recipient = self.server_vid.clone();
}
if request.issued_at.is_none() {
request.issued_at = Some(trust_tasks_rs::issued_at_now());
}
if self.strip_redundant_in_band {
HttpsHandler::new(self.my_vid.clone(), self.server_vid.clone())
.prepare_outbound(&mut request);
}
let mut req = self
.http
.post(self.endpoint.clone())
.header(header::CONTENT_TYPE, "application/json")
.json(&request);
if let Some(token) = &self.my_token {
req = req.bearer_auth(token);
}
let resp = req.send().await?;
let status = resp.status();
let body = read_capped(resp, self.max_response_bytes).await?;
if status.is_success() {
if body.is_empty() {
return Err(ClientError::DuplicateAbsorbed {
http_status: status.as_u16(),
});
}
let received: Value = serde_json::from_slice(&body).map_err(decode_error)?;
let untyped: TrustTask<Value> =
serde_json::from_value(received.clone()).map_err(decode_error)?;
self.check_response_binding(&request, &untyped)?;
self.verify_response_proof(&untyped, &received).await?;
let typed: TrustTask<Req::Response> =
serde_json::from_value(received).map_err(decode_error)?;
Ok(typed)
} else {
let parsed = serde_json::from_slice::<Value>(&body)
.ok()
.and_then(|received| {
serde_json::from_value::<ErrorResponse>(received.clone())
.ok()
.map(|doc| (received, doc))
});
match parsed {
Some((received, error_doc)) => {
if let Err(reason) = self.verify_error_response(&error_doc, &received).await {
return Err(ClientError::UnverifiedErrorResponse {
http_status: status.as_u16(),
reason,
error: Box::new(error_doc),
});
}
if let Some(reported) = error_doc
.payload
.in_response_to
.as_ref()
.and_then(|r| r.id.as_deref())
{
if reported != request.id {
return Err(ClientError::ErrorResponseMismatch {
expected: request.id.clone(),
actual: reported.to_string(),
});
}
}
Err(ClientError::TrustTaskError {
http_status: status.as_u16(),
error: Box::new(error_doc),
})
}
None => Err(ClientError::HttpStatus {
http_status: status.as_u16(),
body: error_body_excerpt(&body),
}),
}
}
}
fn check_response_binding<Req: Payload + serde::Serialize>(
&self,
request: &TrustTask<Req>,
response: &TrustTask<Value>,
) -> Result<(), ClientError> {
let expected_thread = request
.thread_id
.clone()
.unwrap_or_else(|| request.id.clone());
if response.thread_id.as_deref() != Some(expected_thread.as_str()) {
return Err(ClientError::ResponseThreadMismatch {
expected: expected_thread,
actual: response.thread_id.clone(),
});
}
let expected_type: TypeUri = request.type_uri.with_response();
if response.type_uri != expected_type {
return Err(ClientError::ResponseTypeMismatch {
expected: expected_type.to_string(),
actual: response.type_uri.to_string(),
});
}
if let Some(expected) = self.server_vid.as_deref() {
if !self.party_matches(response.issuer.as_deref(), expected) {
return Err(ClientError::ResponseIssuerMismatch {
expected: expected.to_string(),
actual: response.issuer.clone(),
});
}
}
if let Some(expected) = self.my_vid.as_deref() {
if !self.party_matches(response.recipient.as_deref(), expected) {
return Err(ClientError::ResponseRecipientMismatch {
expected: expected.to_string(),
actual: response.recipient.clone(),
});
}
}
Ok(())
}
fn party_matches(&self, actual: Option<&str>, expected: &str) -> bool {
match actual {
Some(v) => v == expected,
None => self.strip_redundant_in_band,
}
}
async fn verify_response_proof(
&self,
response: &TrustTask<Value>,
received: &Value,
) -> Result<(), ClientError> {
let Some(verifier) = &self.response_verifier else {
return Ok(());
};
if response.proof.is_none() {
return Err(ClientError::ResponseProofMissing);
}
verifier
.verify_received(received)
.await
.map_err(|e| ClientError::ResponseProofInvalid(e.to_string()))
}
async fn verify_error_response(
&self,
error: &ErrorResponse,
received: &Value,
) -> Result<(), String> {
let Some(verifier) = &self.response_verifier else {
return Ok(());
};
if error.proof.is_none() {
return Err("the error response carried no proof".to_string());
}
if let Some(expected) = self.server_vid.as_deref() {
if !self.party_matches(error.issuer.as_deref(), expected) {
return Err("the error response's issuer is not the configured server".to_string());
}
}
if let Some(expected) = self.my_vid.as_deref() {
if !self.party_matches(error.recipient.as_deref(), expected) {
return Err("the error response is not addressed to this client".to_string());
}
}
verifier
.verify_received(received)
.await
.map_err(|e| format!("the error response's proof did not verify: {e}"))
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ClientError {
#[error("client configuration error: {0}")]
Config(String),
#[error("HTTP request failed: {0}")]
Http(#[from] reqwest::Error),
#[error("response body exceeds {limit} bytes")]
ResponseTooLarge {
limit: usize,
},
#[error("server returned trust-task-error (HTTP {http_status}): {error}")]
TrustTaskError {
http_status: u16,
error: Box<ErrorResponse>,
},
#[error("non-2xx HTTP response ({http_status}) with non-Trust-Task body")]
HttpStatus {
http_status: u16,
body: String,
},
#[error("response body did not match expected type: {0}")]
ResponseDecode(String),
#[error("consumer absorbed this document as a duplicate (HTTP {http_status}); no result body")]
DuplicateAbsorbed {
http_status: u16,
},
#[error("response threadId does not match the request: expected {expected}, got {actual:?}")]
ResponseThreadMismatch {
expected: String,
actual: Option<String>,
},
#[error("response type does not match the request: expected {expected}, got {actual}")]
ResponseTypeMismatch {
expected: String,
actual: String,
},
#[error("response issuer is not the configured server: expected {expected}, got {actual:?}")]
ResponseIssuerMismatch {
expected: String,
actual: Option<String>,
},
#[error("response recipient is not this client: expected {expected}, got {actual:?}")]
ResponseRecipientMismatch {
expected: String,
actual: Option<String>,
},
#[error("error response reports on a different document: expected {expected}, got {actual}")]
ErrorResponseMismatch {
expected: String,
actual: String,
},
#[error("response carried no proof but this client requires signed responses")]
ResponseProofMissing,
#[error("response proof verification failed: {0}")]
ResponseProofInvalid(String),
#[error("unverified error response (HTTP {http_status}): {reason}")]
UnverifiedErrorResponse {
http_status: u16,
reason: String,
error: Box<ErrorResponse>,
},
}