#[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>,
},
#[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, 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(transparent)]
Crypto(#[from] CryptoError),
}
impl TamgaError {
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>,
}
#[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: "429".to_string(),
code: "TOO_MANY_REQUESTS".to_string(),
title: "Too Many Requests".to_string(),
detail: "rate limited".to_string(),
source: None,
};
let mapped = TamgaError::from_json_api_error(err);
assert!(matches!(mapped, TamgaError::Api(_)));
}
#[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")
);
}
}