Skip to main content

micromegas_auth/
tower.rs

1//! Tower service layer for async authentication with tonic/gRPC.
2//!
3//! This module provides a tower service wrapper that integrates authentication
4//! into tonic gRPC services. It extracts request parts from gRPC metadata,
5//! validates them using an AuthProvider, and injects the AuthContext into request extensions.
6
7use crate::client_ip::resolve_client_ip;
8use crate::log_sanitize::warn_auth_rejection;
9use crate::types::{AuthProvider, GrpcRequestParts, ProviderUnavailable, RequestParts};
10use futures::future::BoxFuture;
11use micromegas_tracing::prelude::*;
12use std::sync::Arc;
13use tonic::Status;
14use tower::Service;
15
16/// Async authentication service wrapper for tonic/gRPC.
17///
18/// This service wraps another tower service and adds authentication:
19/// 1. Extracts request parts from gRPC metadata
20/// 2. Validates request using the configured AuthProvider
21/// 3. Injects AuthContext into request extensions
22/// 4. Logs authentication success/failure
23///
24/// If no auth_provider is configured, requests pass through without authentication.
25///
26/// # Example
27///
28/// ```rust,no_run
29/// use micromegas_auth::api_key::{ApiKeyAuthProvider, parse_key_ring};
30/// use micromegas_auth::tower::AuthService;
31/// use std::sync::Arc;
32///
33/// # async fn example<S>(inner_service: S) -> anyhow::Result<()>
34/// # where
35/// #     S: tower::Service<http::Request<tonic::body::Body>> + Clone + Send + 'static,
36/// #     S::Response: 'static,
37/// #     S::Future: Send + 'static,
38/// #     S::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
39/// # {
40/// // Create auth provider
41/// let keyring = parse_key_ring(r#"[{"name": "test", "key": "secret"}]"#)?;
42/// let auth_provider = Arc::new(ApiKeyAuthProvider::new(keyring));
43///
44/// // Wrap your service with authentication
45/// let auth_service = AuthService {
46///     inner: inner_service,
47///     auth_provider: Some(auth_provider as Arc<dyn micromegas_auth::types::AuthProvider>),
48/// };
49/// # Ok(())
50/// # }
51/// ```
52#[derive(Clone)]
53pub struct AuthService<S> {
54    /// The inner service to wrap
55    pub inner: S,
56    /// Optional authentication provider (None = no auth required)
57    pub auth_provider: Option<Arc<dyn AuthProvider>>,
58}
59
60impl<S> Service<http::Request<tonic::body::Body>> for AuthService<S>
61where
62    S: Service<http::Request<tonic::body::Body>> + Clone + Send + 'static,
63    S::Response: 'static,
64    S::Future: Send + 'static,
65    S::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
66{
67    type Response = S::Response;
68    type Error = Box<dyn std::error::Error + Send + Sync>;
69    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
70
71    fn poll_ready(
72        &mut self,
73        cx: &mut std::task::Context<'_>,
74    ) -> std::task::Poll<Result<(), Self::Error>> {
75        self.inner.poll_ready(cx).map_err(Into::into)
76    }
77
78    fn call(&mut self, req: http::Request<tonic::body::Body>) -> Self::Future {
79        let clone = self.inner.clone();
80        let mut inner = std::mem::replace(&mut self.inner, clone);
81        let auth_provider = self.auth_provider.clone();
82
83        Box::pin(async move {
84            if let Some(provider) = auth_provider {
85                let (mut parts, body) = req.into_parts();
86
87                // Resolved right after `req.into_parts()`, before headers are cloned into
88                // `GrpcRequestParts` -- for gRPC, the `SocketAddr` extension is already present
89                // on `parts.extensions` by the time `AuthService::call` runs
90                // (`ConnectedIncoming`/`ConnectedStream` attach it at TCP-accept time, below
91                // every custom tower layer).
92                let client_ip = resolve_client_ip(&parts.headers, &parts.extensions);
93
94                // Extract request parts for validation
95                let request_parts = GrpcRequestParts {
96                    metadata: tonic::metadata::MetadataMap::from_headers(parts.headers.clone()),
97                    client_ip,
98                };
99
100                // Validate request
101                match provider
102                    .validate_request(&request_parts as &dyn RequestParts)
103                    .await
104                {
105                    Ok(auth_ctx) => {
106                        info!(
107                            "authenticated: subject={} email={:?} issuer={} audience={:?} admin={}",
108                            auth_ctx.subject,
109                            auth_ctx.email,
110                            auth_ctx.issuer,
111                            auth_ctx.audience,
112                            auth_ctx.is_admin()
113                        );
114
115                        // SECURITY: Remove any client-provided auth headers to prevent spoofing
116                        // These headers are only set by the authentication layer
117                        parts.headers.remove("x-auth-subject");
118                        parts.headers.remove("x-auth-email");
119                        parts.headers.remove("x-auth-issuer");
120                        parts.headers.remove("x-allow-delegation");
121                        parts.headers.remove("x-auth-is-admin");
122
123                        // Inject auth context into gRPC metadata headers
124                        parts.headers.insert(
125                            "x-auth-subject",
126                            http::HeaderValue::from_str(&auth_ctx.subject)
127                                .expect("valid user id header"),
128                        );
129                        if let Some(email) = &auth_ctx.email {
130                            parts.headers.insert(
131                                "x-auth-email",
132                                http::HeaderValue::from_str(email).expect("valid email header"),
133                            );
134                        }
135                        parts.headers.insert(
136                            "x-auth-issuer",
137                            http::HeaderValue::from_str(&auth_ctx.issuer)
138                                .expect("valid issuer header"),
139                        );
140                        parts.headers.insert(
141                            "x-allow-delegation",
142                            http::HeaderValue::from_str(&auth_ctx.allow_delegation.to_string())
143                                .expect("valid allow_delegation header"),
144                        );
145                        parts.headers.insert(
146                            "x-auth-is-admin",
147                            http::HeaderValue::from_str(&auth_ctx.is_admin().to_string())
148                                .expect("valid is_admin header"),
149                        );
150
151                        parts.extensions.insert(auth_ctx);
152                        let req = http::Request::from_parts(parts, body);
153                        inner.call(req).await.map_err(Into::into)
154                    }
155                    Err(e) => {
156                        let status = if e.downcast_ref::<ProviderUnavailable>().is_some() {
157                            debug!("authentication failed: {e}");
158                            Status::unavailable("auth provider unavailable")
159                        } else {
160                            warn_auth_rejection("authentication failed:", &request_parts, &e);
161                            Status::unauthenticated("invalid token")
162                        };
163                        Err(Box::new(status) as Box<dyn std::error::Error + Send + Sync>)
164                    }
165                }
166            } else {
167                inner.call(req).await.map_err(Into::into)
168            }
169        })
170    }
171}