use std::fmt;
macro_rules! error_classes {
($($variant:ident => $text:literal,)*) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum V2ErrorClass {
$($variant,)*
}
impl V2ErrorClass {
pub const ALL: &'static [V2ErrorClass] = &[$(V2ErrorClass::$variant,)*];
pub fn as_str(self) -> &'static str {
match self {
$(V2ErrorClass::$variant => $text,)*
}
}
pub fn parse(text: &str) -> Option<V2ErrorClass> {
match text {
$($text => Some(V2ErrorClass::$variant),)*
_ => None,
}
}
}
};
}
error_classes! {
Malformed => "malformed",
UnsupportedObjectType => "unsupported_object_type",
KeyIdMismatch => "key_id_mismatch",
DelegationDigestMismatch => "delegation_digest_mismatch",
ChainLinkageMismatch => "chain_linkage_mismatch",
DuplicateCertificateRef => "duplicate_certificate_ref",
InvalidSignature => "invalid_signature",
InvalidRequiredScope => "invalid_required_scope",
ConfigurationInvalid => "configuration_invalid",
ExpectedChallengeUnavailable => "expected_challenge_unavailable",
NamespaceMismatch => "namespace_mismatch",
StaleReplayEpoch => "stale_replay_epoch",
VerifierIdMismatch => "verifier_id_mismatch",
ChallengeMismatch => "challenge_mismatch",
ChallengeNotFresh => "challenge_not_fresh",
ExpectedAgentMismatch => "expected_agent_mismatch",
SessionContextMismatch => "session_context_mismatch",
ReceiverAudienceRequired => "receiver_audience_required",
ReceiverAudienceMismatch => "receiver_audience_mismatch",
ReceiverBindingRejected => "receiver_binding_rejected",
ClaimReplay => "claim_replay",
StreamSequenceMismatch => "stream_sequence_mismatch",
ClaimStoreUnavailable => "claim_store_unavailable",
ReceiptAbandoned => "receipt_abandoned",
EvaluationCancelled => "evaluation_cancelled",
ClockRegressed => "clock_regressed",
AllowHorizonPassed => "allow_horizon_passed",
ClaimLeaseLive => "claim_lease_live",
ClaimLeaseLost => "claim_lease_lost",
ClaimAlreadyTerminal => "claim_already_terminal",
ClaimNotFound => "claim_not_found",
StatusKeyBindingMismatch => "status_key_binding_mismatch",
StatusObjectRejected => "status_object_rejected",
ReceiptBundleMismatch => "receipt_bundle_mismatch",
BundleHashMismatch => "bundle_hash_mismatch",
TransactionPartyMismatch => "transaction_party_mismatch",
TransactionContextMismatch => "transaction_context_mismatch",
TransactionSignatureSetInvalid => "transaction_signature_set_invalid",
RotationStateMismatch => "rotation_state_mismatch",
RotationKeyReused => "rotation_key_reused",
RotationFutureDated => "rotation_future_dated",
RotationFork => "rotation_fork",
RotationFrozen => "rotation_frozen",
RotationRecoveryInvalid => "rotation_recovery_invalid",
LogStateMismatch => "log_state_mismatch",
LogGap => "log_gap",
LogOrphan => "log_orphan",
LogFork => "log_fork",
LogFrozen => "log_frozen",
}
impl fmt::Display for V2ErrorClass {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct V2Error {
pub class: V2ErrorClass,
pub message: String,
explicit: bool,
}
impl V2Error {
pub fn new(class: V2ErrorClass, message: impl Into<String>) -> Self {
V2Error {
class,
message: message.into(),
explicit: true,
}
}
pub(crate) fn plain(message: impl Into<String>) -> Self {
V2Error {
class: V2ErrorClass::Malformed,
message: message.into(),
explicit: false,
}
}
pub fn classify(mut self, class: V2ErrorClass) -> Self {
if !self.explicit {
self.class = class;
self.explicit = true;
}
self
}
pub(crate) fn is_classified(&self) -> bool {
self.explicit
}
pub fn context(mut self, prefix: impl fmt::Display) -> Self {
self.message = format!("{prefix}: {}", self.message);
self
}
}
impl fmt::Display for V2Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} ({})", self.message, self.class)
}
}
impl std::error::Error for V2Error {}
pub type V2Result<T> = Result<T, V2Error>;
pub(crate) fn err<T>(class: V2ErrorClass, message: impl Into<String>) -> V2Result<T> {
Err(V2Error::new(class, message))
}
pub(crate) fn plain<T>(message: impl Into<String>) -> V2Result<T> {
Err(V2Error::plain(message))
}
pub(crate) trait Classify<T> {
fn classify(self, class: V2ErrorClass) -> V2Result<T>;
}
impl<T> Classify<T> for V2Result<T> {
fn classify(self, class: V2ErrorClass) -> V2Result<T> {
self.map_err(|e| e.classify(class))
}
}
pub fn v2_error_class_of<T>(result: &V2Result<T>) -> Option<V2ErrorClass> {
result.as_ref().err().map(|e| e.class)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum V2SignError {
InvalidObject(V2Error),
IssuerDuty(String),
KeyBinding(String),
InvalidSignerKey(String),
UnsupportedMode,
Provider(String),
Cancelled,
SignatureRejected(V2Error),
}
impl fmt::Display for V2SignError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
V2SignError::InvalidObject(e) => write!(f, "v2 signing refused: {e}"),
V2SignError::IssuerDuty(m) => write!(f, "v2 issuer duty: {m}"),
V2SignError::KeyBinding(m) => write!(f, "v2 signer key binding: {m}"),
V2SignError::InvalidSignerKey(m) => write!(f, "v2 signer key: {m}"),
V2SignError::UnsupportedMode => f.write_str("v2 signer reports an unsupported mode"),
V2SignError::Provider(m) => write!(f, "v2 signer: {m}"),
V2SignError::Cancelled => f.write_str("v2 signing cancelled"),
V2SignError::SignatureRejected(e) => {
write!(f, "v2 signer returned a signature that does not verify: {e}")
}
}
}
}
impl std::error::Error for V2SignError {}
impl V2SignError {
pub fn class(&self) -> V2ErrorClass {
match self {
V2SignError::InvalidObject(e) => e.class,
V2SignError::IssuerDuty(_) => V2ErrorClass::Malformed,
V2SignError::KeyBinding(_) => V2ErrorClass::KeyIdMismatch,
V2SignError::InvalidSignerKey(_) | V2SignError::UnsupportedMode | V2SignError::Provider(_) => {
V2ErrorClass::ConfigurationInvalid
}
V2SignError::Cancelled => V2ErrorClass::EvaluationCancelled,
V2SignError::SignatureRejected(_) => V2ErrorClass::InvalidSignature,
}
}
}
impl From<V2Error> for V2SignError {
fn from(e: V2Error) -> Self {
V2SignError::InvalidObject(e)
}
}
pub type V2SignResult<T> = Result<T, V2SignError>;