Skip to main content

a2a_protocol_types/
auth_rejection.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! Why a request was refused on authentication or authorization grounds.
5//!
6//! A2A defines no error code for either (spec §3.3.2 gives HTTP `401`/`403`,
7//! gRPC `UNAUTHENTICATED`/`PERMISSION_DENIED` and "a JSON-RPC custom error" as
8//! examples), so an [`A2aError`](crate::error::A2aError) that refuses a
9//! credential keeps the code it would otherwise carry and records the refusal
10//! here. Each binding reads it to answer with its own status: that is what
11//! lets a client tell "your credential was refused" from "your request was
12//! malformed", and so refresh a token instead of giving up. An OAuth client
13//! discards a cached token on `401`, and on nothing else.
14//!
15//! It is not part of the error's wire form: the binding's status says it.
16
17/// Which of the two refusals spec §3.3.2 distinguishes.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19#[non_exhaustive]
20pub enum AuthRejectionKind {
21    /// No usable credential: absent, malformed, expired or unknown. HTTP
22    /// `401`, gRPC `UNAUTHENTICATED`.
23    Unauthenticated,
24    /// A valid credential that does not permit this operation. HTTP `403`,
25    /// gRPC `PERMISSION_DENIED`.
26    PermissionDenied,
27}
28
29/// A refused credential, as carried by
30/// [`A2aError::auth_rejection`](crate::error::A2aError::auth_rejection).
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct AuthRejection {
33    kind: AuthRejectionKind,
34    challenge: Option<String>,
35}
36
37impl AuthRejection {
38    pub(crate) const fn unauthenticated(challenge: String) -> Self {
39        Self {
40            kind: AuthRejectionKind::Unauthenticated,
41            challenge: Some(challenge),
42        }
43    }
44
45    pub(crate) const fn permission_denied() -> Self {
46        Self {
47            kind: AuthRejectionKind::PermissionDenied,
48            challenge: None,
49        }
50    }
51
52    /// A refusal for a missing scope: `403` with the RFC 6750 §3 challenge
53    /// naming the scopes, `Bearer error="insufficient_scope", scope="a b"`.
54    /// A scope that is not an RFC 6749 §3.3 `scope-token` (printable ASCII
55    /// but space, `"` and `\`) cannot be quoted, and is left out.
56    pub(crate) fn insufficient_scope<S: AsRef<str>>(scopes: impl IntoIterator<Item = S>) -> Self {
57        let scopes: Vec<String> = scopes
58            .into_iter()
59            .map(|s| s.as_ref().to_owned())
60            .filter(|s| {
61                // scope-token = 1*( %x21 / %x23-5B / %x5D-7E )
62                !s.is_empty()
63                    && s.bytes()
64                        .all(|b| matches!(b, 0x21 | 0x23..=0x5b | 0x5d..=0x7e))
65            })
66            .collect();
67        let challenge = if scopes.is_empty() {
68            "Bearer error=\"insufficient_scope\"".to_owned()
69        } else {
70            format!(
71                "Bearer error=\"insufficient_scope\", scope=\"{}\"",
72                scopes.join(" ")
73            )
74        };
75        Self {
76            kind: AuthRejectionKind::PermissionDenied,
77            challenge: Some(challenge),
78        }
79    }
80
81    /// Which refusal this is.
82    #[must_use]
83    pub const fn kind(&self) -> AuthRejectionKind {
84        self.kind
85    }
86
87    /// The `WWW-Authenticate` challenge an HTTP binding sends with its `401`
88    /// (RFC 9110 §15.5.2 requires one; §11.6.1 defines it), e.g.
89    /// `Bearer realm="a2a"`, or with a `403` for a missing scope (RFC 6750
90    /// §3), `Bearer error="insufficient_scope", scope="tasks:write"`.
91    /// `None` for any other [`AuthRejectionKind::PermissionDenied`].
92    #[must_use]
93    pub fn challenge(&self) -> Option<&str> {
94        self.challenge.as_deref()
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::AuthRejectionKind;
101    use crate::error::{A2aError, ErrorCode};
102
103    #[test]
104    fn unauthenticated_carries_its_challenge_and_keeps_the_json_rpc_code() {
105        let err = A2aError::unauthenticated("authentication required", "Bearer realm=\"a2a\"");
106        assert_eq!(err.code, ErrorCode::InvalidRequest);
107        let rejection = err.auth_rejection().expect("a rejection");
108        assert_eq!(rejection.kind(), AuthRejectionKind::Unauthenticated);
109        assert_eq!(rejection.challenge(), Some("Bearer realm=\"a2a\""));
110    }
111
112    #[test]
113    fn permission_denied_has_no_challenge() {
114        let err = A2aError::permission_denied("not permitted");
115        let rejection = err.auth_rejection().expect("a rejection");
116        assert_eq!(rejection.kind(), AuthRejectionKind::PermissionDenied);
117        assert_eq!(rejection.challenge(), None);
118    }
119
120    /// Spec §3.3.2: the refusal names the missing scope, in the RFC 6750 §3
121    /// challenge, and leaves out what it cannot quote.
122    #[test]
123    fn insufficient_scope_names_the_scopes_in_its_challenge() {
124        let err = A2aError::insufficient_scope("insufficient scope", ["tasks:read", "tasks:write"]);
125        assert_eq!(err.code, ErrorCode::InvalidRequest);
126        let rejection = err.auth_rejection().expect("a rejection");
127        assert_eq!(rejection.kind(), AuthRejectionKind::PermissionDenied);
128        assert_eq!(
129            rejection.challenge(),
130            Some("Bearer error=\"insufficient_scope\", scope=\"tasks:read tasks:write\"")
131        );
132        let unquotable = ["", "a b", "a\"b", "a\\b", "caf\u{e9}", "!#[]~"];
133        let err = A2aError::insufficient_scope("insufficient scope", unquotable);
134        assert_eq!(
135            err.auth_rejection().and_then(|r| r.challenge()),
136            Some("Bearer error=\"insufficient_scope\", scope=\"!#[]~\""),
137            "only the RFC 6749 scope-token survives"
138        );
139        let none: [&str; 0] = [];
140        assert_eq!(
141            A2aError::insufficient_scope("m", none)
142                .auth_rejection()
143                .and_then(|r| r.challenge()),
144            Some("Bearer error=\"insufficient_scope\"")
145        );
146    }
147
148    #[test]
149    fn an_ordinary_error_is_no_rejection() {
150        assert!(
151            A2aError::new(ErrorCode::InvalidRequest, "bad")
152                .auth_rejection()
153                .is_none()
154        );
155    }
156
157    /// The rejection is the binding's to express: the error's JSON is what it
158    /// was before, and nothing on the wire can claim one.
159    #[test]
160    fn the_rejection_is_not_serialized_or_deserialized() {
161        let err = A2aError::unauthenticated("authentication required", "Bearer");
162        let json = serde_json::to_value(&err).expect("serializes");
163        assert_eq!(
164            json,
165            serde_json::json!({"code": -32600, "message": "authentication required"})
166        );
167        let back: A2aError = serde_json::from_value(json).expect("deserializes");
168        assert!(back.auth_rejection().is_none());
169    }
170
171    /// Every `A2aResult` carries an `A2aError`, so its size is paid on every
172    /// call. clippy's `result_large_err` flags one over 128 bytes, and
173    /// `serde_json`'s `preserve_order` feature, which any crate in a build can
174    /// turn on, grows `data` from 32 bytes to 72. clippy flags 128 and over,
175    /// and the rejection is boxed to stay under it either way; this holds
176    /// whichever way `serde_json` was built.
177    #[test]
178    fn a2a_error_stays_small() {
179        assert!(
180            std::mem::size_of::<A2aError>() < 128,
181            "A2aError is {} bytes",
182            std::mem::size_of::<A2aError>()
183        );
184    }
185}