feat: audit_run, audit_cancel and pipdock audit

The Security tab's core reaches both heads. `AuditReport` joins `SCHEMA_TYPES`, which
is the six-place change the P1-A record describes — including `golden.rs`'s own copy of
the list, a new `golden__schema-AuditReport.snap`, and the expected churn in
`golden__schema-unknown-type.snap`, whose error message enumerates every known type.

`audit_run` takes the freeze itself, through the configured engine, because that choice
changes what is audited: pip is invoked with `--all` and includes pip and setuptools,
uv has no such flag. The real run makes that concrete — auditing the SP-4 environment
reports **five advisories in pip 25.0.1** alongside urllib3's eight, which a uv-engine
audit of the same environment would not see. The store guard is read and dropped before
any subprocess.

`AppState.audit` is `Sessions<()>`: nothing is parked, because an audit hands its report
straight back with no second call consuming it the way `health_fix` consumes a
`HealthSession`. What the slot is for is the **token**, which lives beside it so
`audit_cancel` can reach a run the slot no longer owns. Its own slot rather than
health's, for the reason health's is not `sessions` — an audit touches no environment,
so refusing it while Code Health runs would be a lock with no invariant behind it.

`pipdock audit` exits **1 on findings**, as `health` does: an advisory is a result, not
a failure, and a script wants to branch on it. A tool problem outranks the findings, so
a report that is empty because pip-audit never ran cannot exit 0 and read as "nothing
wrong here".

**Run rather than asserted.** Cold, against `spikes/out/target-env` with an isolated
`LOCALAPPDATA`: the audit venv bootstrapped, wrote its manifest, and reported 13
advisories across 2 packages; `--json` emitted **one** camelCase document with
`toolVersion` read back out of that manifest, and exit was 1. The second run did no
bootstrap at all, which is `needs_sync` returning `Fresh` for `AUDIT_TOOLS` — the half
of the venv split that only a warm second run can show.

Two hand-maintained lists were a row short and are not now: ARCHITECTURE §7, which the
new drift test demanded before it would pass, and `golden.rs`'s per-command help list,
which nothing polices — so `help-audit.snap` exists rather than the subcommand's help
going unpinned.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5 committed 2026-08-18 10:55:11 +07:00
1 parent 3463ff8d76
commit 2c6670a336
15 files changed
+714 -2

No files matched your search

+4
View File
@@ -238,6 +238,9 @@ enum Command {
fix: bool,
},
/// Check the environment against the PyPI advisory database.
Audit,
/// Upgrade pip inside the selected environment.
PipUpgrade,
@@ -386,6 +389,7 @@ async fn main() -> ExitCode {
}
Command::Schema { type_name } => run::schema(type_name),
Command::Env(EnvCommand::Use { path }) => run::env_use(&cli.global, path).await,
Command::Audit => run::audit(&cli.global).await,
Command::PipUpgrade => run::pip_upgrade(&cli.global).await,
Command::Snapshot(SnapshotCommand::Rollback { id }) => {
run::snapshot_rollback(&cli.global, id).await
+137
View File
@@ -889,6 +889,143 @@ pub async fn tools_sync(opts: &GlobalOpts, force: bool, python: Option<&Path>) -
Ok(Exit::Success)
}
/// `pipdock audit` — CLI-SPEC §3, PRD P1-1.
///
/// Exits **1 on findings**, the way `health` does: an advisory is a result, not a failure, and a
/// script wants to branch on it. A pip-audit that could not run is a different thing and exits on
/// its catalog code.
///
/// # Errors
/// `PD-ENG-001` or `PD-ENV-*` when the environment cannot be read or frozen, `PD-NET-011` when the
/// audit venv cannot be bootstrapped.
pub async fn audit(opts: &GlobalOpts) -> Result<Exit> {
use pipdock_core::audit;
let env = select_env(opts).await?;
let app_data = app_data_dir();
let store = Store::open(&app_data)?;
let engine = engine::for_id(settings::load(&store)?.engine);
drop(store);
// Taken before the venv is touched, so an unreadable environment fails before a 15-second
// bootstrap rather than after one.
let freeze = engine.freeze(&env).await?;
let dir = health::audit_dir(&app_data);
let sync_needed = health::needs_sync(&dir, health::AUDIT_TOOLS)?.is_needed();
let synced = if sync_needed {
health::sync_steps(health::AUDIT_TOOLS)
} else {
0
};
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<ProgressEvent>();
let quiet = opts.quiet;
let pump = tokio::spawn(async move {
while let Some(event) = rx.recv().await {
if let Some(line) = event.line().filter(|_| !quiet) {
eprintln!("{line}");
}
}
});
let sink = engine::ProgressSink::new(tx, audit::AUDIT_STEPS + synced, CancellationToken::new());
let outcome = async {
if sync_needed {
if !opts.quiet && !opts.json {
println!("building the audit environment (first run)…");
}
let (python, _) = health::choose_tools_python(&envs::scan().await).await?;
health::sync_tools_venv(&dir, &python, health::AUDIT_TOOLS, &sink).await?;
}
// Said before the wait rather than after it: 18-68 seconds of silence reads as a hang, and
// this is the one command whose cost is a network fetch the user cannot see.
if !opts.quiet && !opts.json {
println!(
"checking {} packages against the advisory database…",
freeze.lines().count()
);
}
audit::run(&dir, &env, &freeze, &sink.at(synced)).await
}
.await;
drop(sink);
let _ = pump.await;
let report = outcome?;
if opts.json {
println!(
"{}",
serde_json::to_string_pretty(&report).map_err(|e| PdError::new(
Code::IntUnexpected,
format!("serialize the audit report: {e}")
))?
);
} else {
print_audit(&report);
}
// A tool problem outranks the findings: a report with an empty list because pip-audit never ran
// must not exit 0 and read as "nothing wrong here".
if let Some(problem) = report.problems.first() {
return Ok(exit_for(problem.code));
}
Ok(if report.has_findings() {
Exit::PartialFailure
} else {
Exit::Success
})
}
/// The human form of an audit report.
fn print_audit(report: &pipdock_core::audit::AuditReport) {
if report.cancelled {
println!("stopped before it finished; nothing below is complete");
}
for problem in &report.problems {
eprintln!("error[{}]: {}", problem.code, problem.message);
}
if report.advisories.is_empty() && report.problems.is_empty() {
println!(
"no known advisories against {} packages (pip-audit {})",
report.packages, report.tool_version
);
return;
}
let mut current = String::new();
for a in &report.advisories {
let pkg = a.pkg.to_string();
if pkg != current {
println!("\n{pkg} {}", a.version);
current = pkg;
}
// The fix is the actionable half, so it leads. "no fix" is stated rather than left blank:
// an advisory nothing upgrades away is the one worth reading the description for.
let fix = if a.fix_versions.is_empty() {
"no fix".to_owned()
} else {
format!("fixed in {}", a.fix_versions.join(", "))
};
println!(" {:<20} {fix}", a.id);
if !a.aliases.is_empty() {
println!(" {:<20} {}", "", a.aliases.join(", "));
}
}
println!(
"\n{} advisories across {} of {} packages",
report.advisories.len(),
report
.advisories
.iter()
.map(|a| a.pkg.to_string())
.collect::<std::collections::BTreeSet<_>>()
.len(),
report.packages
);
}
/// `pipdock health`
///
/// Exits **1 when any tool reported a finding**, 0 when all of them were clean. A linter that
+2
View File
@@ -61,6 +61,7 @@ const SCHEMA_TYPES: &[&str] = &[
"Intent",
"Code",
"HealthReport",
"AuditReport",
"FixReport",
];
@@ -125,6 +126,7 @@ fn every_command_documents_itself() {
"snapshot",
"doctor",
"health",
"audit",
"pip-upgrade",
"engine",
"index",
@@ -0,0 +1,41 @@
---
source: crates/pipdock-cli/tests/golden.rs
expression: "stdout_of(&[cmd, \"--help\"])"
---
Check the environment against the PyPI advisory database
Usage: pipdock audit [OPTIONS]
Options:
--env <PATH>
Interpreter or environment directory. Defaults to the last used env, else an auto-detected `.venv` in the working directory
--engine <ENGINE>
Override the configured engine for this invocation
Possible values:
- pip: `<python> -m pip`
- uv: `uv pip --python <python>`
--json
Machine-readable output; NDJSON for streaming commands
-y, --yes
Assume defaults on all prompts. Conflicts resolve to *skip*, never *force*
--quiet
Reduce log output
--verbose
Increase log output
--log-file <PATH>
Tee logs to a file
--no-snapshot
DANGEROUS: skip the pre-batch snapshot. CI images only; prints a warning.
This is the sole documented escape from DATA-FLOW §9.2, and it exists because a throwaway CI container has nothing to roll back to.
-h, --help
Print help (see a summary with '-h')
@@ -19,6 +19,7 @@ Commands:
snapshot Manage snapshots
doctor Engine check and environment sanity report
health Run Code Health (deptry / vulture / ruff) over a project folder
audit Check the environment against the PyPI advisory database
pip-upgrade Upgrade pip inside the selected environment
engine Show or set the configured engine
index Index maintenance
@@ -0,0 +1,322 @@
---
source: crates/pipdock-cli/tests/golden.rs
expression: out
---
{
"$defs": {
"Advisory": {
"description": "One advisory against one installed distribution.",
"properties": {
"aliases": {
"default": [],
"description": "Other ids for the same advisory, which is where the `CVE-*` and `GHSA-*` live.\n\nPRD P1-1 says \"known CVEs\"; a CVE is never the primary id here, so a screen that wants to\nshow one reads this.",
"items": {
"type": "string"
},
"type": "array"
},
"description": {
"description": "The advisory prose, verbatim. Never translated (I18N §2) and never trimmed here.",
"type": "string"
},
"fixVersions": {
"default": [],
"description": "Versions that fix it. **Empty is meaningful** — an advisory with nowhere to upgrade to —\nand [`sort_advisories`] puts those last rather than hiding them.",
"items": {
"type": "string"
},
"type": "array"
},
"id": {
"description": "pip-audit's primary id — `PYSEC-*` under the default service.",
"type": "string"
},
"pkg": {
"$ref": "#/$defs/PkgName",
"description": "The installed distribution the advisory is against."
},
"url": {
"description": "The OSV entry, when the id is shaped like one.\n\n**Built from a validated id rather than taken from the tool**, which is the whole\ndifference between this and `PdHealthReport`'s `finding.url`.\n`capabilities/external-links.json` records that ruff's URL is the only one in the\napplication derived from a third party's output; this one is derived from a string PipDock\nhas checked, so widening the allowlist to `osv.dev` does not widen what can reach it.",
"type": [
"string",
"null"
]
},
"version": {
"$ref": "#/$defs/Version",
"description": "The version installed, not the version that fixes it."
}
},
"required": [
"pkg",
"version",
"id",
"description"
],
"type": "object"
},
"Code": {
"description": "Every code PipDock can surface at v1 launch.\n\n`docs/TESTING.md` §2 requires at least one captured stderr fixture per variant before ship;\nthe test that enforces \"no code without fixture\" lives beside the classifiers.",
"oneOf": [
{
"const": "PD-ENV-001",
"description": "Interpreter path missing or not executable — the env was deleted or moved.",
"type": "string"
},
{
"const": "PD-ENV-002",
"description": "PEP 668 `EXTERNALLY-MANAGED` marker present; mutation blocked by default.",
"type": "string"
},
{
"const": "PD-ENV-003",
"description": "`probe.py` exited non-zero or produced unparseable output.",
"type": "string"
},
{
"const": "PD-ENG-001",
"description": "pip or uv binary not found.",
"type": "string"
},
{
"const": "PD-ENG-002",
"description": "pip older than 22.2, which predates `--dry-run --report`.",
"type": "string"
},
{
"const": "PD-ENG-003",
"description": "uv emitted a shape the adapter does not recognize (uv newer than PipDock).",
"type": "string"
},
{
"const": "PD-ENG-999",
"description": "Fallback for engine failures no classifier matched. Always last.",
"type": "string"
},
{
"const": "PD-RES-001",
"description": "`ResolutionImpossible` or the uv equivalent: constraints cannot be satisfied.",
"type": "string"
},
{
"const": "PD-RES-002",
"description": "Plan older than 10 minutes, or the env's probe hash changed since the preview.",
"type": "string"
},
{
"const": "PD-RES-003",
"description": "A plan is already resolving or executing in this session.\n\nThe GUI drives one resumable flow across several IPC calls, so \"start a plan\" and \"run the\nplan\" are different messages arriving at different times — nothing structurally stops a\nsecond one arriving in between. Refusing is the only safe answer: two concurrent plans\nwould interleave engine commands against one environment, and DATA-FLOW §9.3's staleness\ncheck would be comparing against a set the other plan is busy changing.",
"type": "string"
},
{
"const": "PD-RES-004",
"description": "A removal was asked for that the reverse-dependency guard refused (DATA-FLOW §5).\n\nIts own code rather than a reused one. The CLI printed `PD-PKG-002` here, which means \"no\nmatching distribution\" — the opposite of the truth: every package involved exists, and\nthat is precisely why the removal is being refused. A user grepping their logs for a typo\nwould have found this instead.\n\nNot raised when the guard merely *finds* dependents. That is a report the caller shows and\nthe user answers; the code appears only when execution is attempted anyway without the\nuser having accepted the breakage.",
"type": "string"
},
{
"const": "PD-BLD-001",
"description": "MSVC build tools required but absent.",
"type": "string"
},
{
"const": "PD-BLD-002",
"description": "Build backend failed (`pyproject.toml` error, `metadata-generation-failed`).",
"type": "string"
},
{
"const": "PD-BLD-003",
"description": "Generic sdist wheel-build failure.",
"type": "string"
},
{
"const": "PD-PKG-001",
"description": "No matching distribution, and metadata shows a requires-python mismatch.",
"type": "string"
},
{
"const": "PD-PKG-002",
"description": "No matching distribution: name or version typo, or the release is gone.",
"type": "string"
},
{
"const": "PD-PKG-003",
"description": "The requested release was yanked.",
"type": "string"
},
{
"const": "PD-PKG-004",
"description": "Downloaded artifact failed hash verification.",
"type": "string"
},
{
"const": "PD-NET-001",
"description": "Timeout, connection aborted, or DNS failure.",
"type": "string"
},
{
"const": "PD-NET-002",
"description": "TLS/SSL verification failed — typically proxy or AV interception.",
"type": "string"
},
{
"const": "PD-NET-010",
"description": "PEP 691 index refresh failed; the stale index stays searchable.",
"type": "string"
},
{
"const": "PD-NET-011",
"description": "Code Health tools-venv bootstrap could not reach PyPI.",
"type": "string"
},
{
"const": "PD-PRM-001",
"description": "`PermissionError` writing site-packages (admin-owned Python).",
"type": "string"
},
{
"const": "PD-PRM-002",
"description": "File locked by a running process (`WinError 32`).",
"type": "string"
},
{
"const": "PD-PRM-003",
"description": "A source file in the user's project cannot be written.\n\n**Not `PD-PRM-001`.** That one is scoped to site-packages and its catalogued action is\n\"use a venv\", which is nonsense advice for a read-only `util.py` — the same class of wrong\nanswer P3 removed when a corrupted `ruff.exe` reported `PD-ENG-001`, \"install the engine\".\n\nRaised by PipDock **before anything is written**, never classified from stderr: ruff can\nfail to write a file and still exit 1, which `is_findings_exit` accepts as a clean run, so\na stderr-matched code would arrive after a fix had already reported success.",
"type": "string"
},
{
"const": "PD-SNP-001",
"description": "Snapshot write failed before execution. **The plan is aborted; nothing runs.**",
"type": "string"
},
{
"const": "PD-SNP-002",
"description": "A release needed to restore a snapshot is no longer available on PyPI.",
"type": "string"
},
{
"const": "PD-SYS-001",
"description": "`MAX_PATH` exceeded without the long-path opt-in.",
"type": "string"
},
{
"const": "PD-SYS-002",
"description": "Disk full.",
"type": "string"
},
{
"const": "PD-HLT-001",
"description": "A Code Health tool is missing from the tools venv.",
"type": "string"
},
{
"const": "PD-HLT-002",
"description": "A Code Health tool exited non-zero.",
"type": "string"
},
{
"const": "PD-HLT-003",
"description": "A Code Health tool exceeded its watchdog timeout; partial report shown.",
"type": "string"
},
{
"const": "PD-HLT-004",
"description": "`python -m venv` failed while building the tools environment.\n\n**Raised by PipDock, not classified from engine stderr.** Its own code rather than a reused\none: `PD-NET-011` is `Area::Net`, so `run::exit_for` would map a broken interpreter to exit\n6 and a script retrying on network failure would loop forever; `PD-HLT-001` tells the user\nto re-sync, which is the operation that just failed; and a Python built without `venv` is\nnot `PD-INT-001`'s \"a PipDock bug\".",
"type": "string"
},
{
"const": "PD-INT-001",
"description": "A PipDock bug: panic or unexpected state.",
"type": "string"
}
]
},
"PkgName": {
"description": "A PEP 503-normalized distribution name.\n\nConstructing one is the *only* way a package name reaches an argv array, which is what makes\nSECURITY §2's \"validated before it reaches argv\" claim structural rather than aspirational.",
"type": "string"
},
"ToolProblem": {
"description": "One tool that was asked to run and did not finish.\n\nDeliberately `PdError`-shaped so the UI can hand it straight to `PdErrorRow` rather than\ninventing a second error presentation for the same catalog codes.",
"properties": {
"code": {
"$ref": "#/$defs/Code",
"description": "The catalog code, so the row is localized from the same table as every other error."
},
"message": {
"description": "Developer-facing detail. Never shown as-is (I18N §1).",
"type": "string"
},
"stderrTail": {
"description": "Tail of the tool's stderr, capped as ERROR-CATALOG §3 caps every other one.",
"type": [
"string",
"null"
]
},
"tool": {
"description": "Which tool: `deptry`, `vulture` or `ruff`.",
"type": "string"
}
},
"required": [
"tool",
"code",
"message"
],
"type": "object"
},
"Version": {
"description": "A version string as the engine reported it. Never reshaped or localized (I18N §2).",
"type": "string"
}
},
"$schema": "https://json-schema.org/draft/2020-12/schema",
"description": "What a Security-tab run produced.\n\nShaped like [`crate::health::HealthReport`] deliberately: a `problems` list rather than an\nearly return, so a failed audit still *returns a report* and the screen renders one error row\ninstead of nothing at all. That shape is what makes a partial result expressible.",
"properties": {
"advisories": {
"default": [],
"description": "Deduplicated and ordered by [`sort_advisories`].",
"items": {
"$ref": "#/$defs/Advisory"
},
"type": "array"
},
"cancelled": {
"default": false,
"description": "The user stopped it.\n\nA **state, not an error**, which is the shape `ExecutionSummary.cancelled` established: the\nuser asking a run to stop is not a tool failure, so nothing lands in `problems` and no\ncatalog code is minted for something that went right. It matters here in a way it did not\nfor Code Health, whose runs are 1.3 s — an audit is 18-68 s, which is long enough that\nstopping one is an ordinary thing to want.",
"type": "boolean"
},
"env": {
"description": "`canonical_interpreter` of the environment audited. Data, never localized (I18N §2).",
"type": "string"
},
"packages": {
"description": "Distributions the freeze document listed.\n\n**Separate from `advisories.len()`**, because \"audited 145 packages and found nothing\" and\n\"audited nothing\" are different answers. A screen that cannot tell them apart tells P4's\nlie — *no issues found* before anything has run.",
"format": "uint",
"minimum": 0,
"type": "integer"
},
"problems": {
"description": "Why the run contributed nothing. Empty means it completed.",
"items": {
"$ref": "#/$defs/ToolProblem"
},
"type": "array"
},
"ranAt": {
"description": "When the run finished, RFC 3339.",
"type": "string"
},
"toolVersion": {
"description": "pip-audit's version, out of the audit venv's manifest. Empty if it has never synced.",
"type": "string"
}
},
"required": [
"env",
"ranAt",
"toolVersion",
"packages"
],
"title": "AuditReport",
"type": "object"
}
@@ -2,4 +2,4 @@
source: crates/pipdock-cli/tests/golden.rs
expression: "stderr_of(&[\"schema\", \"NoSuchType\"])"
---
error[PD-PKG-002]: unknown type "NoSuchType"; known types: Dist, OutdatedDist, PyEnv, CheckReport, StepResult, PlanRequest, ResolutionReport, ExecutionSummary, Pin, PinSuggestion, ParsedRequirements, CacheUsage, CacheTarget, GuardReport, Diff, SnapshotMeta, EngineInfo, RollbackPlan, RollbackPreview, Hit, PackageMeta, Freshness, RefreshReport, ProgressEvent, FlowStep, Decision, Intent, Code, HealthReport, FixReport
error[PD-PKG-002]: unknown type "NoSuchType"; known types: Dist, OutdatedDist, PyEnv, CheckReport, StepResult, PlanRequest, ResolutionReport, ExecutionSummary, Pin, PinSuggestion, ParsedRequirements, CacheUsage, CacheTarget, GuardReport, Diff, SnapshotMeta, EngineInfo, RollbackPlan, RollbackPreview, Hit, PackageMeta, Freshness, RefreshReport, ProgressEvent, FlowStep, Decision, Intent, Code, HealthReport, AuditReport, FixReport
+2
View File
@@ -304,6 +304,7 @@ pub fn json_schema(type_name: &str) -> Result<serde_json::Value> {
// into its own TS declaration, so `DeptryIssue` and the rest arrive without being listed.
// Registering them separately would emit each twice.
"HealthReport" => crate::health::HealthReport,
"AuditReport" => crate::audit::AuditReport,
"FixReport" => crate::health::fix::FixReport,
}
}
@@ -339,6 +340,7 @@ pub const SCHEMA_TYPES: &[&str] = &[
"Intent",
"Code",
"HealthReport",
"AuditReport",
"FixReport",
];
+2
View File
@@ -142,6 +142,8 @@ This table is the surface. A command that is not listed here does not exist; add
| `health_fix` | `FixReport` | Apply the gated `ruff` fix (P5). **Not `ExecutionSummary`** — there is no plan, no phase and no per-package counts in a fix, and inventing them would be four lies for one operation. Same correction §7 needed for `pip_upgrade`. |
| `health_dirty` | `number \| null` | Uncommitted entries in the parked report's project, so the fix confirm can name one. `null` means no repository, no git, or git failed — a courtesy, not a precondition. Asked again inside `health_fix`: this decides what to render, that decides what to allow. |
| `health_save_report` | `string[]` | Write a finished report as Markdown **and** JSON beside a user-chosen path, returning both. Rust-side rather than a filesystem capability: `dialog:allow-save` lets the webview ask for a path and nothing more. |
| `audit_run` | `AuditReport` | pip-audit over an environment (PRD P1-1). Takes the freeze itself, because pip is invoked with `--all` and uv is not, so the configured engine changes what is audited. Syncs its **own** venv on first use — a `msgpack` wheel gap fails this and leaves Code Health working. pip-audit failing is not an error: it lands in `problems` and the report still returns.
| `audit_cancel` | `bool` | Stop a running audit, reporting whether there was one. Exists where `health_run` has no equivalent because an audit is **18-68 s** rather than 1.3 s, dominated by a one-off advisory-database fetch. A cancel is a *state* on the report, never `PD-INT-001`. |
| `engine_info` | `EngineInfo[]` | Detected version and availability per engine. Settings shows both, so this returns both. |
| `pip_upgrade` | `StepResult` | Upgrade pip itself in the selected environment. **Not `ExecutionSummary`** — there is no plan, no phase and no per-package counts, and inventing them would be four lies for one step. Carries no versions either (`from`/`to` are always absent): the caller re-probes, which it must do anyway to refresh the row. |
| `settings_get` | `Settings` | Read stored settings. |
+80
View File
@@ -1077,6 +1077,86 @@ pub async fn health_run(
}
}
/// Audit an environment against the PyPI advisory database — PRD P1-1, SECURITY §6.
///
/// Syncs the audit venv on first use, exactly as [`health_run`] syncs Code Health's: the implicit
/// sync belongs to the command that needs it, or the frontend would have two ways to reach one
/// operation. It is a *different* venv, and that is the point — a CPython with no `msgpack` wheel
/// fails this and leaves Code Health working.
///
/// **The freeze is taken here, through the configured engine.** Which engine matters: pip is
/// invoked with `--all` and includes pip and setuptools, uv has no such flag and omits them, so
/// the engine selection changes what is audited. The store guard is read and dropped before any
/// subprocess, per [`pkg_outdated`]'s note.
///
/// **Cancellable, unlike `health_run`.** P4 deferred that for Code Health on a measurement of
/// 1.3 s; an audit measures 18-68 s, which is long enough that stopping one is an ordinary thing
/// to want. The token is registered beside the slot rather than inside it, so [`audit_cancel`] can
/// reach a run the slot no longer owns.
///
/// # Errors
/// `PD-RES-003` when an audit is already running; `PD-ENG-001` or `PD-ENV-*` when the freeze cannot
/// be taken; `PD-NET-011` when the audit venv cannot be bootstrapped. **pip-audit failing is not an
/// error** — it lands in `AuditReport.problems` and the report still returns.
#[tauri::command]
pub async fn audit_run(
app: tauri::AppHandle,
state: tauri::State<'_, AppState>,
env: PyEnv,
) -> Wire<pipdock_core::audit::AuditReport> {
use pipdock_core::{audit, health};
state.audit.claim().await?;
let dir = health::audit_dir(&state.app_data);
let outcome = async {
let engine = {
let store = state.store.lock().await;
engine::for_id(settings::load(&store)?.engine)
};
let freeze = engine.freeze(&env).await?;
let sync_needed = health::needs_sync(&dir, health::AUDIT_TOOLS)?.is_needed();
let synced = if sync_needed {
health::sync_steps(health::AUDIT_TOOLS)
} else {
0
};
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
forward_progress(&app, "audit-progress", rx);
let token = CancellationToken::new();
state.audit.set_cancel(Some(token.clone()));
let sink = engine::ProgressSink::new(tx, audit::AUDIT_STEPS + synced, token);
if sync_needed {
let (python, _) = health::choose_tools_python(&envs::scan().await).await?;
health::sync_tools_venv(&dir, &python, health::AUDIT_TOOLS, &sink).await?;
}
audit::run(&dir, &env, &freeze, &sink.at(synced)).await
}
.await;
// Released on both paths, and the token cleared with it: a token left registered would let the
// *next* `audit_cancel` stop a run that had not started, which is S5's wedge bug wearing a
// different hat.
state.audit.release().await;
state.audit.set_cancel(None);
Ok(outcome?)
}
/// Stop a running audit, and say whether there was one.
///
/// Shaped like [`plan_cancel`] rather than returning `()`: "nothing was running" is a real answer
/// and the caller should not have to guess it from a silent success.
///
/// # Errors
/// Never fails.
#[tauri::command]
pub async fn audit_cancel(state: tauri::State<'_, AppState>) -> Wire<bool> {
Ok(state.audit.stop().await)
}
/// Whether the parked report's project has uncommitted work, so the confirm can say so.
///
/// A command of its own rather than a field on `HealthReport`, because the answer expires: the
+2
View File
@@ -92,6 +92,8 @@ pub fn run() {
commands::health_dirty,
commands::health_fix,
commands::health_run,
commands::audit_run,
commands::audit_cancel,
commands::health_save_report,
commands::index_search,
commands::index_refresh,
+13
View File
@@ -424,6 +424,18 @@ pub struct AppState {
/// the user's consent against a report **the server** is holding — the same shape `ack_ok`
/// checks a `GuardAck` against the guard that produced it. Typed now so P5 does not redo it.
pub health: Sessions<HealthSession>,
/// The Security tab's slot — PRD P1-1.
///
/// `Sessions<()>` because nothing is parked: an audit produces a report and hands it straight
/// back, with no second call that consumes it the way `health_fix` consumes a `HealthSession`.
/// What it is here for is the **token**, which lives beside the slot rather than in it so
/// `audit_cancel` can reach a run the slot no longer owns.
///
/// Its own slot rather than `health`'s, for the reason that one is not `sessions`: an audit
/// touches no environment, so refusing it while Code Health runs would be a lock with no
/// invariant behind it.
pub audit: Sessions<()>,
/// Engine output from the current plan, for the bug-report deep link.
pub log: std::sync::Arc<LogRing>,
}
@@ -442,6 +454,7 @@ impl AppState {
index: std::sync::Mutex::new(IndexSlot::Cold),
sessions: Sessions::default(),
health: Sessions::default(),
audit: Sessions::default(),
log: std::sync::Arc::new(LogRing::default()),
})
}
+72
View File
@@ -6,6 +6,78 @@
// Command signatures are not here — they are not derivable from a schema and stay hand-written
// in `./index.ts`.
/** One advisory against one installed distribution. */
export interface Advisory {
/**
* Other ids for the same advisory, which is where the `CVE-*` and `GHSA-*` live.
*
* PRD P1-1 says "known CVEs"; a CVE is never the primary id here, so a screen that wants to
* show one reads this.
*/
aliases?: string[];
/** The advisory prose, verbatim. Never translated (I18N §2) and never trimmed here. */
description: string;
/**
* Versions that fix it. **Empty is meaningful** — an advisory with nowhere to upgrade to —
* and [`sort_advisories`] puts those last rather than hiding them.
*/
fixVersions?: string[];
/** pip-audit's primary id — `PYSEC-*` under the default service. */
id: string;
/** The installed distribution the advisory is against. */
pkg: PkgName;
/**
* The OSV entry, when the id is shaped like one.
*
* **Built from a validated id rather than taken from the tool**, which is the whole
* difference between this and `PdHealthReport`'s `finding.url`.
* `capabilities/external-links.json` records that ruff's URL is the only one in the
* application derived from a third party's output; this one is derived from a string PipDock
* has checked, so widening the allowlist to `osv.dev` does not widen what can reach it.
*/
url?: string | null;
/** The version installed, not the version that fixes it. */
version: Version;
}
/**
* What a Security-tab run produced.
*
* Shaped like [`crate::health::HealthReport`] deliberately: a `problems` list rather than an
* early return, so a failed audit still *returns a report* and the screen renders one error row
* instead of nothing at all. That shape is what makes a partial result expressible.
*/
export interface AuditReport {
/** Deduplicated and ordered by [`sort_advisories`]. */
advisories?: Advisory[];
/**
* The user stopped it.
*
* A **state, not an error**, which is the shape `ExecutionSummary.cancelled` established: the
* user asking a run to stop is not a tool failure, so nothing lands in `problems` and no
* catalog code is minted for something that went right. It matters here in a way it did not
* for Code Health, whose runs are 1.3 s — an audit is 18-68 s, which is long enough that
* stopping one is an ordinary thing to want.
*/
cancelled?: boolean;
/** `canonical_interpreter` of the environment audited. Data, never localized (I18N §2). */
env: string;
/**
* Distributions the freeze document listed.
*
* **Separate from `advisories.len()`**, because "audited 145 packages and found nothing" and
* "audited nothing" are different answers. A screen that cannot tell them apart tells P4's
* lie — *no issues found* before anything has run.
*/
packages: number;
/** Why the run contributed nothing. Empty means it completed. */
problems?: ToolProblem[];
/** When the run finished, RFC 3339. */
ranAt: string;
/** pip-audit's version, out of the audit venv's manifest. Empty if it has never synced. */
toolVersion: string;
}
/**
* The package responsible for holding another one back.
*
+31 -1
View File
@@ -16,6 +16,7 @@ import { listen, type UnlistenFn } from '@tauri-apps/api/event'
import { open, save } from '@tauri-apps/plugin-dialog'
import type {
AuditReport,
Decision,
Dist,
Freshness,
@@ -78,6 +79,8 @@ export const COMMANDS = [
'snapshot_rollback_preview',
'snapshot_rollback',
'health_run',
'audit_run',
'audit_cancel',
'health_dirty',
'health_fix',
'health_save_report',
@@ -94,7 +97,12 @@ export const COMMANDS = [
export type Command = (typeof COMMANDS)[number]
/** Tauri event channels, per ARCHITECTURE §7. */
export const EVENTS = ['plan-progress', 'scan-progress', 'health-progress'] as const
export const EVENTS = [
'plan-progress',
'scan-progress',
'health-progress',
'audit-progress',
] as const
export type EventName = (typeof EVENTS)[number]
@@ -448,6 +456,20 @@ export const pipUpgrade = (env: PyEnv): Promise<StepResult> => invoke('pip_upgra
export const healthRun = (env: PyEnv, project: string): Promise<HealthReport> =>
invoke('health_run', { env, project })
/**
* Audit one environment against the PyPI advisory database (PRD P1-1).
*
* Takes only the environment: the freeze document is Rust's to produce, because which engine is
* configured changes what is in it — pip includes pip and setuptools, uv does not.
*
* Slow by nature. 18-68 s measured, dominated by a one-off advisory-database fetch rather than by
* the package count, which is why `auditCancel` exists at all and `health_run` has no equivalent.
*/
export const auditRun = (env: PyEnv): Promise<AuditReport> => invoke('audit_run', { env })
/** Stop a running audit; resolves false when there was nothing to stop. */
export const auditCancel = (): Promise<boolean> => invoke('audit_cancel')
/**
* Write the report beside `path`, as Markdown and JSON. Returns the two paths written.
*
@@ -568,3 +590,11 @@ export const onHealthProgress = (
listen<ProgressEvent>('health-progress', (event) => {
handler(event.payload)
})
/** The same payload again, on the Security tab's own channel. */
export const onAuditProgress = (
handler: (event: ProgressEvent) => void,
): Promise<UnlistenFn> =>
listen<ProgressEvent>('audit-progress', (event) => {
handler(event.payload)
})
+4
View File
@@ -47,6 +47,8 @@ export interface IpcMock {
envProbe: ReturnType<typeof vi.fn>
pipUpgrade: ReturnType<typeof vi.fn>
healthRun: ReturnType<typeof vi.fn>
auditRun: ReturnType<typeof vi.fn>
auditCancel: ReturnType<typeof vi.fn>
onHealthProgress: ReturnType<typeof vi.fn>
pickProjectFolder: ReturnType<typeof vi.fn>
pickSavePath: ReturnType<typeof vi.fn>
@@ -97,6 +99,8 @@ export function ipcMock(): IpcMock {
envProbe: vi.fn(),
pipUpgrade: vi.fn().mockResolvedValue(undefined),
healthRun: vi.fn(),
auditRun: vi.fn(),
auditCancel: vi.fn(),
onHealthProgress: vi.fn().mockResolvedValue(() => undefined),
// Cancelled by default. A picker that silently returned a folder would let a test assert a
// run it never actually asked for.