Skip to main content

hyperlane_plugin_audit/
impl.rs

1use super::*;
2
3/// Streaming FIPS 180-4 SHA-256 implementation for zero-allocation audit hashing.
4impl AuditSha256 {
5    /// Initializes a fresh SHA-256 state.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Ready incremental hasher.
10    #[inline(always)]
11    pub(crate) fn new() -> Self {
12        Self {
13            state: SHA256_H0,
14            block: [0u8; 64],
15            block_len: 0,
16            total_bytes: 0,
17        }
18    }
19
20    /// Absorbs a single byte into the running SHA-256 state.
21    ///
22    /// # Arguments
23    ///
24    /// - `u8` - Input byte.
25    #[inline(always)]
26    pub(crate) fn update_byte(&mut self, byte: u8) {
27        let Self {
28            state,
29            block,
30            block_len,
31            total_bytes,
32        } = self;
33        *total_bytes = total_bytes.wrapping_add(1);
34        block[*block_len] = byte;
35        *block_len += 1;
36        if *block_len == 64 {
37            sha256_compress(state, block);
38            *block_len = 0;
39        }
40    }
41
42    /// Absorbs a slice of bytes into the running SHA-256 state.
43    ///
44    /// # Arguments
45    ///
46    /// - `&[u8]` - Input byte slice.
47    #[inline]
48    pub(crate) fn update(&mut self, mut data: &[u8]) {
49        if data.is_empty() {
50            return;
51        }
52        let Self {
53            state,
54            block,
55            block_len,
56            total_bytes,
57        } = self;
58        *total_bytes = total_bytes.wrapping_add(data.len() as u64);
59        if *block_len > 0 {
60            let need: usize = 64 - *block_len;
61            if data.len() < need {
62                block[*block_len..*block_len + data.len()].copy_from_slice(data);
63                *block_len += data.len();
64                return;
65            }
66            block[*block_len..64].copy_from_slice(&data[..need]);
67            sha256_compress(state, block);
68            *block_len = 0;
69            data = &data[need..];
70        }
71        let (chunks, rem): (&[[u8; 64]], &[u8]) = data.as_chunks::<64>();
72        for chunk in chunks {
73            sha256_compress(state, chunk);
74        }
75        if !rem.is_empty() {
76            block[..rem.len()].copy_from_slice(rem);
77            *block_len = rem.len();
78        }
79    }
80
81    /// Finalizes the SHA-256 digest directly into a 64-byte lowercase ASCII hex array.
82    ///
83    /// # Returns
84    ///
85    /// - `[u8; 64]` - 64-byte lowercase hexadecimal digest.
86    #[inline]
87    pub(crate) fn finalize_hex(self) -> [u8; 64] {
88        let Self {
89            mut state,
90            mut block,
91            block_len,
92            total_bytes,
93        } = self;
94        let bit_len: u64 = total_bytes.wrapping_mul(8);
95        block[block_len] = 0x80;
96        if block_len < 56 {
97            block[block_len + 1..56].fill(0);
98            block[56..64].copy_from_slice(&bit_len.to_be_bytes());
99            sha256_compress(&mut state, &block);
100        } else {
101            block[block_len + 1..64].fill(0);
102            sha256_compress(&mut state, &block);
103            let mut last_block: [u8; 64] = [0u8; 64];
104            last_block[56..64].copy_from_slice(&bit_len.to_be_bytes());
105            sha256_compress(&mut state, &last_block);
106        }
107        let mut out: [u8; 64] = [0u8; 64];
108        let mut pos: usize = 0;
109        for word in state {
110            for byte in word.to_be_bytes() {
111                out[pos] = HEX_LOWER[(byte >> 4) as usize];
112                out[pos + 1] = HEX_LOWER[(byte & 0x0f) as usize];
113                pos += 2;
114            }
115        }
116        out
117    }
118}
119
120/// Bounded ring-buffer operations for [`InMemoryAuditSink`].
121impl InMemoryAuditSink {
122    /// Creates a new [`InMemoryAuditSink`] retaining at most `capacity` records (`>= 1`).
123    ///
124    /// # Arguments
125    ///
126    /// - `usize` - Maximum number of records retained in memory.
127    ///
128    /// # Returns
129    ///
130    /// - `Self` - Bounded in-memory audit sink.
131    pub fn new(capacity: usize) -> Self {
132        let cap: usize = capacity.max(1);
133        Self {
134            capacity: cap,
135            records: Mutex::new(VecDeque::with_capacity(cap.min(256))),
136        }
137    }
138
139    /// Returns a cloned snapshot of all currently buffered records in chronological order.
140    ///
141    /// # Returns
142    ///
143    /// - `Vec<AuditRecord>` - Buffered audit records.
144    pub fn snapshot(&self) -> Vec<AuditRecord> {
145        let Self { records, .. } = self;
146        match records.lock() {
147            Ok(guard) => guard.iter().cloned().collect(),
148            Err(_) => Vec::new(),
149        }
150    }
151
152    /// Returns the number of currently buffered audit records.
153    ///
154    /// # Returns
155    ///
156    /// - `usize` - Current buffer length.
157    pub fn len(&self) -> usize {
158        let Self { records, .. } = self;
159        match records.lock() {
160            Ok(guard) => guard.len(),
161            Err(_) => 0,
162        }
163    }
164
165    /// Reports whether zero records are buffered.
166    ///
167    /// # Returns
168    ///
169    /// - `bool` - `true` when empty.
170    pub fn is_empty(&self) -> bool {
171        self.len() == 0
172    }
173
174    /// Clears all buffered records from memory.
175    pub fn clear(&self) {
176        let Self { records, .. } = self;
177        if let Ok(mut guard) = records.lock() {
178            guard.clear();
179        }
180    }
181}
182
183/// Implements [`AuditSink`] for [`InMemoryAuditSink`].
184impl AuditSink for InMemoryAuditSink {
185    /// Appends `event` to the bounded ring buffer, evicting the oldest record if full.
186    ///
187    /// # Arguments
188    ///
189    /// - `AuditRecord` - Finalized audit event.
190    fn record(&self, event: AuditRecord) {
191        let Self {
192            capacity, records, ..
193        } = self;
194        let evicted: Option<AuditRecord> = if let Ok(mut guard) = records.lock() {
195            let old: Option<AuditRecord> = if guard.len() >= *capacity {
196                guard.pop_front()
197            } else {
198                None
199            };
200            guard.push_back(event);
201            old
202        } else {
203            None
204        };
205        drop(evicted);
206    }
207}
208
209/// Default construction for [`AuditConfig`].
210impl Default for AuditConfig {
211    /// Constructs a default [`AuditConfig`] auditing mutating methods and redacting auth/cookie headers.
212    ///
213    /// # Returns
214    ///
215    /// - `Self` - Default configuration.
216    fn default() -> Self {
217        Self {
218            mutations_only: true,
219            include_prefixes: Vec::new(),
220            exclude_prefixes: Vec::new(),
221            capture_headers: Vec::new(),
222            redact_headers: vec![AUTHORIZATION.to_owned(), COOKIE.to_owned()],
223            request_id_header: DEFAULT_REQUEST_ID_HEADER.to_owned(),
224            in_memory_capacity: DEFAULT_AUDIT_CAPACITY,
225        }
226    }
227}
228
229/// Fluent builder helpers for [`AuditConfig`].
230impl AuditConfig {
231    /// Configures whether only state-mutating HTTP methods are audited (`false` audits all methods).
232    ///
233    /// # Arguments
234    ///
235    /// - `bool` - `true` for mutating methods only.
236    ///
237    /// # Returns
238    ///
239    /// - `Self` - Updated configuration.
240    pub fn with_mutations_only(mut self, enabled: bool) -> Self {
241        self.set_mutations_only(enabled);
242        self
243    }
244
245    /// Restricts auditing to requests matching at least one prefix in `prefixes`.
246    ///
247    /// # Arguments
248    ///
249    /// - `I` - Iterator of path prefixes.
250    ///
251    /// # Returns
252    ///
253    /// - `Self` - Updated configuration.
254    pub fn with_include_prefixes<I, S>(mut self, prefixes: I) -> Self
255    where
256        I: IntoIterator<Item = S>,
257        S: Into<String>,
258    {
259        self.set_include_prefixes(prefixes.into_iter().map(Into::into).collect());
260        self
261    }
262
263    /// Excludes matching path prefixes from audit recording.
264    ///
265    /// # Arguments
266    ///
267    /// - `I` - Iterator of excluded path prefixes.
268    ///
269    /// # Returns
270    ///
271    /// - `Self` - Updated configuration.
272    pub fn with_exclude_prefixes<I, S>(mut self, prefixes: I) -> Self
273    where
274        I: IntoIterator<Item = S>,
275        S: Into<String>,
276    {
277        self.set_exclude_prefixes(prefixes.into_iter().map(Into::into).collect());
278        self
279    }
280
281    /// Configures request headers copied into each audit record (sensitive headers are auto-redacted).
282    ///
283    /// # Arguments
284    ///
285    /// - `I` - Iterator of header names.
286    ///
287    /// # Returns
288    ///
289    /// - `Self` - Updated configuration.
290    pub fn with_capture_headers<I, S>(mut self, headers: I) -> Self
291    where
292        I: IntoIterator<Item = S>,
293        S: Into<String>,
294    {
295        self.set_capture_headers(headers.into_iter().map(Into::into).collect());
296        self
297    }
298}
299
300/// Audit filtering, hash-chaining, and recording methods for [`AuditPlugin`].
301impl AuditPlugin {
302    /// Compiles a standalone [`AuditPlugin`] backed by an [`InMemoryAuditSink`].
303    ///
304    /// # Arguments
305    ///
306    /// - `AuditConfig` - Audit configuration.
307    ///
308    /// # Returns
309    ///
310    /// - `Self` - Compiled plugin.
311    pub fn new(config: AuditConfig) -> Self {
312        let mem: Arc<InMemoryAuditSink> =
313            Arc::new(InMemoryAuditSink::new(config.get_in_memory_capacity()));
314        let sink: Arc<dyn AuditSink> = Arc::clone(&mem) as Arc<dyn AuditSink>;
315        Self::build(config, sink, Some(mem))
316    }
317
318    /// Compiles a standalone [`AuditPlugin`] writing events to a custom [`AuditSink`].
319    ///
320    /// # Arguments
321    ///
322    /// - `AuditConfig` - Audit configuration.
323    /// - `Arc<dyn AuditSink>` - Custom sink destination.
324    ///
325    /// # Returns
326    ///
327    /// - `Self` - Compiled plugin.
328    pub fn with_sink(config: AuditConfig, sink: Arc<dyn AuditSink>) -> Self {
329        Self::build(config, sink, None)
330    }
331
332    /// Internal constructor compiling normalized prefix and header tables.
333    ///
334    /// # Arguments
335    ///
336    /// - `AuditConfig` - Audit configuration.
337    /// - `Arc<dyn AuditSink>` - Sink trait object.
338    /// - `Option<Arc<InMemoryAuditSink>>` - Optional in-memory ring buffer reference.
339    ///
340    /// # Returns
341    ///
342    /// - `Self` - Compiled plugin.
343    fn build(
344        config: AuditConfig,
345        sink: Arc<dyn AuditSink>,
346        memory_sink: Option<Arc<InMemoryAuditSink>>,
347    ) -> Self {
348        let include_prefixes: Box<[String]> = config
349            .get_include_prefixes()
350            .iter()
351            .filter(|p: &&String| !p.trim().is_empty())
352            .map(|p: &String| normalize_prefix(p))
353            .collect::<Vec<String>>()
354            .into_boxed_slice();
355        let exclude_prefixes: Box<[String]> = config
356            .get_exclude_prefixes()
357            .iter()
358            .filter(|p: &&String| !p.trim().is_empty())
359            .map(|p: &String| normalize_prefix(p))
360            .collect::<Vec<String>>()
361            .into_boxed_slice();
362        let capture_headers_lower: Box<[String]> = config
363            .get_capture_headers()
364            .iter()
365            .map(|h: &String| h.trim().to_ascii_lowercase())
366            .filter(|h: &String| !h.is_empty())
367            .collect::<Vec<String>>()
368            .into_boxed_slice();
369        let redact_headers_lower: Box<[String]> = config
370            .get_redact_headers()
371            .iter()
372            .map(|h: &String| h.trim().to_ascii_lowercase())
373            .filter(|h: &String| !h.is_empty())
374            .collect::<Vec<String>>()
375            .into_boxed_slice();
376        let request_id_header_lower: String =
377            config.get_request_id_header().trim().to_ascii_lowercase();
378        Self {
379            config,
380            include_prefixes,
381            exclude_prefixes,
382            capture_headers_lower,
383            redact_headers_lower,
384            request_id_header_lower,
385            seq: AtomicU64::new(1),
386            last_hash: Mutex::new(AUDIT_GENESIS_BYTES),
387            sink,
388            memory_sink,
389        }
390    }
391
392    /// Initializes the global [`AuditPlugin`] singleton with an in-memory ring-buffer sink.
393    ///
394    /// # Arguments
395    ///
396    /// - `AuditConfig` - Audit configuration.
397    ///
398    /// # Returns
399    ///
400    /// - `&'static Self` - Reference to the global plugin.
401    pub fn init(config: AuditConfig) -> &'static Self {
402        AUDIT_PLUGIN.get_or_init(|| Self::new(config))
403    }
404
405    /// Initializes the global [`AuditPlugin`] singleton with a custom [`AuditSink`].
406    ///
407    /// # Arguments
408    ///
409    /// - `AuditConfig` - Audit configuration.
410    /// - `Arc<dyn AuditSink>` - Custom audit sink.
411    ///
412    /// # Returns
413    ///
414    /// - `&'static Self` - Reference to the global plugin.
415    pub fn init_with_sink(config: AuditConfig, sink: Arc<dyn AuditSink>) -> &'static Self {
416        AUDIT_PLUGIN.get_or_init(|| Self::with_sink(config, sink))
417    }
418
419    /// Returns the initialized global [`AuditPlugin`], if configured.
420    ///
421    /// # Returns
422    ///
423    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
424    #[inline(always)]
425    pub fn get() -> Option<&'static Self> {
426        AUDIT_PLUGIN.get()
427    }
428
429    /// Returns the built-in [`InMemoryAuditSink`] when initialized via [`AuditPlugin::new`] or [`AuditPlugin::init`].
430    ///
431    /// # Returns
432    ///
433    /// - `Option<&Arc<InMemoryAuditSink>>` - Reference to the in-memory sink.
434    pub fn memory_sink(&self) -> Option<&Arc<InMemoryAuditSink>> {
435        let Self { memory_sink, .. } = self;
436        memory_sink.as_ref()
437    }
438
439    /// Reports whether `request` matches the audit filter policy.
440    ///
441    /// # Arguments
442    ///
443    /// - `&Request` - Incoming HTTP request.
444    ///
445    /// # Returns
446    ///
447    /// - `bool` - `true` when this request should be audited.
448    #[inline]
449    pub fn should_audit(&self, request: &Request) -> bool {
450        let Self {
451            config,
452            include_prefixes,
453            exclude_prefixes,
454            ..
455        } = self;
456        if config.get_mutations_only() && !is_mutating_method(request.get_method()) {
457            return false;
458        }
459        let path: &str = request.get_path();
460        if exclude_prefixes
461            .iter()
462            .any(|p: &String| path_matches_prefix(path, p))
463        {
464            return false;
465        }
466        if !include_prefixes.is_empty()
467            && !include_prefixes
468                .iter()
469                .any(|p: &String| path_matches_prefix(path, p))
470        {
471            return false;
472        }
473        true
474    }
475
476    /// Builds and hash-chains an [`AuditRecord`] for `ctx` without cloning on dispatch.
477    ///
478    /// # Arguments
479    ///
480    /// - `&Context` - Completed request/response context.
481    ///
482    /// # Returns
483    ///
484    /// - `AuditRecord` - Finalized hash-chained audit record.
485    #[inline]
486    fn build_record_for_context(&self, ctx: &Context) -> AuditRecord {
487        let Self {
488            capture_headers_lower,
489            redact_headers_lower,
490            request_id_header_lower,
491            seq,
492            last_hash,
493            ..
494        } = self;
495        let request: &Request = ctx.get_request();
496        let latency_us: u64 = ctx
497            .try_get_attribute_ref::<Instant, _>(ATTR_AUDIT_START)
498            .map(|started: &Instant| started.elapsed().as_micros() as u64)
499            .unwrap_or(0);
500        let actor_ref: &str = ctx
501            .try_get_attribute_ref::<String, _>(ATTR_AUDIT_ACTOR)
502            .map(String::as_str)
503            .unwrap_or(ANONYMOUS_ACTOR);
504        let action_ref: &str = ctx
505            .try_get_attribute_ref::<String, _>(ATTR_AUDIT_ACTION)
506            .map(String::as_str)
507            .unwrap_or_default();
508        let request_id_ref: &str = if request_id_header_lower.is_empty() {
509            EMPTY_STR
510        } else {
511            request
512                .get_headers()
513                .get(request_id_header_lower.as_str())
514                .and_then(|vals: &VecDeque<String>| vals.back())
515                .map(String::as_str)
516                .unwrap_or_default()
517        };
518        let headers: Vec<(String, String)> = if capture_headers_lower.is_empty() {
519            Vec::new()
520        } else {
521            let mut list: Vec<(String, String)> = Vec::with_capacity(capture_headers_lower.len());
522            for name in capture_headers_lower.iter() {
523                if let Some(vals) = request.get_headers().get(name.as_str())
524                    && let Some(val) = vals.back()
525                {
526                    let redacted: bool = redact_headers_lower
527                        .iter()
528                        .any(|r: &String| r.as_str() == name.as_str());
529                    let out_val: String = if redacted {
530                        REDACTED_VALUE.to_owned()
531                    } else {
532                        val.clone()
533                    };
534                    list.push((name.clone(), out_val));
535                }
536            }
537            list
538        };
539        let method_str: String = request.get_method().to_string();
540        let path_ref: &str = request.get_path();
541        let status_code: usize = ctx.get_response().get_status_code();
542        let sequence: u64 = seq.fetch_add(1, Ordering::Relaxed);
543        let timestamp_ms: u64 = current_unix_ms();
544        let (prev_bytes, digest_bytes): ([u8; 64], [u8; 64]) =
545            if let Ok(mut prev_guard) = last_hash.lock() {
546                let prev: [u8; 64] = *prev_guard;
547                let digest: [u8; 64] = compute_record_hash_bytes(
548                    (sequence, timestamp_ms, status_code),
549                    &prev,
550                    (&method_str, path_ref),
551                    (actor_ref, action_ref, request_id_ref),
552                );
553                *prev_guard = digest;
554                (prev, digest)
555            } else {
556                let prev: [u8; 64] = AUDIT_GENESIS_BYTES;
557                let digest: [u8; 64] = compute_record_hash_bytes(
558                    (sequence, timestamp_ms, status_code),
559                    &prev,
560                    (&method_str, path_ref),
561                    (actor_ref, action_ref, request_id_ref),
562                );
563                (prev, digest)
564            };
565        let prev_hash: String = from_utf8(&prev_bytes).unwrap_or_default().to_owned();
566        let entry_hash: String = from_utf8(&digest_bytes).unwrap_or_default().to_owned();
567        AuditRecord {
568            sequence,
569            timestamp_ms,
570            method: method_str,
571            path: path_ref.to_owned(),
572            status_code,
573            latency_us,
574            actor: actor_ref.to_owned(),
575            action: action_ref.to_owned(),
576            request_id: request_id_ref.to_owned(),
577            headers,
578            prev_hash,
579            entry_hash,
580        }
581    }
582
583    /// Builds, hash-chains, and dispatches an [`AuditRecord`] for `ctx` to the configured sink.
584    ///
585    /// # Arguments
586    ///
587    /// - `&Context` - Completed request/response context.
588    ///
589    /// # Returns
590    ///
591    /// - `AuditRecord` - The finalized hash-chained audit record.
592    pub fn record_context(&self, ctx: &Context) -> AuditRecord {
593        let Self { sink, .. } = self;
594        let record: AuditRecord = self.build_record_for_context(ctx);
595        sink.record(record.clone());
596        record
597    }
598
599    /// Builds, hash-chains, and moves an [`AuditRecord`] directly to the sink without cloning.
600    ///
601    /// # Arguments
602    ///
603    /// - `&Context` - Completed request/response context.
604    #[inline]
605    pub(crate) fn record_context_hook(&self, ctx: &Context) {
606        let Self { sink, .. } = self;
607        let record: AuditRecord = self.build_record_for_context(ctx);
608        sink.record(record);
609    }
610}
611
612/// Implements [`ServerHook`] for [`AuditRequestHook`].
613impl ServerHook for AuditRequestHook {
614    /// Constructs a per-request [`AuditRequestHook`].
615    ///
616    /// # Arguments
617    ///
618    /// - `&mut Stream` - Connection stream.
619    /// - `&mut Context` - Request context.
620    ///
621    /// # Returns
622    ///
623    /// - `Self` - Hook instance.
624    #[inline(always)]
625    async fn new(_: &mut Stream, _: &mut Context) -> Self {
626        Self
627    }
628
629    /// Stamps the entry timestamp when the request qualifies for auditing.
630    ///
631    /// # Arguments
632    ///
633    /// - `Self` - Hook instance.
634    /// - `&mut Stream` - Connection stream.
635    /// - `&mut Context` - Request context.
636    ///
637    /// # Returns
638    ///
639    /// - `Status` - Always `Status::Continue`.
640    #[inline(always)]
641    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
642        let Some(plugin) = AuditPlugin::get() else {
643            return Status::Continue;
644        };
645        if plugin.should_audit(ctx.get_request()) {
646            ctx.set_attribute(ATTR_AUDIT_START, Instant::now());
647        }
648        Status::Continue
649    }
650}
651
652/// Implements [`ServerHook`] for [`AuditResponseHook`].
653impl ServerHook for AuditResponseHook {
654    /// Constructs a per-response [`AuditResponseHook`].
655    ///
656    /// # Arguments
657    ///
658    /// - `&mut Stream` - Connection stream.
659    /// - `&mut Context` - Request context.
660    ///
661    /// # Returns
662    ///
663    /// - `Self` - Hook instance.
664    #[inline(always)]
665    async fn new(_: &mut Stream, _: &mut Context) -> Self {
666        Self
667    }
668
669    /// Emits a finalized hash-chained [`AuditRecord`] for audited requests.
670    ///
671    /// # Arguments
672    ///
673    /// - `Self` - Hook instance.
674    /// - `&mut Stream` - Connection stream.
675    /// - `&mut Context` - Request context.
676    ///
677    /// # Returns
678    ///
679    /// - `Status` - Always `Status::Continue`.
680    #[inline(always)]
681    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
682        let Some(plugin) = AuditPlugin::get() else {
683            return Status::Continue;
684        };
685        if plugin.should_audit(ctx.get_request()) {
686            plugin.record_context_hook(ctx);
687        }
688        Status::Continue
689    }
690}