1use super::*;
2
3impl AuditSha256 {
5 #[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 #[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 #[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 #[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
120impl InMemoryAuditSink {
122 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 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 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 pub fn is_empty(&self) -> bool {
171 self.len() == 0
172 }
173
174 pub fn clear(&self) {
176 let Self { records, .. } = self;
177 if let Ok(mut guard) = records.lock() {
178 guard.clear();
179 }
180 }
181}
182
183impl AuditSink for InMemoryAuditSink {
185 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
209impl Default for AuditConfig {
211 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
229impl AuditConfig {
231 pub fn with_mutations_only(mut self, enabled: bool) -> Self {
241 self.set_mutations_only(enabled);
242 self
243 }
244
245 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 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 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
300impl AuditPlugin {
302 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 pub fn with_sink(config: AuditConfig, sink: Arc<dyn AuditSink>) -> Self {
329 Self::build(config, sink, None)
330 }
331
332 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 pub fn init(config: AuditConfig) -> &'static Self {
402 AUDIT_PLUGIN.get_or_init(|| Self::new(config))
403 }
404
405 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 #[inline(always)]
425 pub fn get() -> Option<&'static Self> {
426 AUDIT_PLUGIN.get()
427 }
428
429 pub fn memory_sink(&self) -> Option<&Arc<InMemoryAuditSink>> {
435 let Self { memory_sink, .. } = self;
436 memory_sink.as_ref()
437 }
438
439 #[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 #[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 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 #[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
612impl ServerHook for AuditRequestHook {
614 #[inline(always)]
625 async fn new(_: &mut Stream, _: &mut Context) -> Self {
626 Self
627 }
628
629 #[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
652impl ServerHook for AuditResponseHook {
654 #[inline(always)]
665 async fn new(_: &mut Stream, _: &mut Context) -> Self {
666 Self
667 }
668
669 #[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}