#![doc = "Generated reqwest client with typed errors and streaming bodies."]
use async_trait::async_trait;
use reqwest::Url;
use reqwest_middleware::ClientWithMiddleware;
use spiral_contract::auth::AuthHeader;
use spiral_contract::call::{CallError, ServiceFailure};
use spiral_contract::error::ErrorEnvelope;
use crate::api::authn::AuthnApi;
use crate::api::authn::objects::*;
use crate::http::default_http_client;
#[derive(Clone)]
pub struct AuthnClient {
http: ClientWithMiddleware,
base: Url,
}
impl std::fmt::Debug for AuthnClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AuthnClient")
.field("base", &self.base)
.finish_non_exhaustive()
}
}
impl AuthnClient {
pub fn new(base: &str) -> Result<Self, CallError<AuthnError>> {
let http = default_http_client().map_err(CallError::transport)?;
Self::from_http(base, http)
}
pub fn from_http(
base: &str,
http: impl Into<ClientWithMiddleware>,
) -> Result<Self, CallError<AuthnError>> {
Self::from_transport(base, http.into())
}
pub fn from_transport(
base: &str,
http: ClientWithMiddleware,
) -> Result<Self, CallError<AuthnError>> {
let base =
Url::parse(base).map_err(|_| CallError::<AuthnError>::protocol("invalid base URL"))?;
if !matches!(base.scheme(), "http" | "https")
|| base.host_str().is_none()
|| !base.username().is_empty()
|| base.password().is_some()
|| base.query().is_some()
|| base.fragment().is_some()
{
return Err(CallError::<AuthnError>::protocol("invalid base URL"));
}
Ok(Self { http, base })
}
pub fn with_transport(mut self, http: ClientWithMiddleware) -> Self {
self.http = http;
self
}
pub fn with_http(mut self, http: impl Into<ClientWithMiddleware>) -> Self {
self.http = http.into();
self
}
pub async fn decide_consent_http(
&self,
auth_header: AuthHeader,
challenge: String,
request: ConsentDecision,
) -> Result<ConsentRedirect, CallError<AuthnError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthnError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authn");
path.push("consent");
let segment = challenge.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthnError>::protocol("dot path segment"));
}
path.push(&segment);
}
let builder = self.http.post(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let builder = builder
.header("content-type", "application/json")
.json(&request);
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
pub async fn delete_client_http(
&self,
auth_header: AuthHeader,
client_id: String,
) -> Result<(), CallError<AuthnError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthnError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authn");
path.push("clients");
let segment = client_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthnError>::protocol("dot path segment"));
}
path.push(&segment);
}
let builder = self.http.delete(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
pub async fn delete_client_redirect_http(
&self,
auth_header: AuthHeader,
client_id: String,
name: String,
) -> Result<(), CallError<AuthnError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthnError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authn");
path.push("clients");
let segment = client_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthnError>::protocol("dot path segment"));
}
path.push(&segment);
path.push("redirects");
let segment = name.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthnError>::protocol("dot path segment"));
}
path.push(&segment);
}
let builder = self.http.delete(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
pub async fn get_client_http(
&self,
auth_header: AuthHeader,
client_id: String,
) -> Result<ClientRegistration, CallError<AuthnError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthnError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authn");
path.push("clients");
let segment = client_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthnError>::protocol("dot path segment"));
}
path.push(&segment);
}
let builder = self.http.get(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
pub async fn get_consent_request_http(
&self,
auth_header: AuthHeader,
challenge: String,
) -> Result<ConsentRequest, CallError<AuthnError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthnError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authn");
path.push("consent");
let segment = challenge.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthnError>::protocol("dot path segment"));
}
path.push(&segment);
}
let builder = self.http.get(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
pub async fn get_organization_app_access_http(
&self,
auth_header: AuthHeader,
organization_id: String,
) -> Result<OrganizationAppAccess, CallError<AuthnError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthnError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authn");
path.push("organizations");
let segment = organization_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthnError>::protocol("dot path segment"));
}
path.push(&segment);
path.push("app-access");
}
let builder = self.http.get(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
pub async fn put_client_http(
&self,
auth_header: AuthHeader,
client_id: String,
request: ClientRegistration,
) -> Result<ClientRegistration, CallError<AuthnError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthnError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authn");
path.push("clients");
let segment = client_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthnError>::protocol("dot path segment"));
}
path.push(&segment);
}
let builder = self.http.put(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let builder = builder
.header("content-type", "application/json")
.json(&request);
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
pub async fn put_client_redirect_http(
&self,
auth_header: AuthHeader,
client_id: String,
name: String,
request: ClientRedirect,
) -> Result<ClientRedirect, CallError<AuthnError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthnError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authn");
path.push("clients");
let segment = client_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthnError>::protocol("dot path segment"));
}
path.push(&segment);
path.push("redirects");
let segment = name.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthnError>::protocol("dot path segment"));
}
path.push(&segment);
}
let builder = self.http.put(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let builder = builder
.header("content-type", "application/json")
.json(&request);
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
pub async fn put_organization_app_access_http(
&self,
auth_header: AuthHeader,
organization_id: String,
request: OrganizationAppAccess,
) -> Result<OrganizationAppAccess, CallError<AuthnError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthnError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authn");
path.push("organizations");
let segment = organization_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthnError>::protocol("dot path segment"));
}
path.push(&segment);
path.push("app-access");
}
let builder = self.http.put(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let builder = builder
.header("content-type", "application/json")
.json(&request);
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
pub async fn revoke_consent_http(
&self,
auth_header: AuthHeader,
client_id: String,
user_id: String,
) -> Result<(), CallError<AuthnError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthnError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authn");
path.push("clients");
let segment = client_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthnError>::protocol("dot path segment"));
}
path.push(&segment);
path.push("consents");
let segment = user_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthnError>::protocol("dot path segment"));
}
path.push(&segment);
}
let builder = self.http.delete(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
pub async fn revoke_organization_consent_http(
&self,
auth_header: AuthHeader,
client_id: String,
user_id: String,
organization_id: String,
) -> Result<(), CallError<AuthnError>> {
let mut url = self.base.clone();
{
let mut path = url.path_segments_mut().map_err(|_| {
CallError::<AuthnError>::protocol("base URL cannot contain path segments")
})?;
path.pop_if_empty();
path.push("api");
path.push("authn");
path.push("clients");
let segment = client_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthnError>::protocol("dot path segment"));
}
path.push(&segment);
path.push("consents");
let segment = user_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthnError>::protocol("dot path segment"));
}
path.push(&segment);
path.push("organizations");
let segment = organization_id.to_string();
if matches!(segment.as_str(), "." | "..") {
return Err(CallError::<AuthnError>::protocol("dot path segment"));
}
path.push(&segment);
}
let builder = self.http.delete(url).header("accept", "application/json");
let builder = builder.header("authorization", auth_header.as_str());
let response = self.send(builder, "application/json").await?;
let status = response.status().as_u16();
let bytes = bounded_body(response, 8 * 1024 * 1024).await?;
serde_json::from_slice(&bytes)
.map_err(|_| CallError::protocol_response(status, "invalid JSON response"))
}
async fn send(
&self,
builder: reqwest_middleware::RequestBuilder,
expected_media: &str,
) -> Result<reqwest::Response, CallError<AuthnError>> {
let response = builder
.timeout(std::time::Duration::from_secs(60))
.send()
.await
.map_err(CallError::transport)?;
let status = response.status();
if !status.is_success() {
let status = status.as_u16();
let content_type = response
.headers()
.get("content-type")
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let (bytes, truncated) =
bounded_error_body::<AuthnError>(response, 64 * 1024, status, content_type.clone())
.await?;
if truncated {
return Err(CallError::unknown_remote(status, content_type, bytes, true));
}
return match serde_json::from_slice::<ErrorEnvelope>(&bytes) {
Ok(envelope) => Err(CallError::Service(ServiceFailure::remote(status, envelope))),
Err(_) => Err(CallError::unknown_remote(
status,
content_type,
bytes,
false,
)),
};
}
if !media_matches(&response, expected_media) {
return Err(CallError::protocol_response(
status.as_u16(),
"unexpected response media type",
));
}
Ok(response)
}
}
fn media_matches(response: &reqwest::Response, expected: &str) -> bool {
response
.headers()
.get("content-type")
.and_then(|value| value.to_str().ok())
.and_then(|value| value.split(';').next())
.is_some_and(|value| value.trim().eq_ignore_ascii_case(expected))
}
async fn bounded_body(
mut response: reqwest::Response,
limit: usize,
) -> Result<Vec<u8>, CallError<AuthnError>> {
let status = response.status().as_u16();
let mut result = Vec::new();
while let Some(chunk) = response
.chunk()
.await
.map_err(|error| CallError::transport_response(status, error))?
{
if chunk.len() > limit.saturating_sub(result.len()) {
return Err(CallError::protocol_response(
status,
"response exceeds JSON size limit",
));
}
result.extend_from_slice(&chunk);
}
Ok(result)
}
async fn bounded_error_body<E>(
mut response: reqwest::Response,
limit: usize,
status: u16,
content_type: Option<String>,
) -> Result<(Vec<u8>, bool), CallError<E>> {
let mut result = Vec::new();
loop {
let chunk = response.chunk().await.map_err(|error| {
CallError::unreadable_remote(status, content_type.clone(), result.clone(), error)
})?;
let Some(chunk) = chunk else {
return Ok((result, false));
};
let remaining = limit.saturating_sub(result.len());
if chunk.len() > remaining {
result.extend_from_slice(&chunk[..remaining]);
return Ok((result, true));
}
result.extend_from_slice(&chunk);
}
}
#[async_trait]
impl AuthnApi for AuthnClient {
async fn decide_consent(
&self,
auth_header: AuthHeader,
challenge: String,
request: ConsentDecision,
) -> Result<ConsentRedirect, CallError<AuthnError>> {
let response = Self::decide_consent_http(self, auth_header, challenge, request).await?;
Ok(response)
}
async fn delete_client(
&self,
auth_header: AuthHeader,
client_id: String,
) -> Result<(), CallError<AuthnError>> {
let response = Self::delete_client_http(self, auth_header, client_id).await?;
Ok(response)
}
async fn delete_client_redirect(
&self,
auth_header: AuthHeader,
client_id: String,
name: String,
) -> Result<(), CallError<AuthnError>> {
let response =
Self::delete_client_redirect_http(self, auth_header, client_id, name).await?;
Ok(response)
}
async fn get_client(
&self,
auth_header: AuthHeader,
client_id: String,
) -> Result<ClientRegistration, CallError<AuthnError>> {
let response = Self::get_client_http(self, auth_header, client_id).await?;
Ok(response)
}
async fn get_consent_request(
&self,
auth_header: AuthHeader,
challenge: String,
) -> Result<ConsentRequest, CallError<AuthnError>> {
let response = Self::get_consent_request_http(self, auth_header, challenge).await?;
Ok(response)
}
async fn get_organization_app_access(
&self,
auth_header: AuthHeader,
organization_id: String,
) -> Result<OrganizationAppAccess, CallError<AuthnError>> {
let response =
Self::get_organization_app_access_http(self, auth_header, organization_id).await?;
Ok(response)
}
async fn put_client(
&self,
auth_header: AuthHeader,
client_id: String,
request: ClientRegistration,
) -> Result<ClientRegistration, CallError<AuthnError>> {
let response = Self::put_client_http(self, auth_header, client_id, request).await?;
Ok(response)
}
async fn put_client_redirect(
&self,
auth_header: AuthHeader,
client_id: String,
name: String,
request: ClientRedirect,
) -> Result<ClientRedirect, CallError<AuthnError>> {
let response =
Self::put_client_redirect_http(self, auth_header, client_id, name, request).await?;
Ok(response)
}
async fn put_organization_app_access(
&self,
auth_header: AuthHeader,
organization_id: String,
request: OrganizationAppAccess,
) -> Result<OrganizationAppAccess, CallError<AuthnError>> {
let response =
Self::put_organization_app_access_http(self, auth_header, organization_id, request)
.await?;
Ok(response)
}
async fn revoke_consent(
&self,
auth_header: AuthHeader,
client_id: String,
user_id: String,
) -> Result<(), CallError<AuthnError>> {
let response = Self::revoke_consent_http(self, auth_header, client_id, user_id).await?;
Ok(response)
}
async fn revoke_organization_consent(
&self,
auth_header: AuthHeader,
client_id: String,
user_id: String,
organization_id: String,
) -> Result<(), CallError<AuthnError>> {
let response = Self::revoke_organization_consent_http(
self,
auth_header,
client_id,
user_id,
organization_id,
)
.await?;
Ok(response)
}
}