agentsec-core 0.1.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
//! Plain Mode — temporarily disable MCP servers by renaming `.mcp.json`
//! files to `.mcp.json.suspect` and (optionally) writing an empty stub in
//! their place.
//!
//! ## When to use it
//!
//! User suspects a newly-installed MCP server is malicious and wants to
//! start a clean Agent session **right now**, without manually editing
//! configs. `agentsec plain enable` renames targets to `.suspect`; the
//! Agent then starts with an empty MCP world. `agentsec plain restore`
//! puts everything back.
//!
//! ## What gets renamed
//!
//! Plain Mode only touches **standalone `.mcp.json` files**. It never
//! edits `.claude.json` directly, because that file mixes MCP server
//! config with hooks / permissions / per-project state that we don't
//! want to wipe.
//!
//! Default target: `<cwd>/.mcp.json`. Callers can pass additional
//! absolute paths (typically per-project `.mcp.json` discovered from a
//! scan).
//!
//! ## Ledger
//!
//! [`PLAIN_LEDGER_FILENAME`] under [`crate::Paths::home`] tracks which
//! files were renamed so [`restore`] can put them back. The ledger
//! existing with non-empty `entries` is the canonical signal that Plain
//! Mode is active.
//!
//! ## Invariants
//!
//! - [`enable`] is **idempotent within a session**: if the target's
//!   `.suspect` sibling already exists, enable skips that target (and
//!   reports the skip) rather than clobbering the prior backup.
//! - [`restore`] removes the ledger on success. Repeat calls with an
//!   absent ledger are no-ops.
//! - Dry-run mode performs zero filesystem mutation and returns the same
//!   shape of result so callers can preview.

use std::fs;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::Paths;
use crate::error::Result;

/// Filename of the ledger file under [`Paths::home`].
pub const PLAIN_LEDGER_FILENAME: &str = "plain-mode.json";

/// Suffix appended to a renamed file (so `.mcp.json` becomes
/// `.mcp.json.suspect`).
pub const SUSPECT_SUFFIX: &str = ".suspect";

/// Content of the stub written at the original path while Plain Mode is
/// active. Empty MCP world; the Agent sees zero servers configured.
pub const PLAIN_STUB_BODY: &str = "{\n  \"mcpServers\": {}\n}\n";

/// One row in the persisted ledger.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LedgerEntry {
    /// Original absolute path of the renamed file (the one the Agent
    /// reads). After `enable`, a stub lives here.
    pub original: PathBuf,
    /// `<original><SUSPECT_SUFFIX>` — where the real file was moved to.
    pub suspect: PathBuf,
    /// `true` if a plain-config stub was written at `original` during
    /// enable (the common case; `false` only when the caller asked to
    /// skip stub creation).
    pub stub_created: bool,
}

/// Full ledger persisted to [`PLAIN_LEDGER_FILENAME`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PlainLedger {
    /// All ledger entries, in enable order.
    pub entries: Vec<LedgerEntry>,
}

/// One row of [`enable`]'s outcome.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct EnableRow {
    /// Original path the caller asked us to disable.
    pub original: PathBuf,
    /// Action actually taken for this target.
    pub action: EnableAction,
}

/// Outcome variants for a single target.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum EnableAction {
    /// File was renamed to `<original>.suspect` and a stub was written
    /// at `original`.
    Renamed,
    /// File was renamed to `<original>.suspect` and **no** stub was
    /// written (caller opted out).
    RenamedNoStub,
    /// `<original>.suspect` already existed; we did nothing to avoid
    /// clobbering a prior backup.
    SkippedAlreadySuspect,
    /// `original` does not exist; nothing to disable.
    SkippedMissing,
    /// `--dry-run`: would have renamed, but didn't.
    WouldRename,
    /// `--dry-run`: would have skipped (one of the Skipped reasons).
    WouldSkip { reason: String },
}

/// Outcome of [`enable`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnableOutcome {
    /// Per-target action log.
    pub rows: Vec<EnableRow>,
    /// `true` when the call ran without `dry_run`.
    pub applied: bool,
    /// Ledger path that was (or would be) written.
    pub ledger_path: PathBuf,
}

/// One row of [`restore`]'s outcome.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RestoreRow {
    /// The `original` path from the ledger.
    pub original: PathBuf,
    /// Action actually taken.
    pub action: RestoreAction,
}

/// Outcome variants for restoring a single ledger entry.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum RestoreAction {
    /// `<original>.suspect` was renamed back to `original`. Any stub
    /// previously at `original` was overwritten.
    Restored,
    /// The `.suspect` file was not found; the ledger entry is stale.
    SuspectMissing,
    /// `--dry-run`: would have restored.
    WouldRestore,
    /// `--dry-run`: would have skipped (suspect missing).
    WouldSkip { reason: String },
}

/// Outcome of [`restore`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RestoreOutcome {
    /// Per-entry action log.
    pub rows: Vec<RestoreRow>,
    /// `true` when the call ran without `dry_run`.
    pub applied: bool,
    /// Ledger path that was (or would be) removed.
    pub ledger_path: PathBuf,
}

/// Resolved Plain Mode status — what the on-disk ledger says right now.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlainStatus {
    /// `true` when the ledger exists and has at least one entry.
    pub active: bool,
    /// All ledger entries (empty when `active == false`).
    pub entries: Vec<LedgerEntry>,
    /// Ledger path that was read (whether or not it exists).
    pub ledger_path: PathBuf,
}

/// Read [`PlainStatus`] from disk.
///
/// # Errors
///
/// - [`crate::Error::Io`] on ledger read failure.
/// - [`crate::Error::Json`] on ledger parse failure.
pub fn status(paths: &Paths) -> Result<PlainStatus> {
    let ledger_path = paths.home.join(PLAIN_LEDGER_FILENAME);
    let entries = if ledger_path.exists() {
        let body = fs::read_to_string(&ledger_path)?;
        serde_json::from_str::<PlainLedger>(&body)?.entries
    } else {
        Vec::new()
    };
    Ok(PlainStatus {
        active: !entries.is_empty(),
        entries,
        ledger_path,
    })
}

/// Enable Plain Mode for the given target paths.
///
/// Each target is processed independently; failures on one target don't
/// abort the others (they get a `Skipped*` action in the outcome). The
/// ledger is written only after every target has been processed and only
/// when `dry_run` is false.
///
/// # Errors
///
/// - [`crate::Error::Io`] on ledger directory creation or write failure.
/// - [`crate::Error::Json`] on ledger serialization failure.
pub fn enable(
    paths: &Paths,
    targets: &[PathBuf],
    dry_run: bool,
    write_stub: bool,
) -> Result<EnableOutcome> {
    let ledger_path = paths.home.join(PLAIN_LEDGER_FILENAME);
    let mut rows = Vec::with_capacity(targets.len());
    let mut new_entries = Vec::new();

    for target in targets {
        let suspect = suspect_path(target);
        let action = if !target.exists() {
            if dry_run {
                EnableAction::WouldSkip {
                    reason: "target does not exist".into(),
                }
            } else {
                EnableAction::SkippedMissing
            }
        } else if suspect.exists() {
            if dry_run {
                EnableAction::WouldSkip {
                    reason: "suspect backup already present".into(),
                }
            } else {
                EnableAction::SkippedAlreadySuspect
            }
        } else if dry_run {
            EnableAction::WouldRename
        } else {
            fs::rename(target, &suspect)?;
            if write_stub {
                fs::write(target, PLAIN_STUB_BODY)?;
            }
            new_entries.push(LedgerEntry {
                original: target.clone(),
                suspect: suspect.clone(),
                stub_created: write_stub,
            });
            if write_stub {
                EnableAction::Renamed
            } else {
                EnableAction::RenamedNoStub
            }
        };
        rows.push(EnableRow {
            original: target.clone(),
            action,
        });
    }

    if !dry_run && !new_entries.is_empty() {
        fs::create_dir_all(&paths.home)?;
        // Merge with any prior ledger so we don't lose earlier entries
        // (idempotent enable across sessions).
        let mut ledger = if ledger_path.exists() {
            let body = fs::read_to_string(&ledger_path)?;
            serde_json::from_str::<PlainLedger>(&body).unwrap_or_default()
        } else {
            PlainLedger::default()
        };
        ledger.entries.extend(new_entries);
        let body = serde_json::to_string_pretty(&ledger)?;
        fs::write(&ledger_path, body)?;
    }

    Ok(EnableOutcome {
        rows,
        applied: !dry_run,
        ledger_path,
    })
}

/// Restore everything in the ledger.
///
/// For each entry: rename `suspect` back to `original` (overwriting any
/// stub that lived there), then drop the entry. Entries whose suspect
/// file is missing are surfaced as `SuspectMissing` but don't abort the
/// rest. On success the ledger file is removed.
///
/// # Errors
///
/// - [`crate::Error::Io`] on rename / write / delete failure.
/// - [`crate::Error::Json`] on ledger parse failure.
pub fn restore(paths: &Paths, dry_run: bool) -> Result<RestoreOutcome> {
    let ledger_path = paths.home.join(PLAIN_LEDGER_FILENAME);
    if !ledger_path.exists() {
        return Ok(RestoreOutcome {
            rows: Vec::new(),
            applied: !dry_run,
            ledger_path,
        });
    }

    let body = fs::read_to_string(&ledger_path)?;
    let ledger: PlainLedger = serde_json::from_str(&body)?;
    let mut rows = Vec::with_capacity(ledger.entries.len());

    for entry in &ledger.entries {
        let action = if !entry.suspect.exists() {
            if dry_run {
                RestoreAction::WouldSkip {
                    reason: "suspect file missing".into(),
                }
            } else {
                RestoreAction::SuspectMissing
            }
        } else if dry_run {
            RestoreAction::WouldRestore
        } else {
            // Remove any stub / file currently at `original` so the rename
            // below succeeds on platforms that don't overwrite atomically.
            if entry.original.exists() {
                fs::remove_file(&entry.original)?;
            }
            fs::rename(&entry.suspect, &entry.original)?;
            RestoreAction::Restored
        };
        rows.push(RestoreRow {
            original: entry.original.clone(),
            action,
        });
    }

    if !dry_run {
        fs::remove_file(&ledger_path)?;
    }

    Ok(RestoreOutcome {
        rows,
        applied: !dry_run,
        ledger_path,
    })
}

/// Compute the suspect-sidecar path for a given original path.
fn suspect_path(original: &Path) -> PathBuf {
    let mut s = original.as_os_str().to_os_string();
    s.push(SUSPECT_SUFFIX);
    PathBuf::from(s)
}

/// Default Plain Mode targets — currently just `<cwd>/.mcp.json`.
/// Callers can extend this list with their own absolute paths.
pub fn default_targets() -> Vec<PathBuf> {
    vec![PathBuf::from(".mcp.json")]
}

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

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

    fn write(p: &Path, body: &str) {
        std::fs::write(p, body).unwrap();
    }

    #[test]
    fn enable_dry_run_does_not_touch_filesystem() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join(".mcp.json");
        write(&target, "{\"mcpServers\":{\"x\":1}}");
        let original_body = std::fs::read_to_string(&target).unwrap();

        let outcome = enable(&paths_for(&tmp), &[target.clone()], true, true).unwrap();
        assert!(!outcome.applied);
        assert_eq!(outcome.rows[0].action, EnableAction::WouldRename);
        // Original file untouched, suspect not created, no ledger.
        assert!(target.exists());
        assert_eq!(std::fs::read_to_string(&target).unwrap(), original_body);
        assert!(!suspect_path(&target).exists());
        assert!(!outcome.ledger_path.exists());
    }

    #[test]
    fn enable_renames_and_writes_stub() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join(".mcp.json");
        write(
            &target,
            "{\"mcpServers\":{\"original\":{\"command\":\"x\"}}}",
        );
        let suspect = suspect_path(&target);

        let outcome = enable(&paths_for(&tmp), &[target.clone()], false, true).unwrap();
        assert!(outcome.applied);
        assert_eq!(outcome.rows[0].action, EnableAction::Renamed);
        assert!(suspect.exists(), "suspect file must be created");
        assert!(target.exists(), "stub must be at original path");
        let stub = std::fs::read_to_string(&target).unwrap();
        assert_eq!(stub, PLAIN_STUB_BODY);
        assert!(outcome.ledger_path.exists());
    }

    #[test]
    fn enable_skips_when_suspect_already_present() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join(".mcp.json");
        write(&target, "{}");
        write(&suspect_path(&target), "prior-backup");

        let outcome = enable(&paths_for(&tmp), &[target.clone()], false, true).unwrap();
        assert_eq!(outcome.rows[0].action, EnableAction::SkippedAlreadySuspect);
        // The prior suspect must NOT be overwritten.
        assert_eq!(
            std::fs::read_to_string(suspect_path(&target)).unwrap(),
            "prior-backup"
        );
        // No ledger row was added (since nothing happened).
        assert!(!outcome.ledger_path.exists());
    }

    #[test]
    fn restore_round_trip_returns_original_content() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join(".mcp.json");
        let body = "{\"mcpServers\":{\"real\":{\"command\":\"x\"}}}";
        write(&target, body);

        enable(&paths_for(&tmp), &[target.clone()], false, true).unwrap();
        assert_ne!(std::fs::read_to_string(&target).unwrap(), body);

        let restore_outcome = restore(&paths_for(&tmp), false).unwrap();
        assert!(restore_outcome.applied);
        assert_eq!(restore_outcome.rows[0].action, RestoreAction::Restored);
        // Original content is back, ledger gone.
        assert_eq!(std::fs::read_to_string(&target).unwrap(), body);
        assert!(!suspect_path(&target).exists());
        assert!(!restore_outcome.ledger_path.exists());
    }

    #[test]
    fn status_reflects_ledger_state() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join(".mcp.json");
        write(&target, "{}");

        let before = status(&paths_for(&tmp)).unwrap();
        assert!(!before.active);
        assert!(before.entries.is_empty());

        enable(&paths_for(&tmp), &[target.clone()], false, true).unwrap();
        let during = status(&paths_for(&tmp)).unwrap();
        assert!(during.active);
        assert_eq!(during.entries.len(), 1);
        assert_eq!(during.entries[0].original, target);

        restore(&paths_for(&tmp), false).unwrap();
        let after = status(&paths_for(&tmp)).unwrap();
        assert!(!after.active);
        assert!(after.entries.is_empty());
    }

    #[test]
    fn restore_with_no_ledger_is_a_noop() {
        let tmp = tempfile::tempdir().unwrap();
        let outcome = restore(&paths_for(&tmp), false).unwrap();
        assert!(outcome.rows.is_empty());
        // No error, no ledger left behind.
        assert!(!outcome.ledger_path.exists());
    }

    #[test]
    fn missing_target_yields_skipped_missing() {
        let tmp = tempfile::tempdir().unwrap();
        let outcome = enable(
            &paths_for(&tmp),
            &[tmp.path().join("not-there.json")],
            false,
            true,
        )
        .unwrap();
        assert_eq!(outcome.rows[0].action, EnableAction::SkippedMissing);
        assert!(!outcome.ledger_path.exists());
    }
}