Skip to main content

turul_a2a/middleware/
traits.rs

1//! A2aMiddleware trait and SecurityContribution.
2
3use async_trait::async_trait;
4
5use super::context::RequestContext;
6use super::error::MiddlewareError;
7
8/// Trait implemented by request-scoped middleware that participates in
9/// the framework's auth / authorisation / credential-forwarding plane.
10///
11/// Runs at the Tower layer before any handler or JSON-RPC dispatch.
12/// Typical implementations:
13/// - Authentication (e.g. `BearerMiddleware`, `ApiKeyMiddleware` in `turul-a2a-auth`)
14/// - Trusted-header authorisation (e.g. `LambdaAuthorizerMiddleware` in `turul-a2a-aws-lambda`)
15/// - Inbound credential forwarding (e.g. stashing an upstream API key or Bearer token
16///   onto `ctx.identity.claims` for downstream MCP / A2A calls to consume)
17///
18/// Non-auth interception (metrics, rate-limiting, tracing) should be a
19/// separate Tower layer composed outside this trait — implementations
20/// here only get a `before_request` callback and the failure surface is
21/// shaped for auth errors (401/403 + `WWW-Authenticate`).
22#[async_trait]
23pub trait A2aMiddleware: Send + Sync {
24    /// Validate the request and populate identity on the context.
25    async fn before_request(&self, ctx: &mut RequestContext) -> Result<(), MiddlewareError>;
26
27    /// Security contribution for AgentCard auto-population.
28    fn security_contribution(&self) -> SecurityContribution {
29        SecurityContribution::default()
30    }
31}
32
33/// What a middleware contributes to AgentCard security metadata.
34///
35/// Contains both scheme definitions and requirement groups.
36/// Multiple `SecurityRequirement` entries = OR (alternatives).
37/// Multiple schemes in one `SecurityRequirement` = AND (all required).
38#[derive(Debug, Clone, Default)]
39pub struct SecurityContribution {
40    pub schemes: Vec<(String, turul_a2a_proto::SecurityScheme)>,
41    pub requirements: Vec<turul_a2a_proto::SecurityRequirement>,
42}
43
44impl SecurityContribution {
45    pub fn new() -> Self {
46        Self::default()
47    }
48
49    /// Add a scheme with required scopes and a corresponding requirement.
50    pub fn with_scheme(
51        mut self,
52        name: impl Into<String>,
53        scheme: turul_a2a_proto::SecurityScheme,
54        scopes: Vec<String>,
55    ) -> Self {
56        let name = name.into();
57        self.schemes.push((name.clone(), scheme));
58        let mut req_schemes = std::collections::HashMap::new();
59        req_schemes.insert(name, turul_a2a_proto::StringList { list: scopes });
60        self.requirements
61            .push(turul_a2a_proto::SecurityRequirement {
62                schemes: req_schemes,
63            });
64        self
65    }
66
67    pub fn is_empty(&self) -> bool {
68        self.schemes.is_empty() && self.requirements.is_empty()
69    }
70}