agentsec-core 0.3.0

AgentSec core library — scan / web / paste logic, pure Rust
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Installer / uninstaller for AgentSec.
//!
//! Patches `~/.claude.json` (MCP entry) and `~/.claude/settings.json` (hooks).
//! All public functions accept [`Paths`] so tests can redirect paths via the
//! standard env-override mechanism.
//!
//! ## Dry-run default
//!
//! Both [`install`] and [`uninstall`] accept a `plan` with an `apply: bool`
//! field. When `apply` is `false` (the default) the functions compute what
//! *would* change and return a report, but no file is written and no backup
//! is created. Real writes only happen when `apply` is `true`.

use std::path::PathBuf;

use serde_json::Value;

use crate::config::Paths;
use crate::error::{Error, Result};

pub(crate) mod backup;
pub(crate) mod hooks;
pub(crate) mod mcp;

// ── public types ──────────────────────────────────────────────────────────────

/// Scope for the MCP entry and hook install.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstallScope {
    /// User-level scope: `~/.claude.json:mcpServers.agentsec`.
    User,
    /// Project-level scope: `~/.claude.json:projects.<cwd>.mcpServers.agentsec`.
    Project,
}

/// Parameters for an install operation.
#[derive(Debug, Clone)]
pub struct InstallPlan {
    /// Where to register the MCP entry.
    pub scope: InstallScope,
    /// Optional path to a `.env` file passed as `AGENTSEC_DOTENV` env var in
    /// the MCP entry.
    pub dotenv: Option<PathBuf>,
    /// Whether to register the hook entries in `~/.claude/settings.json`.
    pub with_hooks: bool,
    /// Overwrite existing entries even if they already exist.
    pub force: bool,
    /// If `false` (default), compute changes but do not write any files.
    /// Set `true` to apply mutations.
    pub apply: bool,
}

/// Parameters for an uninstall operation.
#[derive(Debug, Clone)]
pub struct UninstallPlan {
    /// Which scope's MCP entry to remove.
    pub scope: InstallScope,
    /// If `true`, leave the MCP entry in `~/.claude.json` intact.
    pub keep_mcp: bool,
    /// If `true`, leave the hook entries in `~/.claude/settings.json` intact.
    pub keep_hooks: bool,
    /// If `false` (default), compute changes but do not write any files.
    pub apply: bool,
}

/// Kind of change produced by an install/uninstall operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChangeKind {
    /// The entry was created fresh.
    Added,
    /// An existing entry was replaced (force mode).
    Updated,
    /// The entry was deleted.
    Removed,
    /// No change was needed (idempotent).
    NoOp,
}

/// A single file-level mutation.
#[derive(Debug, Clone)]
pub struct MutationChange {
    /// The file that was (or would be) modified.
    pub target: PathBuf,
    /// Kind of change.
    pub kind: ChangeKind,
    /// Human-readable description.
    pub description: String,
}

/// Report returned by [`install`] or [`uninstall`].
#[derive(Debug, Clone)]
pub struct InstallReport {
    /// Change to `~/.claude.json` (MCP entry), if any.
    pub mcp_change: Option<MutationChange>,
    /// Changes to `~/.claude/settings.json` (hooks), one per hook event.
    pub hooks_changes: Vec<MutationChange>,
    /// Paths of backup files created (`apply` mode only; dry-run leaves this
    /// empty).
    pub backups: Vec<PathBuf>,
    /// Whether the plan was applied (`apply = true`).
    pub applied: bool,
}

// ── public API ────────────────────────────────────────────────────────────────

/// Install AgentSec by patching `~/.claude.json` and optionally
/// `~/.claude/settings.json`.
///
/// When `plan.apply` is `false` (the default), no files are written; the
/// returned [`InstallReport`] describes what *would* happen.
pub fn install(paths: &Paths, plan: &InstallPlan) -> Result<InstallReport> {
    let mcp_path = paths.user_home.join(".claude.json");
    let hooks_path = paths.user_home.join(".claude/settings.json");

    // ── MCP entry ──
    let mut mcp_root = load_json_or_empty(&mcp_path)?;
    let mcp_kind = mcp::add_mcp_entry(
        &mut mcp_root,
        plan.scope,
        plan.dotenv.as_deref(),
        plan.force,
    );
    let mcp_change = Some(MutationChange {
        target: mcp_path.clone(),
        kind: mcp_kind.clone(),
        description: format!("MCP entry (scope={:?}): {:?}", plan.scope, mcp_kind),
    });

    // ── Hooks ──
    let mut hooks_root = if plan.with_hooks {
        load_json_or_empty(&hooks_path)?
    } else {
        Value::Null
    };
    let raw_hook_kinds = if plan.with_hooks {
        hooks::add_hooks(&mut hooks_root, plan.force)
    } else {
        vec![]
    };
    let hook_names = ["user-prompt-submit", "session-start"];
    let hooks_changes: Vec<MutationChange> = raw_hook_kinds
        .into_iter()
        .enumerate()
        .map(|(i, kind)| {
            let name = hook_names.get(i).copied().unwrap_or("unknown");
            MutationChange {
                target: hooks_path.clone(),
                kind: kind.clone(),
                description: format!("hook `agentsec hook {name}`: {kind:?}"),
            }
        })
        .collect();

    // ── Apply ──
    //
    // Per-target NoOp skip: if the only change for a file is `NoOp`,
    // skip both the backup and the write — there is literally nothing
    // to persist, and creating an `.bak.<epoch>` of an unchanged file
    // just litters the home dir on every dry-run-becomes-real run.
    let mcp_dirty = mcp_kind != ChangeKind::NoOp;
    let hooks_dirty = hooks_changes.iter().any(|c| c.kind != ChangeKind::NoOp);

    let mut backups = Vec::new();
    if plan.apply {
        // MCP
        if mcp_dirty {
            let bak = backup::backup(&mcp_path)?;
            if !bak.as_os_str().is_empty() {
                backups.push(bak);
            }
            write_json(&mcp_path, &mcp_root)?;
        }

        // Hooks
        if plan.with_hooks && hooks_dirty {
            // Ensure parent dir exists.
            if let Some(parent) = hooks_path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            let bak = backup::backup(&hooks_path)?;
            if !bak.as_os_str().is_empty() {
                backups.push(bak);
            }
            write_json(&hooks_path, &hooks_root)?;
        }
    }

    Ok(InstallReport {
        mcp_change,
        hooks_changes,
        backups,
        applied: plan.apply,
    })
}

/// Uninstall AgentSec by removing entries from `~/.claude.json` and
/// `~/.claude/settings.json`.
///
/// When `plan.apply` is `false`, no files are written.
pub fn uninstall(paths: &Paths, plan: &UninstallPlan) -> Result<InstallReport> {
    let mcp_path = paths.user_home.join(".claude.json");
    let hooks_path = paths.user_home.join(".claude/settings.json");

    // ── MCP entry ──
    let mcp_change = if plan.keep_mcp {
        None
    } else {
        let mut mcp_root = load_json_or_empty(&mcp_path)?;
        let kind = mcp::remove_mcp_entry(&mut mcp_root, plan.scope);
        Some((
            mcp_root,
            MutationChange {
                target: mcp_path.clone(),
                kind: kind.clone(),
                description: format!("MCP entry (scope={:?}): {:?}", plan.scope, kind),
            },
        ))
    };

    // ── Hooks ──
    let hooks_result = if plan.keep_hooks {
        None
    } else {
        let mut hooks_root = load_json_or_empty(&hooks_path)?;
        let raw_kinds = hooks::remove_hooks(&mut hooks_root);
        Some((hooks_root, raw_kinds))
    };

    let hook_names = ["user-prompt-submit", "session-start"];
    let hooks_changes: Vec<MutationChange> = hooks_result
        .as_ref()
        .map(|(_, kinds)| {
            kinds
                .iter()
                .enumerate()
                .map(|(i, kind)| {
                    let name = hook_names.get(i).copied().unwrap_or("unknown");
                    MutationChange {
                        target: hooks_path.clone(),
                        kind: kind.clone(),
                        description: format!("hook `agentsec hook {name}`: {kind:?}"),
                    }
                })
                .collect()
        })
        .unwrap_or_default();

    let mcp_change_report = mcp_change.as_ref().map(|(_, c)| c.clone());

    // ── Apply ──
    //
    // Per-target NoOp skip (parallel to `install`): when the only
    // change for a target is `NoOp`, skip both backup and write —
    // otherwise re-running `uninstall --apply` on an already-clean
    // host produces a `.bak.<epoch>` of an unchanged file every time.
    let mcp_dirty = mcp_change
        .as_ref()
        .is_some_and(|(_, c)| c.kind != ChangeKind::NoOp);
    let hooks_dirty = hooks_changes.iter().any(|c| c.kind != ChangeKind::NoOp);

    let mut backups = Vec::new();
    if plan.apply {
        if mcp_dirty && let Some((mcp_root, _)) = &mcp_change {
            let bak = backup::backup(&mcp_path)?;
            if !bak.as_os_str().is_empty() {
                backups.push(bak);
            }
            write_json(&mcp_path, mcp_root)?;
        }
        if hooks_dirty && let Some((hooks_root, _)) = &hooks_result {
            let bak = backup::backup(&hooks_path)?;
            if !bak.as_os_str().is_empty() {
                backups.push(bak);
            }
            write_json(&hooks_path, hooks_root)?;
        }
    }

    Ok(InstallReport {
        mcp_change: mcp_change_report,
        hooks_changes,
        backups,
        applied: plan.apply,
    })
}

// ── private helpers ───────────────────────────────────────────────────────────

fn load_json_or_empty(path: &std::path::Path) -> Result<Value> {
    if !path.exists() {
        return Ok(Value::Object(serde_json::Map::new()));
    }
    let body = std::fs::read_to_string(path)?;
    if body.trim().is_empty() {
        return Ok(Value::Object(serde_json::Map::new()));
    }
    serde_json::from_str(&body)
        .map_err(|e| Error::Installer(format!("JSON parse error in {}: {e}", path.display())))
}

fn write_json(path: &std::path::Path, value: &Value) -> Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let content = serde_json::to_string_pretty(value)?;
    std::fs::write(path, content)?;
    Ok(())
}

// ── unit tests ────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::LlmConfig;
    use crate::{Config, Paths};
    use tempfile::TempDir;

    fn test_paths(tmp: &TempDir) -> Paths {
        Paths {
            home: tmp.path().to_path_buf(),
            user_home: tmp.path().to_path_buf(),
        }
    }

    fn test_cfg(tmp: &TempDir) -> Config {
        Config {
            paths: test_paths(tmp),
            llm: LlmConfig {
                api_key: None,
                model: "claude-sonnet-4-5".to_string(),
            },
            paste: crate::config::PasteConfig::default(),
            web: crate::config::WebConfig::default(),
            dotenv_path: None,
        }
    }

    #[test]
    fn install_dry_run_no_file_mutation() {
        let tmp = TempDir::new().unwrap();
        let paths = test_paths(&tmp);
        let plan = InstallPlan {
            scope: InstallScope::User,
            dotenv: None,
            with_hooks: true,
            force: false,
            apply: false,
        };
        let report = install(&paths, &plan).unwrap();
        assert!(!report.applied);
        assert!(report.backups.is_empty());
        // No files written
        assert!(!tmp.path().join(".claude.json").exists());
        assert!(!tmp.path().join(".claude/settings.json").exists());
    }

    #[test]
    fn install_apply_creates_files() {
        let tmp = TempDir::new().unwrap();
        let paths = test_paths(&tmp);
        let plan = InstallPlan {
            scope: InstallScope::User,
            dotenv: None,
            with_hooks: true,
            force: false,
            apply: true,
        };
        let report = install(&paths, &plan).unwrap();
        assert!(report.applied);
        assert!(tmp.path().join(".claude.json").exists());
        assert!(tmp.path().join(".claude/settings.json").exists());
        // Verify MCP entry
        let mcp_content = std::fs::read_to_string(tmp.path().join(".claude.json")).unwrap();
        let mcp_json: Value = serde_json::from_str(&mcp_content).unwrap();
        assert!(mcp_json["mcpServers"]["agentsec"].is_object());
    }

    #[test]
    fn install_twice_is_idempotent() {
        let tmp = TempDir::new().unwrap();
        let paths = test_paths(&tmp);
        let plan = InstallPlan {
            scope: InstallScope::User,
            dotenv: None,
            with_hooks: true,
            force: false,
            apply: true,
        };
        install(&paths, &plan).unwrap();
        install(&paths, &plan).unwrap();

        let hooks_content =
            std::fs::read_to_string(tmp.path().join(".claude/settings.json")).unwrap();
        let hooks_json: Value = serde_json::from_str(&hooks_content).unwrap();
        // Should still have exactly 1 entry per event.
        let ups_len = hooks_json["hooks"]["UserPromptSubmit"]
            .as_array()
            .map_or(0, Vec::len);
        assert_eq!(ups_len, 1, "should not duplicate hook entries");
    }

    #[test]
    fn install_apply_creates_backup_when_file_existed() {
        let tmp = TempDir::new().unwrap();
        let paths = test_paths(&tmp);
        // Pre-create target files.
        std::fs::write(tmp.path().join(".claude.json"), "{}").unwrap();
        std::fs::create_dir_all(tmp.path().join(".claude")).unwrap();
        std::fs::write(tmp.path().join(".claude/settings.json"), "{}").unwrap();

        let plan = InstallPlan {
            scope: InstallScope::User,
            dotenv: None,
            with_hooks: true,
            force: false,
            apply: true,
        };
        let report = install(&paths, &plan).unwrap();
        assert_eq!(report.backups.len(), 2, "should create 2 backups");
        for bak in &report.backups {
            assert!(bak.exists());
        }
    }

    #[test]
    fn install_apply_skips_backup_when_all_changes_are_noop() {
        // Idempotency check: after a successful first apply, a second
        // apply against the same home dir should produce ChangeKind::NoOp
        // for every target and therefore skip backup creation entirely.
        // Without this skip, every re-run would litter the home with
        // an `.bak.<epoch>` of an unchanged file.
        let tmp = TempDir::new().unwrap();
        let paths = test_paths(&tmp);
        let plan = InstallPlan {
            scope: InstallScope::User,
            dotenv: None,
            with_hooks: true,
            force: false,
            apply: true,
        };
        // First apply: creates the files (backup count = 0 because
        // files didn't pre-exist; that's the existing semantics).
        let first = install(&paths, &plan).unwrap();
        assert!(first.applied);
        // Second apply: all NoOp, so no backup should be produced.
        let second = install(&paths, &plan).unwrap();
        assert!(second.applied);
        assert_eq!(
            second.mcp_change.as_ref().unwrap().kind,
            super::ChangeKind::NoOp
        );
        assert!(
            second
                .hooks_changes
                .iter()
                .all(|c| c.kind == super::ChangeKind::NoOp),
            "all hooks must report NoOp on second apply"
        );
        assert_eq!(
            second.backups.len(),
            0,
            "second apply must not create backups when nothing changes"
        );
    }

    #[test]
    fn uninstall_apply_skips_backup_when_nothing_to_remove() {
        // Re-running `uninstall --apply` on an already-clean host should
        // be a no-op: no backup, no write.
        let tmp = TempDir::new().unwrap();
        let paths = test_paths(&tmp);
        // Pre-create empty target files so load_json_or_empty succeeds
        // but contains nothing to remove.
        std::fs::write(tmp.path().join(".claude.json"), "{}").unwrap();
        std::fs::create_dir_all(tmp.path().join(".claude")).unwrap();
        std::fs::write(tmp.path().join(".claude/settings.json"), "{}").unwrap();

        let plan = UninstallPlan {
            scope: InstallScope::User,
            keep_mcp: false,
            keep_hooks: false,
            apply: true,
        };
        let report = uninstall(&paths, &plan).unwrap();
        assert!(report.applied);
        assert_eq!(
            report.mcp_change.as_ref().unwrap().kind,
            super::ChangeKind::NoOp
        );
        assert!(
            report
                .hooks_changes
                .iter()
                .all(|c| c.kind == super::ChangeKind::NoOp)
        );
        assert_eq!(
            report.backups.len(),
            0,
            "uninstall on clean host must not create backups"
        );
    }

    // Config helper (used by test_cfg above but needs to compile).
    #[allow(dead_code)]
    fn _use_cfg(tmp: &TempDir) {
        let _ = test_cfg(tmp);
    }
}