use std::fmt;
use std::sync::Arc;
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::claim_ref::{InvalidClaimRefError, parse_claim_ref};
use crate::client::{ClientBuilder, ConfigError, Core, UnavailableReason, decode, error_body};
use crate::transport::{ReqwestTransport, Transport};
pub struct ClaimCheckClient<T = ReqwestTransport> {
core: Arc<Core<T>>,
}
impl<T> ClaimCheckClient<T> {
pub(crate) fn from_core(core: Arc<Core<T>>) -> Self {
Self { core }
}
}
impl<T> Clone for ClaimCheckClient<T> {
fn clone(&self) -> Self {
Self {
core: Arc::clone(&self.core),
}
}
}
impl<T> fmt::Debug for ClaimCheckClient<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ClaimCheckClient")
.field("base_url", &self.core.base_url)
.field(
"header_names",
&crate::client::HeaderNames(&self.core.headers),
)
.field("timeout", &self.core.timeout)
.finish_non_exhaustive()
}
}
impl ClaimCheckClient {
pub fn new(base_url: impl Into<String>) -> Result<Self, ConfigError> {
ClientBuilder::new(base_url).claim_check()
}
}
impl<T: Transport> ClaimCheckClient<T> {
pub async fn redeem(&self, claim_ref: &str, sha256: &str) -> Result<Bytes, ClaimCheckError> {
let parsed = parse_claim_ref(claim_ref)?;
let expected = decode_sha256(sha256)?;
let response = self
.core
.send(http::Method::GET, &parsed.path(), None)
.await
.map_err(ClaimCheckError::Unavailable)?;
let status = response.status();
if status == http::StatusCode::OK {
let digest = Sha256::digest(response.body());
if digest.as_slice() != expected.as_slice() {
return Err(ClaimCheckError::Integrity {
expected: sha256.to_owned(),
actual: hex::encode(digest),
});
}
return Ok(response.into_body());
}
if status == http::StatusCode::NOT_FOUND {
return Err(ClaimCheckError::NotFound);
}
let busy = status == http::StatusCode::REQUEST_TIMEOUT
|| status == http::StatusCode::TOO_MANY_REQUESTS;
if status.is_client_error() && !busy {
return Err(ClaimCheckError::Rejected {
status,
body: error_body(response.body()),
});
}
Err(ClaimCheckError::Unavailable(UnavailableReason::Status(
status,
)))
}
pub async fn health(&self) -> Result<ClaimCheckHealth, ClaimCheckError> {
let response = self
.core
.send(http::Method::GET, "/health", None)
.await
.map_err(ClaimCheckError::Unavailable)?;
if response.status() != http::StatusCode::OK {
return Err(ClaimCheckError::Unavailable(UnavailableReason::Status(
response.status(),
)));
}
decode(response.body()).map_err(ClaimCheckError::Unavailable)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ClaimCheckHealth {
pub status: String,
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ClaimCheckError {
#[error(transparent)]
InvalidRef(#[from] InvalidClaimRefError),
#[error("invalid sha256 {sha256:?}: want 64 lowercase hex characters")]
InvalidSha256 {
sha256: String,
},
#[error("claim not found")]
NotFound,
#[error("claim-check gateway rejected the request (HTTP {status})")]
Rejected {
status: http::StatusCode,
body: serde_json::Value,
},
#[error("claim body does not match sha256 {expected}")]
Integrity {
expected: String,
actual: String,
},
#[error("claim-check gateway unavailable")]
Unavailable(#[source] UnavailableReason),
}
impl ClaimCheckError {
#[must_use]
pub fn is_retryable(&self) -> bool {
matches!(self, Self::Unavailable(_))
}
}
fn decode_sha256(sha256: &str) -> Result<[u8; 32], ClaimCheckError> {
let invalid = || ClaimCheckError::InvalidSha256 {
sha256: sha256.to_owned(),
};
let bytes = sha256.as_bytes();
if bytes.len() != 64
|| !bytes
.iter()
.all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
{
return Err(invalid());
}
let mut digest = [0_u8; 32];
hex::decode_to_slice(sha256, &mut digest).map_err(|_| invalid())?;
Ok(digest)
}
#[cfg(test)]
mod tests {
use super::{ClaimCheckError, decode_sha256};
const HEX: &str = "8e1bed597394cf01672e49232d9929c8bc6b3d6ea4e2f489517ec88701f01581";
#[test]
fn decodes_a_lowercase_digest() {
let digest = decode_sha256(HEX).expect("valid digest");
assert_eq!(digest[0], 0x8e);
assert_eq!(digest[31], 0x81);
}
#[test]
fn refuses_other_digest_shapes() {
let rejected = [
String::new(),
HEX[..63].to_owned(),
format!("{HEX}0"),
HEX.to_uppercase(),
"g".repeat(64),
format!("sha256-{HEX}"),
];
for bad in &rejected {
let err = decode_sha256(bad).expect_err("invalid digest");
assert!(matches!(err, ClaimCheckError::InvalidSha256 { .. }));
}
}
}