logicguard 0.1.0__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.
logicguard/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
logicguard/cli.py ADDED
@@ -0,0 +1,361 @@
1
+ """Typer CLI entry point for LogicGuard (`scan`, `diff`, `rules`)."""
2
+
3
+ import os
4
+ import subprocess
5
+ from collections.abc import Callable, Sequence
6
+ from enum import StrEnum
7
+ from pathlib import Path
8
+ from typing import Annotated, NoReturn
9
+
10
+ import typer
11
+ from rich import box
12
+ from rich.console import Console
13
+ from rich.table import Table
14
+ from rich.text import Text
15
+
16
+ from logicguard.core.engine import SEVERITY_RANK, LogicGuardEngine
17
+ from logicguard.core.models import Finding, ScanResult, Severity
18
+ from logicguard.providers import ProviderError, create_provider
19
+ from logicguard.reporters import (
20
+ format_json,
21
+ format_sarif,
22
+ format_terminal,
23
+ print_terminal,
24
+ )
25
+ from logicguard.rules.base import RuleRegistry, discover_rules
26
+
27
+ DEFAULT_RULES_PACKAGE = "logicguard.rules"
28
+
29
+
30
+ class OutputFormat(StrEnum):
31
+ """Supported CLI report output formats."""
32
+
33
+ TERMINAL = "terminal"
34
+ JSON = "json"
35
+ SARIF = "sarif"
36
+
37
+
38
+ class ProviderChoice(StrEnum):
39
+ """Supported verification provider backends."""
40
+
41
+ OLLAMA = "ollama"
42
+ OPENROUTER = "openrouter"
43
+ ANTHROPIC = "anthropic"
44
+
45
+
46
+ class FailOnLevel(StrEnum):
47
+ """Minimum finding severity threshold that triggers exit code 1."""
48
+
49
+ LOW = "low"
50
+ MEDIUM = "medium"
51
+ HIGH = "high"
52
+ CRITICAL = "critical"
53
+
54
+
55
+ _FAIL_ON_TO_SEVERITY: dict[FailOnLevel, Severity] = {
56
+ FailOnLevel.LOW: Severity.LOW,
57
+ FailOnLevel.MEDIUM: Severity.MEDIUM,
58
+ FailOnLevel.HIGH: Severity.HIGH,
59
+ FailOnLevel.CRITICAL: Severity.CRITICAL,
60
+ }
61
+
62
+ FormatOption = Annotated[
63
+ OutputFormat,
64
+ typer.Option("--format", help="Report output format."),
65
+ ]
66
+ OutputOption = Annotated[
67
+ Path | None,
68
+ typer.Option("--output", help="Write report to a file instead of stdout."),
69
+ ]
70
+ FailOnOption = Annotated[
71
+ FailOnLevel,
72
+ typer.Option("--fail-on", help="Minimum finding severity causing exit code 1."),
73
+ ]
74
+ ProviderOption = Annotated[
75
+ ProviderChoice,
76
+ typer.Option("--provider", help="LLM verification provider backend."),
77
+ ]
78
+ ModelOption = Annotated[
79
+ str | None,
80
+ typer.Option("--model", help="Override the default model for the selected provider."),
81
+ ]
82
+ OfflineOnlyOption = Annotated[
83
+ bool,
84
+ typer.Option("--offline-only", help="Run deterministic AST checks with zero network calls."),
85
+ ]
86
+
87
+ app = typer.Typer(
88
+ name="logicguard",
89
+ help="Diff-aware static + LLM security analyzer.",
90
+ no_args_is_help=True,
91
+ )
92
+
93
+
94
+ def should_fail(findings: Sequence[Finding], fail_on: FailOnLevel) -> bool:
95
+ """Return True when any finding meets or exceeds the fail_on severity threshold."""
96
+ threshold = SEVERITY_RANK[_FAIL_ON_TO_SEVERITY[fail_on]]
97
+ return any(SEVERITY_RANK[finding.severity] >= threshold for finding in findings)
98
+
99
+
100
+ def _run_git(args: list[str], *, cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
101
+ """Execute a git command, raising RuntimeError when git is unavailable."""
102
+ if cwd is not None and not cwd.exists():
103
+ raise FileNotFoundError(f"Working directory does not exist: {cwd}")
104
+ cmd = ["git", *args]
105
+ env = {**os.environ, "LC_ALL": "C", "LANG": "C"}
106
+ try:
107
+ return subprocess.run(
108
+ cmd,
109
+ cwd=cwd,
110
+ env=env,
111
+ capture_output=True,
112
+ text=True,
113
+ encoding="utf-8",
114
+ errors="replace",
115
+ check=False,
116
+ )
117
+ except FileNotFoundError as exc:
118
+ raise RuntimeError("git executable not found on PATH.") from exc
119
+
120
+
121
+ def _is_unborn_head_error(stderr: str) -> bool:
122
+ """Return True if git diff HEAD failed because HEAD does not exist yet."""
123
+ lowered = stderr.lower()
124
+ return (
125
+ "ambiguous argument 'head'" in lowered
126
+ or "unknown revision" in lowered
127
+ or "bad revision 'head'" in lowered
128
+ or "needed a single revision" in lowered
129
+ )
130
+
131
+
132
+ def get_git_diff(base: str | None = None, *, cwd: Path | None = None) -> tuple[str, Path]:
133
+ """Collect unified git diff output and the resolved repository root directory."""
134
+ cleaned_base: str | None = None
135
+ if base is not None:
136
+ cleaned_base = base.strip()
137
+ if not cleaned_base:
138
+ raise ValueError("Git base reference must not be blank.")
139
+ if "\x00" in cleaned_base:
140
+ raise ValueError("Git base reference must not contain NUL bytes.")
141
+ if cleaned_base.startswith("-"):
142
+ raise ValueError(f"Invalid git base reference {base!r}: must not start with '-'.")
143
+
144
+ working_dir = cwd if cwd is not None else Path.cwd()
145
+ top_proc = _run_git(["rev-parse", "--show-toplevel"], cwd=working_dir)
146
+ in_git_repo = top_proc.returncode == 0 and bool(top_proc.stdout.strip())
147
+ repo_root = Path(top_proc.stdout.strip()) if in_git_repo else working_dir
148
+
149
+ ref = cleaned_base if cleaned_base is not None else "HEAD"
150
+ diff_args = ["diff", "--no-ext-diff", "--no-color"]
151
+ diff_proc = _run_git([*diff_args, ref], cwd=repo_root)
152
+
153
+ if (
154
+ diff_proc.returncode != 0
155
+ and cleaned_base is None
156
+ and in_git_repo
157
+ and _is_unborn_head_error(diff_proc.stderr)
158
+ ):
159
+ diff_proc = _run_git(diff_args, cwd=repo_root)
160
+
161
+ if diff_proc.returncode != 0:
162
+ detail = diff_proc.stderr.strip() or f"exit code {diff_proc.returncode}"
163
+ raise RuntimeError(f"git diff failed: {detail}")
164
+
165
+ return diff_proc.stdout, repo_root
166
+
167
+
168
+ def _exit_with_error(exc: BaseException) -> NoReturn:
169
+ """Print an error message to stderr and exit with code 2."""
170
+ err_console = Console(stderr=True)
171
+ err_console.print(f"Error: {exc}", style="bold red", markup=False)
172
+ raise typer.Exit(code=2)
173
+
174
+
175
+ def _write_output_file(output: Path, content: str) -> None:
176
+ """Write formatted report content to disk, creating parent directories if needed."""
177
+ output.parent.mkdir(parents=True, exist_ok=True)
178
+ normalized = content if content.endswith("\n") else f"{content}\n"
179
+ output.write_text(normalized, encoding="utf-8")
180
+
181
+
182
+ def _render_result(
183
+ result: ScanResult,
184
+ *,
185
+ output_format: OutputFormat,
186
+ output: Path | None,
187
+ registry: RuleRegistry,
188
+ repo_root: Path | None = None,
189
+ ) -> None:
190
+ """Render a ScanResult to stdout or a target file in the requested format."""
191
+ if output_format == OutputFormat.TERMINAL:
192
+ if output is not None:
193
+ _write_output_file(output, format_terminal(result, repo_root=repo_root))
194
+ else:
195
+ print_terminal(result, repo_root=repo_root)
196
+ return
197
+
198
+ rendered = (
199
+ format_json(result)
200
+ if output_format == OutputFormat.JSON
201
+ else format_sarif(result, registry=registry)
202
+ )
203
+ if output is not None:
204
+ _write_output_file(output, rendered)
205
+ else:
206
+ typer.echo(rendered)
207
+
208
+
209
+ def _execute_scan(
210
+ *,
211
+ output_format: OutputFormat,
212
+ output: Path | None,
213
+ fail_on: FailOnLevel,
214
+ provider_choice: ProviderChoice,
215
+ model: str | None,
216
+ offline_only: bool,
217
+ scan_fn: Callable[[LogicGuardEngine], tuple[ScanResult, Path | None]],
218
+ ) -> int:
219
+ """Instantiate provider and engine, run scan_fn, render output, and return exit code."""
220
+ registry = discover_rules(DEFAULT_RULES_PACKAGE)
221
+ provider = create_provider(
222
+ provider=provider_choice.value,
223
+ model=model,
224
+ offline_only=offline_only,
225
+ )
226
+ try:
227
+ engine = LogicGuardEngine(provider, registry=registry)
228
+ result, repo_root = scan_fn(engine)
229
+ finally:
230
+ close_fn = getattr(provider, "close", None)
231
+ if callable(close_fn):
232
+ close_fn()
233
+
234
+ _render_result(
235
+ result,
236
+ output_format=output_format,
237
+ output=output,
238
+ registry=registry,
239
+ repo_root=repo_root,
240
+ )
241
+ return 1 if should_fail(result.findings, fail_on) else 0
242
+
243
+
244
+ def _run_guarded(action: Callable[[], int]) -> None:
245
+ """Execute a CLI command body, mapping runtime and config failures to exit code 2."""
246
+ try:
247
+ exit_code = action()
248
+ except (
249
+ ProviderError,
250
+ ImportError,
251
+ SyntaxError,
252
+ OSError,
253
+ ValueError,
254
+ RuntimeError,
255
+ subprocess.SubprocessError,
256
+ ) as exc:
257
+ _exit_with_error(exc)
258
+ if exit_code != 0:
259
+ raise typer.Exit(code=exit_code)
260
+
261
+
262
+ def _print_rules(registry: RuleRegistry) -> None:
263
+ """Display discovered rules as an ASCII table, or a clear empty-state message."""
264
+ console = Console()
265
+ discovered = registry.all()
266
+ if not discovered:
267
+ console.print("No security rules registered.")
268
+ return
269
+
270
+ table = Table(title="Registered Security Rules", box=box.ASCII)
271
+ table.add_column("Rule ID", style="bold", no_wrap=True)
272
+ table.add_column("Title")
273
+ table.add_column("Severity", no_wrap=True)
274
+ table.add_column("CWE", no_wrap=True)
275
+ table.add_column("Languages")
276
+ for rule in discovered:
277
+ table.add_row(
278
+ Text(rule.rule_id),
279
+ Text(rule.title),
280
+ Text(rule.default_severity.value),
281
+ Text(rule.cwe_id.strip() or "-"),
282
+ Text(", ".join(rule.languages)),
283
+ )
284
+ console.print(table)
285
+
286
+
287
+ @app.command()
288
+ def scan(
289
+ target: Annotated[Path, typer.Argument(help="File or directory path to scan.")],
290
+ output_format: FormatOption = OutputFormat.TERMINAL,
291
+ output: OutputOption = None,
292
+ fail_on: FailOnOption = FailOnLevel.MEDIUM,
293
+ provider: ProviderOption = ProviderChoice.OLLAMA,
294
+ model: ModelOption = None,
295
+ offline_only: OfflineOnlyOption = False,
296
+ ) -> None:
297
+ """Scan a file or directory for business-logic vulnerabilities."""
298
+
299
+ def _action() -> int:
300
+ if not target.exists():
301
+ raise FileNotFoundError(f"Scan target does not exist: {target}")
302
+ resolved_cwd = Path.cwd().resolve()
303
+ resolved_target = target.resolve()
304
+ scan_root = (
305
+ resolved_cwd
306
+ if resolved_target.is_relative_to(resolved_cwd)
307
+ else (resolved_target if resolved_target.is_dir() else resolved_target.parent)
308
+ )
309
+ return _execute_scan(
310
+ output_format=output_format,
311
+ output=output,
312
+ fail_on=fail_on,
313
+ provider_choice=provider,
314
+ model=model,
315
+ offline_only=offline_only,
316
+ scan_fn=lambda engine: (engine.scan_path(target), scan_root),
317
+ )
318
+
319
+ _run_guarded(_action)
320
+
321
+
322
+ @app.command()
323
+ def diff(
324
+ base: Annotated[
325
+ str | None,
326
+ typer.Option("--base", help="Git ref or range to diff against (defaults to HEAD)."),
327
+ ] = None,
328
+ output_format: FormatOption = OutputFormat.TERMINAL,
329
+ output: OutputOption = None,
330
+ fail_on: FailOnOption = FailOnLevel.MEDIUM,
331
+ provider: ProviderOption = ProviderChoice.OLLAMA,
332
+ model: ModelOption = None,
333
+ offline_only: OfflineOnlyOption = False,
334
+ ) -> None:
335
+ """Scan changed functions in the current git diff for business-logic vulnerabilities."""
336
+
337
+ def _action() -> int:
338
+ diff_text, repo_root = get_git_diff(base)
339
+ return _execute_scan(
340
+ output_format=output_format,
341
+ output=output,
342
+ fail_on=fail_on,
343
+ provider_choice=provider,
344
+ model=model,
345
+ offline_only=offline_only,
346
+ scan_fn=lambda engine: (engine.scan_diff(diff_text, repo_root=repo_root), repo_root),
347
+ )
348
+
349
+ _run_guarded(_action)
350
+
351
+
352
+ @app.command()
353
+ def rules() -> None:
354
+ """List all auto-discovered security rules."""
355
+
356
+ def _action() -> int:
357
+ registry = discover_rules(DEFAULT_RULES_PACKAGE)
358
+ _print_rules(registry)
359
+ return 0
360
+
361
+ _run_guarded(_action)
File without changes