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: &'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    let act_chain =
73        serde_json::to_value(record.act_chain).unwrap_or_else(|_| serde_json::json!([]));
74    let result = sqlx::query!(
75        "INSERT INTO governance_decisions (id, user_id, session_id, tool_name, agent_id, \
76         agent_scope, decision, policy, reason, evaluated_rules, plugin_id, actor_kind, actor_id, \
77         act_chain, context_id, task_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, \
78         $12, $13, $14, $15, $16)",
79        record.id,
80        record.actor.user_id.as_str(),
81        record.session_id,
82        record.tool_name,
83        record.agent_id,
84        record.agent_scope.map(AccessScope::as_str),
85        record.decision.as_str(),
86        record.policy,
87        record.reason,
88        record.evaluated_rules,
89        record.plugin_id,
90        actor_kind.as_str(),
91        actor_id,
92        act_chain,
93        record.context_id,
94        record.task_id,
95    )
96    .execute(pool)
97    .await;
98    if let Err(error) = &result {
99        tracing::error!(
100            error = %error,
101            actor_kind = actor_kind.as_str(),
102            actor_id,
103            policy = record.policy,
104            decision = record.decision.as_str(),
105            session_id = record.session_id,
106            "governance_decisions insert failed; audit row dropped"
107        );
108        metrics::counter!(
109            AUDIT_WRITE_FAILED_TOTAL,
110            "actor_kind" => actor_kind.as_str(),
111            "decision" => record.decision.as_str(),
112            "policy" => record.policy.to_owned(),
113        )
114        .increment(1);
115    }
116    result.map(|_| ())
117}