Skip to main content

micromegas/servers/
ingestion_auth.rs

1//! Authentication layer for the ingestion routes.
2//!
3//! Wraps [`micromegas_auth::axum::authenticate_quiet`] so a rejected `insert_process` request, the
4//! first call any client makes, or an OTLP export, is logged as one line carrying both the
5//! rejection reason and the identity its body claims. The 401 response is identical to the one
6//! `auth_middleware` returns.
7
8use super::otlp::{OTLP_PATHS, content_type_encoding};
9use axum::body::{Body, to_bytes};
10use axum::extract::Request;
11use axum::middleware::Next;
12use axum::response::Response;
13use futures::StreamExt;
14use micromegas_auth::axum::{
15    AuthError, AuthRejection, QuietAuthError, authenticate, authenticate_quiet,
16};
17use micromegas_auth::log_sanitize::{RejectionFields, sanitize_for_log};
18use micromegas_auth::types::AuthProvider;
19use micromegas_otel_ingestion::rejected::claimed_resource_from_prefix;
20use micromegas_tracing::dispatch;
21use micromegas_tracing::logs::{FILTER_LEVEL_UNSET_VALUE, LogMetadata, LogMsgForm};
22use micromegas_tracing::prelude::*;
23use micromegas_tracing::property_set::PropertySet;
24use moka::sync::Cache;
25use serde::Deserialize;
26use std::collections::HashMap;
27use std::io::Read;
28use std::net::IpAddr;
29use std::sync::Arc;
30use std::sync::atomic::AtomicU32;
31use std::time::Duration;
32use tokio::sync::Semaphore;
33
34pub(crate) const INSERT_PROCESS_PATH: &str = "/ingestion/insert_process";
35
36/// Caps every body read done for inspection: the `insert_process` body (a real `ProcessInfo` is
37/// a few KiB) and the OTLP body prefix, both as sent and after decompression.
38const MAX_INSPECTED_BODY_BYTES: usize = 64 * 1024;
39const BODY_READ_TIMEOUT: Duration = Duration::from_secs(2);
40const CBOR_RECURSION_LIMIT: usize = 16;
41const MAX_CLAIM_CHARS: usize = 128;
42const MAX_HEADER_CHARS: usize = 64;
43/// Bounds the CPU and memory an unauthenticated caller can make us spend on inspection.
44const DEFAULT_MAX_CONCURRENT_INSPECTIONS: usize = 8;
45
46/// Caller-claimed process identity. Separate from `ProcessInfo` because its strict UUID and
47/// timestamp deserializers would reject a malformed id outright and lose every other field.
48#[derive(Deserialize, Default)]
49#[serde(default)]
50struct ClaimedProcessInfo {
51    process_id: Option<String>,
52    exe: Option<String>,
53    username: Option<String>,
54    computer: Option<String>,
55    parent_process_id: Option<String>,
56    start_time: Option<String>,
57    properties: HashMap<String, String>,
58}
59
60/// Build-identity properties worth logging, with their log property names. `command-line` and
61/// `exe_args` are left out because they can carry secrets passed on the command line.
62const LOGGED_PROPERTIES: [(&str, &str); 7] = [
63    ("platform-name", "claimed_platform_name"),
64    ("build-version", "claimed_build_version"),
65    ("engine-version", "claimed_engine_version"),
66    ("build-config", "claimed_build_config"),
67    ("build-target", "claimed_build_target"),
68    ("branch-name", "claimed_branch_name"),
69    ("commit", "claimed_commit"),
70];
71
72/// Logs every rejected `insert_process` and OTLP request, with the claims of its body attached at
73/// most once per client IP and claimed sender per minute.
74pub struct RejectedRequestLogger {
75    recent: Cache<(Option<IpAddr>, String), ()>,
76    inspections: Semaphore,
77}
78
79/// Request headers worth logging next to a rejection, already sanitized.
80#[derive(Default)]
81struct LoggedHeaders {
82    content_type: String,
83    content_encoding: String,
84    content_length: String,
85}
86
87impl LoggedHeaders {
88    fn from_request(req: &Request) -> Self {
89        let clean = |name: axum::http::header::HeaderName| {
90            let value = req.headers().get(name).and_then(|v| v.to_str().ok());
91            sanitize_for_log(value.unwrap_or_default(), MAX_HEADER_CHARS)
92        };
93        Self {
94            content_type: clean(axum::http::header::CONTENT_TYPE),
95            content_encoding: clean(axum::http::header::CONTENT_ENCODING),
96            content_length: clean(axum::http::header::CONTENT_LENGTH),
97        }
98    }
99}
100
101#[derive(Debug)]
102enum PrefixError {
103    Read,
104    Timeout,
105    Undecodable,
106}
107
108impl PrefixError {
109    fn reason(&self) -> &'static str {
110        match self {
111            Self::Read => "read_error",
112            Self::Timeout => "read_timeout",
113            Self::Undecodable => "undecodable",
114        }
115    }
116}
117
118#[derive(Clone, Copy)]
119enum WireEncoding {
120    Identity,
121    Gzip,
122}
123
124/// A deliberate superset of what `RequestDecompressionLayer` accepts (gzip and identity): it
125/// tolerates case, `x-gzip` and an empty value, since it only decides whether to inspect a body
126/// that has already been rejected. Anything else is not worth guessing at.
127fn wire_encoding(req: &Request) -> Option<WireEncoding> {
128    let Some(value) = req.headers().get(axum::http::header::CONTENT_ENCODING) else {
129        return Some(WireEncoding::Identity);
130    };
131    match value.to_str().ok()?.trim().to_ascii_lowercase().as_str() {
132        "" | "identity" => Some(WireEncoding::Identity),
133        "gzip" | "x-gzip" => Some(WireEncoding::Gzip),
134        _ => None,
135    }
136}
137
138/// Reads at most `cap` bytes of the body as sent, then returns them decompressed and capped at
139/// `cap` again, so a small gzip stream can't expand into an unbounded buffer.
140async fn read_body_prefix(
141    body: Body,
142    encoding: WireEncoding,
143    cap: usize,
144) -> Result<Vec<u8>, PrefixError> {
145    let mut stream = body.into_data_stream();
146    let mut wire: Vec<u8> = vec![];
147    let read = async {
148        while wire.len() < cap {
149            match stream.next().await {
150                Some(Ok(chunk)) => wire.extend_from_slice(&chunk),
151                Some(Err(_)) => return Err(PrefixError::Read),
152                None => break,
153            }
154        }
155        Ok(())
156    };
157    tokio::time::timeout(BODY_READ_TIMEOUT, read)
158        .await
159        .map_err(|_| PrefixError::Timeout)??;
160    wire.truncate(cap);
161    match encoding {
162        WireEncoding::Identity => Ok(wire),
163        WireEncoding::Gzip => {
164            let mut out = vec![];
165            let result = flate2::read::GzDecoder::new(&wire[..])
166                .take(cap as u64)
167                .read_to_end(&mut out);
168            // The wire prefix usually ends mid-stream; what decoded before that is still useful.
169            if result.is_err() && out.is_empty() {
170                return Err(PrefixError::Undecodable);
171            }
172            Ok(out)
173        }
174    }
175}
176
177impl Default for RejectedRequestLogger {
178    fn default() -> Self {
179        Self::new()
180    }
181}
182
183impl RejectedRequestLogger {
184    pub fn new() -> Self {
185        Self {
186            recent: Cache::builder()
187                .max_capacity(10_000)
188                .time_to_live(Duration::from_secs(60))
189                .build(),
190            inspections: Semaphore::new(DEFAULT_MAX_CONCURRENT_INSPECTIONS),
191        }
192    }
193
194    pub fn with_max_concurrent_inspections(max: usize) -> Self {
195        Self {
196            inspections: Semaphore::new(max),
197            ..Self::new()
198        }
199    }
200
201    /// `sender` is built from truncated claims, so the key size is bounded.
202    fn is_fresh(&self, client_ip: Option<IpAddr>, sender: String) -> bool {
203        self.recent
204            .entry((client_ip, sender))
205            .or_insert(())
206            .is_fresh()
207    }
208
209    /// Consumes a rejected `insert_process` or OTLP request and logs its single rejection line:
210    /// the provider reason, plus the identity the body claims or why it could not be read.
211    pub async fn log_rejected(&self, req: Request, rejection: &AuthRejection) {
212        let headers = LoggedHeaders::from_request(&req);
213        let inspected = if req.uri().path() == INSERT_PROCESS_PATH {
214            self.inspect_insert_process(req).await
215        } else {
216            self.inspect_otlp(req).await
217        };
218        let inspection = match inspected {
219            // One set of claims per distinct sender, so several apps behind one NAT address all
220            // show up; a repeat still logs the rejection, without the claims.
221            Ok(claims) => {
222                if self.is_fresh(rejection.parts.client_ip, claims.sender) {
223                    Inspection::Claims(claims.properties)
224                } else {
225                    Inspection::Repeat
226                }
227            }
228            Err(reason) => Inspection::NotInspected(reason),
229        };
230        let base = RejectionFields::new(&rejection.parts, &rejection.error);
231        warn_rejection(&base, &headers, &inspection);
232    }
233
234    async fn inspect_insert_process(&self, req: Request) -> Result<Claims, &'static str> {
235        let declared = req
236            .headers()
237            .get(axum::http::header::CONTENT_LENGTH)
238            .and_then(|v| v.to_str().ok())
239            .and_then(|v| v.parse::<usize>().ok())
240            .ok_or("missing_content_length")?;
241        if declared > MAX_INSPECTED_BODY_BYTES {
242            return Err("oversize");
243        }
244        let _permit = self.inspections.try_acquire().map_err(|_| "busy")?;
245        let read = to_bytes(req.into_body(), MAX_INSPECTED_BODY_BYTES);
246        let bytes = match tokio::time::timeout(BODY_READ_TIMEOUT, read).await {
247            Ok(Ok(bytes)) => bytes,
248            Ok(Err(_)) => return Err(PrefixError::Read.reason()),
249            Err(_) => return Err(PrefixError::Timeout.reason()),
250        };
251        let claimed: ClaimedProcessInfo =
252            ciborium::de::from_reader_with_recursion_limit(&bytes[..], CBOR_RECURSION_LIMIT)
253                .map_err(|_| PrefixError::Undecodable.reason())?;
254        Ok(claimed.claims())
255    }
256
257    async fn inspect_otlp(&self, req: Request) -> Result<Claims, &'static str> {
258        let encoding =
259            content_type_encoding(req.headers()).map_err(|_| "unsupported_content_type")?;
260        let wire = wire_encoding(&req).ok_or("unsupported_encoding")?;
261        let _permit = self.inspections.try_acquire().map_err(|_| "busy")?;
262        let prefix = read_body_prefix(req.into_body(), wire, MAX_INSPECTED_BODY_BYTES)
263            .await
264            .map_err(|e| e.reason())?;
265        let claimed = claimed_resource_from_prefix(&prefix, encoding).ok_or("no_resource")?;
266        let clean = |name: &str| clean_claim(claimed.get(name));
267        let sender = format!(
268            "otlp\x1f{}\x1f{}\x1f{}",
269            clean("claimed_exe"),
270            clean("claimed_computer"),
271            clean("claimed_service_instance_id")
272        );
273        let properties = claim_properties(
274            claimed
275                .properties()
276                .iter()
277                .map(|(name, value)| (*name, value.as_str())),
278        );
279        Ok(Claims { sender, properties })
280    }
281}
282
283impl ClaimedProcessInfo {
284    fn claims(&self) -> Claims {
285        fn field(value: &Option<String>) -> &str {
286            value.as_deref().unwrap_or_default()
287        }
288        let fields = [
289            ("claimed_process_id", field(&self.process_id)),
290            ("claimed_exe", field(&self.exe)),
291            ("claimed_username", field(&self.username)),
292            ("claimed_computer", field(&self.computer)),
293            ("claimed_parent_process_id", field(&self.parent_process_id)),
294            ("claimed_start_time", field(&self.start_time)),
295        ];
296        let build = LOGGED_PROPERTIES.iter().map(|(key, name)| {
297            let value = self.properties.get(*key).map(String::as_str);
298            (*name, value.unwrap_or_default())
299        });
300        Claims {
301            sender: format!("insert_process\x1f{}", clean_claim(field(&self.process_id))),
302            properties: claim_properties(fields.into_iter().chain(build)),
303        }
304    }
305}
306
307/// Sanitized identity a rejected request claims.
308struct Claims {
309    /// Tells apart the senders behind one client IP.
310    sender: String,
311    /// `claimed_*` log properties; the ones the caller left empty are omitted.
312    properties: Vec<(&'static str, String)>,
313}
314
315enum Inspection {
316    Claims(Vec<(&'static str, String)>),
317    /// The sender's claims were already logged within the last minute.
318    Repeat,
319    NotInspected(&'static str),
320}
321
322fn clean_claim(value: &str) -> String {
323    sanitize_for_log(value, MAX_CLAIM_CHARS)
324}
325
326fn claim_properties<'a>(
327    claims: impl IntoIterator<Item = (&'static str, &'a str)>,
328) -> Vec<(&'static str, String)> {
329    claims
330        .into_iter()
331        .filter(|(_, value)| !value.is_empty())
332        .map(|(name, value)| (name, clean_claim(value)))
333        .collect()
334}
335
336/// Logged from a runtime property list rather than `warn!`, whose fields are fixed per call
337/// site: which claims are present depends on the route and on what the caller sent.
338fn warn_rejection(base: &RejectionFields, headers: &LoggedHeaders, inspection: &Inspection) {
339    static DESC: LogMetadata = LogMetadata {
340        level: Level::Warn,
341        level_filter: AtomicU32::new(FILTER_LEVEL_UNSET_VALUE),
342        fmt_str: "[auth_failure] {}",
343        target: module_path!(),
344        module_path: module_path!(),
345        file: file!(),
346        line: line!(),
347    };
348    if Level::Warn > STATIC_MAX_LEVEL || Level::Warn > max_level() {
349        return;
350    }
351    let mut properties = vec![
352        DynProperty::new("client_ip", &base.client_ip),
353        DynProperty::new("method", &base.method),
354        DynProperty::new("path", &base.path),
355        DynProperty::new("user_agent", &base.user_agent),
356        DynProperty::new("content_type", &headers.content_type),
357        DynProperty::new("content_encoding", &headers.content_encoding),
358        DynProperty::new("content_length", &headers.content_length),
359    ];
360    match inspection {
361        Inspection::Claims(claims) => properties.extend(
362            claims
363                .iter()
364                .map(|(name, value)| DynProperty::new(name, value)),
365        ),
366        Inspection::Repeat => {}
367        Inspection::NotInspected(reason) => {
368            properties.push(DynProperty::new("inspection", reason));
369        }
370    }
371    dispatch::log_dyn_tagged(
372        &DESC,
373        PropertySet::empty(),
374        &properties,
375        LogMsgForm::Formatted,
376        format_args!("[auth_failure] {}", base.reason),
377    );
378}
379
380/// Like [`micromegas_auth::axum::auth_middleware`], except that a rejected `insert_process` or
381/// OTLP request is logged through `logger`, as one line that includes what its body claims.
382pub async fn ingestion_auth_middleware(
383    provider: Arc<dyn AuthProvider>,
384    logger: Arc<RejectedRequestLogger>,
385    mut req: Request,
386    next: Next,
387) -> Result<Response, AuthError> {
388    let path = req.uri().path();
389    if path != INSERT_PROCESS_PATH && !OTLP_PATHS.contains(&path) {
390        authenticate(provider.as_ref(), &mut req).await?;
391        return Ok(next.run(req).await);
392    }
393    match authenticate_quiet(provider.as_ref(), &mut req).await {
394        Ok(()) => Ok(next.run(req).await),
395        Err(QuietAuthError::Rejected(rejection)) => {
396            logger.log_rejected(req, &rejection).await;
397            Err(AuthError::InvalidToken)
398        }
399        Err(QuietAuthError::Unavailable) => Err(AuthError::Unavailable),
400    }
401}
402
403// Lives here because `read_body_prefix` is private and the bound on its output length is the
404// property under test.
405#[cfg(test)]
406mod tests {
407    use super::*;
408    use flate2::Compression;
409    use flate2::write::GzEncoder;
410    use std::io::Write;
411
412    fn gzip(bytes: &[u8]) -> Vec<u8> {
413        let mut enc = GzEncoder::new(vec![], Compression::best());
414        enc.write_all(bytes).expect("gzip write");
415        enc.finish().expect("gzip finish")
416    }
417
418    #[tokio::test]
419    async fn gzip_bomb_is_stopped_at_the_cap() {
420        let bomb = gzip(&vec![0u8; 64 * 1024 * 1024]);
421        assert!(bomb.len() < MAX_INSPECTED_BODY_BYTES);
422        let out = read_body_prefix(
423            Body::from(bomb),
424            WireEncoding::Gzip,
425            MAX_INSPECTED_BODY_BYTES,
426        )
427        .await
428        .expect("prefix");
429        assert_eq!(out.len(), MAX_INSPECTED_BODY_BYTES);
430    }
431
432    #[tokio::test]
433    async fn plain_body_is_cut_at_the_cap() {
434        let out = read_body_prefix(
435            Body::from(vec![1u8; MAX_INSPECTED_BODY_BYTES * 3]),
436            WireEncoding::Identity,
437            MAX_INSPECTED_BODY_BYTES,
438        )
439        .await
440        .expect("prefix");
441        assert_eq!(out.len(), MAX_INSPECTED_BODY_BYTES);
442    }
443
444    #[tokio::test]
445    async fn invalid_gzip_is_undecodable() {
446        let err = read_body_prefix(Body::from("nope"), WireEncoding::Gzip, 1024)
447            .await
448            .expect_err("undecodable");
449        assert!(matches!(err, PrefixError::Undecodable));
450    }
451}