car-policy 0.55.0

Policy engine for Common Agent Runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! Per-agent approval policy.
//!
//! The action-level [`permission`](crate::permission) tiers answer "how risky
//! is this action?" (`read_only` ⊂ `sandbox_edit` ⊂ `full_access`). This module
//! answers the orthogonal question the user actually configures: **for THIS
//! agent, at THIS risk tier, what should CAR do** — always allow, require
//! approval, or deny.
//!
//! The policy is a fully-specified `default` posture plus sparse per-agent tier
//! overrides and optional exact `(agent_id, tool)` overrides, so a brand-new
//! agent inherits sensible defaults and an operator only tunes the agents they
//! care about. Tool keys are literals: no wildcard, prefix, regex, or tier-wide
//! matching is performed.
//!
//! Pure + serde; the durable store and the `agent_permissions.*` wire surface
//! live in `car-server-core`.

use crate::permission::PermissionTier;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

/// What CAR does when an agent attempts an action of a given risk tier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalMode {
    /// Run without asking.
    AlwaysAllow,
    /// Pause and ask the operator (routes through the HITL `ApprovalLedger`).
    RequireApproval,
    /// Never run; the action is refused.
    Deny,
}

impl ApprovalMode {
    pub fn as_str(self) -> &'static str {
        match self {
            ApprovalMode::AlwaysAllow => "always_allow",
            ApprovalMode::RequireApproval => "require_approval",
            ApprovalMode::Deny => "deny",
        }
    }

    pub fn from_str_opt(s: &str) -> Option<ApprovalMode> {
        match s {
            "always_allow" | "allow" => Some(ApprovalMode::AlwaysAllow),
            "require_approval" | "approval" | "ask" => Some(ApprovalMode::RequireApproval),
            "deny" | "block" => Some(ApprovalMode::Deny),
            _ => None,
        }
    }
}

/// A subject's posture: an optional mode per risk tier. `None` at a tier means
/// "fall through" (used for sparse per-agent overrides; the `default` posture is
/// fully specified).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TierPosture {
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub read_only: Option<ApprovalMode>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub sandbox_edit: Option<ApprovalMode>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub full_access: Option<ApprovalMode>,
}

impl TierPosture {
    pub fn get(&self, tier: PermissionTier) -> Option<ApprovalMode> {
        match tier {
            PermissionTier::ReadOnly => self.read_only,
            PermissionTier::SandboxEdit => self.sandbox_edit,
            PermissionTier::FullAccess => self.full_access,
        }
    }

    pub fn set(&mut self, tier: PermissionTier, mode: ApprovalMode) {
        match tier {
            PermissionTier::ReadOnly => self.read_only = Some(mode),
            PermissionTier::SandboxEdit => self.sandbox_edit = Some(mode),
            PermissionTier::FullAccess => self.full_access = Some(mode),
        }
    }

    /// A uniform posture at every tier (used to build presets).
    pub fn uniform(mode: ApprovalMode) -> Self {
        TierPosture {
            read_only: Some(mode),
            sandbox_edit: Some(mode),
            full_access: Some(mode),
        }
    }
}

/// A named starting posture the onboarding flow offers, mapped onto per-tier
/// modes. Mirrors the host's `ApprovalDefault`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalPreset {
    /// Ask before anything beyond reading.
    Cautious,
    /// Auto-allow safe reads; ask before edits and consequential actions.
    Balanced,
    /// Let agents work; only ask for the highest-risk actions.
    Trusting,
}

/// One exact tool posture. Standing `always_allow` authority is usable only
/// when the live authenticated reverse-callback registration has this exact
/// canonical schema digest. Deny/approval-only postures need no digest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ExactToolApproval {
    pub mode: ApprovalMode,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema_digest: Option<String>,
}

impl<'de> Deserialize<'de> for ExactToolApproval {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Wire {
            Current {
                mode: ApprovalMode,
                #[serde(default)]
                schema_digest: Option<String>,
            },
            Legacy(ApprovalMode),
        }

        Ok(match Wire::deserialize(deserializer)? {
            Wire::Current {
                mode,
                schema_digest,
            } => Self {
                mode,
                schema_digest,
            },
            // A legacy name-only allow remains readable but cannot become
            // standing authority: admission requires a matching live digest.
            Wire::Legacy(mode) => Self {
                mode,
                schema_digest: None,
            },
        })
    }
}

impl ApprovalPreset {
    pub fn posture(self) -> TierPosture {
        use ApprovalMode::*;
        match self {
            ApprovalPreset::Cautious => TierPosture {
                read_only: Some(RequireApproval),
                sandbox_edit: Some(RequireApproval),
                full_access: Some(RequireApproval),
            },
            ApprovalPreset::Balanced => TierPosture {
                read_only: Some(AlwaysAllow),
                sandbox_edit: Some(RequireApproval),
                full_access: Some(RequireApproval),
            },
            ApprovalPreset::Trusting => TierPosture {
                read_only: Some(AlwaysAllow),
                sandbox_edit: Some(AlwaysAllow),
                full_access: Some(RequireApproval),
            },
        }
    }

    pub fn from_str_opt(s: &str) -> Option<ApprovalPreset> {
        match s {
            "cautious" => Some(ApprovalPreset::Cautious),
            "balanced" => Some(ApprovalPreset::Balanced),
            "trusting" => Some(ApprovalPreset::Trusting),
            _ => None,
        }
    }
}

/// The whole per-agent approval policy: a fully-specified default posture plus
/// sparse per-agent tier and exact-tool overrides.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentPermissionPolicy {
    /// Applied to any agent without a specific override. Always fully specified.
    pub default: TierPosture,
    /// Per-agent overrides, keyed by agent id. May be partial.
    #[serde(default)]
    pub agents: BTreeMap<String, TierPosture>,
    /// Exact per-agent, per-tool overrides. Both map keys are literal strings:
    /// no wildcard, prefix, regex, or tier-wide matching is performed.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub tool_overrides: BTreeMap<String, BTreeMap<String, ExactToolApproval>>,
}

impl Default for AgentPermissionPolicy {
    /// The recommended balanced default — safe reads run, edits and
    /// consequential actions ask first.
    fn default() -> Self {
        AgentPermissionPolicy {
            default: ApprovalPreset::Balanced.posture(),
            agents: BTreeMap::new(),
            tool_overrides: BTreeMap::new(),
        }
    }
}

impl AgentPermissionPolicy {
    /// The effective mode for `(agent_id, tier)`: an agent override wins, else
    /// the default, else a safe `RequireApproval` floor (never silently allow).
    pub fn resolve(&self, agent_id: &str, tier: PermissionTier) -> ApprovalMode {
        if let Some(posture) = self.agents.get(agent_id) {
            if let Some(mode) = posture.get(tier) {
                return mode;
            }
        }
        self.default
            .get(tier)
            .unwrap_or(ApprovalMode::RequireApproval)
    }

    /// The effective posture for an agent, tier-by-tier (override → default).
    pub fn effective(&self, agent_id: &str) -> TierPosture {
        TierPosture {
            read_only: Some(self.resolve(agent_id, PermissionTier::ReadOnly)),
            sandbox_edit: Some(self.resolve(agent_id, PermissionTier::SandboxEdit)),
            full_access: Some(self.resolve(agent_id, PermissionTier::FullAccess)),
        }
    }

    /// Whether an agent has any explicit override (vs. running on defaults).
    pub fn has_override(&self, agent_id: &str) -> bool {
        self.agents.contains_key(agent_id)
    }

    /// The explicit mode for an exact `(agent_id, tool)` pair, if configured.
    /// This deliberately does not fall through to tier posture resolution.
    pub fn resolve_tool(&self, agent_id: &str, tool: &str) -> Option<&ExactToolApproval> {
        self.tool_overrides
            .get(agent_id)
            .and_then(|tools| tools.get(tool))
    }

    pub fn set_tool(
        &mut self,
        agent_id: &str,
        tool: &str,
        mode: ApprovalMode,
        schema_digest: Option<String>,
    ) {
        self.tool_overrides
            .entry(agent_id.to_string())
            .or_default()
            .insert(
                tool.to_string(),
                ExactToolApproval {
                    mode,
                    schema_digest,
                },
            );
    }

    /// Drop one exact tool override. Empty per-agent maps are removed so the
    /// persisted policy remains sparse and deterministic.
    pub fn reset_tool(&mut self, agent_id: &str, tool: &str) -> bool {
        let Some(tools) = self.tool_overrides.get_mut(agent_id) else {
            return false;
        };
        let removed = tools.remove(tool).is_some();
        if tools.is_empty() {
            self.tool_overrides.remove(agent_id);
        }
        removed
    }

    pub fn set_agent(&mut self, agent_id: &str, tier: PermissionTier, mode: ApprovalMode) {
        self.agents
            .entry(agent_id.to_string())
            .or_default()
            .set(tier, mode);
    }

    /// Set every tier for an agent at once (e.g. "deny this agent entirely").
    pub fn set_agent_uniform(&mut self, agent_id: &str, mode: ApprovalMode) {
        self.agents
            .insert(agent_id.to_string(), TierPosture::uniform(mode));
    }

    pub fn set_default(&mut self, tier: PermissionTier, mode: ApprovalMode) {
        self.default.set(tier, mode);
    }

    pub fn set_default_preset(&mut self, preset: ApprovalPreset) {
        self.default = preset.posture();
    }

    /// Drop an agent's tier override so it reverts to the default posture.
    /// Exact tool overrides are independently managed by [`Self::reset_tool`].
    pub fn reset_agent(&mut self, agent_id: &str) {
        self.agents.remove(agent_id);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_is_balanced() {
        let p = AgentPermissionPolicy::default();
        assert_eq!(
            p.resolve("any", PermissionTier::ReadOnly),
            ApprovalMode::AlwaysAllow
        );
        assert_eq!(
            p.resolve("any", PermissionTier::SandboxEdit),
            ApprovalMode::RequireApproval
        );
        assert_eq!(
            p.resolve("any", PermissionTier::FullAccess),
            ApprovalMode::RequireApproval
        );
    }

    #[test]
    fn agent_override_wins_then_falls_through() {
        let mut p = AgentPermissionPolicy::default();
        // Override only full_access for one agent; other tiers fall through.
        p.set_agent("risky", PermissionTier::FullAccess, ApprovalMode::Deny);
        assert_eq!(
            p.resolve("risky", PermissionTier::FullAccess),
            ApprovalMode::Deny
        );
        assert_eq!(
            p.resolve("risky", PermissionTier::ReadOnly),
            ApprovalMode::AlwaysAllow
        );
        // A different agent is unaffected.
        assert_eq!(
            p.resolve("other", PermissionTier::FullAccess),
            ApprovalMode::RequireApproval
        );
    }

    #[test]
    fn uniform_and_reset() {
        let mut p = AgentPermissionPolicy::default();
        p.set_agent_uniform("blocked", ApprovalMode::Deny);
        assert_eq!(
            p.resolve("blocked", PermissionTier::ReadOnly),
            ApprovalMode::Deny
        );
        assert!(p.has_override("blocked"));
        p.reset_agent("blocked");
        assert!(!p.has_override("blocked"));
        assert_eq!(
            p.resolve("blocked", PermissionTier::ReadOnly),
            ApprovalMode::AlwaysAllow
        );
    }

    #[test]
    fn presets_map_as_expected() {
        assert_eq!(
            ApprovalPreset::Cautious.posture().read_only,
            Some(ApprovalMode::RequireApproval)
        );
        assert_eq!(
            ApprovalPreset::Trusting.posture().sandbox_edit,
            Some(ApprovalMode::AlwaysAllow)
        );
        assert_eq!(
            ApprovalPreset::Trusting.posture().full_access,
            Some(ApprovalMode::RequireApproval)
        );
    }

    #[test]
    fn roundtrips_through_json() {
        let mut p = AgentPermissionPolicy::default();
        p.set_agent("a", PermissionTier::SandboxEdit, ApprovalMode::AlwaysAllow);
        let json = serde_json::to_string(&p).unwrap();
        let back: AgentPermissionPolicy = serde_json::from_str(&json).unwrap();
        assert_eq!(p, back);
    }

    #[test]
    fn legacy_json_without_tool_overrides_remains_compatible() {
        let legacy = serde_json::json!({
            "default": {
                "read_only": "always_allow",
                "sandbox_edit": "require_approval",
                "full_access": "require_approval"
            },
            "agents": {}
        });
        let policy: AgentPermissionPolicy = serde_json::from_value(legacy.clone()).unwrap();

        assert_eq!(
            policy.resolve_tool("daily-continuity-newsroom", "newsroom.publish"),
            None
        );
        assert_eq!(serde_json::to_value(policy).unwrap(), legacy);
    }

    #[test]
    fn tool_overrides_match_exact_agent_and_exact_tool_only() {
        let mut policy = AgentPermissionPolicy::default();
        policy.set_tool(
            "daily-continuity-newsroom",
            "newsroom.publish",
            ApprovalMode::AlwaysAllow,
            Some("a".repeat(64)),
        );

        assert_eq!(
            policy
                .resolve_tool("daily-continuity-newsroom", "newsroom.publish")
                .map(|rule| rule.mode),
            Some(ApprovalMode::AlwaysAllow),
        );
        assert_eq!(
            policy.resolve_tool("daily-continuity-newsroom", "newsroom.publish.preview"),
            None
        );
        assert_eq!(policy.resolve_tool("other-agent", "newsroom.publish"), None);
        assert_eq!(
            policy.resolve_tool("daily-continuity-newsroom", "newsroom.*"),
            None
        );

        assert!(policy.reset_tool("daily-continuity-newsroom", "newsroom.publish"));
        assert_eq!(
            policy.resolve_tool("daily-continuity-newsroom", "newsroom.publish"),
            None
        );
        assert!(!policy.reset_tool("daily-continuity-newsroom", "newsroom.publish"));
    }

    #[test]
    fn legacy_name_only_tool_override_is_readable_but_unbound() {
        let value = serde_json::json!({
            "default": {
                "read_only": "always_allow",
                "sandbox_edit": "require_approval",
                "full_access": "require_approval"
            },
            "agents": {},
            "tool_overrides": {
                "daily-continuity-newsroom": {
                    "newsroom.publish": "always_allow"
                }
            }
        });
        let policy: AgentPermissionPolicy = serde_json::from_value(value).unwrap();
        let rule = policy
            .resolve_tool("daily-continuity-newsroom", "newsroom.publish")
            .unwrap();
        assert_eq!(rule.mode, ApprovalMode::AlwaysAllow);
        assert_eq!(rule.schema_digest, None);
    }
}