a2a_protocol_server/auth/
mtls.rs1use std::future::Future;
9use std::pin::Pin;
10use std::sync::Arc;
11
12use a2a_protocol_types::error::A2aResult;
13
14use super::{auth_rejected, caller_id};
15use crate::call_context::CallContext;
16use crate::interceptor::ServerInterceptor;
17
18const CHALLENGE: &str = "MutualTLS";
22
23type Namer = dyn Fn(&[u8]) -> Option<String> + Send + Sync;
25
26#[derive(Clone)]
53pub struct MutualTlsAuthInterceptor {
54 namer: Option<Arc<Namer>>,
55 forwarded: Option<super::forwarded_cert::ForwardedClientCert>,
56}
57
58impl MutualTlsAuthInterceptor {
59 #[must_use]
61 pub const fn new() -> Self {
62 Self {
63 namer: None,
64 forwarded: None,
65 }
66 }
67
68 #[must_use]
86 pub fn with_names(namer: impl Fn(&[u8]) -> Option<String> + Send + Sync + 'static) -> Self {
87 Self {
88 namer: Some(Arc::new(namer)),
89 forwarded: None,
90 }
91 }
92
93 #[must_use]
98 pub fn with_forwarded(mut self, forwarded: super::forwarded_cert::ForwardedClientCert) -> Self {
99 self.forwarded = Some(forwarded);
100 self
101 }
102
103 fn certificate(&self, ctx: &CallContext) -> Option<Vec<u8>> {
106 ctx.peer_certificate().or_else(|| {
107 self.forwarded
108 .as_ref()
109 .and_then(|forwarded| forwarded.certificate(ctx))
110 })
111 }
112
113 fn name(&self, der: &[u8]) -> Option<String> {
115 self.namer.as_ref().map_or_else(
116 || Some(caller_id::mtls(&caller_id::certificate_fingerprint(der))),
117 |namer| namer(der).map(|name| caller_id::mtls(&name)),
118 )
119 }
120}
121
122impl Default for MutualTlsAuthInterceptor {
123 fn default() -> Self {
124 Self::new()
125 }
126}
127
128impl std::fmt::Debug for MutualTlsAuthInterceptor {
129 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130 f.debug_struct("MutualTlsAuthInterceptor")
131 .field(
132 "names",
133 &if self.namer.is_some() {
134 "custom"
135 } else {
136 "fingerprint"
137 },
138 )
139 .field("forwarded", &self.forwarded.is_some())
140 .finish()
141 }
142}
143
144impl ServerInterceptor for MutualTlsAuthInterceptor {
145 fn before<'a>(
146 &'a self,
147 ctx: &'a CallContext,
148 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
149 Box::pin(async move {
150 let identity = self
151 .certificate(ctx)
152 .and_then(|der| self.name(&der))
153 .ok_or_else(|| auth_rejected(CHALLENGE))?;
154 ctx.set_caller_identity(identity);
155 ctx.set_auth_scheme("mtls");
156 Ok(())
157 })
158 }
159
160 fn after<'a>(
161 &'a self,
162 _ctx: &'a CallContext,
163 ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
164 Box::pin(async move { Ok(()) })
165 }
166
167 fn authenticates(&self) -> bool {
168 true
169 }
170
171 fn checks_scheme(&self, scheme: &a2a_protocol_types::security::SecurityScheme) -> Option<bool> {
173 Some(matches!(
174 scheme,
175 a2a_protocol_types::security::SecurityScheme::MutualTls(_)
176 ))
177 }
178}
179
180#[cfg(test)]
181mod tests {
182 use super::*;
183
184 const DER: &[u8] = b"not really a certificate, but bytes are bytes";
185
186 async fn run(auth: &MutualTlsAuthInterceptor, ctx: &CallContext) -> A2aResult<()> {
187 auth.before(ctx).await
188 }
189
190 #[tokio::test]
191 async fn the_fingerprint_names_the_caller() {
192 let ctx = CallContext::new("SendMessage").with_peer_certificate(DER);
193 run(&MutualTlsAuthInterceptor::new(), &ctx).await.unwrap();
194 let hex = ring::digest::digest(&ring::digest::SHA256, DER)
195 .as_ref()
196 .iter()
197 .fold(String::new(), |mut out, b| {
198 use std::fmt::Write as _;
199 let _ = write!(out, "{b:02x}");
200 out
201 });
202 let expected = format!("mtls:sha256:{hex}");
203 assert_eq!(ctx.caller_identity(), Some(expected.as_str()));
204 assert_eq!(expected.len(), "mtls:sha256:".len() + 64);
205 assert_eq!(ctx.auth_scheme(), Some("mtls"));
206 }
207
208 #[tokio::test]
209 async fn a_call_without_a_certificate_is_refused() {
210 let ctx = CallContext::new("SendMessage");
211 let err = run(&MutualTlsAuthInterceptor::new(), &ctx)
212 .await
213 .unwrap_err();
214 let rejection = err.auth_rejection().expect("an authentication refusal");
215 assert_eq!(rejection.challenge(), Some("MutualTLS"));
216 assert_eq!(ctx.caller_identity(), None);
217 }
218
219 #[tokio::test]
220 async fn a_namer_names_or_refuses() {
221 let auth = MutualTlsAuthInterceptor::with_names(|der| {
222 (der == DER).then(|| "billing-agent".to_owned())
223 });
224 let ctx = CallContext::new("SendMessage").with_peer_certificate(DER);
225 run(&auth, &ctx).await.unwrap();
226 assert_eq!(ctx.caller_identity(), Some("mtls:billing-agent"));
227
228 let ctx = CallContext::new("SendMessage").with_peer_certificate(b"another");
229 assert!(run(&auth, &ctx).await.is_err());
230 assert_eq!(ctx.caller_identity(), None);
231 }
232
233 #[test]
236 fn debug_names_the_naming_and_nothing_else() {
237 assert_eq!(
238 format!("{:?}", MutualTlsAuthInterceptor::new()),
239 r#"MutualTlsAuthInterceptor { names: "fingerprint", forwarded: false }"#
240 );
241 assert_eq!(
242 format!("{:?}", MutualTlsAuthInterceptor::with_names(|_| None)),
243 r#"MutualTlsAuthInterceptor { names: "custom", forwarded: false }"#
244 );
245 }
246
247 #[test]
248 fn it_checks_the_mutual_tls_scheme_only() {
249 use a2a_protocol_types::security::{MutualTlsSecurityScheme, SecurityScheme};
250 let auth = MutualTlsAuthInterceptor::new();
251 let mtls: SecurityScheme =
252 serde_json::from_value(serde_json::json!({"mtlsSecurityScheme": {}})).unwrap();
253 assert!(matches!(
254 mtls,
255 SecurityScheme::MutualTls(MutualTlsSecurityScheme { .. })
256 ));
257 assert_eq!(auth.checks_scheme(&mtls), Some(true));
258 let key: SecurityScheme = serde_json::from_value(
259 serde_json::json!({"apiKeySecurityScheme": {"location": "header", "name": "k"}}),
260 )
261 .unwrap();
262 assert_eq!(auth.checks_scheme(&key), Some(false));
263 assert!(auth.authenticates());
264 }
265}