sparrow-config 0.9.2

Configuration, provider registry, auth/credential store, permissions, hooks, sandbox and humanize layer for Sparrow
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
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

use sparrow_core::event::{AutonomyLevel, Decision, RiskLevel};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum PermissionMode {
    ReadOnly,
    Plan,
    Supervised,
    Trusted,
    Autonomous,
    EmergencyStop,
}

impl PermissionMode {
    pub fn as_str(&self) -> &'static str {
        match self {
            PermissionMode::ReadOnly => "read-only",
            PermissionMode::Plan => "plan",
            PermissionMode::Supervised => "supervised",
            PermissionMode::Trusted => "trusted",
            PermissionMode::Autonomous => "autonomous",
            PermissionMode::EmergencyStop => "emergency-stop",
        }
    }

    pub fn parse(value: &str) -> Option<Self> {
        match value.trim().to_lowercase().as_str() {
            "read-only" | "readonly" | "read_only" => Some(Self::ReadOnly),
            "plan" => Some(Self::Plan),
            "supervised" => Some(Self::Supervised),
            "trusted" => Some(Self::Trusted),
            "autonomous" => Some(Self::Autonomous),
            "emergency-stop" | "emergency" | "stop" | "kill" => Some(Self::EmergencyStop),
            _ => None,
        }
    }

    pub fn autonomy_level(&self) -> AutonomyLevel {
        match self {
            PermissionMode::Autonomous => AutonomyLevel::Autonomous,
            PermissionMode::Trusted => AutonomyLevel::Trusted,
            PermissionMode::ReadOnly
            | PermissionMode::Plan
            | PermissionMode::Supervised
            | PermissionMode::EmergencyStop => AutonomyLevel::Supervised,
        }
    }
}

impl Default for PermissionMode {
    fn default() -> Self {
        Self::Supervised
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionList {
    #[serde(default)]
    pub allow: Vec<String>,
    #[serde(default)]
    pub ask: Vec<String>,
    #[serde(default)]
    pub deny: Vec<String>,
}

impl Default for PermissionList {
    fn default() -> Self {
        Self {
            allow: Vec::new(),
            ask: Vec::new(),
            deny: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PathPermissions {
    #[serde(default)]
    pub allow: Vec<PathBuf>,
    #[serde(default = "default_denied_paths")]
    pub deny: Vec<PathBuf>,
}

impl Default for PathPermissions {
    fn default() -> Self {
        Self {
            allow: Vec::new(),
            deny: default_denied_paths(),
        }
    }
}

fn default_denied_paths() -> Vec<PathBuf> {
    vec![
        PathBuf::from(".git"),
        PathBuf::from(".env"),
        PathBuf::from(".env.local"),
        PathBuf::from(".ssh"),
        PathBuf::from("id_rsa"),
        PathBuf::from("id_ed25519"),
    ]
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionConfig {
    #[serde(default)]
    pub mode: PermissionMode,
    #[serde(default)]
    pub tools: PermissionList,
    #[serde(default)]
    pub paths: PathPermissions,
    #[serde(default)]
    pub providers: PermissionList,
    #[serde(default)]
    pub surfaces: PermissionList,
    /// Per-tool persisted decisions (loaded from permissions.json).
    /// Not serialized in config.toml — stored separately.
    #[serde(skip)]
    pub store: crate::permissions::store::PermissionStore,
}

impl Default for PermissionConfig {
    fn default() -> Self {
        Self {
            mode: PermissionMode::Supervised,
            tools: PermissionList::default(),
            paths: PathPermissions::default(),
            providers: PermissionList::default(),
            surfaces: PermissionList::default(),
            store: store::PermissionStore::default(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct PermissionContext<'a> {
    pub tool_name: &'a str,
    pub risk: RiskLevel,
    pub args: &'a serde_json::Value,
    pub workspace_root: &'a Path,
    pub provider: Option<&'a str>,
    pub surface: Option<&'a str>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PermissionVerdict {
    pub decision: Decision,
    pub reason: String,
}

impl PermissionConfig {
    pub fn evaluate(&self, ctx: &PermissionContext<'_>) -> PermissionVerdict {
        // ── Check persisted per-tool decisions first ──────────────────────
        // Durable decisions (AllowAlways, Deny) survive across sessions.
        if let Some(pd) = self.store.get(ctx.tool_name) {
            if pd.is_durable() {
                return verdict(
                    pd.to_decision(),
                    format!("tool '{}' has persisted decision: {:?}", ctx.tool_name, pd),
                );
            }
        }

        if matches!(self.mode, PermissionMode::EmergencyStop) {
            return verdict(Decision::Deny, "emergency stop blocks every action");
        }

        if matches!(self.mode, PermissionMode::Plan) {
            return verdict(
                Decision::Deny,
                "plan mode is read-only and executes no tools",
            );
        }

        if matches!(self.mode, PermissionMode::ReadOnly) && ctx.risk != RiskLevel::ReadOnly {
            return verdict(
                Decision::Deny,
                "read-only permission mode blocks mutating, exec, network, and destructive tools",
            );
        }

        if matches_pattern(&self.tools.deny, ctx.tool_name) {
            return verdict(
                Decision::Deny,
                format!("tool '{}' is denied by permissions", ctx.tool_name),
            );
        }
        if matches_pattern(&self.tools.ask, ctx.tool_name) {
            return verdict(
                Decision::AskUser,
                format!("tool '{}' requires approval by permissions", ctx.tool_name),
            );
        }
        if matches_pattern(&self.tools.allow, ctx.tool_name) {
            return verdict(
                Decision::Allow,
                format!(
                    "tool '{}' is explicitly allowed by permissions",
                    ctx.tool_name
                ),
            );
        }

        if let Some(provider) = ctx.provider {
            if matches_pattern(&self.providers.deny, provider) {
                return verdict(
                    Decision::Deny,
                    format!("provider '{}' is denied by permissions", provider),
                );
            }
            if matches_pattern(&self.providers.ask, provider) {
                return verdict(
                    Decision::AskUser,
                    format!("provider '{}' requires approval by permissions", provider),
                );
            }
        }

        if let Some(surface) = ctx.surface {
            if matches_pattern(&self.surfaces.deny, surface) {
                return verdict(
                    Decision::Deny,
                    format!("surface '{}' is denied by permissions", surface),
                );
            }
            if matches_pattern(&self.surfaces.ask, surface) {
                return verdict(
                    Decision::AskUser,
                    format!("surface '{}' requires approval by permissions", surface),
                );
            }
        }

        for path in paths_from_args(ctx.args) {
            let absolute = resolve_path(ctx.workspace_root, &path);
            if self
                .paths
                .deny
                .iter()
                .any(|rule| path_matches(ctx.workspace_root, rule, &absolute))
            {
                return verdict(
                    Decision::Deny,
                    format!("path '{}' is denied by permissions", path.display()),
                );
            }
        }

        verdict(Decision::Allow, "permissions allow autonomy gate to decide")
    }
}

pub fn effective_risk_for_tool(
    tool_name: &str,
    base: RiskLevel,
    args: &serde_json::Value,
) -> RiskLevel {
    if tool_name == "exec" {
        if let Some(command) = args.get("command").and_then(|value| value.as_str()) {
            if is_forced_destructive_command(command) {
                return RiskLevel::Destructive;
            }
        }
    }
    base
}

pub fn is_forced_destructive_command(command: &str) -> bool {
    let lower = command.to_ascii_lowercase();
    let compact = lower.replace(['"', '\''], "");
    let patterns = [
        "rm -rf",
        "rm -fr",
        "del /s",
        "rmdir /s",
        "rd /s",
        "git clean -fdx",
        "git clean -xdf",
        "drop table",
    ];
    patterns.iter().any(|pattern| compact.contains(pattern))
}

fn verdict(decision: Decision, reason: impl Into<String>) -> PermissionVerdict {
    PermissionVerdict {
        decision,
        reason: reason.into(),
    }
}

fn matches_pattern(patterns: &[String], value: &str) -> bool {
    patterns.iter().any(|pattern| {
        let pattern = pattern.trim();
        pattern == "*"
            || pattern.eq_ignore_ascii_case(value)
            || value
                .to_lowercase()
                .contains(pattern.trim_matches('*').to_lowercase().as_str())
    })
}

fn paths_from_args(args: &serde_json::Value) -> Vec<PathBuf> {
    let mut paths = Vec::new();
    collect_paths(args, &mut paths);
    paths
}

fn collect_paths(value: &serde_json::Value, paths: &mut Vec<PathBuf>) {
    match value {
        serde_json::Value::Object(map) => {
            for (key, value) in map {
                let key = key.to_lowercase();
                let pathish = matches!(
                    key.as_str(),
                    "path" | "file" | "filename" | "target" | "source" | "dest" | "destination"
                ) || key.ends_with("_path")
                    || key.ends_with("_file");
                if pathish {
                    if let Some(text) = value.as_str() {
                        paths.push(PathBuf::from(text));
                    }
                }
                collect_paths(value, paths);
            }
        }
        serde_json::Value::Array(items) => {
            for item in items {
                collect_paths(item, paths);
            }
        }
        _ => {}
    }
}

fn resolve_path(root: &Path, path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        root.join(path)
    }
}

fn path_matches(root: &Path, rule: &Path, candidate: &Path) -> bool {
    let rule = resolve_path(root, rule);
    let rule_text = normalize_path(&rule);
    let candidate_text = normalize_path(candidate);
    candidate_text == rule_text || candidate_text.starts_with(&(rule_text + "/"))
}

fn normalize_path(path: &Path) -> String {
    path.components()
        .map(|c| c.as_os_str().to_string_lossy().replace('\\', "/"))
        .collect::<Vec<_>>()
        .join("/")
        .to_lowercase()
}

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

    #[test]
    fn read_only_blocks_mutating_tools() {
        let cfg = PermissionConfig {
            mode: PermissionMode::ReadOnly,
            ..PermissionConfig::default()
        };
        let verdict = cfg.evaluate(&PermissionContext {
            tool_name: "edit",
            risk: RiskLevel::Mutating,
            args: &serde_json::json!({"path":"src/main.rs"}),
            workspace_root: Path::new("/home/dev/project"),
            provider: None,
            surface: Some("cli"),
        });
        assert_eq!(verdict.decision, Decision::Deny);
    }

    #[test]
    fn denied_sensitive_paths_win() {
        let cfg = PermissionConfig::default();
        let verdict = cfg.evaluate(&PermissionContext {
            tool_name: "fs_write",
            risk: RiskLevel::Mutating,
            args: &serde_json::json!({"path":".git/config"}),
            workspace_root: Path::new("/home/dev/project"),
            provider: None,
            surface: None,
        });
        assert_eq!(verdict.decision, Decision::Deny);
    }

    #[test]
    fn ask_tool_requires_user() {
        let mut cfg = PermissionConfig::default();
        cfg.tools.ask.push("exec".into());
        let verdict = cfg.evaluate(&PermissionContext {
            tool_name: "exec",
            risk: RiskLevel::Exec,
            args: &serde_json::json!({"cmd":"cargo test"}),
            workspace_root: Path::new("/home/dev/project"),
            provider: None,
            surface: None,
        });
        assert_eq!(verdict.decision, Decision::AskUser);
    }

    #[test]
    fn exec_dangerous_command_escalates_to_destructive() {
        let risk = effective_risk_for_tool(
            "exec",
            RiskLevel::Exec,
            &serde_json::json!({"command":"git clean -fdx"}),
        );
        assert_eq!(risk, RiskLevel::Destructive);
        assert!(is_forced_destructive_command("DROP TABLE users"));
        assert!(is_forced_destructive_command("rmdir /s target"));
        assert!(!is_forced_destructive_command("cargo test --all-targets"));
    }
}
pub mod store;