Skip to main content

postgres_mcp/
audit.rs

1//! Audit log: one `audit` target line per tool call, with no SQL text, values or error detail.
2
3use std::time::Duration;
4
5use sha2::{Digest, Sha256};
6
7/// What one tool call records.
8pub struct Record<'a> {
9    pub tool: &'a str,
10    pub database: Option<&'a str>,
11    pub ok: bool,
12    pub duration: Duration,
13    pub rows: Option<usize>,
14    pub sqlstate: Option<&'a str>,
15    /// The SQL text; only its digest is logged.
16    pub sql: Option<&'a str>,
17    /// Password hash texts replaced in the result; only the count is logged.
18    pub redacted_hashes: u64,
19}
20
21/// Writes the audit line when the audit log is enabled.
22pub fn record(enabled: bool, record: &Record<'_>) {
23    if !enabled {
24        return;
25    }
26    let sql_sha256 = record.sql.map(sql_digest);
27    let duration_ms = u64::try_from(record.duration.as_millis()).unwrap_or(u64::MAX);
28    let rows = record.rows.map(|n| u64::try_from(n).unwrap_or(u64::MAX));
29    tracing::info!(
30        target: "audit",
31        tool = record.tool,
32        database = record.database,
33        ok = record.ok,
34        duration_ms,
35        rows,
36        sqlstate = record.sqlstate,
37        sql_sha256 = sql_sha256.as_deref(),
38        redacted_hashes = record.redacted_hashes,
39        "tool call"
40    );
41}
42
43/// The first 16 hex characters of the SHA-256 of the SQL text.
44pub fn sql_digest(sql: &str) -> String {
45    Sha256::digest(sql.as_bytes())
46        .iter()
47        .take(8)
48        .map(|byte| format!("{byte:02x}"))
49        .collect()
50}