Skip to main content

adk_auth/web_bot_auth/
error.rs

1//! Errors from Web Bot Auth signing and verification. Spec 3.5 §7.3.
2
3use adk_core::{AdkError, ErrorCategory, ErrorComponent};
4
5/// Why a Web Bot Auth signature could not be produced or verified.
6///
7/// [`is_unverified`](Self::is_unverified) separates the draft's two failure outcomes
8/// (draft-ietf-webbotauth-httpsig-protocol-00 Appendix C.1): an *invalid* signature failed a
9/// check, while an *unverified* one could not be checked because its key material was not
10/// available. Neither grants an identity. Spec 3.5 §7.3, A-I6.
11///
12/// # Example
13///
14/// ```rust
15/// use adk_auth::web_bot_auth::WebBotAuthError;
16///
17/// let err = WebBotAuthError::UnknownKey { origin: "https://bot.example".into(), keyid: "k1".into() };
18/// assert!(err.is_unverified());
19/// let adk: adk_core::AdkError = err.into();
20/// assert!(adk.is_unauthorized());
21/// ```
22#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
23#[non_exhaustive]
24pub enum WebBotAuthError {
25    /// A `Signature`, `Signature-Input` or `Signature-Agent` field is not a valid structured field.
26    #[error(
27        "malformed `{field}` field: {reason}; send it as an RFC 8941 Dictionary as RFC 9421 §4 and the Web Bot Auth draft define"
28    )]
29    MalformedField {
30        /// The field name.
31        field: String,
32        /// What is wrong with it.
33        reason: String,
34    },
35    /// A signature parameter is missing, has the wrong type, or contradicts another.
36    #[error(
37        "signature `{label}` has an invalid `{parameter}` parameter: {reason}; Web Bot Auth signatures carry created, expires, keyid and tag=\"web-bot-auth\""
38    )]
39    InvalidParameter {
40        /// The signature label.
41        label: String,
42        /// The parameter name.
43        parameter: String,
44        /// What is wrong with it.
45        reason: String,
46    },
47    /// The signature does not cover a component the verifier requires.
48    #[error(
49        "signature `{label}` does not cover `{component}`; sign it, as the Web Bot Auth draft §5.2 and the verifier's policy require"
50    )]
51    MissingComponent {
52        /// The signature label.
53        label: String,
54        /// The required component.
55        component: String,
56    },
57    /// The signature names an algorithm other than Ed25519.
58    #[error("signature `{label}` uses algorithm `{alg}`; only alg=\"ed25519\" is accepted")]
59    UnsupportedAlgorithm {
60        /// The signature label.
61        label: String,
62        /// The algorithm it names.
63        alg: String,
64    },
65    /// The signature's `created` time is in the future beyond the allowed clock skew.
66    #[error(
67        "signature `{label}` was created at {created}, after the verifier's time {now} plus the allowed skew; check the signer's clock"
68    )]
69    NotYetValid {
70        /// The signature label.
71        label: String,
72        /// The `created` parameter.
73        created: i64,
74        /// The verifier's time.
75        now: i64,
76    },
77    /// The signature's `expires` time has passed beyond the allowed clock skew.
78    #[error("signature `{label}` expired at {expires} (now {now}); sign each request afresh")]
79    Expired {
80        /// The signature label.
81        label: String,
82        /// The `expires` parameter.
83        expires: i64,
84        /// The verifier's time.
85        now: i64,
86    },
87    /// The signature is valid for longer than the verifier accepts.
88    #[error(
89        "signature `{label}` is valid for {lifetime_secs} s, more than the {max_secs} s the verifier accepts; use a shorter expiry"
90    )]
91    LifetimeTooLong {
92        /// The signature label.
93        label: String,
94        /// `expires - created`.
95        lifetime_secs: i64,
96        /// The verifier's limit.
97        max_secs: u64,
98    },
99    /// The `Signature-Agent` member the signature covers is missing or is not an origin.
100    #[error(
101        "signature `{label}` has an unusable Signature-Agent: {reason}; send an https origin such as \"https://bot.example\""
102    )]
103    InvalidSignatureAgent {
104        /// The signature label.
105        label: String,
106        /// What is wrong with it.
107        reason: String,
108    },
109    /// The `Signature-Agent` member names a discovery type the verifier does not support.
110    #[error(
111        "signature `{label}` uses Signature-Agent discovery type `{kind}`; only the `directory` type is supported"
112    )]
113    UnsupportedDiscovery {
114        /// The signature label.
115        label: String,
116        /// The discovery type.
117        kind: String,
118    },
119    /// The signature base cannot be built from the message (RFC 9421 §2.5).
120    #[error("cannot build the signature base: {reason}")]
121    SignatureBase {
122        /// What is missing or malformed.
123        reason: String,
124    },
125    /// The signature does not verify against the key.
126    #[error(
127        "signature `{label}` does not verify against its key; the message changed or the key is wrong"
128    )]
129    BadSignature {
130        /// The signature label.
131        label: String,
132    },
133    /// The key directory does not contain the key the signature names.
134    #[error(
135        "the key directory at {origin} has no Ed25519 key with thumbprint `{keyid}`; publish the key before signing with it"
136    )]
137    UnknownKey {
138        /// The directory origin.
139        origin: String,
140        /// The `keyid` parameter.
141        keyid: String,
142    },
143    /// The key exists but its `nbf`/`exp` window does not include the current time.
144    #[error("key `{keyid}` at {origin} is outside its validity window")]
145    KeyNotCurrent {
146        /// The directory origin.
147        origin: String,
148        /// The key thumbprint.
149        keyid: String,
150    },
151    /// The key is a published test key (draft §6.8).
152    #[error(
153        "key `{keyid}` is the RFC 9421 test key, which verifiers reject in production; generate a key of your own"
154    )]
155    TestKey {
156        /// The key thumbprint.
157        keyid: String,
158    },
159    /// The key directory could not be fetched.
160    #[error("the key directory at {origin} is unavailable: {reason}")]
161    DirectoryUnavailable {
162        /// The directory origin.
163        origin: String,
164        /// Why the fetch failed.
165        reason: String,
166    },
167    /// The key directory was fetched but is not a valid directory.
168    #[error(
169        "the key directory at {origin} is malformed: {reason}; serve a JWKS as application/http-message-signatures-directory+json"
170    )]
171    MalformedDirectory {
172        /// The directory origin.
173        origin: String,
174        /// What is wrong with it.
175        reason: String,
176    },
177    /// The directory fetch would reach a non-public address or use a refused scheme.
178    #[error("refused to fetch the key directory at {origin}: {reason}")]
179    EgressRefused {
180        /// The directory origin.
181        origin: String,
182        /// Why the fetch was refused.
183        reason: String,
184    },
185    /// Key material is malformed.
186    #[error("invalid key material: {reason}")]
187    InvalidKey {
188        /// What is wrong with it.
189        reason: String,
190    },
191    /// A signer, verifier or source was configured with invalid values.
192    #[error("invalid Web Bot Auth configuration: {reason}")]
193    InvalidConfig {
194        /// What is wrong with it.
195        reason: String,
196    },
197}
198
199impl WebBotAuthError {
200    /// Whether the signature could not be checked rather than failed a check: its key material
201    /// was unavailable, so the request is *unverified* (draft Appendix C.1, §6.10).
202    pub fn is_unverified(&self) -> bool {
203        match self {
204            Self::UnknownKey { .. }
205            | Self::UnsupportedDiscovery { .. }
206            | Self::DirectoryUnavailable { .. }
207            | Self::MalformedDirectory { .. }
208            | Self::EgressRefused { .. } => true,
209            Self::MalformedField { .. }
210            | Self::InvalidParameter { .. }
211            | Self::MissingComponent { .. }
212            | Self::UnsupportedAlgorithm { .. }
213            | Self::NotYetValid { .. }
214            | Self::Expired { .. }
215            | Self::LifetimeTooLong { .. }
216            | Self::InvalidSignatureAgent { .. }
217            | Self::SignatureBase { .. }
218            | Self::BadSignature { .. }
219            | Self::KeyNotCurrent { .. }
220            | Self::TestKey { .. }
221            | Self::InvalidKey { .. }
222            | Self::InvalidConfig { .. } => false,
223        }
224    }
225
226    fn category_and_code(&self) -> (ErrorCategory, &'static str) {
227        match self {
228            Self::MalformedField { .. } => {
229                (ErrorCategory::InvalidInput, "auth.web_bot_auth.malformed_field")
230            }
231            Self::InvalidParameter { .. } => {
232                (ErrorCategory::Unauthorized, "auth.web_bot_auth.invalid_parameter")
233            }
234            Self::MissingComponent { .. } => {
235                (ErrorCategory::Unauthorized, "auth.web_bot_auth.missing_component")
236            }
237            Self::UnsupportedAlgorithm { .. } => {
238                (ErrorCategory::Unauthorized, "auth.web_bot_auth.unsupported_algorithm")
239            }
240            Self::NotYetValid { .. } => {
241                (ErrorCategory::Unauthorized, "auth.web_bot_auth.not_yet_valid")
242            }
243            Self::Expired { .. } => (ErrorCategory::Unauthorized, "auth.web_bot_auth.expired"),
244            Self::LifetimeTooLong { .. } => {
245                (ErrorCategory::Unauthorized, "auth.web_bot_auth.lifetime_too_long")
246            }
247            Self::InvalidSignatureAgent { .. } => {
248                (ErrorCategory::Unauthorized, "auth.web_bot_auth.invalid_signature_agent")
249            }
250            Self::UnsupportedDiscovery { .. } => {
251                (ErrorCategory::Unauthorized, "auth.web_bot_auth.unsupported_discovery")
252            }
253            Self::SignatureBase { .. } => {
254                (ErrorCategory::Unauthorized, "auth.web_bot_auth.signature_base")
255            }
256            Self::BadSignature { .. } => {
257                (ErrorCategory::Unauthorized, "auth.web_bot_auth.bad_signature")
258            }
259            Self::UnknownKey { .. } => {
260                (ErrorCategory::Unauthorized, "auth.web_bot_auth.unknown_key")
261            }
262            Self::KeyNotCurrent { .. } => {
263                (ErrorCategory::Unauthorized, "auth.web_bot_auth.key_not_current")
264            }
265            Self::TestKey { .. } => (ErrorCategory::Unauthorized, "auth.web_bot_auth.test_key"),
266            Self::DirectoryUnavailable { .. } => {
267                (ErrorCategory::Unavailable, "auth.web_bot_auth.directory_unavailable")
268            }
269            Self::MalformedDirectory { .. } => {
270                (ErrorCategory::Unauthorized, "auth.web_bot_auth.malformed_directory")
271            }
272            Self::EgressRefused { .. } => {
273                (ErrorCategory::Forbidden, "auth.web_bot_auth.egress_refused")
274            }
275            Self::InvalidKey { .. } => {
276                (ErrorCategory::InvalidInput, "auth.web_bot_auth.invalid_key")
277            }
278            Self::InvalidConfig { .. } => {
279                (ErrorCategory::InvalidInput, "auth.web_bot_auth.invalid_config")
280            }
281        }
282    }
283}
284
285impl From<WebBotAuthError> for AdkError {
286    fn from(err: WebBotAuthError) -> Self {
287        let (category, code) = err.category_and_code();
288        AdkError::new(ErrorComponent::Auth, category, code, err.to_string()).with_source(err)
289    }
290}