#[derive(Debug, thiserror::Error)]
pub enum TamgaError {
#[error("HTTP transport error: {0}")]
Http(#[from] reqwest::Error),
#[error("failed to parse response body: {0}")]
Json(#[from] serde_json::Error),
#[error("API error {code}: {detail}", code = .0.code, detail = .0.detail)]
Api(Box<JsonApiError>),
#[error("rate limited by the server{}", match retry_after {
Some(s) => format!("; retry after {s}s"),
None => String::new(),
})]
RateLimited {
retry_after: Option<u64>,
response_info: Box<crate::transport::ResponseInfo>,
},
#[error("check-in not required: {detail}", detail = .0.detail)]
CheckInNotRequired(Box<JsonApiError>),
#[error(transparent)]
Checkout(#[from] CheckoutError),
#[error("license not encrypted: {detail}", detail = .0.detail)]
LicenseNotEncrypted(Box<JsonApiError>),
#[error("license key missing: {detail}", detail = .0.detail)]
LicenseKeyMissingApi(Box<JsonApiError>),
#[error("ttl invalid: {detail}", detail = .0.detail)]
TtlInvalidApi(Box<JsonApiError>),
#[error("scheme not supported: {detail}", detail = .0.detail)]
SchemeNotSupportedApi(Box<JsonApiError>),
#[error("fingerprint taken: {detail}", detail = .0.detail)]
FingerprintTaken(Box<JsonApiError>),
#[error("dataset invalid: {detail}", detail = .0.detail)]
DatasetInvalid(Box<JsonApiError>),
#[error("pid taken: {detail}", detail = .0.detail)]
PidTaken(Box<JsonApiError>),
#[error(transparent)]
Proof(#[from] ProofError),
#[error("not found: {detail}", detail = .0.detail)]
NotFound(Box<JsonApiError>),
#[error("unauthorized: {detail}", detail = .0.detail)]
Unauthorized(Box<JsonApiError>),
#[error("forbidden: {detail}", detail = .0.detail)]
Forbidden(Box<JsonApiError>),
#[error("internal server error: {detail}", detail = .0.detail)]
InternalServerError(Box<JsonApiError>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LimitExceededCode {
MachineLimitExceeded,
CoreLimitExceeded,
MemoryLimitExceeded,
DiskLimitExceeded,
TooManyProcesses,
}
impl LimitExceededCode {
pub fn parse(code: &str) -> Option<Self> {
match code {
"MACHINE_LIMIT_EXCEEDED" => Some(LimitExceededCode::MachineLimitExceeded),
"CORE_LIMIT_EXCEEDED" => Some(LimitExceededCode::CoreLimitExceeded),
"MEMORY_LIMIT_EXCEEDED" => Some(LimitExceededCode::MemoryLimitExceeded),
"DISK_LIMIT_EXCEEDED" => Some(LimitExceededCode::DiskLimitExceeded),
"TOO_MANY_PROCESSES" => Some(LimitExceededCode::TooManyProcesses),
_ => None,
}
}
pub fn as_str(self) -> &'static str {
match self {
LimitExceededCode::MachineLimitExceeded => "MACHINE_LIMIT_EXCEEDED",
LimitExceededCode::CoreLimitExceeded => "CORE_LIMIT_EXCEEDED",
LimitExceededCode::MemoryLimitExceeded => "MEMORY_LIMIT_EXCEEDED",
LimitExceededCode::DiskLimitExceeded => "DISK_LIMIT_EXCEEDED",
LimitExceededCode::TooManyProcesses => "TOO_MANY_PROCESSES",
}
}
pub fn as_validation_code(self) -> crate::models::validation::ValidationCode {
use crate::models::validation::ValidationCode;
match self {
LimitExceededCode::MachineLimitExceeded => ValidationCode::TooManyMachines,
LimitExceededCode::CoreLimitExceeded => ValidationCode::TooManyCores,
LimitExceededCode::MemoryLimitExceeded => ValidationCode::TooMuchMemory,
LimitExceededCode::DiskLimitExceeded => ValidationCode::TooMuchDisk,
LimitExceededCode::TooManyProcesses => ValidationCode::TooManyProcesses,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LicenseAuthCode {
LicenseSuspended,
LicenseExpired,
LicenseNotAllowed,
}
impl LicenseAuthCode {
pub fn parse(code: &str) -> Option<Self> {
match code {
"LICENSE_SUSPENDED" => Some(LicenseAuthCode::LicenseSuspended),
"LICENSE_EXPIRED" => Some(LicenseAuthCode::LicenseExpired),
"LICENSE_NOT_ALLOWED" => Some(LicenseAuthCode::LicenseNotAllowed),
_ => None,
}
}
pub fn as_str(self) -> &'static str {
match self {
LicenseAuthCode::LicenseSuspended => "LICENSE_SUSPENDED",
LicenseAuthCode::LicenseExpired => "LICENSE_EXPIRED",
LicenseAuthCode::LicenseNotAllowed => "LICENSE_NOT_ALLOWED",
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum ProofError {
#[error("malformed proof: missing v1x0. prefix")]
MalformedProof,
#[error("invalid base64 in proof signature")]
InvalidBase64,
#[error(transparent)]
Crypto(#[from] CryptoError),
}
#[derive(Debug, Clone, Copy, thiserror::Error, PartialEq, Eq)]
pub enum CryptoError {
#[error("invalid public key")]
InvalidKey,
#[error("invalid signature encoding")]
InvalidSignature,
#[error("signature verification failed")]
VerificationFailed,
#[error("decryption failed (wrong key or tampered ciphertext)")]
DecryptionFailed,
}
#[derive(Debug, thiserror::Error)]
pub enum CheckoutError {
#[error("malformed PEM envelope: missing BEGIN/END markers")]
MalformedPem,
#[error("invalid base64 in certificate payload")]
InvalidBase64,
#[error("invalid JSON in certificate payload: {0}")]
InvalidJson(#[from] serde_json::Error),
#[error("unsupported algorithm: {0}")]
UnsupportedAlgorithm(String),
#[error("license file expired at unix timestamp {exp}")]
Expired {
exp: i64,
},
#[error("license key is required to decrypt an encrypted checkout file")]
LicenseKeyMissing,
#[error("machine fingerprint is required to decrypt an encrypted machine file")]
FingerprintMissing,
#[error("scheme not supported for machine file checkout: RSA_2048_JWT_RS256")]
SchemeNotSupported,
#[error("ttl out of range: {0}")]
TtlOutOfRange(String),
#[error("no signing key for kid {kid} in the supplied key set")]
UnknownSigningKey {
kid: String,
},
#[error(transparent)]
Crypto(#[from] CryptoError),
}
impl TamgaError {
pub fn json_api_error(&self) -> Option<&JsonApiError> {
match self {
TamgaError::Api(err)
| TamgaError::CheckInNotRequired(err)
| TamgaError::LicenseNotEncrypted(err)
| TamgaError::LicenseKeyMissingApi(err)
| TamgaError::TtlInvalidApi(err)
| TamgaError::SchemeNotSupportedApi(err)
| TamgaError::FingerprintTaken(err)
| TamgaError::DatasetInvalid(err)
| TamgaError::PidTaken(err)
| TamgaError::NotFound(err)
| TamgaError::Unauthorized(err)
| TamgaError::Forbidden(err)
| TamgaError::InternalServerError(err) => Some(err),
TamgaError::Http(_)
| TamgaError::Json(_)
| TamgaError::RateLimited { .. }
| TamgaError::Checkout(_)
| TamgaError::Proof(_) => None,
}
}
pub fn code(&self) -> Option<&str> {
self.json_api_error().map(|err| err.code.as_str())
}
pub fn limit_exceeded(&self) -> Option<LimitExceededCode> {
self.code().and_then(LimitExceededCode::parse)
}
pub fn license_auth_failure(&self) -> Option<LicenseAuthCode> {
self.code().and_then(LicenseAuthCode::parse)
}
pub(crate) fn from_json_api_error(err: JsonApiError) -> Self {
match err.code.as_str() {
"CHECK_IN_NOT_REQUIRED" => TamgaError::CheckInNotRequired(Box::new(err)),
"LICENSE_NOT_ENCRYPTED" => TamgaError::LicenseNotEncrypted(Box::new(err)),
"LICENSE_KEY_MISSING" => TamgaError::LicenseKeyMissingApi(Box::new(err)),
"FINGERPRINT_TAKEN" => TamgaError::FingerprintTaken(Box::new(err)),
"PID_TAKEN" => TamgaError::PidTaken(Box::new(err)),
"NOT_FOUND" => TamgaError::NotFound(Box::new(err)),
"UNAUTHORIZED" => TamgaError::Unauthorized(Box::new(err)),
"FORBIDDEN" => TamgaError::Forbidden(Box::new(err)),
"INTERNAL_SERVER_ERROR" => TamgaError::InternalServerError(Box::new(err)),
"DATASET_INVALID" => TamgaError::DatasetInvalid(Box::new(err)),
"TTL_INVALID" => TamgaError::TtlInvalidApi(Box::new(err)),
"SCHEME_NOT_SUPPORTED" => TamgaError::SchemeNotSupportedApi(Box::new(err)),
_ => TamgaError::Api(Box::new(err)),
}
}
}
#[derive(Debug, Clone, serde::Deserialize)]
pub struct JsonApiError {
pub id: String,
pub status: String,
pub code: String,
pub title: String,
pub detail: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub source: Option<JsonApiErrorSource>,
}
#[derive(Debug, Clone, serde::Deserialize)]
pub struct JsonApiErrorSource {
pub pointer: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
pub(crate) struct JsonApiErrorDocument {
pub errors: Vec<JsonApiError>,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum FingerprintError {
#[error("at least one component is required")]
NoComponents,
#[error("component label must not be empty")]
EmptyLabel,
#[error("invalid label {label:?}: labels are ASCII printable 0x21..=0x7E, excluding '='")]
InvalidLabel {
label: String,
},
#[error("duplicate label {label:?}: two values for one label is a caller bug")]
DuplicateLabel {
label: String,
},
#[error("value for label {label:?} contains an ASCII control character")]
ControlCharacterInValue {
label: String,
},
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ArtifactDownloadError {
#[error("failed to obtain a download URL: {0}")]
Api(#[from] TamgaError),
#[error("the download response carried no redirectUrl")]
MissingRedirectUrl,
#[error("the download response carried an unparseable redirectUrl")]
MalformedRedirectUrl,
#[error("redirectUrl has unsupported scheme `{scheme}` (expected http or https)")]
UnsupportedRedirectScheme {
scheme: String,
},
#[error("failed to fetch the presigned URL: {0}")]
Fetch(#[source] reqwest::Error),
#[error("storage host answered HTTP {status}")]
StorageStatus {
status: u16,
},
#[error("artifact exceeds the {limit}-byte ceiling supplied by the caller")]
TooLarge {
limit: u64,
},
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deserializes_representative_error_body() {
let json = serde_json::json!({
"errors": [{
"id": "01926b3e-0000-7000-8000-000000000000",
"status": "404",
"code": "NOT_FOUND",
"title": "Not Found",
"detail": "The requested license was not found",
"source": null,
}]
});
let doc: JsonApiErrorDocument = serde_json::from_value(json).unwrap();
assert_eq!(doc.errors.len(), 1);
assert_eq!(doc.errors[0].code, "NOT_FOUND");
assert_eq!(doc.errors[0].status, "404");
}
#[test]
fn maps_check_in_not_required_code_to_typed_variant() {
let err = JsonApiError {
id: "01926b3e-0000-7000-8000-000000000000".to_string(),
status: "422".to_string(),
code: "CHECK_IN_NOT_REQUIRED".to_string(),
title: "Unprocessable Entity".to_string(),
detail: "this license's policy does not require check-in".to_string(),
source: None,
};
let mapped = TamgaError::from_json_api_error(err);
assert!(matches!(mapped, TamgaError::CheckInNotRequired(_)));
}
#[test]
fn unrecognized_code_maps_to_generic_api_variant() {
let err = JsonApiError {
id: "01926b3e-0000-7000-8000-000000000000".to_string(),
status: "422".to_string(),
code: "SCOPE_NOT_SUPPORTED".to_string(),
title: "Unprocessable Entity".to_string(),
detail: "scope.version is not supported".to_string(),
source: None,
};
let mapped = TamgaError::from_json_api_error(err);
assert!(matches!(mapped, TamgaError::Api(_)));
assert_eq!(mapped.code(), Some("SCOPE_NOT_SUPPORTED"));
}
fn error_with_code(status: &str, code: &str) -> TamgaError {
TamgaError::from_json_api_error(JsonApiError {
id: "01926b3e-0000-7000-8000-000000000000".to_string(),
status: status.to_string(),
code: code.to_string(),
title: String::new(),
detail: String::new(),
source: None,
})
}
#[test]
fn create_time_limit_codes_classify_and_map_onto_validation_codes() {
use crate::models::validation::ValidationCode;
let cases = [
(
"MACHINE_LIMIT_EXCEEDED",
LimitExceededCode::MachineLimitExceeded,
ValidationCode::TooManyMachines,
),
(
"CORE_LIMIT_EXCEEDED",
LimitExceededCode::CoreLimitExceeded,
ValidationCode::TooManyCores,
),
(
"MEMORY_LIMIT_EXCEEDED",
LimitExceededCode::MemoryLimitExceeded,
ValidationCode::TooMuchMemory,
),
(
"DISK_LIMIT_EXCEEDED",
LimitExceededCode::DiskLimitExceeded,
ValidationCode::TooMuchDisk,
),
(
"TOO_MANY_PROCESSES",
LimitExceededCode::TooManyProcesses,
ValidationCode::TooManyProcesses,
),
];
for (wire, expected, validation) in cases {
let err = error_with_code("422", wire);
assert_eq!(err.limit_exceeded(), Some(expected), "code {wire}");
assert_eq!(expected.as_str(), wire);
assert_eq!(expected.as_validation_code(), validation, "code {wire}");
}
}
#[test]
fn license_auth_gate_codes_classify() {
let cases = [
("LICENSE_SUSPENDED", LicenseAuthCode::LicenseSuspended),
("LICENSE_EXPIRED", LicenseAuthCode::LicenseExpired),
("LICENSE_NOT_ALLOWED", LicenseAuthCode::LicenseNotAllowed),
];
for (wire, expected) in cases {
let err = error_with_code("401", wire);
assert_eq!(err.license_auth_failure(), Some(expected), "code {wire}");
assert_eq!(expected.as_str(), wire);
assert_eq!(err.limit_exceeded(), None, "code {wire}");
}
}
#[test]
fn every_code_carrying_variant_still_exposes_its_code() {
let carries_a_body = [
"CHECK_IN_NOT_REQUIRED",
"LICENSE_NOT_ENCRYPTED",
"LICENSE_KEY_MISSING",
"FINGERPRINT_TAKEN",
"PID_TAKEN",
"NOT_FOUND",
"UNAUTHORIZED",
"FORBIDDEN",
"INTERNAL_SERVER_ERROR",
"DATASET_INVALID",
"TTL_INVALID",
"SCHEME_NOT_SUPPORTED",
"SCOPE_NOT_SUPPORTED",
];
for wire in carries_a_body {
let err = error_with_code("422", wire);
assert!(
err.json_api_error().is_some(),
"{wire} lost its server error body"
);
assert_eq!(err.code(), Some(wire), "code {wire}");
}
}
#[test]
fn classifiers_return_none_for_errors_without_a_server_body() {
let err = TamgaError::RateLimited {
retry_after: Some(5),
response_info: Box::default(),
};
assert!(err.json_api_error().is_none());
assert_eq!(err.code(), None);
assert_eq!(err.limit_exceeded(), None);
assert_eq!(err.license_auth_failure(), None);
}
#[test]
fn json_api_error_is_readable_through_a_typed_variant_too() {
let err = error_with_code("404", "NOT_FOUND");
assert!(matches!(err, TamgaError::NotFound(_)));
assert_eq!(err.code(), Some("NOT_FOUND"));
assert_eq!(err.json_api_error().unwrap().status, "404");
}
#[test]
fn fixed_status_codes_map_to_their_typed_variants() {
let build = |code: &str| JsonApiError {
id: "01926b3e-0000-7000-8000-000000000000".to_string(),
status: "0".to_string(),
code: code.to_string(),
title: "".to_string(),
detail: "".to_string(),
source: None,
};
assert!(matches!(
TamgaError::from_json_api_error(build("NOT_FOUND")),
TamgaError::NotFound(_)
));
assert!(matches!(
TamgaError::from_json_api_error(build("UNAUTHORIZED")),
TamgaError::Unauthorized(_)
));
assert!(matches!(
TamgaError::from_json_api_error(build("FORBIDDEN")),
TamgaError::Forbidden(_)
));
assert!(matches!(
TamgaError::from_json_api_error(build("INTERNAL_SERVER_ERROR")),
TamgaError::InternalServerError(_)
));
}
#[test]
fn deserializes_error_with_source_pointer() {
let json = serde_json::json!({
"errors": [{
"id": "01926b3e-0000-7000-8000-000000000000",
"status": "422",
"code": "DATASET_INVALID",
"title": "Unprocessable Entity",
"detail": "dataset must be an object",
"source": { "pointer": "/meta/dataset" },
}]
});
let doc: JsonApiErrorDocument = serde_json::from_value(json).unwrap();
assert_eq!(
doc.errors[0].source.as_ref().unwrap().pointer.as_deref(),
Some("/meta/dataset")
);
}
}