Skip to main content

systemprompt_security/authz/audit/
repository.rs

1//! `governance_decisions` insert primitive.
2//!
3//! Single canonical writer for the table. Both the extension's
4//! `POST /govern/authz` handler (for resolved decisions) and core's
5//! [`DbAuditSink`](super::DbAuditSink) (for webhook-fault, default-deny, and
6//! unrestricted-allow decisions) call this repository so there is exactly one
7//! SQL statement that knows the column layout.
8//!
9//! Copyright (c) systemprompt.io — Business Source License 1.1.
10//! See <https://systemprompt.io> for licensing details.
11
12use sqlx::PgPool;
13use systemprompt_identifiers::Actor;
14
15use crate::authz::types::DecisionTag;
16use crate::policy::types::AccessScope;
17
18/// Prometheus counter incremented whenever a `governance_decisions` INSERT
19/// fails.
20///
21/// Exposed as a `pub const` so alert rules and dashboards can reference the
22/// metric by symbol rather than re-typing the literal.
23pub const AUDIT_WRITE_FAILED_TOTAL: &str = "governance_audit_write_failed_total";
24
25#[derive(Debug)]
26pub struct GovernanceDecisionRecord<'a> {
27    pub id: &'a str,
28    pub actor: &'a Actor,
29    pub session_id: &'a str,
30    pub tool_name: &'a str,
31    pub agent_id: Option<&'a str>,
32    pub agent_scope: Option<AccessScope>,
33    pub decision: DecisionTag,
34    pub policy: &'a str,
35    pub reason: &'a str,
36    // JSON: governance audit blob — typed `DecisionAudit` on the writing side;
37    // payload shape is documented in CHANGELOG and rendered by the dashboard.
38    pub evaluated_rules: &'a serde_json::Value,
39    pub plugin_id: Option<&'a str>,
40    /// RFC 8693 delegation lineage in outermost-first order. Empty for
41    /// direct (non-delegated) tokens.
42    pub act_chain: &'a [Actor],
43    pub context_id: Option<&'a str>,
44    pub task_id: Option<&'a str>,
45}
46
47#[derive(Debug, Clone)]
48pub struct GovernanceDecisionRepository {
49    pool: std::sync::Arc<PgPool>,
50}
51
52impl GovernanceDecisionRepository {
53    pub const fn from_pool(pool: std::sync::Arc<PgPool>) -> Self {
54        Self { pool }
55    }
56
57    pub fn pool(&self) -> &PgPool {
58        &self.pool
59    }
60
61    pub async fn insert(&self, record: &GovernanceDecisionRecord<'_>) -> Result<(), sqlx::Error> {
62        insert_governance_decision(&self.pool, record).await
63    }
64}
65
66pub async fn insert_governance_decision(
67    pool: &PgPool,
68    record: &GovernanceDecisionRecord<'_>,
69) -> Result<(), sqlx::Error> {
70    let actor_kind = record.actor.kind.tag();
71    let actor_id = record.actor.kind.actor_id(&record.actor.user_id);
72    // Why: act_chain is `Vec<Actor>` which is unconditionally serde-compliant,
73    // so serialization failure is unreachable; falling back to `[]` keeps the
74    // audit row writable rather than dropping the entire governance record.
75    let act_chain =
76        serde_json::to_value(record.act_chain).unwrap_or_else(|_| serde_json::json!([]));
77    let result = sqlx::query!(
78        "INSERT INTO governance_decisions (id, user_id, session_id, tool_name, agent_id, \
79         agent_scope, decision, policy, reason, evaluated_rules, plugin_id, actor_kind, actor_id, \
80         act_chain, context_id, task_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, \
81         $12, $13, $14, $15, $16)",
82        record.id,
83        record.actor.user_id.as_str(),
84        record.session_id,
85        record.tool_name,
86        record.agent_id,
87        record.agent_scope.map(AccessScope::as_str),
88        record.decision.as_str(),
89        record.policy,
90        record.reason,
91        record.evaluated_rules,
92        record.plugin_id,
93        actor_kind.as_str(),
94        actor_id,
95        act_chain,
96        record.context_id,
97        record.task_id,
98    )
99    .execute(pool)
100    .await;
101    if let Err(error) = &result {
102        // Why: callers run this inside `tokio::spawn` (fire-and-forget audit
103        // writes), so a swallowed error here is invisible to the HTTP
104        // response. Log + counter at the SQL boundary guarantees every drop
105        // surfaces regardless of caller.
106        tracing::error!(
107            error = %error,
108            actor_kind = actor_kind.as_str(),
109            actor_id,
110            policy = record.policy,
111            decision = record.decision.as_str(),
112            session_id = record.session_id,
113            "governance_decisions insert failed; audit row dropped"
114        );
115        metrics::counter!(
116            AUDIT_WRITE_FAILED_TOTAL,
117            "actor_kind" => actor_kind.as_str(),
118            "decision" => record.decision.as_str(),
119            "policy" => record.policy.to_owned(),
120        )
121        .increment(1);
122    }
123    result.map(|_| ())
124}