use std::sync::Arc;
use bytes::Bytes;
use http::{HeaderValue, Method, StatusCode, header};
use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::core::{PatchBody, TmfError};
use super::error::{Error, Result};
use super::page::{Page, next_link};
use super::patch::Patch;
use super::query::Query;
use super::transport::{TmfRequest, TmfResponse, Transport};
#[derive(Clone)]
pub struct TmfClient {
transport: Arc<dyn Transport>,
base_url: String,
}
impl std::fmt::Debug for TmfClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TmfClient")
.field("base_url", &self.base_url)
.finish_non_exhaustive()
}
}
impl TmfClient {
pub fn new(base_url: impl Into<String>, transport: impl Transport + 'static) -> Result<Self> {
let base_url = base_url.into();
if base_url.trim().is_empty() {
return Err(Error::InvalidBaseUrl("base URL must not be empty".into()));
}
Ok(Self {
transport: Arc::new(transport),
base_url: base_url.trim_end_matches('/').to_owned(),
})
}
#[must_use]
pub fn base_url(&self) -> &str {
&self.base_url
}
#[must_use]
pub fn url(&self, path: &str) -> String {
format!("{}/{}", self.base_url, path.trim_start_matches('/'))
}
pub async fn get<T: DeserializeOwned>(&self, path: &str, id: &str, query: &Query) -> Result<T> {
let mut request = TmfRequest::new(Method::GET, self.url(&format!("{path}/{id}")));
request.query = query.to_params();
let response = self.send(request).await?;
decode(&response)
}
pub async fn get_absolute<T: DeserializeOwned>(&self, url: &str, query: &Query) -> Result<T> {
self.require_same_origin(url)?;
self.get_cross_origin(url, query).await
}
pub async fn get_cross_origin<T: DeserializeOwned>(
&self,
url: &str,
query: &Query,
) -> Result<T> {
let mut request = TmfRequest::new(Method::GET, url.to_owned());
request.query = query.to_params();
let response = self.send(request).await?;
decode(&response)
}
pub fn require_same_origin(&self, url: &str) -> Result<()> {
if same_origin(&self.base_url, url) {
return Ok(());
}
Err(Error::CrossOrigin {
url: url.to_owned(),
base: self.base_url.clone(),
})
}
pub async fn list<T: DeserializeOwned>(&self, path: &str, query: &Query) -> Result<Page<T>> {
let mut request = TmfRequest::new(Method::GET, self.url(path));
request.query = query.to_params();
let response = self.send(request).await?;
Self::page_from(&response, query.offset_value().unwrap_or(0))
}
fn page_from<T: DeserializeOwned>(response: &TmfResponse, offset: usize) -> Result<Page<T>> {
Ok(Page {
items: decode(response)?,
total_count: response.total_count(),
result_count: response.result_count(),
next_link: response
.headers
.get(header::LINK)
.and_then(|v| v.to_str().ok())
.and_then(next_link),
partial: response.status == StatusCode::PARTIAL_CONTENT,
offset,
})
}
pub async fn list_absolute<T: DeserializeOwned>(&self, url: &str) -> Result<Page<T>> {
self.require_same_origin(url)?;
let response = self
.send(TmfRequest::new(Method::GET, url.to_owned()))
.await?;
Self::page_from(&response, 0)
}
pub async fn create<B: Serialize, T: DeserializeOwned>(
&self,
path: &str,
body: &B,
) -> Result<T> {
let mut request = TmfRequest::new(Method::POST, self.url(path));
request.body = Some(encode(body)?);
request.headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
);
let response = self.send(request).await?;
decode(&response)
}
pub async fn patch<'a, U: PatchBody + 'a, T: DeserializeOwned>(
&self,
path: &str,
id: &str,
body: impl Into<Patch<'a, U>>,
) -> Result<T> {
let request = self.patch_request(path, id, &body.into())?;
let response = self.send(request).await?;
decode(&response)
}
pub(super) fn patch_request<U: PatchBody>(
&self,
path: &str,
id: &str,
body: &Patch<'_, U>,
) -> Result<TmfRequest> {
let mut request = TmfRequest::new(Method::PATCH, self.url(&format!("{path}/{id}")));
request.body = Some(Bytes::from(body.to_json().map_err(Error::Encode)?));
request.headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static(body.content_type()),
);
Ok(request)
}
pub async fn delete(&self, path: &str, id: &str) -> Result<()> {
let request = TmfRequest::new(Method::DELETE, self.url(&format!("{path}/{id}")));
self.send(request).await.map(|_| ())
}
pub async fn send(&self, request: TmfRequest) -> Result<TmfResponse> {
let response = self.dispatch(request).await?;
if response.status.is_success() {
return Ok(response);
}
Err(interpret_failure(&response))
}
pub(super) async fn send_conditional(&self, request: TmfRequest) -> Result<TmfResponse> {
let response = self.dispatch(request).await?;
if response.status.is_success() || response.status == StatusCode::NOT_MODIFIED {
return Ok(response);
}
Err(interpret_failure(&response))
}
async fn dispatch(&self, mut request: TmfRequest) -> Result<TmfResponse> {
request
.headers
.entry(header::ACCEPT)
.or_insert_with(|| HeaderValue::from_static("application/json"));
self.transport.execute(request).await
}
}
pub(crate) fn interpret_failure(response: &TmfResponse) -> Error {
match serde_json::from_slice::<TmfError>(&response.body) {
Ok(error) if error.is_populated() => Error::Api {
status: response.status,
error: Box::new(error),
},
_ => Error::Status {
status: response.status,
body: truncate(&String::from_utf8_lossy(&response.body)),
},
}
}
pub(super) fn decode<T: DeserializeOwned>(response: &TmfResponse) -> Result<T> {
if response.body.is_empty() {
if response.status == StatusCode::ACCEPTED {
return Err(Error::Accepted {
status: response.status,
monitor: monitor_url(response),
});
}
if response.status == StatusCode::NO_CONTENT {
return serde_json::from_str("null").map_err(Error::Decode);
}
}
serde_json::from_slice(&response.body).map_err(Error::Decode)
}
fn monitor_url(response: &TmfResponse) -> Option<String> {
[header::LOCATION, header::CONTENT_LOCATION]
.iter()
.find_map(|name| response.headers.get(name))
.and_then(|value| value.to_str().ok())
.map(ToOwned::to_owned)
}
fn encode<B: Serialize>(body: &B) -> Result<Bytes> {
serde_json::to_vec(body)
.map(Bytes::from)
.map_err(Error::Encode)
}
#[must_use]
pub fn same_origin(base: &str, other: &str) -> bool {
fn origin(url: &str) -> Option<(&str, &str)> {
let (scheme, rest) = url.split_once("://")?;
let authority = rest.split(['/', '?', '#']).next()?;
if scheme.is_empty() || authority.is_empty() {
return None;
}
let host = match authority.rsplit_once(':') {
Some((host, port))
if !host.is_empty()
&& !port.is_empty()
&& port.bytes().all(|b| b.is_ascii_digit())
&& default_port(scheme) == Some(port) =>
{
host
}
_ => authority,
};
Some((scheme, host))
}
fn default_port(scheme: &str) -> Option<&'static str> {
if scheme.eq_ignore_ascii_case("https") {
Some("443")
} else if scheme.eq_ignore_ascii_case("http") {
Some("80")
} else {
None
}
}
match (origin(base), origin(other)) {
(Some((base_scheme, base_host)), Some((other_scheme, other_host))) => {
base_scheme.eq_ignore_ascii_case(other_scheme)
&& base_host.eq_ignore_ascii_case(other_host)
}
_ => false,
}
}
fn truncate(body: &str) -> String {
const MAX: usize = 512;
if body.len() <= MAX {
return body.to_owned();
}
let mut end = MAX;
while !body.is_char_boundary(end) {
end -= 1;
}
format!("{}… ({} bytes total)", &body[..end], body.len())
}
#[cfg(test)]
mod tests {
use http::HeaderMap;
use super::*;
#[test]
fn truncates_on_a_char_boundary() {
let body = "ä".repeat(400); let out = truncate(&body);
assert!(out.ends_with("bytes total)"));
assert!(out.is_char_boundary(0));
}
#[test]
fn rejects_an_empty_base_url() {
struct Never;
#[async_trait::async_trait]
impl Transport for Never {
async fn execute(&self, _: TmfRequest) -> Result<TmfResponse> {
unreachable!()
}
}
assert!(matches!(
TmfClient::new(" ", Never),
Err(Error::InvalidBaseUrl(_))
));
}
fn failure(body: &'static str) -> Error {
interpret_failure(&TmfResponse::new(
StatusCode::BAD_GATEWAY,
HeaderMap::new(),
Bytes::from_static(body.as_bytes()),
))
}
#[test]
fn a_pagination_link_may_not_leave_the_origin() {
let base = "https://catalog.example/tmf-api/productCatalogManagement/v5";
assert!(same_origin(
base,
"https://catalog.example/tmf-api/x?cursor=2"
));
assert!(same_origin(base, "HTTPS://Catalog.Example/other"));
assert!(!same_origin(base, "https://attacker.example/steal"));
assert!(
!same_origin(base, "https://catalog.example:8443/other"),
"a port is part of the origin"
);
assert!(
!same_origin(base, "http://catalog.example/other"),
"so is the scheme"
);
assert!(
!same_origin(base, "/relative/path"),
"unreadable is not same-origin"
);
}
#[test]
fn an_explicit_default_port_is_the_same_origin() {
assert!(same_origin(
"https://host/tmf-api/x/v5",
"https://host:443/tmf-api/y/v5/a/1"
));
assert!(same_origin("https://host:443/x", "https://host/x"));
assert!(same_origin("http://host:80/x", "http://host/x"));
assert!(!same_origin("https://host:8443/x", "https://host/x"));
assert!(!same_origin("https://host:80/x", "https://host/x"));
assert!(!same_origin("http://host:443/x", "http://host/x"));
}
#[test]
fn userinfo_cannot_disguise_another_host() {
let base = "https://catalog.example/tmf-api/x/v5";
assert!(!same_origin(
base,
"https://catalog.example@attacker.example/steal"
));
assert!(!same_origin(
base,
"https://attacker.example@catalog.example/x"
));
}
#[test]
fn an_ipv6_literal_keeps_its_brackets_and_its_port() {
assert!(same_origin("https://[::1]/x", "https://[::1]:443/y"));
assert!(!same_origin("https://[::1]/x", "https://[::2]/y"));
assert!(!same_origin("https://[::1]/x", "https://[::1]:8443/y"));
}
#[test]
fn a_tmf_error_body_becomes_a_typed_error() {
let error = failure(r#"{"code":"50201","reason":"upstream down"}"#);
assert_eq!(
error.tmf_error().and_then(|e| e.code.as_deref()),
Some("50201")
);
}
#[test]
fn an_unrelated_json_body_keeps_its_raw_text() {
let error = failure(r#"{"message":"gateway timeout","upstream":"catalog"}"#);
match error {
Error::Status { body, .. } => assert!(body.contains("gateway timeout")),
other => panic!("expected a raw status error, got {other:?}"),
}
}
}