purser 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
purser/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Purser: ML model security scanner with policy-based supply-chain controls."""
2
+
3
+ __version__ = "0.1.1"
purser/api.py ADDED
@@ -0,0 +1,302 @@
1
+ """Purser REST API.
2
+
3
+ Endpoints:
4
+ GET /healthz liveness/readiness (never authenticated)
5
+ GET /v1/policy effective policy
6
+ GET /v1/origins publisher -> country database
7
+ POST /v1/scan/upload multipart file upload scan
8
+ POST /v1/scan/path scan a path visible to the server (mounted volume)
9
+ POST /v1/scan/huggingface download + scan an HF repo (needs purser[hf])
10
+
11
+ The active policy is loaded from PURSER_POLICY (path to YAML); in
12
+ Kubernetes this is mounted from a ConfigMap so policy changes need no image
13
+ rebuild.
14
+
15
+ Security-relevant environment variables:
16
+ PURSER_API_KEY if set, all /v1 endpoints require this key via
17
+ `Authorization: Bearer <key>` or `X-API-Key`.
18
+ Multiple comma-separated keys are accepted.
19
+ PURSER_MAX_CONCURRENT_SCANS cap on in-flight scans (default 4); excess
20
+ requests get HTTP 429.
21
+ PURSER_RATE_LIMIT_RPM per-client (API key, else IP) requests/minute;
22
+ 0 disables (default). Over-limit -> HTTP 429.
23
+ PURSER_ENABLE_HF "1"/"true" to enable the HuggingFace download
24
+ endpoint (disabled by default — it makes the
25
+ server fetch caller-chosen repos).
26
+ PURSER_HF_ALLOWLIST comma-separated org/repo prefixes permitted for
27
+ the HF endpoint (empty = any, once enabled).
28
+ PURSER_METRICS_ENABLED "0"/"false" to disable the /metrics endpoint
29
+ (Prometheus text format; enabled by default).
30
+ PURSER_AUDIT off | stdout | syslog — structured JSON audit log
31
+ per scan (default off). PURSER_SYSLOG_ADDRESS
32
+ ("/dev/log" or "host:port") targets a collector.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import hashlib
38
+ import hmac
39
+ import os
40
+ import shutil
41
+ import tempfile
42
+ import threading
43
+ import time
44
+ from pathlib import Path
45
+
46
+ from fastapi import Depends, FastAPI, File, Header, HTTPException, Request, UploadFile
47
+ from fastapi.responses import PlainTextResponse
48
+ from pydantic import BaseModel
49
+
50
+ from purser import __version__
51
+ from purser.core import metrics
52
+ from purser.core.env import env_get
53
+ from purser.core.hf import HFNotAvailable, download_repo
54
+ from purser.core.policy import Policy, PolicyError
55
+ from purser.core.provenance import origin_db
56
+ from purser.core.scanner import scan_target
57
+
58
+ MAX_UPLOAD_BYTES = int(env_get("MAX_UPLOAD_MB", "10240")) * 1024 * 1024
59
+ MAX_CONCURRENT_SCANS = int(env_get("MAX_CONCURRENT_SCANS", "4"))
60
+
61
+ app = FastAPI(title="Purser", version=__version__,
62
+ description="ML model security scanner with policy-based controls")
63
+
64
+ # Bounded concurrency: reject rather than queue so a flood of large uploads
65
+ # can't exhaust memory/disk. Non-blocking acquire -> HTTP 429 when full.
66
+ _scan_slots = threading.BoundedSemaphore(max(1, MAX_CONCURRENT_SCANS))
67
+
68
+
69
+ class _ScanSlot:
70
+ def __enter__(self):
71
+ if not _scan_slots.acquire(blocking=False):
72
+ metrics.reject("capacity")
73
+ raise HTTPException(status_code=429, detail="scanner at capacity; retry later")
74
+ metrics.inc_inflight()
75
+ return self
76
+
77
+ def __exit__(self, *exc):
78
+ metrics.dec_inflight()
79
+ _scan_slots.release()
80
+
81
+
82
+ def _configured_keys() -> list[str]:
83
+ raw = env_get("API_KEY", "")
84
+ return [k.strip() for k in raw.split(",") if k.strip()]
85
+
86
+
87
+ # --- per-client rate limiting (token bucket) --------------------------------
88
+ # PURSER_RATE_LIMIT_RPM requests/minute per client (API key, else client
89
+ # IP); 0 disables. Burst capacity == the per-minute allowance.
90
+ _buckets: dict[str, tuple[float, float]] = {}
91
+ _bucket_lock = threading.Lock()
92
+ _MAX_BUCKETS = 10000
93
+
94
+
95
+ def _rate_limit_rpm() -> int:
96
+ try:
97
+ return int(env_get("RATE_LIMIT_RPM", "0"))
98
+ except ValueError:
99
+ return 0
100
+
101
+
102
+ def _client_id(request: Request, authorization: str | None, x_api_key: str | None) -> str:
103
+ key = x_api_key
104
+ if authorization and authorization.lower().startswith("bearer "):
105
+ key = authorization[7:].strip()
106
+ if key:
107
+ return "k:" + hashlib.sha256(key.encode()).hexdigest()[:16]
108
+ host = request.client.host if request.client else "unknown"
109
+ return "ip:" + host
110
+
111
+
112
+ def rate_limit(
113
+ request: Request,
114
+ authorization: str | None = Header(default=None),
115
+ x_api_key: str | None = Header(default=None),
116
+ ) -> None:
117
+ rpm = _rate_limit_rpm()
118
+ if rpm <= 0:
119
+ return
120
+ rate = rpm / 60.0
121
+ cid = _client_id(request, authorization, x_api_key)
122
+ now = time.monotonic()
123
+ with _bucket_lock:
124
+ if len(_buckets) > _MAX_BUCKETS: # crude prune to bound memory
125
+ _buckets.clear()
126
+ tokens, last = _buckets.get(cid, (float(rpm), now))
127
+ tokens = min(float(rpm), tokens + (now - last) * rate)
128
+ if tokens < 1.0:
129
+ retry = int((1.0 - tokens) / rate) + 1
130
+ metrics.reject("rate_limit")
131
+ raise HTTPException(
132
+ status_code=429, detail="rate limit exceeded",
133
+ headers={"Retry-After": str(retry)},
134
+ )
135
+ _buckets[cid] = (tokens - 1.0, now)
136
+
137
+
138
+ def require_auth(
139
+ authorization: str | None = Header(default=None),
140
+ x_api_key: str | None = Header(default=None),
141
+ ) -> None:
142
+ """Dependency enforcing API-key auth when PURSER_API_KEY is set.
143
+
144
+ No key configured => open (documented default for trusted networks).
145
+ """
146
+ keys = _configured_keys()
147
+ if not keys:
148
+ return
149
+ presented = x_api_key
150
+ if authorization and authorization.lower().startswith("bearer "):
151
+ presented = authorization[7:].strip()
152
+ # constant-time comparison against each accepted key
153
+ if presented and any(hmac.compare_digest(presented, k) for k in keys):
154
+ return
155
+ metrics.reject("auth")
156
+ raise HTTPException(status_code=401, detail="missing or invalid API key")
157
+
158
+
159
+ def get_policy() -> Policy:
160
+ path = env_get("POLICY")
161
+ if not path:
162
+ return Policy.default()
163
+ try:
164
+ return Policy.load(path)
165
+ except (OSError, PolicyError) as exc:
166
+ raise HTTPException(status_code=500, detail=f"policy load failed: {exc}")
167
+
168
+
169
+ class PathScanRequest(BaseModel):
170
+ path: str
171
+ origin: str | None = None
172
+ publisher: str | None = None
173
+
174
+
175
+ class HFScanRequest(BaseModel):
176
+ repo_id: str
177
+ revision: str | None = None
178
+ origin: str | None = None
179
+
180
+
181
+ @app.get("/healthz")
182
+ def healthz() -> dict:
183
+ return {"status": "ok", "version": __version__}
184
+
185
+
186
+ @app.get("/metrics")
187
+ def prometheus_metrics() -> PlainTextResponse:
188
+ """Prometheus scrape endpoint. Unauthenticated by design (scrapers usually
189
+ are); disable with PURSER_METRICS_ENABLED=0, and network-restrict it."""
190
+ if (env_get("METRICS_ENABLED", "1") or "1").lower() in ("0", "false", "no"):
191
+ raise HTTPException(status_code=404, detail="metrics disabled")
192
+ return PlainTextResponse(metrics.render(),
193
+ media_type="text/plain; version=0.0.4; charset=utf-8")
194
+
195
+
196
+ @app.get("/v1/policy")
197
+ def policy(_: None = Depends(require_auth),
198
+ __: None = Depends(rate_limit)) -> dict:
199
+ return get_policy().to_dict()
200
+
201
+
202
+ @app.get("/v1/origins")
203
+ def origins(_: None = Depends(require_auth),
204
+ __: None = Depends(rate_limit)) -> dict:
205
+ return {"publishers": origin_db()}
206
+
207
+
208
+ @app.post("/v1/scan/upload")
209
+ async def scan_upload(
210
+ file: UploadFile = File(...),
211
+ origin: str | None = None,
212
+ publisher: str | None = None,
213
+ _: None = Depends(require_auth),
214
+ __: None = Depends(rate_limit),
215
+ ) -> dict:
216
+ pol = get_policy()
217
+ tmpdir = Path(tempfile.mkdtemp(prefix="purser-upload-"))
218
+ try:
219
+ # Never trust the client-provided filename for paths.
220
+ safe_name = Path(file.filename or "upload.bin").name or "upload.bin"
221
+ dest = tmpdir / safe_name
222
+ written = 0
223
+ with open(dest, "wb") as out:
224
+ while chunk := await file.read(1024 * 1024):
225
+ written += len(chunk)
226
+ if written > MAX_UPLOAD_BYTES:
227
+ metrics.reject("upload_too_large")
228
+ raise HTTPException(status_code=413, detail="upload too large")
229
+ out.write(chunk)
230
+ with _ScanSlot():
231
+ report = scan_target(dest, policy=pol, origin=origin, publisher=publisher)
232
+ report.target = safe_name
233
+ for fr in report.files:
234
+ fr.path = Path(fr.path).name
235
+ for f in report.all_findings:
236
+ f.file = Path(f.file).name if f.file else ""
237
+ return report.to_dict()
238
+ finally:
239
+ shutil.rmtree(tmpdir, ignore_errors=True)
240
+
241
+
242
+ @app.post("/v1/scan/path")
243
+ def scan_path(req: PathScanRequest, _: None = Depends(require_auth),
244
+ __: None = Depends(rate_limit)) -> dict:
245
+ allowed_root = env_get("SCAN_ROOT", "/models")
246
+ target = Path(req.path).resolve()
247
+ root = Path(allowed_root).resolve()
248
+ if target != root and root not in target.parents:
249
+ raise HTTPException(
250
+ status_code=403,
251
+ detail=f"path scanning is restricted to {allowed_root}",
252
+ )
253
+ if not target.exists():
254
+ raise HTTPException(status_code=404, detail="path not found")
255
+ with _ScanSlot():
256
+ report = scan_target(target, policy=get_policy(), origin=req.origin,
257
+ publisher=req.publisher)
258
+ return report.to_dict()
259
+
260
+
261
+ def _hf_enabled() -> bool:
262
+ return env_get("ENABLE_HF", "").lower() in ("1", "true", "yes")
263
+
264
+
265
+ def _hf_repo_allowed(repo_id: str) -> bool:
266
+ raw = env_get("HF_ALLOWLIST", "")
267
+ prefixes = [p.strip() for p in raw.split(",") if p.strip()]
268
+ if not prefixes:
269
+ return True
270
+ return any(repo_id == p or repo_id.startswith(p.rstrip("/") + "/") for p in prefixes)
271
+
272
+
273
+ @app.post("/v1/scan/huggingface")
274
+ def scan_hf(req: HFScanRequest, _: None = Depends(require_auth),
275
+ __: None = Depends(rate_limit)) -> dict:
276
+ if not _hf_enabled():
277
+ raise HTTPException(
278
+ status_code=403,
279
+ detail="HuggingFace scanning is disabled; set PURSER_ENABLE_HF=1",
280
+ )
281
+ if not _hf_repo_allowed(req.repo_id):
282
+ raise HTTPException(
283
+ status_code=403,
284
+ detail="repo_id not permitted by PURSER_HF_ALLOWLIST",
285
+ )
286
+ try:
287
+ with _ScanSlot():
288
+ local = download_repo(req.repo_id, revision=req.revision,
289
+ token=os.environ.get("HF_TOKEN"))
290
+ try:
291
+ report = scan_target(local, policy=get_policy(), origin=req.origin,
292
+ repo_id=req.repo_id)
293
+ report.target = f"hf://{req.repo_id}"
294
+ return report.to_dict()
295
+ finally:
296
+ shutil.rmtree(local, ignore_errors=True)
297
+ except HFNotAvailable as exc:
298
+ raise HTTPException(status_code=501, detail=str(exc))
299
+ except HTTPException:
300
+ raise
301
+ except Exception as exc:
302
+ raise HTTPException(status_code=502, detail=f"download failed: {exc}")
purser/cli.py ADDED
@@ -0,0 +1,280 @@
1
+ """Purser CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import typer
9
+ from rich.console import Console
10
+ from rich.table import Table
11
+
12
+ from purser import __version__
13
+ from purser.core.findings import ScanReport, Severity
14
+ from purser.core.hf import HFNotAvailable, download_repo, parse_hf_uri
15
+ from purser.core.policy import Policy, PolicyError
16
+ from purser.core.provenance import origin_db
17
+ from purser.core.scanner import EXIT_CODES, scan_target
18
+ from purser.core.signing import (
19
+ SigningError,
20
+ generate_keypair,
21
+ load_trust_store,
22
+ verify_target,
23
+ write_signature,
24
+ )
25
+
26
+ app = typer.Typer(help="Purser — ML model security scanner with policy controls.",
27
+ no_args_is_help=True)
28
+ console = Console(stderr=False)
29
+
30
+ SEV_STYLE = {
31
+ "CRITICAL": "bold white on red",
32
+ "HIGH": "bold red",
33
+ "MEDIUM": "yellow",
34
+ "LOW": "cyan",
35
+ "INFO": "dim",
36
+ }
37
+ VERDICT_STYLE = {
38
+ "PASS": "bold green",
39
+ "WARN": "bold yellow",
40
+ "FAIL": "bold red",
41
+ "BLOCKED": "bold white on red",
42
+ "ERROR": "bold magenta",
43
+ }
44
+
45
+
46
+ def _load_policy(policy_path: str | None) -> Policy:
47
+ if policy_path is None:
48
+ return Policy.default()
49
+ try:
50
+ return Policy.load(policy_path)
51
+ except (OSError, PolicyError) as exc:
52
+ console.print(f"[bold red]Policy error:[/] {exc}")
53
+ raise typer.Exit(3)
54
+
55
+
56
+ def _render_table(report: ScanReport) -> None:
57
+ style = VERDICT_STYLE.get(report.verdict.value, "")
58
+ console.print(f"\n[bold]Target:[/] {report.target}")
59
+ if report.metadata.get("repo_id"):
60
+ console.print(f"[bold]Repo:[/] {report.metadata['repo_id']}")
61
+ if report.provenance_verified:
62
+ prov = "[bold green]✓ signature-verified[/]"
63
+ else:
64
+ prov = report.metadata.get("provenance_source", "unknown")
65
+ console.print(f"[bold]Policy:[/] {report.policy_name}"
66
+ f" [bold]Publisher:[/] {report.publisher or '-'}"
67
+ f" [bold]Origin:[/] {report.origin or 'unknown'}"
68
+ f" ({prov})")
69
+ console.print(f"[bold]Files scanned:[/] {len(report.files)}"
70
+ f" [bold]Duration:[/] {report.duration_seconds:.2f}s")
71
+
72
+ findings = report.all_findings
73
+ if findings:
74
+ table = Table(title=None, expand=False, show_lines=False)
75
+ table.add_column("Severity", no_wrap=True)
76
+ table.add_column("Rule")
77
+ table.add_column("Finding")
78
+ table.add_column("File", overflow="fold")
79
+ for f in sorted(findings, key=lambda x: -int(x.severity)):
80
+ table.add_row(
81
+ f"[{SEV_STYLE.get(f.severity.name, '')}]{f.severity.name}[/]",
82
+ f.rule_id,
83
+ f.title,
84
+ Path(f.file).name if f.file else "-",
85
+ )
86
+ console.print(table)
87
+ else:
88
+ console.print("[green]No findings.[/]")
89
+
90
+ counts = {k: v for k, v in report.severity_counts().items() if v}
91
+ if counts:
92
+ console.print("[bold]Counts:[/] " + " ".join(f"{k}={v}" for k, v in counts.items()))
93
+ console.print(f"\n[bold]Verdict:[/] [{style}] {report.verdict.value} [/]\n")
94
+
95
+
96
+ def _to_sarif(report: ScanReport) -> dict:
97
+ sev_to_level = {
98
+ Severity.CRITICAL: "error", Severity.HIGH: "error",
99
+ Severity.MEDIUM: "warning", Severity.LOW: "note", Severity.INFO: "note",
100
+ }
101
+ rules: dict[str, dict] = {}
102
+ results = []
103
+ for f in report.all_findings:
104
+ rules.setdefault(f.rule_id, {
105
+ "id": f.rule_id,
106
+ "shortDescription": {"text": f.title[:120]},
107
+ })
108
+ results.append({
109
+ "ruleId": f.rule_id,
110
+ "level": sev_to_level[f.severity],
111
+ "message": {"text": f"{f.title}. {f.detail}".strip()},
112
+ "properties": {"severity": f.severity.name, "tags": f.tags},
113
+ "locations": [{
114
+ "physicalLocation": {
115
+ "artifactLocation": {"uri": f.file or report.target},
116
+ }
117
+ }],
118
+ })
119
+ return {
120
+ "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
121
+ "version": "2.1.0",
122
+ "runs": [{
123
+ "tool": {"driver": {
124
+ "name": "Purser",
125
+ "version": __version__,
126
+ "rules": list(rules.values()),
127
+ }},
128
+ "results": results,
129
+ "properties": {"verdict": report.verdict.value, "policy": report.policy_name},
130
+ }],
131
+ }
132
+
133
+
134
+ def _emit(report: ScanReport, fmt: str, output: str | None) -> None:
135
+ if fmt == "json":
136
+ text = json.dumps(report.to_dict(), indent=2)
137
+ elif fmt == "sarif":
138
+ text = json.dumps(_to_sarif(report), indent=2)
139
+ else:
140
+ if output:
141
+ Path(output).write_text(json.dumps(report.to_dict(), indent=2))
142
+ _render_table(report)
143
+ return
144
+ if output:
145
+ Path(output).write_text(text)
146
+ console.print(f"Report written to {output}")
147
+ else:
148
+ print(text)
149
+
150
+
151
+ @app.command()
152
+ def scan(
153
+ target: str = typer.Argument(..., help="File, directory, or hf://org/repo to scan"),
154
+ policy: str = typer.Option(None, "--policy", "-p", help="Path to policy YAML"),
155
+ origin: str = typer.Option(None, "--origin", help="Explicit country of origin (ISO 3166-1 alpha-2)"),
156
+ publisher: str = typer.Option(None, "--publisher", help="Model publisher (e.g. HF org)"),
157
+ repo_id_opt: str = typer.Option(None, "--repo-id", help="Logical model id/name for policy matching (e.g. org/name), for local scans"),
158
+ fmt: str = typer.Option("table", "--format", "-f", help="Output: table | json | sarif"),
159
+ output: str = typer.Option(None, "--output", "-o", help="Write report to file"),
160
+ revision: str = typer.Option(None, "--revision", help="HF revision when scanning hf:// targets"),
161
+ ):
162
+ """Scan a model artifact, directory, or HuggingFace repo."""
163
+ pol = _load_policy(policy)
164
+ hf_repo = parse_hf_uri(target) # only hf:// triggers a download
165
+ repo_id = hf_repo or repo_id_opt # logical id for policy matching
166
+ local_target = Path(target)
167
+ if hf_repo is not None:
168
+ try:
169
+ console.print(f"Downloading [bold]{hf_repo}[/] from HuggingFace Hub…")
170
+ local_target = download_repo(hf_repo, revision=revision)
171
+ except HFNotAvailable as exc:
172
+ console.print(f"[bold red]{exc}[/]")
173
+ raise typer.Exit(3)
174
+ except Exception as exc:
175
+ console.print(f"[bold red]Download failed:[/] {exc}")
176
+ raise typer.Exit(3)
177
+
178
+ report = scan_target(local_target, policy=pol, origin=origin,
179
+ publisher=publisher, repo_id=repo_id)
180
+ if hf_repo is not None:
181
+ report.target = target
182
+ _emit(report, fmt, output)
183
+ raise typer.Exit(EXIT_CODES[report.verdict])
184
+
185
+
186
+ @app.command("policy-check")
187
+ def policy_check(policy: str = typer.Argument(..., help="Path to policy YAML")):
188
+ """Validate a policy file and print its effective configuration."""
189
+ pol = _load_policy(policy)
190
+ console.print_json(json.dumps(pol.to_dict()))
191
+ console.print("[green]Policy is valid.[/]")
192
+
193
+
194
+ @app.command()
195
+ def origins(publisher: str = typer.Argument(None, help="Look up one publisher")):
196
+ """Show the publisher -> country origin database."""
197
+ db = origin_db()
198
+ if publisher:
199
+ code = db.get(publisher.lower())
200
+ if code:
201
+ console.print(f"{publisher.lower()} -> {code}")
202
+ else:
203
+ console.print(f"[yellow]{publisher}: unknown origin[/]")
204
+ raise typer.Exit(1)
205
+ return
206
+ table = Table()
207
+ table.add_column("Publisher")
208
+ table.add_column("Country")
209
+ for pub, code in sorted(db.items()):
210
+ table.add_row(pub, code)
211
+ console.print(table)
212
+
213
+
214
+ @app.command()
215
+ def keygen(
216
+ out: str = typer.Option("purser", "--out", "-o", help="Output filename prefix"),
217
+ ):
218
+ """Generate an Ed25519 signing keypair (<out>.key private, <out>.pub public)."""
219
+ try:
220
+ priv_pem, pub_pem = generate_keypair()
221
+ except SigningError as exc:
222
+ console.print(f"[bold red]{exc}[/]")
223
+ raise typer.Exit(3)
224
+ priv_path = Path(f"{out}.key")
225
+ pub_path = Path(f"{out}.pub")
226
+ priv_path.write_bytes(priv_pem)
227
+ priv_path.chmod(0o600)
228
+ pub_path.write_bytes(pub_pem)
229
+ console.print(f"Private key: [bold]{priv_path}[/] (keep secret, chmod 600)")
230
+ console.print(f"Public key: [bold]{pub_path}[/] (add to trust_store.yaml)")
231
+
232
+
233
+ @app.command()
234
+ def sign(
235
+ target: str = typer.Argument(..., help="Model file or directory to sign"),
236
+ key: str = typer.Option(..., "--key", "-k", help="Path to the private key (PEM)"),
237
+ key_id: str = typer.Option(..., "--key-id", help="Key id recorded in the signature"),
238
+ ):
239
+ """Sign a model artifact, producing a detached signature sidecar."""
240
+ from datetime import datetime, timezone
241
+ created = datetime.now(timezone.utc).isoformat(timespec="seconds")
242
+ try:
243
+ out = write_signature(Path(target), Path(key).read_bytes(), key_id,
244
+ created=created)
245
+ except (SigningError, OSError) as exc:
246
+ console.print(f"[bold red]Signing failed:[/] {exc}")
247
+ raise typer.Exit(3)
248
+ console.print(f"[green]Signed[/] {target} -> {out} (key_id={key_id})")
249
+
250
+
251
+ @app.command()
252
+ def verify(
253
+ target: str = typer.Argument(..., help="Model file or directory to verify"),
254
+ trust_store: str = typer.Option(None, "--trust-store", "-t",
255
+ help="Path to trust_store.yaml"),
256
+ ):
257
+ """Verify a model's signature against the trust store."""
258
+ store = load_trust_store(trust_store) if trust_store else load_trust_store()
259
+ result = verify_target(Path(target), store)
260
+ style = "bold green" if result.verified else "bold red"
261
+ console.print(f"[{style}]{result.status.upper()}[/]: {result.reason}")
262
+ if result.verified:
263
+ console.print(f" key_id: {result.key_id}")
264
+ console.print(f" publisher: {result.publisher}")
265
+ console.print(f" origin: {result.origin}")
266
+ raise typer.Exit(0 if result.verified else 1)
267
+
268
+
269
+ @app.command()
270
+ def version():
271
+ """Print version."""
272
+ console.print(f"purser {__version__}")
273
+
274
+
275
+ def main() -> None: # console_scripts entry point
276
+ app()
277
+
278
+
279
+ if __name__ == "__main__":
280
+ main()
File without changes
purser/core/audit.py ADDED
@@ -0,0 +1,95 @@
1
+ """Structured audit logging.
2
+
3
+ Emits one JSON record per scan — target, verdict, severity counts, provenance,
4
+ duration, finding rule-ids — suitable for a SIEM. Output is controlled by env:
5
+
6
+ PURSER_AUDIT off | stdout | syslog (default: off)
7
+ PURSER_SYSLOG_ADDRESS "/dev/log" (default) or "host:port" for a UDP collector
8
+ PURSER_SYSLOG_FACILITY facility name (default: "user")
9
+
10
+ stdlib-only (``logging.handlers.SysLogHandler``); no external dependency.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import logging
17
+ import logging.handlers
18
+ from datetime import datetime, timezone
19
+
20
+ from purser.core.env import env_get
21
+ from purser.core.findings import ScanReport
22
+
23
+ _logger = logging.getLogger("purser.audit")
24
+ _logger.propagate = False
25
+ _current_mode: str | None = None
26
+
27
+
28
+ def _mode() -> str:
29
+ return (env_get("AUDIT", "off") or "off").lower()
30
+
31
+
32
+ def _facility() -> int:
33
+ name = (env_get("SYSLOG_FACILITY", "user") or "user").lower()
34
+ return logging.handlers.SysLogHandler.facility_names.get(name, logging.handlers.SysLogHandler.LOG_USER)
35
+
36
+
37
+ def _configure(mode: str) -> None:
38
+ """(Re)attach the handler matching the current mode."""
39
+ global _current_mode
40
+ if mode == _current_mode:
41
+ return
42
+ for h in list(_logger.handlers):
43
+ _logger.removeHandler(h)
44
+ if mode == "syslog":
45
+ addr = env_get("SYSLOG_ADDRESS", "/dev/log") or "/dev/log"
46
+ if ":" in addr:
47
+ host, port = addr.rsplit(":", 1)
48
+ address: object = (host, int(port))
49
+ else:
50
+ address = addr
51
+ handler: logging.Handler = logging.handlers.SysLogHandler(
52
+ address=address, facility=_facility()
53
+ )
54
+ handler.setFormatter(logging.Formatter("purser %(message)s"))
55
+ elif mode == "stdout":
56
+ handler = logging.StreamHandler()
57
+ handler.setFormatter(logging.Formatter("%(message)s"))
58
+ else: # off
59
+ handler = logging.NullHandler()
60
+ _logger.addHandler(handler)
61
+ _logger.setLevel(logging.INFO)
62
+ _current_mode = mode
63
+
64
+
65
+ def build_record(report: ScanReport) -> dict:
66
+ """The structured audit record for a scan (also handy for tests)."""
67
+ max_sev = report.max_severity
68
+ return {
69
+ "ts": datetime.now(timezone.utc).isoformat(timespec="seconds"),
70
+ "event": "model_scan",
71
+ "target": report.target,
72
+ "verdict": report.verdict.value,
73
+ "policy": report.policy_name,
74
+ "origin": report.origin,
75
+ "publisher": report.publisher,
76
+ "provenance_verified": report.provenance_verified,
77
+ "files": len(report.files),
78
+ "severity_counts": report.severity_counts(),
79
+ "max_severity": max_sev.name if max_sev is not None else None,
80
+ "duration_seconds": round(report.duration_seconds, 3),
81
+ "finding_rule_ids": sorted({f.rule_id for f in report.all_findings})[:20],
82
+ }
83
+
84
+
85
+ def record_scan(report: ScanReport) -> None:
86
+ """Emit the audit record if auditing is enabled; never raises."""
87
+ mode = _mode()
88
+ if mode not in ("stdout", "syslog"):
89
+ return
90
+ try:
91
+ _configure(mode)
92
+ _logger.info(json.dumps(build_record(report), separators=(",", ":")))
93
+ except Exception:
94
+ # auditing must never break a scan
95
+ pass