Skip to main content

micromegas/servers/
firehose_common.rs

1//! Shared Kinesis Data Firehose HTTP Endpoint Delivery plumbing, reused by every
2//! Firehose-backed ingestion route (metrics, CloudWatch Logs, and any future signal).
3//!
4//! Everything here is signal-agnostic — it only knows about the Firehose transport
5//! (access-key header, ack shape), not what's inside a record. Firehose's only credential
6//! channel is the non-standard `X-Amz-Firehose-Access-Key` header — it cannot send
7//! `Authorization: Bearer`. So a Firehose route cannot sit under the global Bearer
8//! `auth_middleware`; it has its own auth step that synthesizes a bearer header from the
9//! Firehose header and reuses the same `AuthProvider` (constant-time keyring check)
10//! verbatim.
11
12use axum::body::Body;
13use axum::extract::Request;
14use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
15use axum::middleware::Next;
16use axum::response::Response;
17use chrono::Utc;
18use micromegas_auth::client_ip::resolve_client_ip;
19use micromegas_auth::log_sanitize::warn_auth_rejection;
20use micromegas_auth::types::{AuthProvider, HttpRequestParts, ProviderUnavailable, RequestParts};
21use micromegas_tracing::prelude::*;
22use std::sync::Arc;
23
24pub(crate) const HEADER_ACCESS_KEY: &str = "X-Amz-Firehose-Access-Key";
25pub(crate) const HEADER_REQUEST_ID: &str = "X-Amz-Firehose-Request-Id";
26
27/// Ack/error response body per the Firehose HTTP Endpoint Delivery contract:
28/// `{requestId, timestamp}` on success, `{requestId, timestamp, errorMessage}` on failure.
29#[derive(serde::Serialize)]
30struct FirehoseResponseBody<'a> {
31    #[serde(rename = "requestId")]
32    request_id: &'a str,
33    timestamp: i64,
34    #[serde(rename = "errorMessage", skip_serializing_if = "Option::is_none")]
35    error_message: Option<&'a str>,
36}
37
38pub(crate) fn firehose_response(
39    status: StatusCode,
40    request_id: &str,
41    error_message: Option<&str>,
42) -> Response {
43    let body = FirehoseResponseBody {
44        request_id,
45        timestamp: Utc::now().timestamp_millis(),
46        error_message,
47    };
48    Response::builder()
49        .status(status)
50        .header(
51            header::CONTENT_TYPE,
52            HeaderValue::from_static("application/json"),
53        )
54        .body(Body::from(
55            serde_json::to_vec(&body).expect("serializing firehose response"),
56        ))
57        .expect("building firehose response")
58}
59
60pub(crate) fn request_id_from(headers: &HeaderMap) -> String {
61    headers
62        .get(HEADER_REQUEST_ID)
63        .and_then(|v| v.to_str().ok())
64        .unwrap_or("")
65        .to_string()
66}
67
68/// Firehose-specific auth: read `X-Amz-Firehose-Access-Key`, synthesize an
69/// `Authorization: Bearer <key>` header, and validate via the same `AuthProvider` the rest
70/// of the ingestion service uses (reuses the constant-time keyring check verbatim). On
71/// failure, return the Firehose error shape (non-200 JSON) so Firehose retries/spills
72/// rather than dropping data.
73pub async fn firehose_auth_middleware(
74    provider: Arc<dyn AuthProvider>,
75    mut req: Request,
76    next: Next,
77) -> Response {
78    let request_id = request_id_from(req.headers());
79    let Some(access_key) = req
80        .headers()
81        .get(HEADER_ACCESS_KEY)
82        .and_then(|v| v.to_str().ok())
83    else {
84        return firehose_response(
85            StatusCode::UNAUTHORIZED,
86            &request_id,
87            Some("missing X-Amz-Firehose-Access-Key"),
88        );
89    };
90    let client_ip = resolve_client_ip(req.headers(), req.extensions());
91    let mut headers = req.headers().clone();
92    if let Ok(bearer) = HeaderValue::from_str(&format!("Bearer {access_key}")) {
93        headers.insert(header::AUTHORIZATION, bearer);
94    }
95    let parts = HttpRequestParts {
96        headers,
97        method: req.method().clone(),
98        uri: req.uri().clone(),
99        client_ip,
100    };
101    match provider.validate_request(&parts as &dyn RequestParts).await {
102        Ok(ctx) => {
103            // SECURITY: strip any client-provided auth headers to prevent spoofing, matching
104            // the shared `auth_middleware` (auth/src/axum.rs). These headers must only ever be
105            // trusted when set by the authentication layer, never by the incoming request.
106            req.headers_mut().remove("x-auth-subject");
107            req.headers_mut().remove("x-auth-email");
108            req.headers_mut().remove("x-auth-issuer");
109            req.headers_mut().remove("x-allow-delegation");
110            req.headers_mut().remove("x-auth-is-admin");
111            // Insert the validated `AuthContext` into the request extensions, mirroring
112            // `auth_middleware`'s success path, so downstream handlers can resolve a write
113            // audience from it.
114            req.extensions_mut().insert(ctx);
115            next.run(req).await
116        }
117        Err(e) => {
118            // A DB-backed `ingestion_api_keys` outage must not look like a
119            // rejected Firehose access key: both Firehose routers validate
120            // through the same `MultiAuthProvider` chain as every other
121            // ingestion route, so an outage here gets the same 503 treatment
122            // `micromegas_auth::axum::auth_middleware` gives the plain routes.
123            if e.downcast_ref::<ProviderUnavailable>().is_some() {
124                debug!("[firehose auth_failure] {e}");
125                firehose_response(
126                    StatusCode::SERVICE_UNAVAILABLE,
127                    &request_id,
128                    Some("auth provider unavailable"),
129                )
130            } else {
131                warn_auth_rejection("[firehose auth_failure]", &parts, &e);
132                firehose_response(
133                    StatusCode::UNAUTHORIZED,
134                    &request_id,
135                    Some("invalid access key"),
136                )
137            }
138        }
139    }
140}