From d4c9af07125974fcdb13704440d25f530c2e0baf Mon Sep 17 00:00:00 2001 From: officialfrancismendoza Date: Sat, 14 Nov 2026 13:54:54 +0700 Subject: [PATCH 1/2] Add automatically generated security regression tests (#41) --- .github/workflows/tests.yml | 22 + README.md | 8 + docs/EVENT_LOGGING.md | 8 + docs/REGRESSION_TESTS.md | 245 ++++++ openhack/__main__.py | 31 + openhack/agents/coordinator.py | 60 ++ openhack/agents/session.py | 51 +- openhack/config.py | 16 + openhack/headless_scan.py | 22 + openhack/prompts/__init__.py | 3 + openhack/prompts/regression_test.py | 66 ++ openhack/regression/__init__.py | 15 + openhack/regression/evidence.py | 141 ++++ openhack/regression/frameworks.py | 763 ++++++++++++++++++ openhack/regression/generator.py | 324 ++++++++ openhack/regression/headless.py | 169 ++++ openhack/regression/invariants.py | 292 +++++++ openhack/regression/models.py | 132 +++ openhack/regression/pipeline.py | 726 +++++++++++++++++ openhack/regression/workspace.py | 394 +++++++++ openhack/sandbox/container_runner.py | 183 +++++ openhack/sandbox/orchestrator.py | 22 +- openhack/tui.py | 118 ++- tests/conftest.py | 4 + .../regression/idor_notes_app/fixed_app.py | 101 +++ .../idor_notes_app/vulnerable/Dockerfile | 7 + .../idor_notes_app/vulnerable/app.py | 101 +++ .../idor_notes_app/vulnerable/pytest.ini | 3 + .../vulnerable/requirements.txt | 2 + .../vulnerable/tests/conftest.py | 20 + .../vulnerable/tests/test_notes.py | 12 + tests/regression_support.py | 429 ++++++++++ tests/test_cli_dispatch.py | 2 +- tests/test_regression_e2e_docker.py | 288 +++++++ tests/test_regression_evidence.py | 76 ++ tests/test_regression_frameworks.py | 270 +++++++ tests/test_regression_invariants.py | 136 ++++ tests/test_regression_lifecycle.py | 383 +++++++++ tests/test_regression_pipeline.py | 512 ++++++++++++ tests/test_regression_workspace.py | 144 ++++ 40 files changed, 6279 insertions(+), 22 deletions(-) create mode 100644 docs/REGRESSION_TESTS.md create mode 100644 openhack/prompts/regression_test.py create mode 100644 openhack/regression/__init__.py create mode 100644 openhack/regression/evidence.py create mode 100644 openhack/regression/frameworks.py create mode 100644 openhack/regression/generator.py create mode 100644 openhack/regression/headless.py create mode 100644 openhack/regression/invariants.py create mode 100644 openhack/regression/models.py create mode 100644 openhack/regression/pipeline.py create mode 100644 openhack/regression/workspace.py create mode 100644 openhack/sandbox/container_runner.py create mode 100644 tests/fixtures/regression/idor_notes_app/fixed_app.py create mode 100644 tests/fixtures/regression/idor_notes_app/vulnerable/Dockerfile create mode 100644 tests/fixtures/regression/idor_notes_app/vulnerable/app.py create mode 100644 tests/fixtures/regression/idor_notes_app/vulnerable/pytest.ini create mode 100644 tests/fixtures/regression/idor_notes_app/vulnerable/requirements.txt create mode 100644 tests/fixtures/regression/idor_notes_app/vulnerable/tests/conftest.py create mode 100644 tests/fixtures/regression/idor_notes_app/vulnerable/tests/test_notes.py create mode 100644 tests/regression_support.py create mode 100644 tests/test_regression_e2e_docker.py create mode 100644 tests/test_regression_evidence.py create mode 100644 tests/test_regression_frameworks.py create mode 100644 tests/test_regression_invariants.py create mode 100644 tests/test_regression_lifecycle.py create mode 100644 tests/test_regression_pipeline.py create mode 100644 tests/test_regression_workspace.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index e9ace70..7340719 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -27,3 +27,25 @@ jobs: - name: Run tests run: uv run python -m pytest tests/ -v + + regression-sandbox-e2e: + # Security regression test generation validated in real Docker containers + # (skipped in the matrix above, which runs without OPENHACK_DOCKER_TESTS). + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Install uv + uses: astral-sh/setup-uv@v4 + + - name: Set up Python 3.12 + run: uv python install 3.12 + + - name: Install dependencies + run: uv sync --dev + + - name: Run Docker end-to-end tests + env: + OPENHACK_DOCKER_TESTS: "1" + run: uv run python -m pytest tests/test_regression_e2e_docker.py -v diff --git a/README.md b/README.md index f85051c..5089205 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,8 @@ OpenHack does `recon` -> `hunting` -> `validation` -> `verification` all in one **Verification**: Verification agent performs a full browser + sandbox based attack to find verify vulnerabilities in a real docker / DOM environment. +**Regression tests** *(opt-in)*: For verified vulnerabilities, OpenHack can write a security regression test in your repo's own test framework, and keeps it only after the sandbox shows it fails on the vulnerable code and passes on the fix. + ## Quick start @@ -70,6 +72,7 @@ OpenHack runs a multi-agent pipeline against your codebase: - **Validators** — re-read the suspect code to confirm or reject each candidate finding - **Sandbox verification** (`/verify sandbox`) *(Beta — requires Docker)* — spins up your app in a Docker container and attempts to exploit each finding with live HTTP requests. Findings that are successfully exploited get a ✓ mark. - **Browser verification** (`/verify browser`) *(Beta — requires Docker when combined with sandbox)* — launches a headless browser against the sandboxed app to verify client-side vulnerabilities (XSS, CSRF, DOM-based issues) with real browser execution. +- **Security regression tests** *(Beta, opt-in — requires Docker)* — for sandbox-verified IDOR findings in pytest projects, extracts the violated security invariant and generates a test in your repo's existing suite. The test is only accepted after it fails on the vulnerable revision and passes on the fixed revision in locked-down containers. You get it as a `git apply`-able patch, and it's included in the `/copy` fix prompt. Enable with `regression_tests_enabled`; see [docs/REGRESSION_TESTS.md](docs/REGRESSION_TESTS.md). > **Docker prerequisite.** Sandbox verification requires Docker Desktop (or any working Docker daemon) installed and running on the machine where the scan runs. Browser verification inherits this when used with sandbox. If Docker isn't running, `/verify sandbox` will fail with a clear error before the scan starts. @@ -151,6 +154,7 @@ OpenHack runs the same pipeline as the TUI, prints progress to stdout, writes a | `openhack --plan ""` | Draft a read-only attack plan | | `openhack --sessions` | List all saved scans | | `openhack --resume ` | Resume a scan from its last checkpoint | +| `openhack --regression-tests [rev]` | Generate or re-validate security regression tests for a saved scan against the fixed revision `rev` (git ref or directory) | | `openhack --classify [path]` | Classify frameworks + detect entry points (no LLM calls) | | `openhack --login` | Log in to your OpenHack account | | `openhack --setup` | Run the setup wizard | @@ -199,6 +203,10 @@ You can override at runtime via environment variables: | `OPENHACK_API_KEY` | Bearer token for the OpenHack inference API | | `OPENHACK_DEV=1` | Point the CLI at local dev servers (app on `:9080`, inference on `:8787`) for self-hosted setups | | `PROMPT_CACHING=0` | Stop sending `prompt_cache_key` with API calls — needed for OpenAI-compatible endpoints that reject it (also: `/config prompt_caching false`) | +| `REGRESSION_TESTS_ENABLED=1` | Generate sandbox-validated security regression tests for verified findings (also: `/config regression_tests_enabled true`) | +| `REGRESSION_TESTS_FIXED_REF` | Git revision (or directory) holding the fix that regression tests are validated against | + +Further regression-test settings (attempts, runs, timeouts, base image) are listed in [docs/REGRESSION_TESTS.md](docs/REGRESSION_TESTS.md). ## Privacy diff --git a/docs/EVENT_LOGGING.md b/docs/EVENT_LOGGING.md index d608228..26eaecf 100644 --- a/docs/EVENT_LOGGING.md +++ b/docs/EVENT_LOGGING.md @@ -33,6 +33,14 @@ not silently discard the remainder: - When shell output exceeds the context cap, its complete stdout/stderr is saved under `~/.openhack/scans/artifacts//` with mode `0600`. - The tool result and journal contain the artifact path, size, and SHA-256. +- Security regression tests (the test file, a `git apply` patch and the + validation record) are saved under + `~/.openhack/scans/artifacts//regression-tests/` with the same + owner-only permissions; see [REGRESSION_TESTS.md](REGRESSION_TESTS.md). + +Reports also record the scanned revision (`repository`: commit, branch, and +whether tracked files had uncommitted changes), so later regression-test +validation can materialize exactly the code that was scanned. ## Completion contract diff --git a/docs/REGRESSION_TESTS.md b/docs/REGRESSION_TESTS.md new file mode 100644 index 0000000..17e21a9 --- /dev/null +++ b/docs/REGRESSION_TESTS.md @@ -0,0 +1,245 @@ +# Security regression tests + +When OpenHack verifies a vulnerability by exploiting it in its sandbox, it can +also write a **security regression test** for it. The test goes into your +repository's existing test suite and keeps the bug from coming back. + +A generated test is only accepted after OpenHack shows, in its Docker +sandbox, that the test **fails on the vulnerable code because the +vulnerability exists** and **passes on the remediated code**. An accepted +test is an ordinary test file. It runs with your normal test command and in +your CI, with no OpenHack install and no LLM calls. + +The feature is **opt-in and disabled by default**. It needs Docker, the same +as sandbox verification. + +## Where it fits + +``` +recon → hunters → validation → sandbox exploit verification → (browser verification) + │ records redacted exploit evidence + ▼ + Step 6: security regression tests + invariant → generate → sandbox validation + ▼ + finding.regressionTest · patch artifact · /copy fix prompt +``` + +The open-source scanner does not apply fixes or open pull requests. The +validated test is delivered in three ways: as a patch you can `git apply`, +alongside the finding in the report and the TUI, and inside the `/copy` +AI-fix prompt. That way it lands in the same change as the fix. + +## Requirements + +- **Docker** running locally (the same daemon sandbox verification uses). +- **Sandbox verification** enabled (`sandbox_enabled`, or `/verify sandbox` + in the TUI). The invariant is derived from the recorded exploit, so a + finding that was only reviewed by the LLM validator is reported as + `missing_evidence`. +- **A remediated revision** to validate against: a git commit, branch or tag + containing the fix, or a directory with the fixed code. +- **An existing test suite** that OpenHack supports (currently pytest). + OpenHack never bootstraps a test framework your repository doesn't use. + +## Enabling and configuring + +Each setting can go in `~/.openhack/config`, an environment variable (the +upper-cased name), or a `.env` file. `regression_tests_enabled` and +`regression_tests_fixed_ref` can also be set from the TUI with `/config`. + +| Setting | Default | Purpose | +| --- | --- | --- | +| `regression_tests_enabled` | `false` | Run Step 6 for every scan | +| `regression_tests_fixed_ref` | unset | Git revision or directory holding the fix | +| `regression_tests_max_attempts` | `3` | Generation attempts per finding, each with validation feedback | +| `regression_tests_validation_runs` | `2` | Sandbox runs per revision (outcomes must be identical) | +| `regression_tests_timeout` | `180` | Seconds per test run before the container is killed | +| `regression_tests_build_timeout` | `900` | Seconds to build a sandbox image | +| `regression_tests_base_image` | `python:-slim` | Base image for sandbox images (`` from `.python-version`/`runtime.txt`) | +| `regression_test_model_id` | session model | Model used by the generator agent | + +```bash +export SANDBOX_ENABLED=true +export REGRESSION_TESTS_ENABLED=true +openhack --scan . +``` + +## Workflows + +### Scan, fix, then validate + +This is the most common order of events, because a fix usually doesn't exist +yet when the scan runs. + +1. Run `openhack --scan .` with the feature enabled. Each verified finding + gets a test that has been shown to fail on the vulnerable code. With no fix + to validate against, its status is `remediation_unavailable` and the test + is saved as a pending artifact. +2. Fix the vulnerability on a branch, for example with the `/copy` prompt, + which already contains the pending test as an acceptance criterion. +3. Validate against the fix: + + ```bash + openhack --regression-tests fix/idor + ``` + + The vulnerable revision is the commit that was scanned (recorded in the + report). If the scan ran on uncommitted changes, the working tree is used + instead. The remediated revision is, in order of preference: the argument; + then `regression_tests_fixed_ref`; then `HEAD`, if it has moved past the + scanned commit. Pass a directory (for example `.`) to validate an + uncommitted fix in the working tree. A pending test is re-validated + **without any LLM call**. A new test is generated only if the pending one + no longer reproduces the vulnerability. + +The command updates the saved report and exits non-zero if any eligible +finding ended without a validated test. Unsupported classes and findings +without exploit evidence don't count as failures. + +### The fix already exists + +Set `regression_tests_fixed_ref` (for example in CI, to the PR branch) and the +scan validates against it immediately. + +### In the TUI + +`/config regression_tests_enabled true`, then `/scan`. The Findings tab shows +each finding's regression-test status, the generated test, its run command +and the patch path. `/copy` includes the test in the AI-fix prompt. + +## How a test is generated and validated + +1. **Security invariant.** For IDOR, the sandbox exploit request (for example + `GET /api/notes/1`) is generalized into an endpoint template + (`/api/notes/{note_id}`), the object identifier, and the operation. From + those, OpenHack states the property the exploit violated: *an + authenticated principal must not read/update/delete an object owned by + another principal, whatever identifier it supplies*. It also records what + must keep working: the owner still has access. Captured credentials are + redacted before any of this is stored or shown to a model. +2. **Generation.** An agent reads a private copy of the repository + (read-only, jailed) and writes one new test file using your existing + framework, fixtures and conventions. It must declare which test functions + are **invariant tests** (expected to fail on vulnerable code) and which are + **control tests** (legitimate access, expected to pass on both versions). +3. **Checks before anything runs.** The test must be a new file under your + existing test directory that pytest will discover. It can never overwrite, + modify or delete an existing test. A static policy rejects skips and + xfails, swallowed assertions, network or subprocess use, dynamic code + execution, sleeps, pytest hooks, and embedded credentials. +4. **Sandbox validation.** For each revision, OpenHack builds an image from a + private copy of that revision plus your project's own test dependencies, + then runs the test in a fresh locked-down container (by default twice per + revision). The test is accepted only if: + - on the **vulnerable** code, every control test passes and at least one + invariant test fails *on an assertion*. A crash, import error, missing + fixture, skip or error doesn't count; + - on the **remediated** code, every test passes; + - every declared test ran, and all runs of a revision produced identical + outcomes. +5. **Feedback.** A rejected test is sent back to the generator with the + precise reason and per-test outcomes, up to `regression_tests_max_attempts` + times. One case is never retried: if an invariant test still fails its + assertion on the remediated code, the fix may be incomplete. Retrying would + mean weakening the test until it passes, so the finding is reported as + `validation_failed` instead. + +## Sandbox isolation + +Generated tests and the repository code they exercise are treated as +untrusted. They only ever execute inside a container started with: + +- `--network none`. Dependencies are installed during the image build, but + the test run can't reach the network. +- No host mounts. The test goes in, and results come out, via `docker cp`. +- A non-root user (`65534`), `--cap-drop ALL` and `no-new-privileges`. +- Memory, CPU and PID limits, plus a wall-clock timeout after which the + container is killed. +- A fresh container per run, always removed afterwards. Images are removed + when the run finishes. + +The private workspace copies leave out `.env` files (templates like +`.env.example` are kept), private keys, `.npmrc`/`.pypirc`/`.netrc`, cloud +credential directories, symlinks and git submodules. Your checkout is never +modified. + +## Results and artifacts + +Every finding gets a `regressionTest` entry in the scan report +(`~/.openhack/scans/.json`). It holds the status, the reason, the +invariant, the test path and code, the run command, and per-revision +outcomes. Verified findings also carry their redacted `exploitEvidence`. + +Validated and pending tests are written, owner-only, to +`~/.openhack/scans/artifacts//regression-tests//`: + +- the test file, at its repository path; +- `regression-test.patch`, to apply from the repository root with + `git apply `; +- `result.json`, the full validation record. + +Rejected tests are kept in the report for review but are never written as +artifacts. + +### Statuses + +| Status | Meaning | What to do | +| --- | --- | --- | +| `validated` | Fails on the vulnerable revision, passes on the remediated one | Apply the patch with your fix | +| `remediation_unavailable` | Reproduces the vulnerability; there was no fix to validate against | Fix it, then run `openhack --regression-tests ` | +| `unsupported_vulnerability` | The class isn't supported yet | — | +| `unsupported_framework` | No supported existing test suite was found | — | +| `missing_evidence` | The finding wasn't verified by sandbox exploitation | Enable sandbox verification | +| `generation_failed` | No valid test was produced (the policy rejected every attempt, or the model never submitted one) | Retry, or use a stronger `regression_test_model_id` | +| `validation_failed` | Candidate tests ran but didn't meet the criteria (including an incomplete fix) | Read the reason; check that the fix covers every operation | +| `sandbox_error` | Docker was unavailable, or an image couldn't be built | Start Docker; check dependency installation or `regression_tests_base_image` | + +## Supported classes and frameworks + +- **Vulnerability classes:** IDOR / broken object-level authorization + (CWE-639). +- **Test frameworks:** pytest (Python), including Flask, FastAPI, Starlette and + pytest-django projects. Requirements files (including `-r`/`-c` includes), + `pyproject.toml` test extras and installable projects are supported, and so + are monorepos: the project containing the finding is used. +- **Not yet supported** (reported as unsupported): other vulnerability + classes; Jest, Vitest, Mocha and other JavaScript runners; Go `testing`; + JUnit; RSpec; PHPUnit; and Django's `manage.py test` runner without pytest. + +To add a vulnerability class, subclass `VulnerabilityClassSpec` in +`openhack/regression/invariants.py` and register it in `CLASS_SPECS`. To add a +test framework, subclass `FrameworkAdapter` in +`openhack/regression/frameworks.py` and register it in `ADAPTERS`. + +## Limitations + +- Tests that need external services (databases, caches, message brokers) + can't run, because the container has no network and no service containers. + Suites that use in-process test clients with in-memory or SQLite state work. +- Building a sandbox image installs your dependencies, which needs network + access to your package index. Behind a private index or TLS interception, + set `regression_tests_base_image` to an image configured for it. +- Validation proves the test tells the two revisions apart. Validate against + a focused fix commit: unrelated changes in the remediated revision make that + signal less specific. +- The static policy is a guardrail, not the isolation boundary — the container + is. A test runs inside the same process as pytest, so result integrity also + relies on the policy and on cross-checking declared tests against reported + outcomes. +- During a scan, the vulnerable revision is the working tree that was scanned. +- Only one test file is generated per finding, and existing tests are never + edited. + +## Testing this feature + +```bash +uv run python -m pytest tests/test_regression_*.py +# Real Docker end-to-end (needs network access for image builds): +OPENHACK_DOCKER_TESTS=1 uv run python -m pytest tests/test_regression_e2e_docker.py +``` + +`OPENHACK_TEST_BASE_IMAGE` overrides the base image used by the end-to-end +tests. The fixture is an intentionally vulnerable Flask notes API with its own +pytest suite, plus its remediated counterpart, in +`tests/fixtures/regression/idor_notes_app/`. diff --git a/openhack/__main__.py b/openhack/__main__.py index 9c853d9..e2fe1b9 100644 --- a/openhack/__main__.py +++ b/openhack/__main__.py @@ -9,6 +9,9 @@ openhack --agent [path] Interactive agent prompt loop (no TUI) openhack --sessions List all saved scan sessions openhack --resume Resume a previous scan session + openhack --regression-tests [fixed-revision] + Generate/validate security regression tests + for a saved scan against the fixed code openhack --classify [path] Classify frameworks and detect entry points openhack --login Log in to your OpenHack account openhack --setup Run the setup wizard @@ -179,6 +182,33 @@ def _cmd_resume(): _launch_tui(resume_session_id=report_path.stem) +def _cmd_regression_tests(): + """Generate or re-validate security regression tests for a saved scan.""" + session_id = sys.argv[2] if len(sys.argv) > 2 else None + if not session_id: + print("Usage: openhack --regression-tests [fixed-revision]") + print(" fixed-revision: git commit/branch/tag (or a directory) containing the fix;") + print(" defaults to regression_tests_fixed_ref, then HEAD if it moved past the scan.") + return + fixed = sys.argv[3] if len(sys.argv) > 3 else None + + from openhack.config import settings + if not settings.openhack_api_key: + print("Error: not logged in.") + print("Run 'openhack --login' to set up your account, or set OPENHACK_API_KEY.") + return + + import asyncio + from openhack.regression.headless import run_regression_tests_for_report + try: + code = asyncio.run(run_regression_tests_for_report(session_id, fixed)) + except KeyboardInterrupt: + print() + return + if code: + sys.exit(code) + + def _cmd_classify(): """Classify frameworks and detect entry points.""" from pathlib import Path @@ -306,6 +336,7 @@ def _cmd_setup(): "scan": _cmd_scan, "sessions": _cmd_sessions, "resume": _cmd_resume, + "regression-tests": _cmd_regression_tests, "classify": _cmd_classify, "login": _cmd_login, "setup": _cmd_setup, diff --git a/openhack/agents/coordinator.py b/openhack/agents/coordinator.py index ab492e3..4ff5540 100644 --- a/openhack/agents/coordinator.py +++ b/openhack/agents/coordinator.py @@ -38,6 +38,7 @@ from openhack.categories import normalize_category, normalize_severity from openhack.framework_detection import detect_frameworks from openhack.quality import run_quality_gates +from openhack.regression.evidence import sanitize_exploit_evidence # Static validator removed — line number correction in hunter, semantic validation by LLM from openhack.config import settings @@ -935,6 +936,11 @@ async def run_pass2(task_text, batch_idx): finding.poc = r["working_poc"] finding.validated = True finding.source = "sandbox_verified" + # Keep a redacted record of the exploit: regression + # test generation derives the violated invariant from it. + finding.exploit_evidence = ( + sanitize_exploit_evidence(r) or finding.exploit_evidence + ) # Remove findings that couldn't be exploited in sandbox if not_exploitable: @@ -1070,6 +1076,14 @@ async def run_pass2(task_text, batch_idx): content=f"Browser verification failed: {str(e)}. Findings preserved.", ) + # Step 6: Security regression tests (optional) + if settings.regression_tests_enabled and self.session.findings: + regression_cost, regression_tokens = await self._run_regression_tests() + total_cost += regression_cost + total_tokens += regression_tokens + self.session.total_cost = total_cost + self.session.total_tokens = total_tokens + self.session.status = SessionStatus.COMPLETED # Clean up checkpoints on successful completion @@ -1101,5 +1115,51 @@ async def run_pass2(task_text, batch_idx): logger.debug(f"Scan failed: {e}", exc_info=True) raise + async def _run_regression_tests(self) -> tuple[float, int]: + """Step 6: turn verified findings into sandbox-validated regression tests. + + Every finding gets a regression_test status (validated, unsupported, + missing evidence, ...). A failure here never costs the scan its findings. + Returns the step's (cost, tokens). + """ + from openhack.regression.pipeline import PipelineOptions, RegressionTestPipeline + + self.session.add_trace( + agent="coordinator", event_type="step_start", + content=f"Step 6: Security regression tests ({len(self.session.findings)} findings)", + ) + regression_llm: Optional[LLMClient] = None + try: + regression_llm = self._create_llm_for_agent("regression_test") + options = PipelineOptions.from_settings(settings, self.session.target_dir) + pipeline = RegressionTestPipeline( + regression_llm, self.session, self.session.target_dir, options, + ) + results = await pipeline.run(self.session.findings) + except asyncio.CancelledError: + raise + except Exception as e: + logger.debug(f"Regression test generation failed: {e}", exc_info=True) + self.session.add_trace( + agent="coordinator", event_type="regression_test_error", + content=f"Regression test generation failed: {e}. Findings preserved.", + ) + results = [] + cost = regression_llm.total_cost if regression_llm else 0.0 + tokens = regression_llm.total_tokens if regression_llm else 0 + self.session.record_step_cost( + "regression_tests", cost, tokens, + input_tokens=regression_llm.total_input_tokens if regression_llm else 0, + output_tokens=regression_llm.total_output_tokens if regression_llm else 0, + ) + statuses: dict[str, int] = {} + for result in results: + statuses[result.status.value] = statuses.get(result.status.value, 0) + 1 + self.session.add_trace( + agent="coordinator", event_type="step_complete", + content={"step": "regression_tests", "statuses": statuses, "cost": cost, "tokens": tokens}, + ) + return cost, tokens + async def run(self, task: str, context: Optional[dict] = None) -> dict: return await self.run_full_scan() diff --git a/openhack/agents/session.py b/openhack/agents/session.py index b2a69de..9a2b88b 100644 --- a/openhack/agents/session.py +++ b/openhack/agents/session.py @@ -42,6 +42,10 @@ class Finding: confidence: str = "medium" validated: bool = False source: Optional[str] = None + # Redacted record of the sandbox exploit that verified this finding. + exploit_evidence: Optional[dict] = None + # Outcome of security regression test generation (see openhack.regression). + regression_test: Optional[dict] = None def fingerprint(self) -> str: import hashlib @@ -70,8 +74,36 @@ def to_dict(self) -> dict: } if self.source: d["verificationSource"] = self.source + if self.exploit_evidence: + d["exploitEvidence"] = self.exploit_evidence + if self.regression_test: + d["regressionTest"] = self.regression_test return d + @classmethod + def from_dict(cls, data: dict) -> "Finding": + """Rebuild a Finding from a saved report entry (camelCase or snake_case).""" + finding = cls( + category=data.get("category", "") or "", + severity=(data.get("severity") or "info"), + title=data.get("title", "") or "", + description=data.get("description", "") or "", + file_path=data.get("file_path") or data.get("filePath") or "", + line_number=data.get("line_number") or data.get("lineNumber"), + code_snippet=data.get("code_snippet") or data.get("relevantCode"), + poc=data.get("poc"), + fix=data.get("fix") or data.get("recommendation"), + cvss_score=data.get("cvss_score") or data.get("cvssScore"), + confidence=data.get("confidence", "medium"), + validated=bool(data.get("validated", False)), + source=data.get("source") or data.get("verificationSource"), + exploit_evidence=data.get("exploit_evidence") or data.get("exploitEvidence"), + regression_test=data.get("regression_test") or data.get("regressionTest"), + ) + if data.get("id"): + finding.id = str(data["id"]) + return finding + def _generate_vulnerability_type(self) -> str: category_lower = self.category.lower().replace(" ", "_").replace("-", "_") if "xss" in category_lower: @@ -186,6 +218,9 @@ def __init__( # Lazily created on first access because Session may be instantiated # outside an event loop (e.g. in serialization tests). self._pause_event: Optional[Any] = None + # Kept (not just journaled) so reports can record the exact commit that + # was scanned — regression-test validation materializes it later. + self.repository: dict[str, Any] = self._repository_snapshot() self.record_event( "session_started", { @@ -194,7 +229,7 @@ def __init__( "target_dir": self.target_dir, "pid": os.getpid(), "execution": self._execution_snapshot(), - "repository": self._repository_snapshot(), + "repository": self.repository, }, agent="system", ) @@ -278,6 +313,20 @@ def git(*args: str) -> str: "worktrees": worktrees, } + def repository_summary(self) -> dict[str, Any]: + """The scanned revision, as recorded in reports.""" + repo = getattr(self, "repository", None) or {} + # Only tracked-file changes mean HEAD differs from what was scanned. + changed = [ + line for line in str(repo.get("status") or "").splitlines() + if line.strip() and not line.startswith("??") + ] + return { + "head": repo.get("head", ""), + "branch": repo.get("branch", ""), + "dirty": bool(changed), + } + @property def events(self) -> list: return self.journal.records diff --git a/openhack/config.py b/openhack/config.py index e936492..c22ecb7 100644 --- a/openhack/config.py +++ b/openhack/config.py @@ -196,6 +196,22 @@ class Settings(BaseSettings): browser_max_exploit_attempts: int = 7 browser_timeout_ms: int = 30000 + # Security regression tests (opt-in; needs Docker). For sandbox-verified + # findings of a supported class, generate a test in the target repo's own + # framework and accept it only once the sandbox shows it fails on the + # vulnerable code and passes on the remediated revision (fixed_ref: a git + # revision or directory holding the fix). + regression_tests_enabled: bool = False + regression_tests_fixed_ref: Optional[str] = None + regression_tests_max_attempts: int = 3 + regression_tests_validation_runs: int = 2 + regression_tests_timeout: int = 180 + regression_tests_build_timeout: int = 900 + # "" = python:-slim. Override for a mirror or a base + # image that trusts a corporate TLS root. + regression_tests_base_image: str = "" + regression_test_model_id: Optional[str] = None + # Negotiate the Kitty keyboard protocol (CSI-u) in the TUI so modifier # combos that legacy terminal encoding collapses — Option/Alt+Backspace, # lone Escape, Ctrl+key — arrive disambiguated. Harmless on terminals that diff --git a/openhack/headless_scan.py b/openhack/headless_scan.py index 0099d2e..23c0d92 100644 --- a/openhack/headless_scan.py +++ b/openhack/headless_scan.py @@ -32,6 +32,9 @@ def _on_trace(entry: TraceEntry): event = entry.event_type or "" if event == "tool_call": pass + elif event == "regression_test_result": + data = entry.content if isinstance(entry.content, dict) else {} + print(f" [{agent}] REGRESSION TEST: {data.get('label', '?')} — {data.get('title', '')}") elif "finding" in event.lower(): print(f" [{agent}] FINDING: {entry.content}") elif event in ("status", "step_start", "step_complete", "resume"): @@ -39,6 +42,22 @@ def _on_trace(entry: TraceEntry): print(f" [{agent}] {event}: {snippet}") +def format_regression_status(finding: Finding) -> list[str]: + """Human-readable regression-test status lines for one finding.""" + data = finding.regression_test + if not isinstance(data, dict): + return [] + lines = [f"Regression test: {data.get('status_label') or data.get('status')}"] + if data.get("test_path") and data.get("status") in ("validated", "remediation_unavailable"): + lines[0] += f" — {data['test_path']}" + if data.get("reason"): + lines.append(f" {data['reason']}") + patch = (data.get("artifacts") or {}).get("patch") + if patch: + lines.append(f" Patch: {patch} (apply from the repository root: git apply )") + return lines + + def _write_report( session: Session, target_dir: str, @@ -69,6 +88,7 @@ def _write_report( "event_log_path": session.event_log_path, "event_count": len(session.events), "event_log_error": session.journal.last_error, + "repository": session.repository_summary(), "pid": os.getpid(), "started_at": datetime.fromtimestamp(start_time).isoformat(), "duration_seconds": round(elapsed, 2), @@ -190,6 +210,8 @@ async def run_headless_scan( desc = f.description or "" if desc: print(f" {desc}") + for line in format_regression_status(f): + print(f" {line}") print() cost = session.get_cost_breakdown() diff --git a/openhack/prompts/__init__.py b/openhack/prompts/__init__.py index e755f5c..f44ffd1 100644 --- a/openhack/prompts/__init__.py +++ b/openhack/prompts/__init__.py @@ -21,6 +21,7 @@ from .validator_continuation_incomplete import VALIDATOR_CONTINUATION_INCOMPLETE from .sandbox_verifier import SANDBOX_VERIFIER_PROMPT, SANDBOX_VERIFIER_TOOL_INSTRUCTIONS from .browser_verifier import BROWSER_VERIFIER_PROMPT, BROWSER_VERIFIER_TOOL_INSTRUCTIONS +from .regression_test import REGRESSION_TEST_PROMPT, REGRESSION_TEST_TOOL_INSTRUCTIONS from .feature_hunter import FEATURE_HUNTER_PROMPT, FEATURE_EXTRACTION_PROMPT from .nextjs import ( NEXTJS_PROMPTS, @@ -80,6 +81,8 @@ "SANDBOX_VERIFIER_TOOL_INSTRUCTIONS", "BROWSER_VERIFIER_PROMPT", "BROWSER_VERIFIER_TOOL_INSTRUCTIONS", + "REGRESSION_TEST_PROMPT", + "REGRESSION_TEST_TOOL_INSTRUCTIONS", "ALL_FRAMEWORK_PROMPTS", "NEXTJS_PROMPTS", "NEXTJS_IDOR_PROMPT", diff --git a/openhack/prompts/regression_test.py b/openhack/prompts/regression_test.py new file mode 100644 index 0000000..771b7aa --- /dev/null +++ b/openhack/prompts/regression_test.py @@ -0,0 +1,66 @@ +""" +Regression test generator agent prompt template. + +The agent turns a sandbox-verified vulnerability and its extracted security +invariant into a new test written in the target repository's own framework. +OpenHack then proves the test fails on the vulnerable code and passes on the +remediated code before accepting it. +""" + +REGRESSION_TEST_PROMPT = """You are the Regression Test Generator agent for OpenHack. A vulnerability in this repository was confirmed by actually exploiting it in OpenHack's sandbox. Your job is to write ONE new automated test that protects against this class of bug ever coming back. + +{project_context} + +## The confirmed vulnerability + +{finding_details} + +## The security invariant the exploit violated + +{invariant_details} + +The test must protect this INVARIANT — the underlying security property — not merely check that one exploit payload is blocked. + +## The repository's existing test suite + +{framework_details} +Suggested path for the new test file: `{suggested_path}` (relative to the project root). + +{class_guidance} + +## How your test will be judged + +OpenHack runs your test in an isolated sandbox (no network) against two versions of the code: +1. The VULNERABLE version. Your control tests must PASS and at least one invariant test must FAIL on an assertion — because the vulnerability exists, not because of a crash, a missing fixture, or an import error. +2. The REMEDIATED version. Every test must PASS. +Each version is run more than once; outcomes must be identical every time. A test that cannot be validated this way is rejected. + +## Rules + +1. Use the repository's existing test framework, fixtures, helpers and conventions. Read the existing tests and conftest/fixture files first and imitate them; reuse fixtures instead of rebuilding the app setup. +2. Create a NEW test file. Never modify, weaken or delete existing tests, and never modify application code. +3. Exercise the application in-process (its test client / app factory). No real network calls, no subprocesses, no sleeps, no reliance on test order, no randomness that can change outcomes. +4. Never skip or xfail anything, never catch AssertionError (or bare `except:`), never define pytest hooks, never call sys.exit. +5. Never copy tokens, cookies, session IDs, passwords or other values from the exploit evidence. Create throwaway users and credentials through the application itself. +6. Keep each test focused, give it a descriptive name, and give every assertion a clear failure message that explains the security property being protected. +7. Start the file with a short module docstring describing the invariant (and CWE) it protects. + +## Tools + +- `read_file`, `list_dir`, `glob`, `grep` — inspect the repository (read-only). +- `submit_regression_test` — submit the complete test file. Call it exactly once per attempt. +""" + +REGRESSION_TEST_TOOL_INSTRUCTIONS = """ + +## CRITICAL: How to submit + +Investigate briefly (the relevant route/handler, the auth mechanism, existing fixtures and tests), then call `submit_regression_test` with: +- `path`: the new test file path, relative to the project root +- `code`: the complete file contents +- `invariant_tests`: names of the test functions that assert the invariant (expected to FAIL on the vulnerable code) +- `control_tests`: names of the test functions proving legitimate access still works (expected to PASS on both versions) +- `summary`: one sentence describing what the test protects + +Do NOT stop without calling `submit_regression_test`. If OpenHack sends validation feedback, fix the problem it describes and submit the complete corrected file again. +""" diff --git a/openhack/regression/__init__.py b/openhack/regression/__init__.py new file mode 100644 index 0000000..eb54217 --- /dev/null +++ b/openhack/regression/__init__.py @@ -0,0 +1,15 @@ +""" +Security regression test generation for verified vulnerabilities. + +When enabled (``regression_tests_enabled``), OpenHack turns each eligible +sandbox-verified finding into a test written in the target repository's own +framework, and accepts it only after proving in the Docker sandbox that it +fails on the vulnerable code and passes on the remediated code. + +Entry point: ``openhack.regression.pipeline.RegressionTestPipeline``. +See docs/REGRESSION_TESTS.md. +""" + +from .models import RegressionTestResult, RegressionTestStatus, SecurityInvariant + +__all__ = ["RegressionTestResult", "RegressionTestStatus", "SecurityInvariant"] diff --git a/openhack/regression/evidence.py b/openhack/regression/evidence.py new file mode 100644 index 0000000..8e541c8 --- /dev/null +++ b/openhack/regression/evidence.py @@ -0,0 +1,141 @@ +""" +Exploit evidence from sandbox verification, made safe to persist and reuse. + +The sandbox verifier talks to a live application with real session tokens, +cookies and passwords. Only a redacted, bounded summary is kept on the +Finding: it feeds invariant extraction and the generator prompt, so it must +never be able to carry a credential into a generated test, a report, or an +LLM request. Generated test code gets a second, independent secret scan. +""" + +from __future__ import annotations + +import json +import re +from typing import Any, Optional + +from openhack.agents.eventlog import redact + +MAX_EVIDENCE_CHARS = 2000 +MAX_POC_CHARS = 4000 +MAX_BODY_CHARS = 1000 + +_SENSITIVE_HEADER = re.compile( + r"(authorization|cookie|api[-_]?key|auth[-_]?token|csrf|xsrf|session|secret)", + re.IGNORECASE, +) +_JWT = re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}") +_COOKIE_LINE = re.compile(r"(?im)^(\s*(?:set-)?cookie\s*:\s*).+$") +_ASSIGNED_SECRET = re.compile( + r"""(?ix) + (["']?(?:password|passwd|secret|token|api[_-]?key|session(?:_?id)?|cookie)["']? + \s*[:=]\s*) + (["'])(?:(?!\2).){4,}\2 + """ +) + +# Credential shapes that must never appear in a generated test. These are +# deliberately specific: tests legitimately contain throwaway passwords such +# as "correct-horse", but a live JWT or cloud key is always a leak. +SECRET_PATTERNS: list[tuple[str, re.Pattern]] = [ + ("JSON Web Token", _JWT), + ("private key", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----")), + ("AWS access key", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")), + ("GitHub token", re.compile(r"\bgh[pousr]_[A-Za-z0-9]{20,}\b")), + ("Slack token", re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}\b")), + ("Google API key", re.compile(r"\bAIza[0-9A-Za-z_-]{35}\b")), + ("Stripe live key", re.compile(r"\b[sr]k_live_[0-9A-Za-z]{16,}\b")), + ("API secret key", re.compile(r"\bsk-[A-Za-z0-9_-]{20,}\b")), + ("literal bearer token", re.compile(r"(?i)bearer\s+[A-Za-z0-9._~+/-]{24,}=*")), + ("redacted evidence placeholder", re.compile(r"\[REDACTED[A-Z_]*\]")), +] + + +def scrub_text(text: str) -> str: + """Remove credentials from free-form evidence text.""" + if not text: + return "" + cleaned = redact(str(text)) + cleaned = _JWT.sub("[REDACTED_JWT]", cleaned) + cleaned = _COOKIE_LINE.sub(r"\1[REDACTED]", cleaned) + cleaned = _ASSIGNED_SECRET.sub(r"\1\2[REDACTED]\2", cleaned) + return cleaned + + +def _bounded(text: str, limit: int) -> str: + return text if len(text) <= limit else text[: limit - 1] + "…" + + +def _sanitize_body(body: Any) -> Optional[str]: + if body is None or body == "": + return None + if isinstance(body, (dict, list)): + return _bounded(scrub_text(json.dumps(redact(body), default=str)), MAX_BODY_CHARS) + text = str(body) + try: + parsed = json.loads(text) + except (json.JSONDecodeError, ValueError): + return _bounded(scrub_text(text), MAX_BODY_CHARS) + return _bounded(scrub_text(json.dumps(redact(parsed), default=str)), MAX_BODY_CHARS) + + +def _sanitize_request(request: Any) -> Optional[dict]: + if not isinstance(request, dict): + return None + path = str(request.get("path") or request.get("url") or "").strip() + method = str(request.get("method") or "").strip().upper() + if not path and not method: + return None + headers = request.get("headers") + clean_headers: dict[str, str] = {} + if isinstance(headers, dict): + for key, value in list(headers.items())[:30]: + name = str(key)[:100] + clean_headers[name] = ( + "[REDACTED]" if _SENSITIVE_HEADER.search(name) + else _bounded(scrub_text(str(value)), 200) + ) + body = request.get("json_body", request.get("body")) + return { + "method": method[:10], + "path": _bounded(scrub_text(path), 500), + "headers": clean_headers, + "body": _sanitize_body(body), + } + + +def sanitize_exploit_evidence(result: Optional[dict]) -> Optional[dict]: + """Build the persisted evidence record from a sandbox ``exploitable`` result. + + Returns None when the result carries nothing that identifies the exploit, + so "verified but evidence-free" findings are treated as missing evidence + instead of producing a guessed invariant. + """ + if not isinstance(result, dict): + return None + request = _sanitize_request(result.get("exploit_request")) + evidence = _bounded(scrub_text(str(result.get("evidence") or "")), MAX_EVIDENCE_CHARS) + poc = _bounded(scrub_text(str(result.get("working_poc") or "")), MAX_POC_CHARS) + if not request and not evidence.strip() and not poc.strip(): + return None + try: + attempts = int(result.get("attempts_made") or 0) + except (TypeError, ValueError): + attempts = 0 + return { + "source": "sandbox", + "exploit_request": request, + "evidence": evidence, + "working_poc": poc, + "attempts_made": attempts, + "confidence": str(result.get("confidence") or ""), + } + + +def find_secrets(code: str) -> list[str]: + """Return the names of credential patterns present in generated code.""" + found = [] + for name, pattern in SECRET_PATTERNS: + if pattern.search(code or ""): + found.append(name) + return found diff --git a/openhack/regression/frameworks.py b/openhack/regression/frameworks.py new file mode 100644 index 0000000..308dcb7 --- /dev/null +++ b/openhack/regression/frameworks.py @@ -0,0 +1,763 @@ +""" +Test-framework adapters for generated regression tests. + +An adapter knows how a repository's *own* test suite is laid out and run: +where tests live and how they are discovered, which fixtures already exist, +how to install the project's test dependencies into a sandbox image, how to +run a single test file inside that container, and how to read the results +back. Generated tests must use the repository's existing framework so they +keep running in its normal CI without OpenHack. + +pytest is the initial adapter; ``ADAPTERS`` is the extension point. +""" + +from __future__ import annotations + +import ast +import configparser +import fnmatch +import json +import os +import re +import tomllib +import xml.etree.ElementTree as ET +from abc import ABC, abstractmethod +from dataclasses import asdict, dataclass, field +from pathlib import Path, PurePosixPath +from typing import Callable, Optional + +from .evidence import find_secrets, scrub_text +from .models import SecurityInvariant + +SKIP_DIRS = { + ".git", "node_modules", "__pycache__", ".venv", "venv", "env", ".tox", + ".mypy_cache", ".pytest_cache", "dist", "build", ".eggs", "site-packages", +} +RESULTS_DIR = "/openhack-results" +MAX_RESULTS_BYTES = 5_000_000 + + +class UnsupportedFrameworkError(Exception): + """The repository has no test framework OpenHack can generate tests for.""" + + +@dataclass +class FrameworkProfile: + """What an adapter learned about the repository's existing test suite.""" + + adapter: str + language: str + project_root: str + test_dir: str + file_patterns: list[str] + config_file: Optional[str] = None + dependency_files: list[str] = field(default_factory=list) + installable_project: bool = False + install_extras: list[str] = field(default_factory=list) + fixtures: dict[str, str] = field(default_factory=dict) + example_tests: list[str] = field(default_factory=list) + app_frameworks: list[str] = field(default_factory=list) + runtime_version: str = "" + framework_in_dependencies: bool = False + + def to_dict(self) -> dict: + return asdict(self) + + +@dataclass +class CaseOutcome: + name: str + classname: str + outcome: str # passed | failed | error | skipped + message: str = "" + # For failures: whether the test failed an assertion (the invariant check) + # rather than crashing on an unexpected exception. + assertion: bool = False + + @property + def base_name(self) -> str: + return self.name.split("[", 1)[0] + + +@dataclass +class RunReport: + cases: list[CaseOutcome] = field(default_factory=list) + exit_code: Optional[int] = None + timed_out: bool = False + collection_error: Optional[str] = None + output_tail: str = "" + + def outcomes(self) -> dict[str, str]: + return {f"{c.classname}::{c.name}": c.outcome for c in self.cases} + + +class FrameworkAdapter(ABC): + """Extension point for a test framework.""" + + name: str = "" + language: str = "" + + @abstractmethod + def detect(self, repo_root: Path, hint_path: Optional[str] = None) -> Optional[FrameworkProfile]: + """Return a profile if the repository uses this framework.""" + + @abstractmethod + def suggest_test_path( + self, profile: FrameworkProfile, invariant: SecurityInvariant, + exists: Callable[[str], bool], + ) -> str: + """A new, discoverable test path relative to the project root.""" + + @abstractmethod + def validate_test_path(self, profile: FrameworkProfile, relpath: str) -> Optional[str]: + """Return why ``relpath`` is unacceptable, or None.""" + + @abstractmethod + def static_check(self, code: str) -> list[str]: + """Policy violations in generated test code (never executes it).""" + + @abstractmethod + def default_base_image(self, profile: FrameworkProfile) -> str: + """Container base image when none is configured.""" + + @abstractmethod + def dockerfile(self, profile: FrameworkProfile, base_image: str) -> str: + """Dockerfile that installs the project's test dependencies.""" + + @abstractmethod + def container_command(self, profile: FrameworkProfile, test_relpath: str) -> list[str]: + """Command that runs one test file and writes results to RESULTS_DIR.""" + + @abstractmethod + def display_command(self, profile: FrameworkProfile, test_relpath: str) -> str: + """How a developer runs the test with the repository's normal runner.""" + + @abstractmethod + def parse_results(self, results_dir: Path, exit_code: Optional[int], timed_out: bool) -> RunReport: + """Read the results a container run copied back to the host.""" + + def prompt_context(self, profile: FrameworkProfile) -> str: + fixtures = ", ".join( + f"`{name}` ({path})" for name, path in sorted(profile.fixtures.items()) + ) or "none found" + examples = ", ".join(f"`{p}`" for p in profile.example_tests) or "none found" + return ( + f"- Test framework: **{self.name}** ({self.language})\n" + f"- Project root (relative to repository): `{profile.project_root}`\n" + f"- Test directory: `{profile.test_dir}` · discovery patterns: " + f"{', '.join(profile.file_patterns)}\n" + f"- Configuration: `{profile.config_file or 'defaults'}`\n" + f"- Existing fixtures: {fixtures}\n" + f"- Existing tests to imitate: {examples}\n" + f"- Application frameworks: {', '.join(profile.app_frameworks) or 'unknown'}\n" + ) + + +# ── Shared helpers ────────────────────────────────────────────────── + +def _iter_files(root: Path, pattern: str, max_depth: int = 6): + """Yield files matching ``pattern`` without descending into SKIP_DIRS. + + Pruning during the walk (rather than filtering rglob output) keeps large + node_modules / virtualenv trees from being traversed at all. + """ + root = Path(root) + for dirpath, dirnames, filenames in os.walk(root): + depth = len(Path(dirpath).relative_to(root).parts) + dirnames[:] = [ + d for d in dirnames + if d not in SKIP_DIRS and not d.endswith(".egg-info") + ] if depth < max_depth else [] + for name in filenames: + if fnmatch.fnmatch(name, pattern): + yield Path(dirpath) / name + + +def _read(path: Path, limit: int = 400_000) -> str: + try: + with open(path, "r", encoding="utf-8", errors="replace") as fp: + return fp.read(limit) + except OSError: + return "" + + +def _posix(path: Path | PurePosixPath | str) -> str: + return PurePosixPath(*Path(path).parts).as_posix() if str(path) not in ("", ".") else "." + + +def _xml_is_safe(text: str) -> bool: + lowered = text[:4096].lower() + return " str: + parts: list[str] = [] + while isinstance(node, ast.Attribute): + parts.append(node.attr) + node = node.value + if isinstance(node, ast.Name): + parts.append(node.id) + return ".".join(reversed(parts)) + return "" + + +def _module_root_forbidden(module: str) -> Optional[str]: + for name, why in _FORBIDDEN_MODULES.items(): + if module == name or module.startswith(name + "."): + return why + return None + + +class PytestAdapter(FrameworkAdapter): + name = "pytest" + language = "python" + + # ── detection ── + + def detect(self, repo_root: Path, hint_path: Optional[str] = None) -> Optional[FrameworkProfile]: + repo_root = repo_root.resolve() + candidates = self._candidate_roots(repo_root) + if not candidates: + return None + root = self._pick_root(candidates, hint_path) + project = repo_root / root if root != "." else repo_root + config_file, ini = self._pytest_config(project) + test_files = [p for p in self._test_files(project, ini)] + conftests = list(_iter_files(project, "conftest.py")) + deps = self._dependency_files(project) + pyproject = self._load_pyproject(project) + dep_text = "\n".join(_read(project / d) for d in deps).lower() + dep_text += "\n" + json.dumps(pyproject).lower() + # Any pytest-ecosystem package (pytest, pytest-django, ...) counts. + has_pytest_dep = bool(re.search(r"(? list[str]: + markers = ("pytest.ini", "pyproject.toml", "setup.cfg", "tox.ini", "setup.py", + "conftest.py", "requirements.txt") + roots: set[str] = set() + for marker in markers: + for path in _iter_files(repo_root, marker, max_depth=3): + rel = path.parent.relative_to(repo_root) + # A conftest.py inside tests/ belongs to the project above it. + if marker == "conftest.py" and rel.parts and rel.parts[-1] in ("tests", "test"): + rel = rel.parent + roots.add(_posix(rel)) + return sorted(roots, key=lambda r: (r.count("/"), r)) + + @staticmethod + def _pick_root(candidates: list[str], hint_path: Optional[str]) -> str: + if hint_path: + hint = _posix(hint_path) + best = None + for root in candidates: + if root == "." or hint == root or hint.startswith(root + "/"): + if best is None or len(root) > len(best): + best = root + if best is not None: + return best + return "." if "." in candidates else candidates[0] + + @staticmethod + def _pytest_config(project: Path) -> tuple[Optional[str], dict]: + ini_path = project / "pytest.ini" + if ini_path.is_file(): + parser = configparser.ConfigParser(interpolation=None) + try: + parser.read_string(_read(ini_path)) + return "pytest.ini", dict(parser["pytest"]) if parser.has_section("pytest") else {} + except configparser.Error: + return "pytest.ini", {} + pyproject = project / "pyproject.toml" + if pyproject.is_file(): + try: + data = tomllib.loads(_read(pyproject)) + except tomllib.TOMLDecodeError: + data = {} + options = data.get("tool", {}).get("pytest", {}).get("ini_options") + if isinstance(options, dict): + return "pyproject.toml", {k: v for k, v in options.items()} + for name, section in (("setup.cfg", "tool:pytest"), ("tox.ini", "pytest")): + path = project / name + if path.is_file(): + parser = configparser.ConfigParser(interpolation=None) + try: + parser.read_string(_read(path)) + except configparser.Error: + continue + if parser.has_section(section): + return name, dict(parser[section]) + return None, {} + + @staticmethod + def _ini_list(value) -> list[str]: + if isinstance(value, list): + return [str(v) for v in value] + if isinstance(value, str): + return value.split() + return [] + + def _patterns(self, ini: dict) -> list[str]: + return self._ini_list(ini.get("python_files")) or ["test_*.py", "*_test.py"] + + def _test_files(self, project: Path, ini: dict) -> list[Path]: + found: list[Path] = [] + for pattern in self._patterns(ini): + for path in _iter_files(project, pattern): + if path.name != "conftest.py" and path not in found: + found.append(path) + return found + + def _test_dir(self, project: Path, ini: dict, test_files: list[Path]) -> str: + for entry in self._ini_list(ini.get("testpaths")): + if (project / entry).is_dir(): + return _posix(PurePosixPath(entry)) + counts: dict[str, int] = {} + for path in test_files: + rel = _posix(path.parent.relative_to(project)) + counts[rel] = counts.get(rel, 0) + 1 + for preferred in ("tests", "test"): + if preferred in counts or (project / preferred).is_dir(): + return preferred + if counts: + return max(counts.items(), key=lambda kv: (kv[1], -kv[0].count("/")))[0] + return "tests" + + @staticmethod + def _dependency_files(project: Path) -> list[str]: + files: list[str] = [n for n in _REQUIREMENTS_NAMES if (project / n).is_file()] + req_dir = project / "requirements" + if req_dir.is_dir(): + files += sorted(_posix(p.relative_to(project)) for p in req_dir.glob("*.txt")) + # Follow `-r other.txt` / `-c constraints.txt` includes so the image + # build sees every file the listed requirements reference. + queue = list(files) + while queue: + current = queue.pop() + base = PurePosixPath(current).parent + for line in _read(project / current).splitlines(): + match = re.match(r"\s*(?:-r|--requirement|-c|--constraint)\s*=?\s*(\S+)", line) + if not match: + continue + include = _posix(base / match.group(1)) + if include not in files and ".." not in include and (project / include).is_file(): + files.append(include) + queue.append(include) + return files + + @staticmethod + def _load_pyproject(project: Path) -> dict: + path = project / "pyproject.toml" + if not path.is_file(): + return {} + try: + return tomllib.loads(_read(path)) + except tomllib.TOMLDecodeError: + return {} + + @staticmethod + def _fixtures(project: Path, conftests: list[Path]) -> dict[str, str]: + fixtures: dict[str, str] = {} + for conftest in conftests: + try: + tree = ast.parse(_read(conftest)) + except SyntaxError: + continue + rel = _posix(conftest.relative_to(project)) + for node in ast.walk(tree): + if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + continue + for dec in node.decorator_list: + target = dec.func if isinstance(dec, ast.Call) else dec + if _dotted(target) in ("pytest.fixture", "fixture"): + fixtures.setdefault(node.name, rel) + return fixtures + + @staticmethod + def _examples(project: Path, test_files: list[Path], hint_path: Optional[str]) -> list[str]: + hint_words = set(re.findall(r"[a-z]{3,}", (hint_path or "").lower())) + + def score(path: Path) -> tuple[int, str]: + words = set(re.findall(r"[a-z]{3,}", path.stem.lower())) + return (-len(words & hint_words), path.as_posix()) + + ranked = sorted(test_files, key=score) + return [_posix(p.relative_to(project)) for p in ranked[:3]] + + @staticmethod + def _python_version(project: Path, pyproject: dict) -> str: + pinned = _read(project / ".python-version").strip().splitlines() + if pinned: + match = re.match(r"(\d+\.\d+)", pinned[0].strip()) + if match: + return match.group(1) + runtime = re.search(r"python-(\d+\.\d+)", _read(project / "runtime.txt")) + if runtime: + return runtime.group(1) + requires = str(pyproject.get("project", {}).get("requires-python") or "") + upper = re.search(r"<\s*3\.(\d+)", requires) + if upper and int(upper.group(1)) <= 12: + return f"3.{int(upper.group(1)) - 1}" + return "3.12" + + # ── paths ── + + def suggest_test_path(self, profile, invariant, exists) -> str: + slug = re.sub(r"[^a-z0-9]+", "_", f"{invariant.vulnerability_class}_{invariant.resource}".lower()).strip("_") + base = PurePosixPath(profile.test_dir) / f"test_security_{slug or 'regression'}.py" + candidate = base.as_posix() + n = 2 + while exists(candidate): + candidate = (base.parent / f"{base.stem}_{n}.py").as_posix() + n += 1 + return candidate + + def validate_test_path(self, profile, relpath) -> Optional[str]: + raw = (relpath or "").strip() + if not raw: + return "no test file path was provided" + if "\\" in raw: + return "use forward slashes in the test path" + if not re.fullmatch(r"[A-Za-z0-9_./-]+", raw): + return f"test path may only contain letters, digits, '_', '-', '.' and '/': {raw}" + path = PurePosixPath(raw) + if path.is_absolute() or ".." in path.parts or raw.startswith("~"): + return f"test path must be relative to the project root without '..': {raw}" + if path.suffix != ".py": + return f"test file must be a .py file: {raw}" + if path.name == "conftest.py": + return "the regression test must be a new test module, not conftest.py" + if not any(fnmatch.fnmatch(path.name, pat) for pat in profile.file_patterns): + return ( + f"`{path.name}` would not be discovered by pytest " + f"(patterns: {', '.join(profile.file_patterns)})" + ) + test_dir = PurePosixPath(profile.test_dir) + if profile.test_dir not in (".", "") and test_dir not in path.parents: + return f"place the test under the existing test directory `{profile.test_dir}/`" + return None + + # ── static policy ── + + def static_check(self, code: str) -> list[str]: + violations: list[str] = [] + try: + tree = ast.parse(code or "") + except SyntaxError as exc: + return [f"syntax error on line {exc.lineno}: {exc.msg}"] + + tests = [ + n for n in ast.walk(tree) + if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name.startswith("test") + ] + if not tests: + violations.append("defines no test functions (names must start with `test`)") + if not any(isinstance(n, ast.Assert) for n in ast.walk(tree)): + violations.append("contains no assert statements") + + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + why = _module_root_forbidden(alias.name) + if why: + violations.append(f"imports `{alias.name}`, which {why}") + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + why = _module_root_forbidden(module) + if why: + violations.append(f"imports from `{module}`, which {why}") + for alias in node.names: + dotted = f"{module}.{alias.name}" + if dotted in _FORBIDDEN_CALLS: + violations.append(f"imports `{dotted}`, which {_FORBIDDEN_CALLS[dotted]}") + elif dotted.startswith(_FORBIDDEN_PREFIXES): + violations.append(f"imports `{dotted}`, which spawns processes") + elif dotted in _FORBIDDEN_MARKERS: + violations.append(f"imports `{dotted}`, so the test could pass without running") + elif isinstance(node, ast.Call): + name = _dotted(node.func) + if name in _FORBIDDEN_CALLS: + violations.append(f"calls `{name}()`, which {_FORBIDDEN_CALLS[name]}") + elif name.startswith(_FORBIDDEN_PREFIXES): + violations.append(f"calls `{name}()`, which spawns processes") + elif name.endswith(".skipTest"): + violations.append(f"calls `{name}()`, which skips the test, so it can never fail") + elif isinstance(node, ast.Attribute): + name = _dotted(node) + if name in _FORBIDDEN_MARKERS: + violations.append(f"uses `{name}`, so the test could pass without running") + elif isinstance(node, ast.ExceptHandler): + caught = _dotted(node.type) if node.type is not None else "" + names = {caught} + if isinstance(node.type, ast.Tuple): + names = {_dotted(elt) for elt in node.type.elts} + if node.type is None or names & {"AssertionError", "BaseException", "Exception"}: + violations.append( + "catches AssertionError/Exception (or uses a bare except), " + "which can swallow the invariant check" + ) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + if node.name.startswith("pytest_"): + violations.append(f"defines pytest hook `{node.name}`") + + for secret in find_secrets(code or ""): + violations.append( + f"embeds a {secret}; tests must create their own throwaway credentials " + "and never contain captured exploit data" + ) + # De-duplicate while keeping order so feedback stays readable. + return list(dict.fromkeys(violations)) + + # ── sandbox image + execution ── + + def default_base_image(self, profile) -> str: + return f"python:{profile.runtime_version or '3.12'}-slim" + + def dockerfile(self, profile, base_image) -> str: + root = profile.project_root + workdir = "/workspace" if root == "." else f"/workspace/{root}" + lines = [ + "# Generated by OpenHack to validate a security regression test.", + f"FROM {base_image}", + "ENV PYTHONDONTWRITEBYTECODE=1 PIP_DISABLE_PIP_VERSION_CHECK=1 " + "PIP_NO_INPUT=1 PIP_ROOT_USER_ACTION=ignore", + f"WORKDIR {workdir}", + ] + if profile.dependency_files: + for dep in profile.dependency_files: + src = dep if root == "." else f"{root}/{dep}" + lines.append(f"COPY {json.dumps([src, f'{workdir}/{dep}'])}") + flags = " ".join(f"-r {json.dumps(d)}" for d in profile.dependency_files) + lines.append(f"RUN pip install --no-cache-dir {flags}") + lines.append('COPY [".", "/workspace"]') + if profile.installable_project: + target = "." + (f"[{','.join(profile.install_extras)}]" if profile.install_extras else "") + lines.append( + f"RUN pip install --no-cache-dir -e {json.dumps(target)} " + "|| echo 'openhack: project install failed; continuing with listed requirements'" + ) + lines += [ + 'RUN python -c "import pytest" 2>/dev/null || pip install --no-cache-dir pytest', + f"RUN mkdir -p {RESULTS_DIR} && chown -R 65534:65534 /workspace {RESULTS_DIR}", + ] + return "\n".join(lines) + "\n" + + def container_command(self, profile, test_relpath) -> list[str]: + # Output goes to a file so a noisy test can't flood the host, and the + # repository's own pytest configuration (rootdir, conftest, plugins) + # still applies. --maxfail overrides any `-x` in addopts so every + # declared test reports an outcome. + script = ( + 'python -m pytest "$1" -p no:cacheprovider --maxfail=100000 ' + f"-o junit_family=xunit2 --junitxml={RESULTS_DIR}/junit.xml " + f"> {RESULTS_DIR}/output.txt 2>&1" + ) + return ["sh", "-c", script, "openhack-pytest", test_relpath] + + def display_command(self, profile, test_relpath) -> str: + cmd = f"python -m pytest {test_relpath}" + return cmd if profile.project_root == "." else f"cd {profile.project_root} && {cmd}" + + def parse_results(self, results_dir: Path, exit_code: Optional[int], timed_out: bool) -> RunReport: + output = "" + out_path = results_dir / "output.txt" + if out_path.is_file(): + try: + with open(out_path, "rb") as fp: + fp.seek(0, 2) + size = fp.tell() + fp.seek(max(0, size - 6000)) + output = scrub_text(fp.read().decode("utf-8", errors="replace")) + except OSError: + output = "" + report = RunReport(exit_code=exit_code, timed_out=timed_out, output_tail=output) + if timed_out: + return report + junit = results_dir / "junit.xml" + if not junit.is_file(): + report.collection_error = ( + f"pytest produced no results (exit code {exit_code}). Output:\n{output[-2000:]}" + ) + return report + if junit.stat().st_size > MAX_RESULTS_BYTES: + report.collection_error = "test results file is unreasonably large; rejected" + return report + text = junit.read_text(encoding="utf-8", errors="replace") + if not _xml_is_safe(text): + report.collection_error = "test results contained a DTD/entity declaration; rejected" + return report + try: + root = ET.fromstring(text) + except ET.ParseError as exc: + report.collection_error = f"could not parse test results: {exc}" + return report + + for case in root.iter("testcase"): + name = case.get("name", "") + classname = case.get("classname", "") + outcome, message, assertion = "passed", "", False + for child in case: + tag = child.tag + detail = scrub_text(((child.get("message") or "") + "\n" + (child.text or "")).strip()) + if tag == "failure": + outcome = "failed" + assertion = "AssertionError" in detail or detail.startswith("assert") + message = detail[-1500:] + elif tag == "error": + outcome = "error" + message = detail[-1500:] + elif tag == "skipped": + outcome = "skipped" + message = detail[-300:] + if outcome == "error" and (not classname or "collection failure" in message): + report.collection_error = message or "collection failed" + continue + report.cases.append(CaseOutcome(name, classname, outcome, message, assertion)) + if not report.cases and report.collection_error is None: + report.collection_error = f"no tests were collected. Output:\n{output[-2000:]}" + return report + + +ADAPTERS: list[FrameworkAdapter] = [PytestAdapter()] + + +def _describe_unsupported(repo_root: Path) -> str: + """Name the test framework we found but cannot drive yet, if any.""" + for pkg in _iter_files(repo_root, "package.json", max_depth=3): + try: + data = json.loads(_read(pkg)) + except (json.JSONDecodeError, ValueError): + continue + deps = {**(data.get("dependencies") or {}), **(data.get("devDependencies") or {})} + script = str((data.get("scripts") or {}).get("test") or "") + for runner in ("jest", "vitest", "mocha", "ava", "tap", "jasmine", "playwright"): + if runner in deps or runner in script: + return f"JavaScript test framework `{runner}`" + if (repo_root / "go.mod").is_file(): + return "Go `testing`" + if (repo_root / "pom.xml").is_file() or (repo_root / "build.gradle").is_file(): + return "JUnit (JVM)" + if "rspec" in _read(repo_root / "Gemfile").lower(): + return "RSpec" + if (repo_root / "composer.json").is_file(): + return "PHPUnit" + if (repo_root / "manage.py").is_file(): + return "Django's built-in test runner (pytest-django projects are supported)" + return "" + + +def detect_framework(repo_root: Path, hint_path: Optional[str] = None) -> tuple[FrameworkAdapter, FrameworkProfile]: + """Find the adapter for the repository's existing test suite. + + Raises UnsupportedFrameworkError with an explanation when there is no + existing suite we can drive — OpenHack does not bootstrap a framework the + repository does not already use. + """ + for adapter in ADAPTERS: + profile = adapter.detect(repo_root, hint_path) + if profile is not None: + return adapter, profile + supported = ", ".join(a.name for a in ADAPTERS) + other = _describe_unsupported(repo_root) + if other: + raise UnsupportedFrameworkError( + f"the repository's tests use {other}, which is not supported yet " + f"(supported: {supported})" + ) + raise UnsupportedFrameworkError( + "no existing test suite was detected (looked for pytest configuration, " + f"conftest.py and test files); supported frameworks: {supported}" + ) diff --git a/openhack/regression/generator.py b/openhack/regression/generator.py new file mode 100644 index 0000000..4e62ace --- /dev/null +++ b/openhack/regression/generator.py @@ -0,0 +1,324 @@ +""" +Regression test generator agent. + +Reads the repository (read-only, jailed to the vulnerable revision's +workspace copy) and submits one new test file through +``submit_regression_test``. The pipeline validates every submission and, when +one fails, sends precise feedback back into the same conversation so the +agent can correct it rather than starting over. +""" + +from __future__ import annotations + +import asyncio +import json +import logging +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Optional + +from openhack.agents.base import BaseAgent +from openhack.agents.llm import Message, ToolResult +from openhack.prompts import ( + REGRESSION_TEST_PROMPT, + REGRESSION_TEST_TOOL_INSTRUCTIONS, + format_project_context, +) +from .evidence import scrub_text + +if TYPE_CHECKING: + from openhack.agents.session import Finding + from .frameworks import FrameworkAdapter, FrameworkProfile + from .invariants import VulnerabilityClassSpec + from .models import SecurityInvariant + +logger = logging.getLogger(__name__) + + +SUBMIT_REGRESSION_TEST_TOOL = { + "name": "submit_regression_test", + "description": ( + "Submit the complete security regression test file. OpenHack validates it " + "in an isolated sandbox against the vulnerable and the remediated code." + ), + "parameters": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "New test file path relative to the project root (must not exist yet)", + }, + "code": {"type": "string", "description": "Complete contents of the test file"}, + "invariant_tests": { + "type": "array", + "items": {"type": "string"}, + "description": "Test function names asserting the invariant (fail on vulnerable code)", + }, + "control_tests": { + "type": "array", + "items": {"type": "string"}, + "description": "Test function names proving legitimate access works (pass on both)", + }, + "summary": {"type": "string", "description": "One sentence: what the test protects"}, + }, + "required": ["path", "code", "invariant_tests", "control_tests"], + }, +} + + +@dataclass +class CandidateTest: + path: str + code: str + invariant_tests: list[str] = field(default_factory=list) + control_tests: list[str] = field(default_factory=list) + summary: str = "" + + +def _string_list(value) -> Optional[list[str]]: + if isinstance(value, str): + value = [value] + if not isinstance(value, list) or not all(isinstance(v, str) and v.strip() for v in value): + return None + return [v.strip().split("::")[-1].split("[", 1)[0] for v in value] + + +class RegressionTestGeneratorAgent(BaseAgent): + """Writes a regression test for one verified finding.""" + + name = "regression_test" + description = "Generating security regression test" + + def __init__( + self, + *args, + finding: "Finding", + invariant: "SecurityInvariant", + spec: "VulnerabilityClassSpec", + adapter: "FrameworkAdapter", + profile: "FrameworkProfile", + suggested_path: str, + finding_index: int = 0, + max_iterations: int = 24, + **kwargs, + ): + super().__init__(*args, **kwargs) + self.finding = finding + self.invariant = invariant + self.spec = spec + self.adapter = adapter + self.profile = profile + self.suggested_path = suggested_path + self.max_iterations = max_iterations + self.submission: Optional[CandidateTest] = None + self.name = f"regression_test:finding_{finding_index}" + self.description = f"Generating regression test for finding {finding_index}" + self._system_prompt = self.get_system_prompt({}) + + def get_system_prompt(self, context: dict) -> str: + f = self.finding + evidence = f.exploit_evidence or {} + request = evidence.get("exploit_request") or {} + request_line = " ".join( + part for part in (request.get("method"), request.get("path")) if part + ) or "not recorded" + location = f.file_path + (f":{f.line_number}" if f.line_number else "") + finding_details = f"""### {f.title} +- **Category**: {f.category} · **Severity**: {f.severity} +- **Location**: {location or 'unknown'} +- **Description**: {scrub_text(f.description or 'No description')} +- **Vulnerable code**: +``` +{f.code_snippet or 'No code snippet'} +``` +- **Exploited request (sandbox)**: `{request_line}` +- **Exploit evidence (redacted)**: {scrub_text(evidence.get('evidence') or 'none recorded')} +- **Recommended remediation** (context only — do not assert implementation details of any particular fix): +{scrub_text(f.fix or 'none recorded')} +""" + inv = self.invariant + invariant_details = f"""- **Invariant ({inv.cwe})**: {inv.statement} +- **Endpoint**: `{inv.method} {inv.path_template}` (object identifier: `{inv.object_param or 'unknown'}`, in {inv.param_location or 'unknown location'}) +- **Must hold**: {inv.denial} +- **Must keep working**: {inv.control} +""" + prompt = REGRESSION_TEST_PROMPT.format( + project_context=format_project_context(self.session.project_context), + finding_details=finding_details, + invariant_details=invariant_details, + framework_details=self.adapter.prompt_context(self.profile), + suggested_path=self.suggested_path, + class_guidance=self.spec.generation_guidance(inv), + ) + return prompt + REGRESSION_TEST_TOOL_INSTRUCTIONS + + def get_tools(self) -> list[dict]: + return super().get_tools() + [SUBMIT_REGRESSION_TEST_TOOL] + + async def generate(self, note: str = "") -> Optional[CandidateTest]: + """Start the conversation and return the first submission (or None).""" + task = ( + "Write a security regression test for the confirmed vulnerability above, " + "using the repository's existing test framework, then submit it." + ) + if note: + task += "\n\n" + note + self.session.current_agent = self.name + self.session.start_turn(task, self.name) + self.messages = [] + self._append_message(Message(role="user", content=task), source="run") + self._seed_existing_instructions() + self.session.record_event( + "agent_configuration", + { + "agent": self.name, + "model": self.llm.model, + "provider": getattr(self.llm, "provider", None), + "system_prompt": self._system_prompt, + "tools": self.get_tools(), + }, + agent=self.name, + ) + submission = await self._loop() + self.session.finish_turn( + "completed" if submission else "no_submission", + {"submitted": submission is not None}, agent=self.name, + ) + return submission + + async def revise(self, feedback: str) -> Optional[CandidateTest]: + """Send validation feedback and return the corrected submission (or None).""" + self.session.start_turn("revise regression test", self.name) + self._append_message( + Message( + role="user", + content=( + "[VALIDATION FEEDBACK] OpenHack rejected the submitted test:\n" + f"{feedback}\n\nFix the problem and submit the complete corrected file " + "with submit_regression_test." + ), + ), + source="validation_feedback", + ) + submission = await self._loop() + self.session.finish_turn( + "completed" if submission else "no_submission", + {"submitted": submission is not None}, agent=self.name, + ) + return submission + + def _handle_submit(self, args: dict) -> dict: + path = args.get("path") + code = args.get("code") + invariant_tests = _string_list(args.get("invariant_tests")) + control_tests = _string_list(args.get("control_tests", [])) + problems = [] + if not isinstance(path, str) or not path.strip(): + problems.append("`path` must be a non-empty string") + if not isinstance(code, str) or not code.strip(): + problems.append("`code` must contain the complete test file") + if not invariant_tests: + problems.append("`invariant_tests` must list at least one test function name") + if control_tests is None: + problems.append("`control_tests` must be a list of test function names") + if problems or not isinstance(path, str) or not isinstance(code, str) or not invariant_tests: + return {"error": "Submission rejected: " + "; ".join(problems)} + self.submission = CandidateTest( + path=path.strip(), + code=code, + invariant_tests=invariant_tests, + control_tests=control_tests or [], + summary=str(args.get("summary") or "").strip(), + ) + return { + "status": "received", + "note": "OpenHack will now validate the test in the sandbox and report back.", + } + + async def _loop(self) -> Optional[CandidateTest]: + self.submission = None + nudged = False + for _ in range(self.max_iterations): + if self.session.cancelled: + return None + await self.session.wait_if_paused() + self._inject_pending_instructions() + self._preflight_compact(self._system_prompt) + + response = await self.llm.chat( + messages=self.messages, tools=self.get_tools(), system=self._system_prompt, + ) + self._record_response_usage(response) + if response.content: + self.session.add_trace( + agent=self.name, event_type="thinking", content=response.content, + model_call_id=response.model_call_id, + ) + + if not response.tool_calls: + self._append_message( + Message(role="assistant", content=response.content, + response_items=response.response_items), + source="model_text_response", + ) + if nudged: + return None + nudged = True + self._append_message( + Message(role="user", content=( + "You have not submitted a test. Call submit_regression_test " + "with the complete test file now." + )), + source="submission_guard", + ) + continue + + self._append_message( + Message( + role="assistant", content=response.content, + response_items=response.response_items, + tool_calls=[ + {"id": tc.id, "type": "function", + "function": {"name": tc.name, "arguments": json.dumps(tc.arguments)}} + for tc in response.tool_calls + ], + ), + source="model_tool_response", + ) + for tool_call in response.tool_calls: + self.session.add_trace( + agent=self.name, event_type="tool_call", + content=f"Calling {tool_call.name}", + tool_name=tool_call.name, tool_input=tool_call.arguments, + model_call_id=response.model_call_id, tool_call_id=tool_call.id, + ) + try: + if tool_call.name == "submit_regression_test": + result = self._handle_submit(tool_call.arguments) + elif self.tools.is_async_tool(tool_call.name): + result = await self.tools.execute_tool_async( + tool_call.name, tool_call.arguments + ) + else: + result = await asyncio.to_thread( + self.tools.execute_tool, tool_call.name, tool_call.arguments + ) + except Exception as exc: + result = {"error": f"{tool_call.name} failed: {exc}"} + self.session.add_trace( + agent=self.name, event_type="tool_result", + content=f"Result from {tool_call.name}", + tool_name=tool_call.name, tool_output=result, + model_call_id=response.model_call_id, tool_call_id=tool_call.id, + ) + raw = json.dumps(result, default=str) if isinstance(result, dict) else str(result) + truncated = self.context_manager.truncate_tool_result(tool_call.name, raw) + self._append_message( + ToolResult(tool_call_id=tool_call.id, content=truncated).to_message(), + source=f"tool_result:{tool_call.name}", + ) + if self.submission is not None: + return self.submission + if self.context_manager.needs_compaction(): + self.messages = self.context_manager.compact_messages(self.messages) + logger.info(f"[{self.name}] no submission within {self.max_iterations} iterations") + return None diff --git a/openhack/regression/headless.py b/openhack/regression/headless.py new file mode 100644 index 0000000..71a41cb --- /dev/null +++ b/openhack/regression/headless.py @@ -0,0 +1,169 @@ +""" +Headless regression-test run for a saved scan (``openhack --regression-tests``). + +The usual order of events is: a scan verifies a vulnerability, a developer +fixes it, and only then is there a remediated revision to validate against. +This entry point loads the saved report, uses the commit that was scanned as +the vulnerable revision, validates (or generates) a regression test for each +finding against the fixed revision, and writes the results back into the +report — re-validating an already generated test costs no LLM calls. +""" + +from __future__ import annotations + +import json +import logging +import os +from datetime import datetime, timezone +from pathlib import Path +from typing import Optional + +from openhack.agents.session import Finding, Session, TraceEntry +from openhack.config import reload_settings, settings +from openhack.headless_scan import SCANS_DIR, format_regression_status +from .pipeline import PipelineOptions, RegressionTestPipeline +from .workspace import RevisionSpec, WorkspaceError, git_info, resolve_commit + +logger = logging.getLogger(__name__) + + +def find_report(session_id: str, scans_dir: Optional[Path] = None) -> Optional[Path]: + scans_dir = scans_dir or SCANS_DIR + exact = scans_dir / f"{session_id}.json" + if exact.is_file(): + return exact + matches = sorted(scans_dir.glob(f"{session_id}*.json")) + return matches[0] if matches else None + + +def choose_revisions( + report: dict, target: Path, fixed: Optional[str], +) -> tuple[RevisionSpec, Optional[RevisionSpec], list[str]]: + """Pick the vulnerable and remediated revisions for a saved scan. + + Vulnerable: the commit that was scanned, when the scan ran on a clean tree + (otherwise the working tree). Remediated: the explicit argument, then the + regression_tests_fixed_ref setting, then HEAD when it has moved past the + scanned commit. + """ + notes: list[str] = [] + repo = report.get("repository") or {} + info = git_info(target) + vulnerable = RevisionSpec.worktree() + scanned = repo.get("head") or "" + if info.get("is_repo") and scanned and not repo.get("dirty"): + try: + resolve_commit(target, scanned) + vulnerable = RevisionSpec.git(scanned) + except WorkspaceError: + notes.append(f"scanned commit {scanned[:12]} is not in this repository; using the working tree") + elif repo.get("dirty"): + notes.append("the scan ran on uncommitted changes; using the working tree as the vulnerable revision") + else: + notes.append("no scanned commit recorded; using the working tree as the vulnerable revision") + + raw = fixed or settings.regression_tests_fixed_ref + remediation: Optional[RevisionSpec] = None + if raw: + remediation = RevisionSpec.parse(raw, target) + elif vulnerable.kind == "git" and info.get("head") and info["head"] != scanned: + remediation = RevisionSpec.git(info["head"]) + notes.append("using HEAD as the remediated revision") + return vulnerable, remediation, notes + + +def _write_report_atomically(path: Path, report: dict) -> None: + tmp = path.with_suffix(".json.tmp") + with open(tmp, "w") as fp: + json.dump(report, fp, indent=2, default=str, ensure_ascii=False) + os.replace(tmp, path) + + +def _on_trace(entry: TraceEntry) -> None: + if entry.event_type == "status": + print(f" [{entry.agent}] {str(entry.content or '')[:140]}") + elif entry.event_type == "regression_test_check": + data = entry.content if isinstance(entry.content, dict) else {} + mark = "ok" if data.get("passed") else "rejected" + print(f" [{entry.agent}] {data.get('revision')} revision: {mark} — {str(data.get('detail', ''))[:160]}") + + +async def run_regression_tests_for_report(session_id: str, fixed: Optional[str] = None) -> int: + """Run the regression-test workflow for a saved scan. Returns an exit status.""" + reload_settings() + report_path = find_report(session_id) + if report_path is None: + print(f"Session {session_id} not found in ~/.openhack/scans/") + print("List saved sessions with: openhack --sessions") + return 1 + report = json.loads(report_path.read_text()) + target = Path(report.get("target_dir") or "") + if not target.is_dir(): + print(f"Error: the scanned directory no longer exists: {target}") + return 1 + findings = [Finding.from_dict(fd) for fd in report.get("findings") or [] if isinstance(fd, dict)] + if not findings: + print("No findings in this session.") + return 0 + + try: + vulnerable, remediation, notes = choose_revisions(report, target, fixed) + except WorkspaceError as exc: + print(f"Error: {exc}") + return 1 + scan_id = report.get("scan_id") or report_path.stem + print(f"\n{'='*60}") + print(" SECURITY REGRESSION TESTS") + print(f" Session: {scan_id}") + print(f" Target: {target}") + print(f" Vulnerable: {vulnerable.describe()}") + print(f" Remediated: {remediation.describe() if remediation else 'none (validation will stop at the vulnerable revision)'}") + for note in notes: + print(f" Note: {note}") + print(f"{'='*60}\n") + + from openhack.agents.llm import LLMClient + + session = Session(target_dir=str(target), on_trace=_on_trace, parent_session_id=scan_id) + llm = LLMClient( + model=settings.regression_test_model_id, provider=settings.llm_provider, + temperature=0.0, max_tokens=8192, prompt_cache_key=session.id, + ) + options = PipelineOptions.from_settings( + settings, str(target), vulnerable=vulnerable, remediation=remediation, report_id=scan_id, + ) + pipeline = RegressionTestPipeline(llm, session, target, options) + results = await pipeline.run(findings) + + by_id = {f.id: f for f in findings} + for entry in report.get("findings") or []: + if isinstance(entry, dict) and entry.get("id") in by_id: + entry["regressionTest"] = by_id[entry["id"]].regression_test + statuses: dict[str, int] = {} + for result in results: + statuses[result.status.value] = statuses.get(result.status.value, 0) + 1 + report["regression_tests"] = { + "updated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "session_id": session.id, + "vulnerable": vulnerable.describe(), + "remediated": remediation.describe() if remediation else None, + "statuses": statuses, + "cost": pipeline.total_cost, + } + _write_report_atomically(report_path, report) + + print(f"\n{'='*60}") + print(" RESULTS") + print(f"{'='*60}") + for i, finding in enumerate(findings, 1): + print(f" {i}. [{finding.severity.upper()}] {finding.category} — {finding.file_path}") + for line in format_regression_status(finding): + print(f" {line}") + print() + print(f" Cost: ${pipeline.total_cost:.4f}") + print(f" Report: {report_path}\n") + # Non-zero only when an eligible finding ended without a validated test; + # unsupported classes and evidence-free findings are not failures. + not_applicable = {"unsupported_vulnerability", "missing_evidence"} + failed = [r for r in results if r.status.value not in not_applicable | {"validated"}] + return 2 if failed else 0 diff --git a/openhack/regression/invariants.py b/openhack/regression/invariants.py new file mode 100644 index 0000000..44aa604 --- /dev/null +++ b/openhack/regression/invariants.py @@ -0,0 +1,292 @@ +""" +Security-invariant extraction, one spec per vulnerability class. + +A confirmed exploit is a single witness ("user B fetched note 2"). The +regression test must instead protect the property that witness violated +("no principal can read or modify an object it does not own"), so a variant +payload, another operation on the same object, or a later refactor cannot +reintroduce the bug unnoticed. + +Each VulnerabilityClassSpec turns a verified Finding plus its sandbox exploit +evidence into a SecurityInvariant, and contributes class-specific guidance to +the generator prompt. Adding a class means adding a spec to ``CLASS_SPECS``. +""" + +from __future__ import annotations + +import re +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Optional +from urllib.parse import parse_qsl, urlsplit + +from openhack.categories import normalize_category +from .models import SecurityInvariant + +if TYPE_CHECKING: + from openhack.agents.session import Finding + + +class MissingEvidenceError(Exception): + """The finding has no exploit evidence to derive an invariant from.""" + + +class VulnerabilityClassSpec(ABC): + """Extension point for a vulnerability class.""" + + key: str = "" + label: str = "" + cwe: str = "" + # Whether a passing "legitimate use still works" test is mandatory. It is + # what stops an always-denying (or broken) endpoint from looking fixed. + requires_control_test: bool = True + + @abstractmethod + def matches(self, finding: "Finding") -> bool: + """Whether this spec handles the finding's vulnerability class.""" + + @abstractmethod + def extract_invariant(self, finding: "Finding") -> SecurityInvariant: + """Derive the violated invariant; raise MissingEvidenceError if unable.""" + + @abstractmethod + def generation_guidance(self, invariant: SecurityInvariant) -> str: + """Class-specific instructions appended to the generator prompt.""" + + +# ── Request parsing helpers ───────────────────────────────────────── + +_UUID = r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}" +_ID_SEGMENT = re.compile(rf"^(?:\d+|{_UUID}|[0-9a-fA-F]{{24}}|[0-9a-fA-F]{{32}})$") +# A templated segment in a PoC f-string, e.g. "{note_id}". +_PLACEHOLDER_SEGMENT = re.compile(r"^\{([A-Za-z_]\w*)\}$") +_SNAKE_ID_KEY = re.compile(r"(?:^|_)(?:id|uuid|pk)$", re.IGNORECASE) +_CAMEL_ID_KEY = re.compile(r"[a-z0-9](?:Id|ID|Uuid)$") +# `requests.get("…")`, `session.post(BASE + "…")`, `client.delete(f"{BASE}/…")` +_POC_REQUEST = re.compile( + r"""\b\w+\.(get|post|put|patch|delete)\(\s*(?:[A-Za-z_][\w.]*\s*\+\s*)?f?["']([^"']+)["']""", + re.IGNORECASE, +) +_CURL_METHOD = re.compile(r"(?:-X|--request)\s*([A-Za-z]+)") +_URL = re.compile(r"https?://[^\s\"']+") + +_OPERATIONS = { + "GET": "read", "HEAD": "read", + "PUT": "update", "PATCH": "update", + "DELETE": "delete", + "POST": "act on", +} + + +def _singular(word: str) -> str: + word = word.strip().lower() + if word.endswith("ies") and len(word) > 3: + return word[:-3] + "y" + if word.endswith("sses"): + return word[:-2] + if word.endswith("s") and not word.endswith("ss") and len(word) > 1: + return word[:-1] + return word + + +def _is_id_key(key: str) -> bool: + return bool(_SNAKE_ID_KEY.search(key) or _CAMEL_ID_KEY.search(key)) + + +def _path_only(raw: str) -> str: + """Strip scheme/host (or a leading ``{BASE_URL}`` placeholder) from a URL.""" + raw = (raw or "").strip() + if raw.startswith(("http://", "https://")): + parts = urlsplit(raw) + return parts.path + (f"?{parts.query}" if parts.query else "") + if raw.startswith("{") and "}/" in raw: + return raw[raw.index("}/") + 1:] + return raw + + +def request_from_poc(poc: str) -> tuple[str, str]: + """Best-effort (method, path) of the exploit request in a Python/curl PoC. + + PoCs usually register/log in first, so the exploit is taken to be the last + request that addresses an object identifier (else simply the last request). + """ + if not poc: + return "", "" + candidates: list[tuple[str, str]] = [] + for match in _POC_REQUEST.finditer(poc): + path = _path_only(match.group(2)) + if path.startswith("/"): + candidates.append((match.group(1).upper(), path)) + for line in poc.splitlines(): + if "curl" not in line: + continue + url = _URL.search(line) + if url: + method = _CURL_METHOD.search(line) + candidates.append(((method.group(1).upper() if method else "GET"), _path_only(url.group(0)))) + if not candidates: + return "", "" + with_ids = [c for c in candidates if templatize_path(c[1])[1] or _query_id_param(c[1])] + return (with_ids or candidates)[-1] + + +def templatize_path(path: str) -> tuple[str, Optional[str], str]: + """Replace identifier segments with named placeholders. + + Returns (template, object_param, resource). ``/api/users/7/notes/42`` + becomes ``/api/users/{user_id}/notes/{note_id}`` with object_param + ``note_id`` — the last identifier names the object being accessed. + """ + split = urlsplit(path) + segments = [s for s in split.path.split("/") if s] + out: list[str] = [] + object_param: Optional[str] = None + resource = "" + for i, segment in enumerate(segments): + placeholder = _PLACEHOLDER_SEGMENT.match(segment) + if _ID_SEGMENT.match(segment) or placeholder: + owner = _singular(segments[i - 1]) if i > 0 else "object" + object_param = placeholder.group(1) if placeholder else f"{owner}_id" + resource = owner + out.append("{" + object_param + "}") + else: + out.append(segment) + if not resource: + nouns = [ + s for s in segments + if not _ID_SEGMENT.match(s) and not _PLACEHOLDER_SEGMENT.match(s) + ] + resource = _singular(nouns[-1]) if nouns else "object" + template = "/" + "/".join(out) + return template, object_param, resource + + +def _query_id_param(path: str) -> Optional[str]: + for key, _value in parse_qsl(urlsplit(path).query, keep_blank_values=True): + if _is_id_key(key): + return key + return None + + +def _body_id_param(body: Optional[str]) -> Optional[str]: + if not body: + return None + for key in re.findall(r'"([A-Za-z_][A-Za-z0-9_]*)"\s*:', body): + if _is_id_key(key): + return key + return None + + +# ── IDOR / broken object-level authorization ──────────────────────── + +class IdorSpec(VulnerabilityClassSpec): + key = "idor" + label = "IDOR / broken object-level authorization" + cwe = "CWE-639" + requires_control_test = True + + def matches(self, finding: "Finding") -> bool: + return normalize_category(finding.category or "") == "IDOR" + + def extract_invariant(self, finding: "Finding") -> SecurityInvariant: + evidence = finding.exploit_evidence or {} + if not evidence: + raise MissingEvidenceError( + "the finding was not verified by sandbox exploitation, so there is " + "no exploit evidence to derive the violated invariant from " + "(enable sandbox verification with sandbox_enabled or /verify sandbox)" + ) + request = evidence.get("exploit_request") or {} + method = str(request.get("method") or "").upper() + path = _path_only(str(request.get("path") or "")) + if not path: + poc_method, path = request_from_poc(evidence.get("working_poc") or "") + method = method or poc_method + if not path: + raise MissingEvidenceError( + "the sandbox evidence does not identify the HTTP request that " + "exploited the object reference" + ) + method = method or "GET" + template, object_param, resource = templatize_path(path) + location = "path" if object_param else None + if not object_param: + object_param = _query_id_param(path) + location = "query" if object_param else None + if not object_param: + object_param = _body_id_param(request.get("body")) + location = "body" if object_param else None + operation = _OPERATIONS.get(method, "access") + query = urlsplit(path).query + endpoint = f"{method} {template}" + (f"?{query}" if location == "query" else "") + statement = ( + f"Object-level authorization ({self.cwe}): an authenticated principal " + f"must not be able to {operation} a {resource} owned by another principal " + f"through {endpoint}, no matter which {object_param or 'object identifier'} " + "it supplies. Only principals authorized for the object (its owner) may " + f"{operation} it." + ) + denial = ( + "A request for another principal's object is rejected (401, 403 or 404), " + "the response does not disclose the object's data, and a rejected " + "write/delete leaves the object unchanged." + ) + control = ( + f"The owner can still {operation} their own {resource} through the same " + "endpoint (proves the denial comes from authorization, not a broken route)." + ) + summary = (evidence.get("evidence") or "").strip() + location_str = finding.file_path or "" + if finding.line_number: + location_str += f":{finding.line_number}" + return SecurityInvariant( + vulnerability_class=self.key, + cwe=self.cwe, + statement=statement, + operation=operation, + resource=resource, + method=method, + path_template=template, + example_path=path, + object_param=object_param, + param_location=location, + denial=denial, + control=control, + evidence=summary[:800], + source_location=location_str, + ) + + def generation_guidance(self, invariant: SecurityInvariant) -> str: + param = invariant.object_param or "the object identifier" + return f"""### Class-specific requirements: {self.label} +- Create TWO distinct principals through the application's own mechanisms + (existing fixtures, factories, registration/login endpoints): an owner and an + unrelated second principal. Never reuse tokens, cookies or passwords from the + exploit evidence; use clearly fake test credentials. +- Have the owner create (or own) a {invariant.resource} with a distinctive marker + value in it, through the application, so ownership is real. +- Control test(s): the owner can {invariant.operation} their own {invariant.resource} + via `{invariant.method} {invariant.path_template}` and gets a success response. +- Invariant test(s): the second principal supplies the owner's {param} to + `{invariant.method} {invariant.path_template}` and MUST be denied. Assert the + status is one of 401/403/404 (accept any of them — never pin the one status a + particular fix happens to return) AND that the owner's marker value is absent + from the response body. +- Protect the invariant, not the payload: if the same object is reachable through + other operations on that route (read/update/delete), add an invariant test per + operation. For write/delete attempts, re-read the object as the owner afterwards + and assert it is unchanged. +""" + + +CLASS_SPECS: list[VulnerabilityClassSpec] = [IdorSpec()] + + +def spec_for_finding(finding: "Finding") -> Optional[VulnerabilityClassSpec]: + for spec in CLASS_SPECS: + if spec.matches(finding): + return spec + return None + + +def supported_classes() -> list[str]: + return [spec.label for spec in CLASS_SPECS] diff --git a/openhack/regression/models.py b/openhack/regression/models.py new file mode 100644 index 0000000..27cbc0f --- /dev/null +++ b/openhack/regression/models.py @@ -0,0 +1,132 @@ +""" +Data model for security regression test generation. + +A generated regression test is only *accepted* when it demonstrably fails +because the vulnerability exists and passes once the vulnerability has been +remediated. Every finding the workflow looks at ends in exactly one +RegressionTestStatus, so an operator can tell "validated" apart from the many +legitimate reasons a test is not available. +""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass, field, fields +from enum import Enum +from typing import Any, Optional + + +class RegressionTestStatus(str, Enum): + VALIDATED = "validated" + UNSUPPORTED_VULNERABILITY = "unsupported_vulnerability" + UNSUPPORTED_FRAMEWORK = "unsupported_framework" + MISSING_EVIDENCE = "missing_evidence" + GENERATION_FAILED = "generation_failed" + VALIDATION_FAILED = "validation_failed" + REMEDIATION_UNAVAILABLE = "remediation_unavailable" + SANDBOX_ERROR = "sandbox_error" + + @property + def label(self) -> str: + return STATUS_LABELS[self] + + +STATUS_LABELS: dict[RegressionTestStatus, str] = { + RegressionTestStatus.VALIDATED: "generated and validated", + RegressionTestStatus.UNSUPPORTED_VULNERABILITY: "unsupported vulnerability class", + RegressionTestStatus.UNSUPPORTED_FRAMEWORK: "unsupported test framework", + RegressionTestStatus.MISSING_EVIDENCE: "missing exploit evidence", + RegressionTestStatus.GENERATION_FAILED: "test generation failed", + RegressionTestStatus.VALIDATION_FAILED: "test validation failed", + RegressionTestStatus.REMEDIATION_UNAVAILABLE: "remediation unavailable", + RegressionTestStatus.SANDBOX_ERROR: "sandbox error", +} + + +@dataclass +class SecurityInvariant: + """The security property a confirmed exploit violated. + + The generated test asserts this property for every principal and + operation it covers, rather than replaying the one payload that happened + to work in the sandbox. + """ + + vulnerability_class: str + cwe: str + statement: str + operation: str + resource: str + method: str = "" + path_template: str = "" + example_path: str = "" + object_param: Optional[str] = None + param_location: Optional[str] = None + denial: str = "" + control: str = "" + evidence: str = "" + source_location: str = "" + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> "SecurityInvariant": + known = {f.name for f in fields(cls)} + return cls(**{k: v for k, v in data.items() if k in known}) + + +@dataclass +class RegressionTestResult: + """Outcome of the regression-test workflow for one finding. + + Serialized onto ``Finding.regression_test`` (and therefore into the scan + report), so it must stay JSON-safe. + """ + + finding_id: str + status: RegressionTestStatus + reason: str + vulnerability_class: Optional[str] = None + invariant: Optional[SecurityInvariant] = None + framework: Optional[str] = None + test_path: Optional[str] = None + test_code: Optional[str] = None + run_command: Optional[str] = None + invariant_tests: list[str] = field(default_factory=list) + control_tests: list[str] = field(default_factory=list) + summary: str = "" + validation: dict[str, Any] = field(default_factory=dict) + attempts: int = 0 + artifacts: dict[str, str] = field(default_factory=dict) + generated_at: str = "" + cost: float = 0.0 + + @property + def reproduces_vulnerability(self) -> bool: + """True when the test was proven to fail on the vulnerable revision.""" + vulnerable = self.validation.get("vulnerable") or {} + return bool(vulnerable.get("passed")) + + def to_dict(self) -> dict[str, Any]: + data = asdict(self) + data["status"] = self.status.value + data["status_label"] = self.status.label + data["invariant"] = self.invariant.to_dict() if self.invariant else None + data.pop("finding_id", None) + return data + + @classmethod + def from_dict(cls, finding_id: str, data: dict[str, Any]) -> "RegressionTestResult": + known = {f.name for f in fields(cls)} + kwargs = {k: v for k, v in data.items() if k in known} + kwargs["finding_id"] = finding_id + try: + kwargs["status"] = RegressionTestStatus(data.get("status")) + except ValueError: + kwargs["status"] = RegressionTestStatus.GENERATION_FAILED + kwargs.setdefault("reason", "") + invariant = data.get("invariant") + kwargs["invariant"] = ( + SecurityInvariant.from_dict(invariant) if isinstance(invariant, dict) else None + ) + return cls(**kwargs) diff --git a/openhack/regression/pipeline.py b/openhack/regression/pipeline.py new file mode 100644 index 0000000..85c6e3e --- /dev/null +++ b/openhack/regression/pipeline.py @@ -0,0 +1,726 @@ +""" +Security regression test generation for verified findings. + +For every finding the workflow looks at: + + eligibility ─► invariant ─► generate (LLM) ─► path + static policy + ─► sandbox, vulnerable revision: control tests pass and an invariant + test fails on an assertion (N runs, identical outcomes) + ─► sandbox, remediated revision: every test passes (N runs) + ─► accept: attach to the finding, write the test + a patch artifact + +Rejections are fed back to the generator for another attempt. A test is never +accepted unless it was shown to fail *because the vulnerability exists* and to +pass once it is fixed. Without a remediated revision, a test that reproduces +the vulnerability is kept as a pending artifact (``remediation_unavailable``) +and can be re-validated later without another LLM call. +""" + +from __future__ import annotations + +import asyncio +import json +import logging +import os +import re +import tempfile +import textwrap +from dataclasses import dataclass, field +from datetime import datetime, timezone +from pathlib import Path, PurePosixPath +from typing import Any, Optional +from uuid import uuid4 + +from openhack.agents.session import Finding, Session +from openhack.sandbox.container_runner import ContainerLimits, ContainerTestRunner +from openhack.sandbox.orchestrator import SandboxError +from openhack.tools.registry import ToolRegistry +from .frameworks import ( + FrameworkAdapter, FrameworkProfile, RunReport, UnsupportedFrameworkError, detect_framework, +) +from .generator import RegressionTestGeneratorAgent, CandidateTest +from .invariants import ( + MissingEvidenceError, VulnerabilityClassSpec, spec_for_finding, supported_classes, +) +from .models import RegressionTestResult, RegressionTestStatus, SecurityInvariant +from .workspace import ( + MaterializedRevision, RevisionSpec, WorkspaceError, git_info, materialize, + new_file_patch, remove_tree, write_private_file, +) + +logger = logging.getLogger(__name__) + +AGENT = "regression_tests" +Status = RegressionTestStatus + + +@dataclass +class PipelineOptions: + vulnerable: RevisionSpec = field(default_factory=RevisionSpec.worktree) + remediation: Optional[RevisionSpec] = None + max_attempts: int = 3 + validation_runs: int = 2 + base_image: str = "" + limits: ContainerLimits = field(default_factory=ContainerLimits) + artifacts_root: Optional[Path] = None + # Session quoted in re-validation hints and used to group artifacts. + report_id: Optional[str] = None + + @classmethod + def from_settings(cls, settings, target_dir: str, **overrides: Any) -> "PipelineOptions": + remediation = None + if settings.regression_tests_fixed_ref: + remediation = RevisionSpec.parse(settings.regression_tests_fixed_ref, Path(target_dir)) + options = cls( + remediation=remediation, + max_attempts=max(1, int(settings.regression_tests_max_attempts)), + validation_runs=max(1, int(settings.regression_tests_validation_runs)), + base_image=settings.regression_tests_base_image or "", + limits=ContainerLimits( + run_timeout=int(settings.regression_tests_timeout), + build_timeout=int(settings.regression_tests_build_timeout), + ), + ) + for key, value in overrides.items(): + setattr(options, key, value) + return options + + +@dataclass +class RevisionCheck: + passed: bool + detail: str + # False when retrying cannot help without weakening the test. + retryable: bool = True + deterministic: bool = True + outcomes: dict[str, str] = field(default_factory=dict) + failures: dict[str, str] = field(default_factory=dict) + output_tail: str = "" + + def to_dict(self, revision: MaterializedRevision) -> dict: + return { + "revision": revision.label, + "resolved": revision.resolved, + "passed": self.passed, + "deterministic": self.deterministic, + "outcomes": {k.split("::")[-1]: v for k, v in self.outcomes.items()}, + "detail": self.detail, + } + + +def evaluate_runs( + reports: list[RunReport], + submission: CandidateTest, + expect: str, + require_control: bool, + timeout: int, +) -> RevisionCheck: + """Judge repeated runs of a candidate test against one revision. + + ``expect="vulnerable"``: controls pass and at least one invariant test + fails on an assertion. ``expect="remediated"``: every test passes. + """ + first = reports[0] + outcomes = first.outcomes() + failures = {c.name: c.message for c in first.cases if c.outcome != "passed" and c.message} + deterministic = all(r.outcomes() == outcomes for r in reports[1:]) + + def result(passed: bool, detail: str, retryable: bool = True) -> RevisionCheck: + return RevisionCheck(passed, detail, retryable, deterministic, outcomes, failures, first.output_tail) + + if any(r.timed_out for r in reports): + return result(False, f"the test run timed out after {timeout}s (does it block, sleep or need the network?)") + errors = [r.collection_error for r in reports if r.collection_error] + if errors: + return result(False, f"the test could not be collected or run: {errors[0][:1500]}") + if not deterministic: + changed = sorted( + k.split("::")[-1] for r in reports[1:] for k in set(outcomes) | set(r.outcomes()) + if outcomes.get(k) != r.outcomes().get(k) + ) + return result( + False, + f"outcomes differed between {len(reports)} identical runs " + f"({', '.join(dict.fromkeys(changed))}); the test is nondeterministic", + ) + + names = {c.base_name for c in first.cases} + invariant = set(submission.invariant_tests) + control = set(submission.control_tests) + if not invariant: + return result(False, "no invariant tests were declared") + if require_control and not control: + return result(False, "at least one control test (legitimate access still works) is required") + if invariant & control: + return result(False, f"tests declared as both invariant and control: {', '.join(sorted(invariant & control))}") + missing = (invariant | control) - names + if missing: + return result(False, f"declared tests were not collected: {', '.join(sorted(missing))}") + undeclared = names - invariant - control + if undeclared: + return result(False, f"tests neither declared invariant nor control: {', '.join(sorted(undeclared))}") + broken = [c for c in first.cases if c.outcome in ("error", "skipped")] + if broken: + return result(False, "tests errored or were skipped: " + ", ".join(f"{c.name} ({c.outcome})" for c in broken)) + + if expect == "vulnerable": + failed_controls = [c.name for c in first.cases if c.base_name in control and c.outcome != "passed"] + if failed_controls: + return result( + False, + f"control test(s) failed on the VULNERABLE code ({', '.join(failed_controls)}), so the " + "failure is not caused by the vulnerability — the legitimate flow must work on both versions", + ) + failed = [c for c in first.cases if c.base_name in invariant and c.outcome == "failed"] + if not failed: + return result( + False, + "every invariant test PASSED on the VULNERABLE code, so the test does not detect the " + "vulnerability; assert the security property the exploit violated", + ) + crashed = [c.name for c in failed if not c.assertion] + if crashed: + return result( + False, + f"invariant test(s) {', '.join(crashed)} failed with an unexpected exception rather than " + "an assertion, so it is not the security property that failed", + ) + return result( + True, + f"{len(failed)} invariant test(s) failed on assertions while {len(control)} control test(s) passed", + ) + + failing = [c for c in first.cases if c.outcome != "passed"] + if failing: + invariant_assertions = [ + c.name for c in failing if c.base_name in invariant and c.outcome == "failed" and c.assertion + ] + if invariant_assertions: + return result( + False, + f"invariant test(s) {', '.join(invariant_assertions)} still fail their assertions on the " + "REMEDIATED code: either the remediation is incomplete for that operation or the test " + "pins a detail of one particular fix. OpenHack does not weaken a test to make it pass — " + "review the fix and the test", + retryable=False, + ) + return result( + False, + "test(s) failed on the REMEDIATED code: " + ", ".join(c.name for c in failing) + + ". The test setup must work against the fixed code too", + ) + return result(True, f"all {len(first.cases)} test(s) passed") + + +def _feedback(stage: str, check: RevisionCheck) -> str: + lines = [f"Stage: {stage}", f"Problem: {check.detail}"] + if check.outcomes: + lines.append("Outcomes: " + ", ".join( + f"{name.split('::')[-1]}={outcome}" for name, outcome in check.outcomes.items() + )) + for name, message in list(check.failures.items())[:6]: + lines.append(f"--- {name} ---\n{message[-800:]}") + if not check.outcomes and check.output_tail: + lines.append(f"Test output (tail):\n{check.output_tail[-1500:]}") + lines.append( + "Keep every invariant test that covers an operation on the object; fix setup or " + "assertions that pin implementation details instead of removing coverage." + ) + return "\n".join(lines) + + +def _with_provenance(code: str, invariant: SecurityInvariant) -> str: + """Normalize line endings and credit the test's origin in a header comment.""" + code = code.replace("\r\n", "\n") + if not code.endswith("\n"): + code += "\n" + if "openhack" in code[:800].lower(): + return code + header = [ + "# Security regression test generated by OpenHack from a sandbox-verified finding.", + f"# Invariant ({invariant.cwe}):", + *[f"# {line}" for line in textwrap.wrap(invariant.statement, 76)], + ] + lines = code.split("\n") + insert_at = 0 + while insert_at < min(2, len(lines)) and ( + lines[insert_at].startswith("#!") or re.match(r"#.*coding[:=]", lines[insert_at]) + ): + insert_at += 1 + return "\n".join(lines[:insert_at] + header + lines[insert_at:]) + + +@dataclass +class _Verdict: + ok: bool + pending: bool + retryable: bool + reason: str + feedback: str + validation: dict + + +class _ImageCache: + """One sandbox image per (revision, project root), shared by all findings.""" + + def __init__(self, runner: ContainerTestRunner, base_image: str, run_id: str): + self.runner = runner + self.base_image = base_image + self.run_id = run_id + self._tags: dict[tuple[str, str], str] = {} + self._errors: dict[tuple[str, str], SandboxError] = {} + + async def get(self, revision: MaterializedRevision, label: str, + adapter: FrameworkAdapter, profile: FrameworkProfile) -> str: + key = (label, profile.project_root) + if key in self._errors: + raise self._errors[key] + if key not in self._tags: + tag = f"openhack-regression:{self.run_id}-{label}-{len(self._tags)}" + base = self.base_image or adapter.default_base_image(profile) + try: + await self.runner.build_image(revision.root, adapter.dockerfile(profile, base), tag) + except SandboxError as exc: + self._errors[key] = exc + raise + self._tags[key] = tag + return self._tags[key] + + +def default_artifacts_root(session: Session) -> Path: + if session.event_log_path: + return Path(session.event_log_path).parent / "artifacts" + return Path.home() / ".openhack" / "scans" / "artifacts" + + +class RegressionTestPipeline: + """Runs the regression-test workflow for a list of findings.""" + + def __init__( + self, + llm, + session: Session, + target_dir: str | Path, + options: Optional[PipelineOptions] = None, + runner: Optional[ContainerTestRunner] = None, + ): + self.llm = llm + self.session = session + self.target_dir = Path(target_dir).resolve() + self.options = options or PipelineOptions() + self.runner = runner or ContainerTestRunner(self.options.limits) + self.run_id = uuid4().hex[:10] + self.git = git_info(self.target_dir) + + @property + def total_cost(self) -> float: + return float(getattr(self.llm, "total_cost", 0.0) or 0.0) + + async def run(self, findings: list[Finding]) -> list[RegressionTestResult]: + results: dict[str, RegressionTestResult] = {} + eligible: list[tuple[int, Finding, VulnerabilityClassSpec, SecurityInvariant]] = [] + for index, finding in enumerate(findings): + spec = spec_for_finding(finding) + if spec is None: + results[finding.id] = self._result( + finding, Status.UNSUPPORTED_VULNERABILITY, + f"{finding.category or 'This category'} is not supported yet " + f"(supported: {', '.join(supported_classes())})", + ) + continue + try: + invariant = spec.extract_invariant(finding) + except MissingEvidenceError as exc: + results[finding.id] = self._result(finding, Status.MISSING_EVIDENCE, str(exc), spec) + continue + eligible.append((index, finding, spec, invariant)) + + if eligible: + self.session.add_trace( + agent=AGENT, event_type="status", + content=f"Generating regression tests for {len(eligible)} eligible finding(s)", + ) + try: + await self._run_eligible(eligible, results) + except asyncio.CancelledError: + raise + except Exception as exc: + # Never leave an eligible finding without a status. + logger.warning(f"Regression test workflow failed: {exc}", exc_info=True) + for _, finding, spec, invariant in eligible: + results.setdefault(finding.id, self._result( + finding, Status.GENERATION_FAILED, + f"the regression test workflow failed: {exc}", spec, invariant, + )) + + ordered = [] + for finding in findings: + result = results[finding.id] + finding.regression_test = result.to_dict() + self.session.add_trace( + agent=AGENT, event_type="regression_test_result", + content={ + "title": finding.title, + "status": result.status.value, + "label": result.status.label, + "reason": result.reason, + "test_path": result.test_path or "", + }, + ) + ordered.append(result) + return ordered + + async def _run_eligible(self, eligible, results: dict[str, RegressionTestResult]) -> None: + work_dir = Path(tempfile.mkdtemp(prefix="openhack-regression-")) + try: + try: + vulnerable = await asyncio.to_thread( + materialize, self.target_dir, self.options.vulnerable, work_dir / "vulnerable" + ) + except WorkspaceError as exc: + for _, finding, spec, invariant in eligible: + results[finding.id] = self._result( + finding, Status.SANDBOX_ERROR, + f"could not prepare the vulnerable revision " + f"({self.options.vulnerable.describe()}): {exc}", spec, invariant, + ) + return + remediated, remediation_note = await self._prepare_remediated(work_dir, vulnerable) + try: + await self.runner.ensure_available() + except SandboxError as exc: + for _, finding, spec, invariant in eligible: + results[finding.id] = self._result(finding, Status.SANDBOX_ERROR, str(exc), spec, invariant) + return + + images = _ImageCache(self.runner, self.options.base_image, self.run_id) + for index, finding, spec, invariant in eligible: + if self.session.cancelled: + results[finding.id] = self._result( + finding, Status.GENERATION_FAILED, + "cancelled before a regression test was generated", spec, invariant, + ) + continue + try: + adapter, profile = detect_framework(vulnerable.root, finding.file_path) + except UnsupportedFrameworkError as exc: + results[finding.id] = self._result( + finding, Status.UNSUPPORTED_FRAMEWORK, str(exc), spec, invariant, + ) + continue + results[finding.id] = await self._process( + index, finding, spec, invariant, adapter, profile, + vulnerable, remediated, remediation_note, images, + ) + finally: + await self.runner.remove_images() + await asyncio.to_thread(remove_tree, work_dir) + + async def _prepare_remediated( + self, work_dir: Path, vulnerable: MaterializedRevision, + ) -> tuple[Optional[MaterializedRevision], str]: + spec = self.options.remediation + hint = f"openhack --regression-tests {self.options.report_id or self.session.id} " + if spec is None: + return None, ( + "no remediated revision was available to validate against (set " + f"regression_tests_fixed_ref, or re-validate after fixing with `{hint}`)" + ) + try: + remediated = await asyncio.to_thread( + materialize, self.target_dir, spec, work_dir / "remediated" + ) + except WorkspaceError as exc: + return None, f"the remediated revision could not be prepared ({spec.describe()}): {exc}" + if remediated.fingerprint == vulnerable.fingerprint: + return None, ( + f"the remediated revision ({remediated.label}) is identical to the vulnerable " + f"revision — commit the fix and re-validate with `{hint}`" + ) + return remediated, "" + + @staticmethod + def _stored_submission(finding: Finding) -> Optional[CandidateTest]: + """A previously generated test that already reproduced the vulnerability.""" + data = finding.regression_test + if not isinstance(data, dict): + return None + if data.get("status") not in (Status.VALIDATED.value, Status.REMEDIATION_UNAVAILABLE.value): + return None + if not data.get("test_code") or not data.get("test_path") or not data.get("invariant_tests"): + return None + return CandidateTest( + path=data["test_path"], code=data["test_code"], + invariant_tests=list(data.get("invariant_tests") or []), + control_tests=list(data.get("control_tests") or []), + summary=data.get("summary") or "", + ) + + async def _process( + self, index: int, finding: Finding, spec: VulnerabilityClassSpec, + invariant: SecurityInvariant, adapter: FrameworkAdapter, profile: FrameworkProfile, + vulnerable: MaterializedRevision, remediated: Optional[MaterializedRevision], + remediation_note: str, images: _ImageCache, + ) -> RegressionTestResult: + cost_before = self.total_cost + self.session.add_trace( + agent=AGENT, event_type="regression_test_started", + content={"title": finding.title, "class": spec.key, + "endpoint": f"{invariant.method} {invariant.path_template}"}, + ) + root = profile.project_root + + def repo_path(rel: str) -> str: + return rel if root == "." else f"{root}/{rel}" + + def available(rel: str, stored_code: Optional[str] = None) -> bool: + path = repo_path(rel) + if vulnerable.exists(path): + return False + if remediated is not None and remediated.exists(path): + # The developer may have committed our pending test alongside + # the fix; re-validating that identical file is fine. + existing = (remediated.root / path).read_text(encoding="utf-8", errors="replace") + return stored_code is not None and existing == stored_code + return True + + suggested = adapter.suggest_test_path(profile, invariant, lambda rel: not available(rel)) + + def outcome(status: RegressionTestStatus, reason: str) -> RegressionTestResult: + return self._result(finding, status, reason, spec, invariant, adapter.name, + attempts, self.total_cost - cost_before) + + candidate = self._stored_submission(finding) + candidate_is_stored = candidate is not None + agent: Optional[RegressionTestGeneratorAgent] = None + generation_note = "" + feedback = "" + attempts = 0 + executed = False + last_status, last_reason, last_validation = Status.GENERATION_FAILED, "no test was generated", {} + last_candidate: Optional[CandidateTest] = None + + while True: + if self.session.cancelled: + return outcome(Status.GENERATION_FAILED, "cancelled") + if candidate is None: + if attempts >= self.options.max_attempts: + break + if self.llm is None: + last_reason = "no LLM is configured to generate a new test" + break + attempts += 1 + self.session.add_trace( + agent=AGENT, event_type="status", + content=f"{finding.title}: generation attempt {attempts}/{self.options.max_attempts}", + ) + try: + if agent is None: + agent = RegressionTestGeneratorAgent( + self.llm, ToolRegistry(target_dir=vulnerable.root), self.session, + finding=finding, invariant=invariant, spec=spec, adapter=adapter, + profile=profile, suggested_path=suggested, finding_index=index, + ) + submission = await agent.generate(note=generation_note) + else: + submission = await agent.revise(feedback) + except asyncio.CancelledError: + raise + except Exception as exc: + logger.warning(f"Regression test generator failed: {exc}", exc_info=True) + last_status = Status.VALIDATION_FAILED if executed else Status.GENERATION_FAILED + last_reason = f"the generator failed: {exc}" + break + if submission is None: + feedback = "No test was submitted. Call submit_regression_test with the complete file." + if not executed: + last_status, last_reason = Status.GENERATION_FAILED, "the generator did not submit a test" + continue + candidate = CandidateTest( + path=submission.path, + code=_with_provenance(submission.code, invariant), + invariant_tests=submission.invariant_tests, + control_tests=submission.control_tests, + summary=submission.summary, + ) + candidate_is_stored = False + + last_candidate = candidate + problems: list[str] = [] + path_error = adapter.validate_test_path(profile, candidate.path) + if path_error: + problems.append(path_error) + elif not available(candidate.path, candidate.code if candidate_is_stored else None): + problems.append( + f"`{candidate.path}` already exists in the repository; existing tests are never " + f"modified — use a new file such as `{suggested}`" + ) + problems += adapter.static_check(candidate.code) + if problems: + feedback = "The test was rejected before execution:\n" + "\n".join(f"- {p}" for p in problems) + last_status = Status.VALIDATION_FAILED if executed else Status.GENERATION_FAILED + last_reason = "rejected before execution: " + "; ".join(problems[:3]) + if candidate_is_stored: + generation_note = f"A previously generated test was unusable: {feedback}" + candidate = None + continue + + try: + verdict = await self._validate(candidate, spec, adapter, profile, vulnerable, remediated, images) + except SandboxError as exc: + return outcome(Status.SANDBOX_ERROR, str(exc)) + executed = True + if verdict.ok or verdict.pending: + if verdict.ok: + assert remediated is not None + status = Status.VALIDATED + reason = ( + f"Fails on the vulnerable revision ({vulnerable.label}) and passes on the " + f"remediated revision ({remediated.label}) in " + f"{self.options.validation_runs}/{self.options.validation_runs} sandbox runs each." + ) + else: + status = Status.REMEDIATION_UNAVAILABLE + reason = ( + f"The test reproduces the vulnerability (fails on {vulnerable.label} in " + f"{self.options.validation_runs}/{self.options.validation_runs} sandbox runs) " + f"but was not validated against a fix: {remediation_note}." + ) + return self._accept(finding, status, reason, spec, invariant, adapter, profile, + candidate, verdict.validation, attempts, cost_before) + + last_status, last_reason, last_validation = Status.VALIDATION_FAILED, verdict.reason, verdict.validation + if not verdict.retryable: + break + feedback = verdict.feedback + if candidate_is_stored: + generation_note = ( + "A previously generated test for this finding failed re-validation:\n" + f"{verdict.feedback}\n\nPrevious test (`{candidate.path}`):\n```\n{candidate.code}\n```\n" + "Write a corrected test." + ) + candidate = None + + result = outcome(last_status, last_reason) + result.validation = last_validation + if last_candidate is not None and executed: + # Keep the rejected test for review, but never as an accepted artifact. + result.test_path = last_candidate.path + result.test_code = last_candidate.code + result.invariant_tests = list(last_candidate.invariant_tests) + result.control_tests = list(last_candidate.control_tests) + return result + + async def _validate( + self, candidate: CandidateTest, spec: VulnerabilityClassSpec, + adapter: FrameworkAdapter, profile: FrameworkProfile, + vulnerable: MaterializedRevision, remediated: Optional[MaterializedRevision], + images: _ImageCache, + ) -> _Verdict: + runs = self.options.validation_runs + timeout = self.options.limits.run_timeout + validation: dict[str, Any] = {"runs_per_revision": runs, "vulnerable": None, "remediated": None} + + image = await images.get(vulnerable, "vulnerable", adapter, profile) + reports = [await self._run_once(image, adapter, profile, candidate) for _ in range(runs)] + check = evaluate_runs(reports, candidate, "vulnerable", spec.requires_control_test, timeout) + validation["vulnerable"] = check.to_dict(vulnerable) + self.session.add_trace( + agent=AGENT, event_type="regression_test_check", + content={"revision": "vulnerable", "passed": check.passed, "detail": check.detail}, + ) + if not check.passed: + return _Verdict(False, False, True, f"On the vulnerable revision: {check.detail}", + _feedback("vulnerable revision", check), validation) + if remediated is None: + return _Verdict(False, True, False, check.detail, "", validation) + + image = await images.get(remediated, "remediated", adapter, profile) + reports = [await self._run_once(image, adapter, profile, candidate) for _ in range(runs)] + check = evaluate_runs(reports, candidate, "remediated", spec.requires_control_test, timeout) + validation["remediated"] = check.to_dict(remediated) + self.session.add_trace( + agent=AGENT, event_type="regression_test_check", + content={"revision": "remediated", "passed": check.passed, "detail": check.detail}, + ) + if not check.passed: + return _Verdict(False, False, check.retryable, f"On the remediated revision: {check.detail}", + _feedback("remediated revision", check), validation) + return _Verdict(True, False, False, "", "", validation) + + async def _run_once(self, image: str, adapter: FrameworkAdapter, + profile: FrameworkProfile, candidate: CandidateTest) -> RunReport: + root = profile.project_root + rel_in_repo = candidate.path if root == "." else f"{root}/{candidate.path}" + workdir = "/workspace" if root == "." else f"/workspace/{root}" + run = await self.runner.run_test( + image, {rel_in_repo: candidate.code}, + adapter.container_command(profile, candidate.path), workdir=workdir, + ) + try: + return adapter.parse_results(run.results_dir, run.exit_code, run.timed_out) + finally: + run.cleanup() + + def _result( + self, finding: Finding, status: RegressionTestStatus, reason: str, + spec: Optional[VulnerabilityClassSpec] = None, + invariant: Optional[SecurityInvariant] = None, + framework: Optional[str] = None, attempts: int = 0, cost: float = 0.0, + ) -> RegressionTestResult: + return RegressionTestResult( + finding_id=finding.id, status=status, reason=reason, + vulnerability_class=spec.key if spec else None, invariant=invariant, + framework=framework, attempts=attempts, cost=round(cost, 6), + generated_at=datetime.now(timezone.utc).isoformat(timespec="seconds"), + ) + + def _accept( + self, finding: Finding, status: RegressionTestStatus, reason: str, + spec: VulnerabilityClassSpec, invariant: SecurityInvariant, + adapter: FrameworkAdapter, profile: FrameworkProfile, candidate: CandidateTest, + validation: dict, attempts: int, cost_before: float, + ) -> RegressionTestResult: + result = self._result(finding, status, reason, spec, invariant, adapter.name, + attempts, self.total_cost - cost_before) + result.test_path = candidate.path + result.test_code = candidate.code + result.run_command = adapter.display_command(profile, candidate.path) + result.invariant_tests = list(candidate.invariant_tests) + result.control_tests = list(candidate.control_tests) + result.summary = candidate.summary + result.validation = validation + try: + result.artifacts = self._write_artifacts(finding, result, profile) + except OSError as exc: + logger.warning(f"Could not write regression test artifacts: {exc}") + return result + + def _write_artifacts(self, finding: Finding, result: RegressionTestResult, + profile: FrameworkProfile) -> dict[str, str]: + root = self.options.artifacts_root or default_artifacts_root(self.session) + session_dir = root / (self.options.report_id or self.session.id) + art_dir = session_dir / "regression-tests" / finding.id[:8] + art_dir.mkdir(parents=True, exist_ok=True) + for directory in (session_dir, art_dir.parent, art_dir): + try: + os.chmod(directory, 0o700) + except OSError: + pass + parts = [p for p in (self.git.get("prefix", ""), profile.project_root, result.test_path) if p and p != "."] + repo_path = PurePosixPath(*parts).as_posix() + test_file = art_dir / repo_path + patch = art_dir / "regression-test.patch" + write_private_file(test_file, result.test_code or "") + write_private_file(patch, new_file_patch(repo_path, result.test_code or "")) + artifacts = { + "dir": str(art_dir), + "test_file": str(test_file), + "patch": str(patch), + "repo_path": repo_path, + "apply": f"git apply {patch}", + } + record = result.to_dict() + record["artifacts"] = artifacts + write_private_file(art_dir / "result.json", json.dumps(record, indent=2, default=str)) + return artifacts diff --git a/openhack/regression/workspace.py b/openhack/regression/workspace.py new file mode 100644 index 0000000..a420e4a --- /dev/null +++ b/openhack/regression/workspace.py @@ -0,0 +1,394 @@ +""" +Revision workspaces for regression-test validation. + +Validation needs two concrete trees: the vulnerable implementation (what was +scanned) and the remediated one (a fix commit or branch, or a directory +holding the fixed code). Each is materialized into a private temporary +directory that becomes the sandbox's Docker build context. The user's +checkout is never modified, and credential files are left out so neither a +generated test nor the image build can read them. +""" + +from __future__ import annotations + +import hashlib +import os +import shutil +import subprocess +from dataclasses import dataclass +from pathlib import Path, PurePosixPath +from typing import Optional + +MAX_FILES = 20_000 +MAX_BYTES = 300 * 1024 * 1024 +GIT_TIMEOUT = 120 + +_EXCLUDED_DIRS = { + ".git", "node_modules", "__pycache__", ".venv", "venv", ".tox", ".nox", + ".mypy_cache", ".pytest_cache", ".ruff_cache", ".openhack-evidence", + ".ssh", ".aws", ".gnupg", ".docker", ".kube", ".azure", +} +_SENSITIVE_NAMES = { + ".npmrc", ".pypirc", ".netrc", ".git-credentials", ".htpasswd", ".pgpass", + "id_rsa", "id_dsa", "id_ecdsa", "id_ed25519", "credentials.json", + "service-account.json", "secrets.json", "secrets.yml", "secrets.yaml", +} +_SENSITIVE_SUFFIXES = (".pem", ".key", ".p12", ".pfx", ".jks", ".keystore", ".kdbx") +_ENV_TEMPLATES = {".env.example", ".env.sample", ".env.template", ".env.dist", ".env.defaults"} + + +class WorkspaceError(Exception): + """A revision could not be materialized for validation.""" + + +@dataclass(frozen=True) +class RevisionSpec: + """Where a revision's code comes from.""" + + kind: str # "worktree" | "git" | "directory" + value: str = "" + + @classmethod + def worktree(cls) -> "RevisionSpec": + return cls("worktree") + + @classmethod + def git(cls, ref: str) -> "RevisionSpec": + return cls("git", ref) + + @classmethod + def directory(cls, path: str | Path) -> "RevisionSpec": + return cls("directory", str(Path(path).expanduser().resolve())) + + @classmethod + def parse(cls, raw: str, base_dir: Optional[Path] = None) -> "RevisionSpec": + """An existing directory path, otherwise a git revision (sha/branch/tag).""" + raw = (raw or "").strip() + if not raw: + raise WorkspaceError("empty revision") + candidate = Path(raw).expanduser() + if not candidate.is_absolute() and base_dir is not None: + candidate = base_dir / candidate + if candidate.is_dir(): + return cls.directory(candidate) + return cls.git(raw) + + def describe(self) -> str: + if self.kind == "worktree": + return "working tree" + if self.kind == "git": + return f"git revision `{self.value}`" + return f"directory {self.value}" + + +@dataclass +class MaterializedRevision: + spec: RevisionSpec + root: Path + resolved: str + fingerprint: str + file_count: int + + def exists(self, relpath: str) -> bool: + return (self.root / relpath).exists() + + @property + def label(self) -> str: + if self.spec.kind == "git": + short = self.resolved[:12] + # A revision given as a (possibly abbreviated) sha needs no repeat. + if self.resolved.startswith(self.spec.value): + return short + return f"{self.spec.value} ({short})" + return self.spec.describe() + + +def is_excluded_path(relpath: str) -> bool: + """Paths never copied into a validation workspace.""" + parts = PurePosixPath(relpath).parts + if not parts: + return True + for part in parts[:-1]: + if part in _EXCLUDED_DIRS or part.endswith(".egg-info"): + return True + name = parts[-1] + lowered = name.lower() + if name.startswith(".openhack-"): + return True + if lowered == ".env" or (lowered.startswith(".env.") and lowered not in _ENV_TEMPLATES): + return True + if lowered in _SENSITIVE_NAMES or lowered.startswith(("id_rsa", "id_ed25519")): + return True + return lowered.endswith(_SENSITIVE_SUFFIXES) + + +def _git(target: Path, *args: str, timeout: int = GIT_TIMEOUT) -> subprocess.CompletedProcess: + return subprocess.run( + ["git", "-C", str(target), *args], + capture_output=True, text=True, timeout=timeout, check=False, + ) + + +def git_info(target: Path) -> dict: + """Repository facts for ``target`` (which may be a repo subdirectory).""" + try: + top = _git(target, "rev-parse", "--show-toplevel", timeout=10) + except (OSError, subprocess.SubprocessError): + return {"is_repo": False} + if top.returncode != 0: + return {"is_repo": False} + prefix = _git(target, "rev-parse", "--show-prefix", timeout=10).stdout.strip() + head = _git(target, "rev-parse", "HEAD", timeout=10) + status = _git(target, "status", "--porcelain", "--untracked-files=no", timeout=30) + return { + "is_repo": True, + "toplevel": top.stdout.strip(), + "prefix": prefix.rstrip("/"), + "head": head.stdout.strip() if head.returncode == 0 else "", + "dirty": bool(status.stdout.strip()), + } + + +def resolve_commit(target: Path, ref: str) -> str: + try: + result = _git(target, "rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}", timeout=15) + except (OSError, subprocess.SubprocessError) as exc: + raise WorkspaceError(f"git is unavailable: {exc}") from exc + sha = result.stdout.strip() + if result.returncode != 0 or not sha: + raise WorkspaceError(f"`{ref}` is not a commit in {target}") + return sha + + +class _Copier: + """Copies files into a workspace while enforcing limits and hashing content.""" + + def __init__(self, dest: Path): + self.dest = dest.resolve() + self.count = 0 + self.bytes = 0 + self.entries: list[tuple[str, str]] = [] + + def _target(self, relpath: str) -> Path: + path = (self.dest / relpath).resolve() + if not path.is_relative_to(self.dest): + raise WorkspaceError(f"refusing to write outside the workspace: {relpath}") + return path + + def add(self, relpath: str, stream, executable: bool = False) -> None: + self.count += 1 + if self.count > MAX_FILES: + raise WorkspaceError(f"revision has more than {MAX_FILES} files") + target = self._target(relpath) + target.parent.mkdir(parents=True, exist_ok=True) + digest = hashlib.sha256() + with open(target, "wb") as out: + while True: + block = stream.read(1024 * 1024) + if not block: + break + self.bytes += len(block) + if self.bytes > MAX_BYTES: + raise WorkspaceError(f"revision is larger than {MAX_BYTES // (1024 * 1024)} MB") + digest.update(block) + out.write(block) + os.chmod(target, 0o755 if executable else 0o644) + self.entries.append((relpath, digest.hexdigest())) + + def fingerprint(self) -> str: + digest = hashlib.sha256() + for relpath, file_hash in sorted(self.entries): + digest.update(f"{relpath}\0{file_hash}\n".encode()) + return digest.hexdigest() + + +def _copy_tree_files(source: Path, relpaths: list[str], copier: _Copier) -> None: + source = source.resolve() + for rel in relpaths: + rel = PurePosixPath(rel).as_posix() + if is_excluded_path(rel): + continue + path = source / rel + # Symlinks are skipped: one pointing outside the tree would otherwise + # smuggle host files into the build context. + if path.is_symlink() or not path.is_file(): + continue + with open(path, "rb") as stream: + copier.add(rel, stream, executable=os.access(path, os.X_OK)) + + +def _walk_relpaths(source: Path) -> list[str]: + out: list[str] = [] + for dirpath, dirnames, filenames in os.walk(source): + dirnames[:] = [d for d in dirnames if d not in _EXCLUDED_DIRS and not d.endswith(".egg-info")] + rel_dir = Path(dirpath).relative_to(source) + for name in filenames: + out.append((rel_dir / name).as_posix()) + return out + + +def _git_worktree_relpaths(target: Path) -> list[str]: + result = subprocess.run( + ["git", "-C", str(target), "ls-files", "-z", "--cached", "--others", "--exclude-standard"], + capture_output=True, timeout=GIT_TIMEOUT, check=False, + ) + if result.returncode != 0: + raise WorkspaceError(f"git ls-files failed: {result.stderr.decode(errors='replace')[:300]}") + return [p for p in result.stdout.decode("utf-8", errors="replace").split("\0") if p] + + +class _ExactReader: + """File-like view of exactly ``size`` bytes of a shared stream.""" + + def __init__(self, stream, size: int): + self.stream = stream + self.remaining = size + + def read(self, n: int = -1) -> bytes: + if self.remaining <= 0: + return b"" + n = self.remaining if n < 0 else min(n, self.remaining) + data = self.stream.read(n) + if not data: + raise WorkspaceError("git cat-file ended early") + self.remaining -= len(data) + return data + + +def _extract_git_revision(target: Path, sha: str, prefix: str, copier: _Copier) -> None: + """Copy a commit's tree verbatim. + + ``git archive`` is deliberately avoided: it honors export-ignore and + export-subst attributes, and some repositories export-ignore their tests, + which would silently drop the suite the regression test belongs to. + """ + treeish = f"{sha}:{prefix}" if prefix else sha + # --full-tree: run from a subdirectory, ls-tree would otherwise filter the + # listing by that directory and return nothing for the subtree. + listing = subprocess.run( + ["git", "-C", str(target), "ls-tree", "-r", "-z", "--full-tree", treeish], + capture_output=True, timeout=GIT_TIMEOUT, check=False, + ) + if listing.returncode != 0: + raise WorkspaceError( + f"git ls-tree {treeish} failed: {listing.stderr.decode(errors='replace')[:300]}" + ) + entries: list[tuple[str, str, bool]] = [] + for record in listing.stdout.split(b"\0"): + if not record: + continue + meta, _, raw_path = record.partition(b"\t") + try: + mode, obj_type, obj = meta.decode().split() + except ValueError: + continue + # Regular blobs only: symlinks (120000) and submodules (160000) are + # never materialized, and absolute or `..` paths are rejected. + if obj_type != "blob" or mode not in ("100644", "100755"): + continue + path = PurePosixPath(raw_path.decode("utf-8", errors="replace")) + if path.is_absolute() or ".." in path.parts or is_excluded_path(path.as_posix()): + continue + entries.append((path.as_posix(), obj, mode == "100755")) + + proc = subprocess.Popen( + ["git", "-C", str(target), "cat-file", "--batch"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + ) + stdin, stdout = proc.stdin, proc.stdout + assert stdin is not None and stdout is not None + try: + for rel, obj, executable in entries: + stdin.write(f"{obj}\n".encode()) + stdin.flush() + header = stdout.readline().decode(errors="replace").split() + if len(header) != 3 or header[1] != "blob": + raise WorkspaceError(f"could not read {rel} from {sha[:12]}") + copier.add(rel, _ExactReader(stdout, int(header[2])), executable=executable) + stdout.read(1) # newline terminating each object + finally: + try: + stdin.close() + except OSError: + pass + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + + +def materialize(target_dir: Path, spec: RevisionSpec, dest: Path) -> MaterializedRevision: + """Copy one revision of ``target_dir`` into the empty directory ``dest``.""" + target_dir = Path(target_dir).resolve() + dest.mkdir(parents=True, exist_ok=True) + copier = _Copier(dest) + try: + if spec.kind == "git": + info = git_info(target_dir) + if not info.get("is_repo"): + raise WorkspaceError(f"{target_dir} is not a git repository, so `{spec.value}` cannot be resolved") + sha = resolve_commit(target_dir, spec.value) + _extract_git_revision(target_dir, sha, info.get("prefix", ""), copier) + resolved = sha + elif spec.kind == "worktree": + info = git_info(target_dir) + if info.get("is_repo"): + relpaths = _git_worktree_relpaths(target_dir) + resolved = f"working tree @ {info.get('head', '')[:12]}" + (" (modified)" if info.get("dirty") else "") + else: + relpaths = _walk_relpaths(target_dir) + resolved = "working tree" + _copy_tree_files(target_dir, relpaths, copier) + elif spec.kind == "directory": + source = Path(spec.value) + if not source.is_dir(): + raise WorkspaceError(f"directory not found: {source}") + _copy_tree_files(source, _walk_relpaths(source), copier) + resolved = str(source) + else: + raise WorkspaceError(f"unknown revision kind: {spec.kind}") + except subprocess.TimeoutExpired as exc: + raise WorkspaceError(f"timed out materializing {spec.describe()}") from exc + except OSError as exc: + raise WorkspaceError(f"could not materialize {spec.describe()}: {exc}") from exc + if copier.count == 0: + raise WorkspaceError(f"{spec.describe()} contains no files") + return MaterializedRevision( + spec=spec, root=dest.resolve(), resolved=resolved, + fingerprint=copier.fingerprint(), file_count=copier.count, + ) + + +def new_file_patch(relpath: str, content: str) -> str: + """A git-style patch that adds one new file (apply with ``git apply``).""" + if not content.endswith("\n"): + content += "\n" + lines = content.splitlines(keepends=True) + header = ( + f"diff --git a/{relpath} b/{relpath}\n" + "new file mode 100644\n" + "--- /dev/null\n" + f"+++ b/{relpath}\n" + f"@@ -0,0 +1,{len(lines)} @@\n" + ) + return header + "".join(f"+{line}" for line in lines) + + +def write_private_file(path: Path, content: str) -> None: + """Write an artifact readable only by the current user.""" + path.parent.mkdir(parents=True, exist_ok=True) + try: + os.chmod(path.parent, 0o700) + except OSError: + pass + path.write_text(content, encoding="utf-8") + try: + os.chmod(path, 0o600) + except OSError: + pass + + +def remove_tree(path: Optional[Path]) -> None: + if path is not None: + shutil.rmtree(path, ignore_errors=True) diff --git a/openhack/sandbox/container_runner.py b/openhack/sandbox/container_runner.py new file mode 100644 index 0000000..ea498e9 --- /dev/null +++ b/openhack/sandbox/container_runner.py @@ -0,0 +1,183 @@ +""" +Locked-down container execution for generated test code. + +Generated tests, and the repository code they exercise, are untrusted. They +only ever execute inside a Docker container started by this runner — never +on the host: + +- no network (``--network none``): the image build may fetch the project's + dependencies, but the test run itself cannot reach anything; +- no host mounts: code goes in through the image and ``docker cp``, results + come back out the same way, so the container cannot write to the host; +- unprivileged: non-root user, every capability dropped, no-new-privileges; +- bounded: memory, CPU and PID limits plus a wall-clock timeout, after which + the container is killed; +- disposable: every run gets a fresh container that is always removed. +""" + +from __future__ import annotations + +import logging +import os +import shutil +import tempfile +from dataclasses import dataclass, field +from pathlib import Path +from typing import Optional +from uuid import uuid4 + +from .orchestrator import SandboxError, SandboxOrchestrator, SandboxTimeoutError + +logger = logging.getLogger(__name__) + +LABEL = "openhack.regression=1" +UNPRIVILEGED_USER = "65534:65534" + + +@dataclass +class ContainerLimits: + run_timeout: int = 180 + build_timeout: int = 900 + memory: str = "1g" + cpus: str = "1" + pids: int = 256 + + +@dataclass +class ContainerRunResult: + exit_code: Optional[int] + timed_out: bool + results_dir: Path + stderr: str = "" + container: str = field(default="", repr=False) + + def cleanup(self) -> None: + shutil.rmtree(self.results_dir, ignore_errors=True) + + +async def _run(cmd: list[str], timeout: int, check: bool = True): + try: + return await SandboxOrchestrator._run_command(cmd, timeout=timeout, check=check) + except FileNotFoundError as exc: + raise SandboxError("the Docker CLI was not found on PATH") from exc + + +class ContainerTestRunner: + """Builds per-revision images and runs one test file per fresh container.""" + + def __init__(self, limits: Optional[ContainerLimits] = None): + self.limits = limits or ContainerLimits() + self._images: set[str] = set() + + def lockdown_flags(self) -> list[str]: + limits = self.limits + return [ + "--network", "none", + "--memory", limits.memory, + "--memory-swap", limits.memory, + "--cpus", str(limits.cpus), + "--pids-limit", str(limits.pids), + "--cap-drop", "ALL", + "--security-opt", "no-new-privileges", + "--user", UNPRIVILEGED_USER, + "--env", "HOME=/tmp", + "--env", "PYTHONDONTWRITEBYTECODE=1", + ] + + async def ensure_available(self) -> None: + try: + await _run(["docker", "version", "--format", "{{.Server.Version}}"], timeout=30) + except SandboxError as exc: + raise SandboxError( + f"Docker is required to validate regression tests but is not available: {exc}" + ) from exc + + async def build_image(self, context_dir: Path, dockerfile: str, tag: str) -> None: + dockerfile_path = context_dir / ".openhack-regression.Dockerfile" + dockerfile_path.write_text(dockerfile, encoding="utf-8") + cmd = [ + "docker", "build", "--label", LABEL, "-t", tag, + "-f", str(dockerfile_path), str(context_dir), + ] + try: + await _run(cmd, timeout=self.limits.build_timeout) + except SandboxTimeoutError as exc: + raise SandboxError( + f"sandbox image build timed out after {self.limits.build_timeout}s" + ) from exc + except SandboxError as exc: + detail = str(exc) + raise SandboxError( + "sandbox image build failed (could the project's test dependencies " + f"be installed?): {detail[-1500:]}" + ) from exc + self._images.add(tag) + + async def run_test( + self, + image: str, + files: dict[str, str], + command: list[str], + workdir: str = "/workspace", + results_path: str = "/openhack-results", + ) -> ContainerRunResult: + """Run ``command`` in a fresh locked-down container of ``image``. + + ``files`` (path relative to /workspace -> content) are copied in before + start; ``results_path`` is copied back out afterwards. The container is + removed whatever happens. + """ + name = f"openhack-regression-{uuid4().hex[:12]}" + results_dir = Path(tempfile.mkdtemp(prefix="openhack-results-")) + staging = Path(tempfile.mkdtemp(prefix="openhack-stage-")) + created = False + try: + await _run( + ["docker", "create", "--name", name, "--label", LABEL, + *self.lockdown_flags(), "--workdir", workdir, image, *command], + timeout=60, + ) + created = True + for relpath, content in files.items(): + target = (staging / relpath).resolve() + if not target.is_relative_to(staging.resolve()): + raise SandboxError(f"refusing to stage a file outside the workspace: {relpath}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content, encoding="utf-8") + os.chmod(target, 0o644) + await _run(["docker", "cp", f"{staging}{os.sep}.", f"{name}:/workspace"], timeout=60) + + exit_code: Optional[int] = None + timed_out = False + stderr = "" + try: + proc = await _run( + ["docker", "start", "-a", name], + timeout=self.limits.run_timeout, check=False, + ) + exit_code = proc.returncode + stderr = (proc.stderr or "")[-2000:] + except SandboxTimeoutError: + timed_out = True + await self._quiet(["docker", "kill", name]) + await self._quiet(["docker", "cp", f"{name}:{results_path}/.", str(results_dir)]) + return ContainerRunResult(exit_code, timed_out, results_dir, stderr, name) + except BaseException: + shutil.rmtree(results_dir, ignore_errors=True) + raise + finally: + shutil.rmtree(staging, ignore_errors=True) + if created: + await self._quiet(["docker", "rm", "-f", name]) + + async def remove_images(self) -> None: + for tag in list(self._images): + await self._quiet(["docker", "rmi", "-f", tag]) + self._images.discard(tag) + + @staticmethod + async def _quiet(cmd: list[str]) -> None: + try: + await _run(cmd, timeout=60, check=False) + except (SandboxError, OSError) as exc: + logger.debug(f"sandbox cleanup command failed ({' '.join(cmd)}): {exc}") diff --git a/openhack/sandbox/orchestrator.py b/openhack/sandbox/orchestrator.py index 8dcf547..e675443 100644 --- a/openhack/sandbox/orchestrator.py +++ b/openhack/sandbox/orchestrator.py @@ -480,8 +480,13 @@ async def _run_command( cwd: Optional[Path] = None, env: Optional[dict] = None, timeout: int = 60, + check: bool = True, ) -> asyncio.subprocess.Process: - """Run a shell command asynchronously.""" + """Run a shell command asynchronously. + + With check=False a non-zero exit is returned rather than raised — for + commands like `docker start -a` whose exit code is the result. + """ import os full_env = {**os.environ, **(env or {})} @@ -498,12 +503,14 @@ async def _run_command( except asyncio.TimeoutError: proc.kill() await proc.communicate() - raise SandboxError(f"Command timed out after {timeout}s: {' '.join(cmd)}") + raise SandboxTimeoutError(f"Command timed out after {timeout}s: {' '.join(cmd)}") - proc.stdout = stdout.decode() if stdout else "" - proc.stderr = stderr.decode() if stderr else "" + # Output can come from untrusted code in the container; never let a + # stray byte sequence turn into a UnicodeDecodeError here. + proc.stdout = stdout.decode(errors="replace") if stdout else "" + proc.stderr = stderr.decode(errors="replace") if stderr else "" - if proc.returncode != 0: + if check and proc.returncode != 0: raise SandboxError( f"Command failed (exit {proc.returncode}): {' '.join(cmd)}\n" f"STDERR: {proc.stderr[:2000]}" @@ -515,3 +522,8 @@ async def _run_command( class SandboxError(Exception): """Raised when sandbox operations fail.""" pass + + +class SandboxTimeoutError(SandboxError): + """Raised when a sandbox command exceeds its time limit.""" + pass diff --git a/openhack/tui.py b/openhack/tui.py index 3fe924b..2036805 100644 --- a/openhack/tui.py +++ b/openhack/tui.py @@ -66,6 +66,7 @@ from openhack.agents.llm import LLMClient, Message, LLMResponse from openhack.agents.session import Session, SessionStatus, Finding, TraceEntry from openhack.agents.eventlog import redact +from openhack.regression.evidence import sanitize_exploit_evidence logger = logging.getLogger(__name__) from openhack.config import ( @@ -383,6 +384,8 @@ def _sev_label(severity: str) -> str: ("openhack_model_id", "OpenHack model ID"), ("fast_mode", "Throughput-first OpenHack inference routing"), ("tips_enabled", "Rotating status-bar guidance"), + ("regression_tests_enabled", "Generate sandbox-validated regression tests for verified findings"), + ("regression_tests_fixed_ref", "Git revision (or directory) holding the fix to validate against"), ] _GENERAL_TIPS = ( @@ -982,6 +985,35 @@ def update_from_trace(self, entry: TraceEntry) -> None: ]) return + if etype == "regression_test_check": + data = entry.content if isinstance(entry.content, dict) else {} + verdict = "ok" if data.get("passed") else "rejected" + self._append_trace(agent, [ + ("class:trace.time", ts), + ("class:trace.agent", f" {agent:>24}"), + ("class:trace.dim", f" {data.get('revision', '?')} revision {verdict} · " + f"{str(data.get('detail', ''))[:160]}"), + ]) + return + + if etype == "regression_test_result": + data = entry.content if isinstance(entry.content, dict) else {} + status = data.get("status", "") + label = data.get("label") or status + style = { + "validated": "class:verified", + "remediation_unavailable": "class:sev.medium", + }.get(status, "class:trace.dim") + self.last_message = f"regression test · {label}" + self._append_trace(agent, [ + ("class:trace.time", ts), + ("class:trace.agent", f" {agent:>24}"), + ("class:trace.arrow", " · "), + (style, label), + ("class:trace.dim", f" {data.get('title', '')}"), + ]) + return + # ── Bang / shell mode ────────────────────────────────────── if etype == "shell_start": cmd = str(entry.content or "") @@ -1117,6 +1149,69 @@ def _section_header(label: str) -> list[tuple[str, str]]: ] +# Regression tests that reproduced the vulnerability (validated, or pending a fix). +_USABLE_REGRESSION_STATUSES = ("validated", "remediation_unavailable") + + +def _regression_test_fragments(finding: Finding) -> list[tuple[str, str]]: + """Details-pane section describing a finding's security regression test.""" + data = getattr(finding, "regression_test", None) + if not isinstance(data, dict) or not data.get("status"): + return [] + status = data["status"] + if status == "validated": + style, mark = "class:verified", "✓ " + elif status == "remediation_unavailable": + style, mark = "class:sev.medium", "◐ " + else: + style, mark = "class:trace.dim", "✗ " + out = _section_header("Regression test") + out += [("", "\n"), (style, mark + (data.get("status_label") or status))] + if data.get("test_path"): + out.append(("class:finding.path", f" {data['test_path']}")) + out.append(("", "\n")) + if data.get("reason"): + out.append(("class:trace.dim", f"{data['reason']}\n")) + if status in _USABLE_REGRESSION_STATUSES: + if data.get("run_command"): + out.append(("class:trace.dim", f"run: {data['run_command']}\n")) + patch = (data.get("artifacts") or {}).get("patch") + if patch: + out.append(("class:trace.dim", f"patch: {patch}\n")) + if data.get("test_code"): + out.append(("", "\n")) + out.extend(_highlight_code(data["test_code"], data.get("test_path") or "")) + out.append(("", "\n\n")) + return out + + +def _regression_test_prompt_lines(finding: Finding) -> list[str]: + """Regression-test section of the /copy remediation prompt.""" + data = getattr(finding, "regression_test", None) + if not isinstance(data, dict) or data.get("status") not in _USABLE_REGRESSION_STATUSES: + return [] + code, path = data.get("test_code"), data.get("test_path") + if not code or not path: + return [] + if data["status"] == "validated": + intro = ( + "OpenHack generated this security regression test and validated it in its " + "sandbox: it fails on the vulnerable code and passes once the vulnerability is fixed." + ) + else: + intro = ( + "OpenHack generated this security regression test. In its sandbox it fails on the " + "current code because of this vulnerability; it has not been validated against a " + "fix yet, so it must pass after your fix." + ) + lang = "python" if path.endswith(".py") else "" + return [ + "## Regression test", "", intro, + f"Add it unchanged at `{path}` in the same change and do not weaken its assertions.", + "", f"```{lang}", code.rstrip("\n"), "```", "", + ] + + def _findings_list_cursor_row(findings: list[Finding], selected: int) -> int: """Rendered row containing ``selected`` in the variable-height list.""" has_verification_badge = any( @@ -3387,6 +3482,7 @@ def _details_text_raw(): else: out.append(("class:trace.dim", "No fix saved for this finding.\n")) + out.extend(_regression_test_fragments(f)) return out def details_text(): @@ -5103,6 +5199,8 @@ def _format_finding_for_agent(f: Finding) -> str: if fix: lines += ["## Recommended fix", "", fix, ""] + lines += _regression_test_prompt_lines(f) + if f.file_path: lines.append(f"Apply the recommended fix to `{f.file_path}`.") @@ -5776,20 +5874,7 @@ def _findings_from_report(data: dict) -> list[Finding]: loaded: list[Finding] = [] for fd in (data.get("findings") or []): try: - loaded.append(Finding( - category=fd.get("category", "") or "", - severity=(fd.get("severity") or "info"), - title=fd.get("title", "") or "", - description=fd.get("description", "") or "", - file_path=fd.get("file_path") or fd.get("filePath") or "", - line_number=fd.get("line_number") or fd.get("lineNumber"), - code_snippet=fd.get("code_snippet") or fd.get("relevantCode"), - poc=fd.get("poc"), - fix=fd.get("fix") or fd.get("recommendation"), - cvss_score=fd.get("cvss_score") or fd.get("cvssScore"), - confidence=fd.get("confidence", "medium"), - validated=bool(fd.get("validated", False)), - )) + loaded.append(Finding.from_dict(fd)) except Exception: continue return loaded @@ -6135,7 +6220,7 @@ def _cmd_config(self, arg: str) -> None: parts = arg.strip().split(None, 1) key = parts[0].lower() value = parts[1] if len(parts) > 1 else "" - valid = {"provider", "model", "openhack_api_key", "openhack_model_id", "openhack_base_url", "prompt_caching", "fast_mode", "tips_enabled"} + valid = {"provider", "model", "openhack_api_key", "openhack_model_id", "openhack_base_url", "prompt_caching", "fast_mode", "tips_enabled", "regression_tests_enabled", "regression_tests_fixed_ref"} if key not in valid: self.last_status_line = f"unknown config key: {key}" return @@ -6533,6 +6618,8 @@ async def _run_verification(self, kind: str, target_dir: str, evidence = item.get("evidence") if evidence and not f.poc: f.poc = evidence + if kind == "sandbox": + f.exploit_evidence = sanitize_exploit_evidence(item) or f.exploit_evidence verified_count += 1 # Persist the now-annotated findings so the user can find them in /sessions. @@ -7286,6 +7373,7 @@ def _trace_dict(e: TraceEntry) -> dict: "event_log_path": session.event_log_path, "event_count": len(session.events), "event_log_error": session.journal.last_error, + "repository": session.repository_summary(), "pid": os.getpid(), "started_at": datetime.fromtimestamp(session.created_at).isoformat(), "duration_seconds": round(elapsed, 2), diff --git a/tests/conftest.py b/tests/conftest.py index c2a5e12..e3e4702 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -6,6 +6,10 @@ from openhack.tools.filesystem import FileSystemTools from openhack.tools.registry import ToolRegistry +# Fixture applications carry their own test suites; those only ever run inside +# the regression-test sandbox, never as part of OpenHack's own test run. +collect_ignore_glob = ["fixtures/*"] + @pytest.fixture(autouse=True) def _stub_api_key(monkeypatch): diff --git a/tests/fixtures/regression/idor_notes_app/fixed_app.py b/tests/fixtures/regression/idor_notes_app/fixed_app.py new file mode 100644 index 0000000..d8a8aab --- /dev/null +++ b/tests/fixtures/regression/idor_notes_app/fixed_app.py @@ -0,0 +1,101 @@ +""" +Notes API: the remediated counterpart of the IDOR fixture used by OpenHack's +regression-test generation tests. Do not deploy. + +Users register, log in for a bearer token, and keep private notes. The +single-note routes only ever return or change notes the caller owns. +""" + +import secrets + +from flask import Flask, abort, jsonify, request + + +def create_app(): + app = Flask(__name__) + users = {} # username -> {"id": int, "password": str} + tokens = {} # token -> user id + notes = {} # note id -> {"id", "owner_id", "title", "body"} + counters = {"user": 0, "note": 0} + + def current_user_id(): + header = request.headers.get("Authorization", "") + token = header[len("Bearer "):] if header.startswith("Bearer ") else "" + user_id = tokens.get(token) + if user_id is None: + abort(401) + return user_id + + def owned_note(note_id, user_id): + note = notes.get(note_id) + # Same answer whether the note is missing or someone else's, so note + # IDs cannot be probed. + if note is None or note["owner_id"] != user_id: + abort(404) + return note + + @app.post("/api/register") + def register(): + data = request.get_json(force=True) or {} + username, password = data.get("username"), data.get("password") + if not username or not password: + abort(400) + if username in users: + abort(409) + counters["user"] += 1 + users[username] = {"id": counters["user"], "password": password} + return jsonify({"id": counters["user"], "username": username}), 201 + + @app.post("/api/login") + def login(): + data = request.get_json(force=True) or {} + user = users.get(data.get("username")) + if not user or user["password"] != data.get("password"): + abort(401) + token = secrets.token_urlsafe(24) + tokens[token] = user["id"] + return jsonify({"token": token}) + + @app.post("/api/notes") + def create_note(): + owner_id = current_user_id() + data = request.get_json(force=True) or {} + counters["note"] += 1 + note = { + "id": counters["note"], + "owner_id": owner_id, + "title": data.get("title", ""), + "body": data.get("body", ""), + } + notes[note["id"]] = note + return jsonify(note), 201 + + @app.get("/api/notes") + def list_notes(): + owner_id = current_user_id() + return jsonify([n for n in notes.values() if n["owner_id"] == owner_id]) + + @app.get("/api/notes/") + def get_note(note_id): + return jsonify(owned_note(note_id, current_user_id())) + + @app.put("/api/notes/") + def update_note(note_id): + note = owned_note(note_id, current_user_id()) + data = request.get_json(force=True) or {} + note.update({key: data[key] for key in ("title", "body") if key in data}) + return jsonify(note) + + @app.delete("/api/notes/") + def delete_note(note_id): + note = owned_note(note_id, current_user_id()) + notes.pop(note["id"]) + return "", 204 + + return app + + +app = create_app() + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=3000) diff --git a/tests/fixtures/regression/idor_notes_app/vulnerable/Dockerfile b/tests/fixtures/regression/idor_notes_app/vulnerable/Dockerfile new file mode 100644 index 0000000..72ae1a7 --- /dev/null +++ b/tests/fixtures/regression/idor_notes_app/vulnerable/Dockerfile @@ -0,0 +1,7 @@ +FROM python:3.12-slim +WORKDIR /app +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt +COPY . . +EXPOSE 3000 +CMD ["python", "app.py"] diff --git a/tests/fixtures/regression/idor_notes_app/vulnerable/app.py b/tests/fixtures/regression/idor_notes_app/vulnerable/app.py new file mode 100644 index 0000000..be629f5 --- /dev/null +++ b/tests/fixtures/regression/idor_notes_app/vulnerable/app.py @@ -0,0 +1,101 @@ +""" +Notes API: an intentionally vulnerable IDOR fixture for OpenHack's +regression-test generation tests. Do not deploy. + +Users register, log in for a bearer token, and keep private notes. The +single-note routes look a note up by ID without checking who owns it. +""" + +import secrets + +from flask import Flask, abort, jsonify, request + + +def create_app(): + app = Flask(__name__) + users = {} # username -> {"id": int, "password": str} + tokens = {} # token -> user id + notes = {} # note id -> {"id", "owner_id", "title", "body"} + counters = {"user": 0, "note": 0} + + def current_user_id(): + header = request.headers.get("Authorization", "") + token = header[len("Bearer "):] if header.startswith("Bearer ") else "" + user_id = tokens.get(token) + if user_id is None: + abort(401) + return user_id + + @app.post("/api/register") + def register(): + data = request.get_json(force=True) or {} + username, password = data.get("username"), data.get("password") + if not username or not password: + abort(400) + if username in users: + abort(409) + counters["user"] += 1 + users[username] = {"id": counters["user"], "password": password} + return jsonify({"id": counters["user"], "username": username}), 201 + + @app.post("/api/login") + def login(): + data = request.get_json(force=True) or {} + user = users.get(data.get("username")) + if not user or user["password"] != data.get("password"): + abort(401) + token = secrets.token_urlsafe(24) + tokens[token] = user["id"] + return jsonify({"token": token}) + + @app.post("/api/notes") + def create_note(): + owner_id = current_user_id() + data = request.get_json(force=True) or {} + counters["note"] += 1 + note = { + "id": counters["note"], + "owner_id": owner_id, + "title": data.get("title", ""), + "body": data.get("body", ""), + } + notes[note["id"]] = note + return jsonify(note), 201 + + @app.get("/api/notes") + def list_notes(): + owner_id = current_user_id() + return jsonify([n for n in notes.values() if n["owner_id"] == owner_id]) + + @app.get("/api/notes/") + def get_note(note_id): + current_user_id() + note = notes.get(note_id) + if note is None: + abort(404) + return jsonify(note) + + @app.put("/api/notes/") + def update_note(note_id): + current_user_id() + note = notes.get(note_id) + if note is None: + abort(404) + data = request.get_json(force=True) or {} + note.update({key: data[key] for key in ("title", "body") if key in data}) + return jsonify(note) + + @app.delete("/api/notes/") + def delete_note(note_id): + current_user_id() + if notes.pop(note_id, None) is None: + abort(404) + return "", 204 + + return app + + +app = create_app() + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=3000) diff --git a/tests/fixtures/regression/idor_notes_app/vulnerable/pytest.ini b/tests/fixtures/regression/idor_notes_app/vulnerable/pytest.ini new file mode 100644 index 0000000..4584de7 --- /dev/null +++ b/tests/fixtures/regression/idor_notes_app/vulnerable/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +testpaths = tests +pythonpath = . diff --git a/tests/fixtures/regression/idor_notes_app/vulnerable/requirements.txt b/tests/fixtures/regression/idor_notes_app/vulnerable/requirements.txt new file mode 100644 index 0000000..0facad4 --- /dev/null +++ b/tests/fixtures/regression/idor_notes_app/vulnerable/requirements.txt @@ -0,0 +1,2 @@ +flask>=3.0,<4 +pytest>=8.0 diff --git a/tests/fixtures/regression/idor_notes_app/vulnerable/tests/conftest.py b/tests/fixtures/regression/idor_notes_app/vulnerable/tests/conftest.py new file mode 100644 index 0000000..5c58d93 --- /dev/null +++ b/tests/fixtures/regression/idor_notes_app/vulnerable/tests/conftest.py @@ -0,0 +1,20 @@ +import pytest + +from app import create_app + + +@pytest.fixture +def client(): + return create_app().test_client() + + +@pytest.fixture +def auth_headers(client): + """Register and log in a user; returns that user's Authorization headers.""" + + def login(username, password="correct-horse-battery"): + client.post("/api/register", json={"username": username, "password": password}) + response = client.post("/api/login", json={"username": username, "password": password}) + return {"Authorization": f"Bearer {response.get_json()['token']}"} + + return login diff --git a/tests/fixtures/regression/idor_notes_app/vulnerable/tests/test_notes.py b/tests/fixtures/regression/idor_notes_app/vulnerable/tests/test_notes.py new file mode 100644 index 0000000..054a7af --- /dev/null +++ b/tests/fixtures/regression/idor_notes_app/vulnerable/tests/test_notes.py @@ -0,0 +1,12 @@ +def test_create_and_list_own_notes(client, auth_headers): + headers = auth_headers("alice") + created = client.post("/api/notes", json={"title": "groceries", "body": "milk"}, headers=headers) + assert created.status_code == 201 + + listed = client.get("/api/notes", headers=headers) + assert [note["title"] for note in listed.get_json()] == ["groceries"] + + +def test_notes_require_authentication(client): + assert client.get("/api/notes").status_code == 401 + assert client.post("/api/notes", json={"title": "x"}).status_code == 401 diff --git a/tests/regression_support.py b/tests/regression_support.py new file mode 100644 index 0000000..9cf3eed --- /dev/null +++ b/tests/regression_support.py @@ -0,0 +1,429 @@ +"""Shared fixtures for the security regression test generation tests. + +The IDOR fixture app lives in tests/fixtures/regression/idor_notes_app: a +Flask notes API with its own pytest suite (``vulnerable/``) and the remediated +``fixed_app.py``. ``make_fixture_repo`` turns it into a real git repository +whose main branch is vulnerable and whose ``fix/idor-notes`` branch holds the +fix, exactly as a developer's repository would look after remediation. +""" + +from __future__ import annotations + +import re +import shutil +import subprocess +import tempfile +from pathlib import Path +from typing import Callable, Optional, Union +from xml.sax.saxutils import escape, quoteattr + +from openhack.agents.llm import LLMResponse, ToolCall +from openhack.agents.session import Finding +from openhack.regression.evidence import sanitize_exploit_evidence +from openhack.sandbox.container_runner import ContainerRunResult +from openhack.sandbox.orchestrator import SandboxError + +FIXTURE_APP = Path(__file__).parent / "fixtures" / "regression" / "idor_notes_app" +FIX_BRANCH = "fix/idor-notes" + + +def git(repo: Path, *args: str) -> str: + return subprocess.run( + ["git", "-C", str(repo), *args], capture_output=True, text=True, check=True, + ).stdout.strip() + + +def make_fixture_repo(tmp_path: Path) -> dict: + """Create the IDOR fixture as a git repo; returns paths and commit ids.""" + repo = tmp_path / "notes-app" + shutil.copytree(FIXTURE_APP / "vulnerable", repo) + git(repo, "init", "-q", "-b", "main") + git(repo, "config", "user.email", "dev@example.invalid") + git(repo, "config", "user.name", "dev") + git(repo, "add", "-A") + git(repo, "commit", "-q", "-m", "Notes API") + vulnerable_sha = git(repo, "rev-parse", "HEAD") + git(repo, "checkout", "-q", "-b", FIX_BRANCH) + shutil.copy(FIXTURE_APP / "fixed_app.py", repo / "app.py") + git(repo, "commit", "-q", "-am", "Check note ownership") + fixed_sha = git(repo, "rev-parse", "HEAD") + git(repo, "checkout", "-q", "main") + return {"repo": repo, "vulnerable_sha": vulnerable_sha, "fixed_sha": fixed_sha} + + +def sandbox_result(**overrides) -> dict: + """An `exploitable` result as SandboxVerifierAgent reports it.""" + result = { + "finding_index": 0, + "status": "exploitable", + "confidence": "high", + "working_poc": ( + "import requests\n" + "BASE = 'http://localhost:40123'\n" + "s = requests.post(BASE + '/api/login', json={'username': 'mallory', " + "'password': 'hunter2!'})\n" + "tok = s.json()['token']\n" + "r = requests.get(BASE + '/api/notes/1', headers={'Authorization': 'Bearer ' + tok})\n" + "print(r.status_code, r.text)\n" + ), + "evidence": ( + "Logged in as mallory (Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJtYWxsb3J5In0.c2lnbmF0dXJlLXZhbHVl) " + "and fetched note 1 owned by alice: HTTP 200 {\"body\": \"alice's private note\"}" + ), + "attempts_made": 2, + "exploit_request": { + "method": "GET", + "path": "/api/notes/1", + "headers": { + "Authorization": "Bearer xyzzy-live-session-token-0123456789", + "Accept": "application/json", + }, + }, + } + result.update(overrides) + return result + + +def verified_idor_finding(**overrides) -> Finding: + finding = Finding( + category="IDOR", + severity="high", + title="IDOR in app.py", + description="GET/PUT/DELETE /api/notes/ never check that the note belongs to the caller.", + file_path="app.py", + line_number=70, + code_snippet="note = notes.get(note_id)\nreturn jsonify(note)", + fix="Look the note up by id AND owner; return 404 when the caller does not own it.", + validated=True, + source="sandbox_verified", + exploit_evidence=sanitize_exploit_evidence(sandbox_result()), + ) + for key, value in overrides.items(): + setattr(finding, key, value) + return finding + + +# ── Generated test sources the scripted LLM submits ───────────────── + +GOOD_TEST = '''"""Object-level authorization regression test for notes (CWE-639). + +A user must never be able to read, modify or delete another user's note by +supplying its id; the owner keeps full access. +""" + +import pytest + +DENIED = (401, 403, 404) +SECRET_BODY = "owner-only-marker-7f3a" + + +@pytest.fixture +def owner_note(client, auth_headers): + owner = auth_headers("note-owner") + created = client.post("/api/notes", json={"title": "private", "body": SECRET_BODY}, headers=owner) + assert created.status_code == 201, "setup: the owner must be able to create a note" + return owner, created.get_json()["id"] + + +def test_owner_can_read_own_note(client, owner_note): + owner, note_id = owner_note + response = client.get(f"/api/notes/{note_id}", headers=owner) + assert response.status_code == 200, "the owner must keep access to their own note" + assert response.get_json()["body"] == SECRET_BODY + + +def test_other_user_cannot_read_note(client, auth_headers, owner_note): + _, note_id = owner_note + intruder = auth_headers("intruder") + response = client.get(f"/api/notes/{note_id}", headers=intruder) + assert response.status_code in DENIED, f"another user read a note they do not own (HTTP {response.status_code})" + assert SECRET_BODY not in response.get_data(as_text=True), "note contents leaked to another user" + + +def test_other_user_cannot_modify_note(client, auth_headers, owner_note): + owner, note_id = owner_note + intruder = auth_headers("intruder") + response = client.put(f"/api/notes/{note_id}", json={"body": "tampered"}, headers=intruder) + assert response.status_code in DENIED, f"another user modified a note they do not own (HTTP {response.status_code})" + after = client.get(f"/api/notes/{note_id}", headers=owner) + assert after.get_json()["body"] == SECRET_BODY, "a rejected update must leave the note unchanged" + + +def test_other_user_cannot_delete_note(client, auth_headers, owner_note): + owner, note_id = owner_note + intruder = auth_headers("intruder") + response = client.delete(f"/api/notes/{note_id}", headers=intruder) + assert response.status_code in DENIED, f"another user deleted a note they do not own (HTTP {response.status_code})" + assert client.get(f"/api/notes/{note_id}", headers=owner).status_code == 200, "a rejected delete must leave the note in place" +''' + +GOOD_INVARIANT_TESTS = [ + "test_other_user_cannot_read_note", + "test_other_user_cannot_modify_note", + "test_other_user_cannot_delete_note", +] +GOOD_CONTROL_TESTS = ["test_owner_can_read_own_note"] + +# Plausible but useless: it checks authentication, not object ownership, so it +# passes against the vulnerable code and must be rejected. +WEAK_TEST = '''"""Notes require authentication.""" + + +def test_owner_can_list_notes(client, auth_headers): + headers = auth_headers("note-owner") + assert client.get("/api/notes", headers=headers).status_code == 200 + + +def test_anonymous_cannot_read_note(client, auth_headers): + owner = auth_headers("note-owner") + created = client.post("/api/notes", json={"title": "t", "body": "b"}, headers=owner) + response = client.get(f"/api/notes/{created.get_json()['id']}") + assert response.status_code in (401, 403, 404), "anonymous users must not read notes" +''' +WEAK_INVARIANT_TESTS = ["test_anonymous_cannot_read_note"] +WEAK_CONTROL_TESTS = ["test_owner_can_list_notes"] + +TEST_PATH = "tests/test_security_idor_note.py" + + +def submit(code: str = GOOD_TEST, path: str = TEST_PATH, + invariant: Optional[list[str]] = None, control: Optional[list[str]] = None, + call_id: str = "submit-1") -> LLMResponse: + return LLMResponse( + tool_calls=[ToolCall( + id=call_id, + name="submit_regression_test", + arguments={ + "path": path, + "code": code, + "invariant_tests": GOOD_INVARIANT_TESTS if invariant is None else invariant, + "control_tests": GOOD_CONTROL_TESTS if control is None else control, + "summary": "Users cannot read, modify or delete notes they do not own.", + }, + )], + finish_reason="tool_calls", + model_call_id=call_id, + ) + + +def submit_weak(call_id: str = "submit-weak") -> LLMResponse: + return submit(WEAK_TEST, invariant=WEAK_INVARIANT_TESTS, control=WEAK_CONTROL_TESTS, call_id=call_id) + + +def read_file_call(path: str = "tests/conftest.py", call_id: str = "read-1") -> LLMResponse: + return LLMResponse( + tool_calls=[ToolCall(id=call_id, name="read_file", arguments={"path": path})], + finish_reason="tool_calls", + model_call_id=call_id, + ) + + +class ScriptedLLM: + """Returns pre-scripted responses and records every request it receives.""" + + model = "scripted-model" + provider = "scripted" + + def __init__(self, responses: list[Union[LLMResponse, Exception]]): + self.responses = list(responses) + self.calls = 0 + self.requests: list[list] = [] + self.event_callback = None + self.total_cost = 0.0 + self.total_tokens = 0 + self.total_input_tokens = 0 + self.total_output_tokens = 0 + self.prompt_cache_key = None + + async def chat(self, messages=None, tools=None, system=None, **kwargs): + self.requests.append(list(messages or [])) + if self.calls >= len(self.responses): + raise AssertionError("ScriptedLLM ran out of scripted responses") + response = self.responses[self.calls] + self.calls += 1 + if isinstance(response, Exception): + raise response + self.total_cost += 0.01 + self.total_tokens += 100 + return response + + def last_user_text(self) -> str: + for message in reversed(self.requests[-1] if self.requests else []): + if message.role == "user": + return message.content or "" + return "" + + +# ── Scan stages ───────────────────────────────────────────────────── + +class StubStage: + """An LLM-backed scan stage replaced by a canned result.""" + + result: dict = {} + + def __init__(self, *args, **kwargs): + self.total_cost = 0.0 + self.total_tokens = 0 + self.total_input_tokens = 0 + self.total_output_tokens = 0 + + async def run(self, task, context=None): + return self.result + + +HUNTER_FINDING = { + "category": "IDOR", + "severity": "high", + "file_path": "app.py", + "line_number": 70, + "description": "GET /api/notes/ returns any note without checking ownership.", + "code_snippet": "note = notes.get(note_id)", +} + + +def install_scan_stubs(monkeypatch, regression_llm) -> dict: + """Stub the LLM-backed stages (recon, hunters, validators, sandbox verifier) + with canned results for the notes-app IDOR, and route the regression-test + agent to ``regression_llm``. Everything else in the scan stays real. + Returns the LLMs handed out, keyed by agent type.""" + import openhack.agents.coordinator as coordinator_mod + + class Recon(StubStage): + result = {"summary": ""} + + class Hunters(StubStage): + result = {"findings": [dict(HUNTER_FINDING)], "files_analyzed": ["app.py"]} + + class Validators(StubStage): + result = {"validated_findings": [{ + "original_index": 0, "status": "confirmed", "confidence": "high", + "poc": "GET /api/notes/1 as another user", "fix": "Check note ownership.", "cvss_score": 8.1, + }], "false_positives": []} + + class Sandbox(StubStage): + result = {"exploitable": [sandbox_result()], "not_exploitable": []} + + def no_attack_surface(*args, **kwargs): + raise RuntimeError("attack surface discovery is not needed here") + + monkeypatch.setattr(coordinator_mod, "ReconAgent", Recon) + monkeypatch.setattr(coordinator_mod, "HunterSwarmAgent", Hunters) + monkeypatch.setattr(coordinator_mod, "ValidatorSwarmAgent", Validators) + monkeypatch.setattr(coordinator_mod, "SandboxVerifierSwarmAgent", Sandbox) + monkeypatch.setattr(coordinator_mod, "discover_attack_surface", no_attack_surface) + + llms: dict = {} + + def create_llm(self, agent_type): + llms[agent_type] = regression_llm if agent_type == "regression_test" else ScriptedLLM([]) + return llms[agent_type] + + monkeypatch.setattr(coordinator_mod.CoordinatorAgent, "_create_llm_for_agent", create_llm) + return llms + + +# ── Fake container runner (writes real JUnit XML) ─────────────────── + +def names_in(code: str) -> list[str]: + """Test function names defined in generated code.""" + return re.findall(r"^def (test_\w+)\(", code, flags=re.MULTILINE) + + +def junit_xml(cases: dict[str, str], classname: str = "tests.test_security_idor_note") -> str: + """JUnit XML in pytest's format. Outcomes: passed, failed (assertion), + crashed (non-assertion failure), error, skipped.""" + rows = [] + for name, outcome in cases.items(): + attrs = f"classname={quoteattr(classname)} name={quoteattr(name)} time=\"0.01\"" + if outcome == "passed": + rows.append(f"") + elif outcome == "failed": + msg = "AssertionError: another user read a note they do not own (HTTP 200)" + body = f"def {name}(...):\n> assert response.status_code in DENIED\nE {msg}" + rows.append(f"{escape(body)}") + elif outcome == "crashed": + msg = "KeyError: 'id'" + rows.append(f"E {escape(msg)}") + elif outcome == "error": + msg = 'failed on setup with "fixture \'database\' not found"' + rows.append(f"{escape(msg)}") + elif outcome == "skipped": + rows.append(f"") + failures = sum(o in ("failed", "crashed") for o in cases.values()) + return ( + '' + + "".join(rows) + "" + ) + + +COLLECTION_ERROR_XML = ( + '' + 'ImportError while importing test module: ' + "ModuleNotFoundError: No module named 'notes'" +) + +Behavior = Callable[[str, str, int], Union[dict, str]] + + +def realistic_idor(label: str, code: str, run_index: int) -> dict: + """What the GOOD/WEAK tests really do against the fixture app.""" + outcomes = {} + for name in names_in(code): + if "other_user_cannot" in name: + outcomes[name] = "failed" if label == "vulnerable" else "passed" + else: + outcomes[name] = "passed" + return outcomes + + +class FakeRunner: + """Stands in for ContainerTestRunner. ``behavior(label, code, run_index)`` + returns {test: outcome}, or "timeout" / "collection_error" / "no_results".""" + + def __init__(self, behavior: Behavior = realistic_idor, available: bool = True, + build_error: Optional[str] = None): + self.behavior = behavior + self.available = available + self.build_error = build_error + self.builds: list[tuple[str, str]] = [] + self.runs: list[dict] = [] + self.images_removed = False + + async def ensure_available(self) -> None: + if not self.available: + raise SandboxError("Docker is required to validate regression tests but is not available: daemon down") + + async def build_image(self, context_dir: Path, dockerfile: str, tag: str) -> None: + self.builds.append((tag, dockerfile)) + if self.build_error: + raise SandboxError(f"sandbox image build failed: {self.build_error}") + + async def run_test(self, image, files, command, workdir="/workspace", results_path="/openhack-results"): + label = "vulnerable" if "-vulnerable-" in image else "remediated" + code = next(iter(files.values())) + run_index = sum(1 for r in self.runs if r["label"] == label and r["code"] == code) + self.runs.append({"label": label, "image": image, "files": dict(files), + "command": list(command), "workdir": workdir, "code": code}) + results = Path(tempfile.mkdtemp(prefix="fake-results-")) + outcome = self.behavior(label, code, run_index) + if outcome == "timeout": + return ContainerRunResult(None, True, results) + if outcome == "no_results": + (results / "output.txt").write_text("ERROR: usage: pytest [options]\n") + return ContainerRunResult(4, False, results) + if outcome == "collection_error": + (results / "junit.xml").write_text(COLLECTION_ERROR_XML) + (results / "output.txt").write_text("ModuleNotFoundError: No module named 'notes'\n") + return ContainerRunResult(2, False, results) + (results / "junit.xml").write_text(junit_xml(outcome)) + (results / "output.txt").write_text("collected tests\n") + failed = any(o != "passed" for o in outcome.values()) + return ContainerRunResult(1 if failed else 0, False, results) + + async def remove_images(self) -> None: + self.images_removed = True + + def runs_for(self, label: str) -> list[dict]: + return [r for r in self.runs if r["label"] == label] diff --git a/tests/test_cli_dispatch.py b/tests/test_cli_dispatch.py index 7babbfe..f62f329 100644 --- a/tests/test_cli_dispatch.py +++ b/tests/test_cli_dispatch.py @@ -39,7 +39,7 @@ def test_no_args_launches_tui_on_cwd(routed): @pytest.mark.parametrize("flag,name", [ ("--scan", "scan"), ("--hack", "hack"), ("--plan", "plan"), ("--agent", "agent"), ("--sessions", "sessions"), ("--resume", "resume"), - ("--classify", "classify"), + ("--regression-tests", "regression-tests"), ("--classify", "classify"), ("--login", "login"), ("--setup", "setup"), ]) def test_flag_forms_route_to_command(routed, flag, name): diff --git a/tests/test_regression_e2e_docker.py b/tests/test_regression_e2e_docker.py new file mode 100644 index 0000000..4dadd82 --- /dev/null +++ b/tests/test_regression_e2e_docker.py @@ -0,0 +1,288 @@ +"""End to end: a verified IDOR becomes a sandbox-validated regression test. + +This drives the real workflow — a saved scan report, `openhack +--regression-tests`, revision workspaces, Docker image builds, locked-down +test containers, validation, and the report/patch it writes — against the +intentionally vulnerable notes app and its fix. Only the LLM is scripted: it +first submits a plausible test that checks authentication rather than +ownership (which must be rejected), then a proper invariant test. + +It then shows the accepted test is independent of OpenHack: after `git +apply`, the repository's own `python -m pytest` passes on the fixed code and +fails on the vulnerable code. + +Requires a Docker daemon plus network access for image builds, so it only runs +with OPENHACK_DOCKER_TESTS=1. OPENHACK_TEST_BASE_IMAGE overrides the base +image (for example one that trusts a corporate TLS root). +""" + +import asyncio +import contextlib +import io +import json +import os +import shutil +import subprocess +import time +from pathlib import Path +from uuid import uuid4 + +import pytest + +from openhack.agents.session import Session +from openhack.config import settings +from openhack.regression import headless +from openhack.regression.models import RegressionTestStatus as Status +from openhack.regression.pipeline import PipelineOptions, RegressionTestPipeline +from openhack.regression.workspace import RevisionSpec +from openhack.sandbox.container_runner import ContainerLimits, ContainerTestRunner +from tests.regression_support import ( + FIX_BRANCH, + GOOD_INVARIANT_TESTS, + TEST_PATH, + ScriptedLLM, + git, + install_scan_stubs, + make_fixture_repo, + read_file_call, + submit, + submit_weak, + verified_idor_finding, +) + + +def _docker_ready() -> bool: + if os.environ.get("OPENHACK_DOCKER_TESTS") != "1" or not shutil.which("docker"): + return False + return subprocess.run(["docker", "version"], capture_output=True).returncode == 0 + + +pytestmark = pytest.mark.skipif( + not _docker_ready(), reason="set OPENHACK_DOCKER_TESTS=1 and run a Docker daemon", +) +BASE_IMAGE = os.environ.get("OPENHACK_TEST_BASE_IMAGE", "python:3.12-slim") + + +def _docker(*args: str, timeout: int = 600) -> subprocess.CompletedProcess: + return subprocess.run(["docker", *args], capture_output=True, text=True, timeout=timeout) + + +def _run_repo_suite(checkout: Path) -> subprocess.CompletedProcess: + """Run the repository's own test command in a plain container — no OpenHack code involved.""" + (checkout / "Dockerfile.ci").write_text( + f"FROM {BASE_IMAGE}\nWORKDIR /app\nCOPY requirements.txt .\n" + "RUN pip install --no-cache-dir -r requirements.txt\nCOPY . .\n" + ) + tag = f"openhack-e2e-ci:{uuid4().hex[:10]}" + build = _docker("build", "-q", "-t", tag, "-f", str(checkout / "Dockerfile.ci"), str(checkout)) + assert build.returncode == 0, build.stderr + try: + return _docker("run", "--rm", "--network", "none", tag, + "python", "-m", "pytest", "-q", "-p", "no:cacheprovider", timeout=300) + finally: + _docker("rmi", "-f", tag) + + +def _checkout(repo: Path, ref: str, dest: Path) -> Path: + subprocess.run(["git", "clone", "-q", str(repo), str(dest)], check=True) + git(dest, "checkout", "-q", ref) + return dest + + +def test_verified_idor_becomes_a_validated_regression_test(tmp_path, monkeypatch): + fx = make_fixture_repo(tmp_path) + finding = verified_idor_finding() + scan_id = "e2e00000-0000-4000-8000-000000000001" + scans = tmp_path / "scans" + scans.mkdir() + report_path = scans / f"{scan_id}.json" + report_path.write_text(json.dumps({ + "scan_id": scan_id, + "target_dir": str(fx["repo"]), + "status": "completed", + "repository": {"head": fx["vulnerable_sha"], "branch": "main", "dirty": False}, + "findings": [finding.to_dict()], + })) + + llm = ScriptedLLM([read_file_call(), submit_weak(), submit(call_id="submit-good")]) + monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path) + monkeypatch.setattr(headless, "SCANS_DIR", scans) + monkeypatch.setattr(headless, "reload_settings", lambda: None) + monkeypatch.setattr("openhack.agents.llm.LLMClient", lambda *a, **k: llm) + monkeypatch.setattr(settings, "regression_tests_base_image", BASE_IMAGE) + monkeypatch.setattr(settings, "regression_tests_fixed_ref", None) + monkeypatch.setattr(settings, "regression_tests_validation_runs", 2) + + out = io.StringIO() + started = time.monotonic() + with contextlib.redirect_stdout(out): + code = asyncio.run(headless.run_regression_tests_for_report(scan_id, FIX_BRANCH)) + print(out.getvalue()) + print(f"regression workflow took {time.monotonic() - started:.1f}s") + + assert code == 0, out.getvalue() + status = json.loads(report_path.read_text())["findings"][0]["regressionTest"] + assert status["status"] == "validated", status["reason"] + assert status["attempts"] == 2 # the weak test was rejected first + vulnerable, remediated = status["validation"]["vulnerable"], status["validation"]["remediated"] + assert vulnerable["resolved"] == fx["vulnerable_sha"] + assert remediated["resolved"] == fx["fixed_sha"] + assert {name for name, o in vulnerable["outcomes"].items() if o == "failed"} == set(GOOD_INVARIANT_TESTS) + assert vulnerable["outcomes"]["test_owner_can_read_own_note"] == "passed" + assert set(remediated["outcomes"].values()) == {"passed"} + assert "every invariant test PASSED on the VULNERABLE code" in next( + m.content for m in reversed(llm.requests[2]) if m.role == "user" + ) + patch = Path(status["artifacts"]["patch"]) + assert patch.is_file() and Path(status["artifacts"]["test_file"]).read_text() == status["test_code"] + # Nothing was left behind in Docker. + leftovers = _docker("ps", "-a", "--filter", "label=openhack.regression=1", "-q").stdout.strip() + assert leftovers == "" + + # Independence: with the patch applied, the repository's normal test + # runner — not OpenHack — passes on the fix and fails on the vulnerable code. + fixed = _checkout(fx["repo"], FIX_BRANCH, tmp_path / "ci-fixed") + vuln = _checkout(fx["repo"], fx["vulnerable_sha"], tmp_path / "ci-vulnerable") + for checkout in (fixed, vuln): + subprocess.run(["git", "-C", str(checkout), "apply", str(patch)], check=True) + + fixed_run = _run_repo_suite(fixed) + print(fixed_run.stdout) + assert fixed_run.returncode == 0, fixed_run.stdout + assert "6 passed" in fixed_run.stdout + + vuln_run = _run_repo_suite(vuln) + print(vuln_run.stdout) + assert vuln_run.returncode == 1 + assert "3 failed, 3 passed" in vuln_run.stdout + for name in GOOD_INVARIANT_TESTS: + assert f"{TEST_PATH}::{name}" in vuln_run.stdout + + +def test_headless_scan_with_regression_tests_enabled(tmp_path, monkeypatch): + """`openhack --scan` with regression tests enabled: Step 6 validates in Docker.""" + import openhack.headless_scan as headless_scan + + fx = make_fixture_repo(tmp_path) + llm = ScriptedLLM([submit()]) + install_scan_stubs(monkeypatch, llm) + monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path) + monkeypatch.setattr(headless_scan, "SCANS_DIR", tmp_path / "scans") + # run_headless_scan reloads settings, so configure it the way a user would. + for key, value in { + "REGRESSION_TESTS_ENABLED": "true", "REGRESSION_TESTS_FIXED_REF": FIX_BRANCH, + "REGRESSION_TESTS_BASE_IMAGE": BASE_IMAGE, "SANDBOX_ENABLED": "true", + "FEATURE_HUNT_ENABLED": "false", "CHECKPOINT_ENABLED": "false", + }.items(): + monkeypatch.setenv(key, value) + snapshot = {name: getattr(settings, name) for name in type(settings).model_fields} + out = io.StringIO() + try: + with contextlib.redirect_stdout(out): + asyncio.run(headless_scan.run_headless_scan(str(fx["repo"]))) + finally: + for name, value in snapshot.items(): + setattr(settings, name, value) + print(out.getvalue()) + + report = json.loads(next((tmp_path / "scans").glob("*.json")).read_text()) + assert report["status"] == "completed" + assert report["repository"]["head"] == fx["vulnerable_sha"] + finding = report["findings"][0] + assert finding["verificationSource"] == "sandbox_verified" + assert finding["exploitEvidence"]["exploit_request"]["headers"]["Authorization"] == "[REDACTED]" + status = finding["regressionTest"] + assert status["status"] == "validated", status["reason"] + assert status["validation"]["remediated"]["resolved"] == fx["fixed_sha"] + assert "regression_tests" in report["cost"]["steps"] + assert "Regression test: generated and validated" in out.getvalue() + assert "REGRESSION TEST: generated and validated" in out.getvalue() + + +def test_incomplete_fix_is_reported_not_weakened(tmp_path): + fx = make_fixture_repo(tmp_path) + repo = fx["repo"] + # A "fix" that only protects reads: updates and deletes stay vulnerable. + git(repo, "checkout", "-q", "-b", "fix/reads-only", fx["vulnerable_sha"]) + app = (repo / "app.py").read_text() + partial = app.replace( + " def get_note(note_id):\n current_user_id()\n note = notes.get(note_id)\n" + " if note is None:\n", + " def get_note(note_id):\n user_id = current_user_id()\n note = notes.get(note_id)\n" + " if note is None or note[\"owner_id\"] != user_id:\n", + ) + assert partial != app + (repo / "app.py").write_text(partial) + git(repo, "commit", "-q", "-am", "Check ownership on reads") + git(repo, "checkout", "-q", "main") + + llm = ScriptedLLM([submit(), submit(call_id="must-not-be-requested")]) + pipeline = RegressionTestPipeline( + llm, Session(str(repo), persist_events=False), repo, + PipelineOptions(remediation=RevisionSpec.git("fix/reads-only"), base_image=BASE_IMAGE, + artifacts_root=tmp_path / "artifacts"), + ) + result = asyncio.run(pipeline.run([verified_idor_finding()]))[0] + + assert result.status is Status.VALIDATION_FAILED + assert "remediation is incomplete" in result.reason + assert "test_other_user_cannot_modify_note" in result.reason + assert "test_other_user_cannot_delete_note" in result.reason + assert result.validation["remediated"]["outcomes"]["test_other_user_cannot_read_note"] == "passed" + assert llm.calls == 1 # never asked to "fix" the test by dropping coverage + assert result.artifacts == {} + + +def _probe_image(tmp_path: Path, runner: ContainerTestRunner) -> str: + context = tmp_path / "probe" + context.mkdir() + tag = f"openhack-regression:probe-{uuid4().hex[:8]}" + asyncio.run(runner.build_image( + context, + f"FROM {BASE_IMAGE}\nRUN mkdir -p /openhack-results /workspace && " + "chown -R 65534:65534 /openhack-results /workspace\n", + tag, + )) + return tag + + +def test_test_containers_are_locked_down(tmp_path): + runner = ContainerTestRunner(ContainerLimits(run_timeout=60)) + image = _probe_image(tmp_path, runner) + try: + script = ( + "id -u > /openhack-results/uid; " + "cat /workspace/tests/staged.txt > /openhack-results/staged; " + "grep CapEff /proc/self/status > /openhack-results/caps; " + "python -c \"import socket; socket.create_connection(('1.1.1.1', 53), 3)\" " + "> /openhack-results/net 2>&1; echo $? > /openhack-results/net_rc; " + "touch /openhack-results/done" + ) + run = asyncio.run(runner.run_test(image, {"tests/staged.txt": "staged-by-openhack"}, ["sh", "-c", script])) + try: + results = run.results_dir + assert run.exit_code == 0 and not run.timed_out + assert (results / "uid").read_text().strip() == "65534" + assert (results / "staged").read_text() == "staged-by-openhack" + assert (results / "caps").read_text().split()[-1] == "0000000000000000" + assert (results / "net_rc").read_text().strip() != "0" + assert "unreachable" in (results / "net").read_text().lower() + finally: + run.cleanup() + assert _docker("ps", "-a", "--filter", f"name={run.container}", "-q").stdout.strip() == "" + finally: + asyncio.run(runner.remove_images()) + + +def test_hanging_tests_are_killed_at_the_timeout(tmp_path): + runner = ContainerTestRunner(ContainerLimits(run_timeout=5)) + image = _probe_image(tmp_path, runner) + try: + started = time.monotonic() + run = asyncio.run(runner.run_test(image, {}, ["sleep", "300"])) + run.cleanup() + assert run.timed_out and run.exit_code is None + assert time.monotonic() - started < 60 + assert _docker("ps", "-a", "--filter", f"name={run.container}", "-q").stdout.strip() == "" + finally: + asyncio.run(runner.remove_images()) diff --git a/tests/test_regression_evidence.py b/tests/test_regression_evidence.py new file mode 100644 index 0000000..12ef0d8 --- /dev/null +++ b/tests/test_regression_evidence.py @@ -0,0 +1,76 @@ +"""Exploit evidence is redacted before it is persisted or shown to an LLM.""" + +import json + +import pytest + +from openhack.regression.evidence import find_secrets, sanitize_exploit_evidence, scrub_text +from tests.regression_support import sandbox_result + + +def test_sanitized_evidence_keeps_the_exploit_shape_but_no_credentials(): + record = sanitize_exploit_evidence(sandbox_result( + exploit_request={ + "method": "put", + "path": "http://localhost:40123/api/notes/1", + "headers": {"Authorization": "Bearer live-token-123", "Cookie": "session=abc", + "X-CSRF-Token": "t0k", "Accept": "application/json"}, + "json_body": {"body": "tampered", "password": "hunter2!"}, + }, + )) + serialized = json.dumps(record) + + assert record["source"] == "sandbox" + assert record["exploit_request"]["method"] == "PUT" + assert record["exploit_request"]["path"] == "http://localhost:40123/api/notes/1" + assert record["exploit_request"]["headers"]["Accept"] == "application/json" + for header in ("Authorization", "Cookie", "X-CSRF-Token"): + assert record["exploit_request"]["headers"][header] == "[REDACTED]" + assert "tampered" in record["exploit_request"]["body"] + for secret in ("live-token-123", "session=abc", "hunter2!", "eyJhbGciOiJIUzI1NiJ9"): + assert secret not in serialized + + +def test_poc_and_evidence_text_are_scrubbed_and_bounded(): + record = sanitize_exploit_evidence(sandbox_result( + working_poc="requests.get(u, headers={'Authorization': 'Bearer sk-livekeylivekeylivekey123'})\n" * 200, + )) + assert "sk-livekey" not in record["working_poc"] + assert len(record["working_poc"]) <= 4000 + assert "eyJhbGci" not in record["evidence"] + + +def test_empty_results_carry_no_evidence(): + assert sanitize_exploit_evidence(None) is None + assert sanitize_exploit_evidence({}) is None + assert sanitize_exploit_evidence({"evidence": " ", "exploit_request": {}}) is None + + +@pytest.mark.parametrize("text,leak", [ + ("Cookie: session=deadbeef; csrftoken=abc", "deadbeef"), + ('{"password": "s3cr3t-pass"}', "s3cr3t-pass"), + ("token = 'abcd1234efgh'", "abcd1234efgh"), + ("Authorization: Bearer abc.def.ghi", "abc.def.ghi"), +]) +def test_scrub_text(text, leak): + assert leak not in scrub_text(text) + + +@pytest.mark.parametrize("code,expected", [ + ("TOKEN = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.c2lnbmF0dXJl'", "JSON Web Token"), + ("key = 'AKIAIOSFODNN7EXAMPLE'", "AWS access key"), + ("api = 'sk-abcdefghijklmnopqrstuvwxyz'", "API secret key"), + ("headers = {'Authorization': 'Bearer 3f9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c'}", "literal bearer token"), + ("headers = {'Authorization': 'Bearer [REDACTED]'}", "redacted evidence placeholder"), + ("-----BEGIN RSA PRIVATE KEY-----", "private key"), +]) +def test_find_secrets_flags_credentials(code, expected): + assert expected in find_secrets(code) + + +def test_find_secrets_allows_ordinary_test_credentials(): + code = ( + 'headers = {"Authorization": f"Bearer {token}"}\n' + 'client.post("/api/login", json={"username": "alice", "password": "correct-horse-battery"})\n' + ) + assert find_secrets(code) == [] diff --git a/tests/test_regression_frameworks.py b/tests/test_regression_frameworks.py new file mode 100644 index 0000000..b884beb --- /dev/null +++ b/tests/test_regression_frameworks.py @@ -0,0 +1,270 @@ +"""Test-framework detection, policy checks and result parsing (pytest adapter).""" + +import json +import shutil + +import pytest + +from openhack.regression.frameworks import ( + PytestAdapter, + UnsupportedFrameworkError, + detect_framework, +) +from openhack.regression.invariants import IdorSpec +from tests.conftest import write_file +from tests.regression_support import ( + COLLECTION_ERROR_XML, + FIXTURE_APP, + GOOD_TEST, + junit_xml, + verified_idor_finding, +) + +adapter = PytestAdapter() + + +@pytest.fixture +def notes_repo(tmp_path): + repo = tmp_path / "repo" + shutil.copytree(FIXTURE_APP / "vulnerable", repo) + return repo + + +def test_detects_the_repositorys_own_pytest_conventions(notes_repo): + found, profile = detect_framework(notes_repo, "app.py") + + assert found.name == "pytest" + assert profile.project_root == "." + assert profile.test_dir == "tests" + assert profile.config_file == "pytest.ini" + assert profile.file_patterns == ["test_*.py", "*_test.py"] + assert profile.fixtures == {"client": "tests/conftest.py", "auth_headers": "tests/conftest.py"} + assert profile.example_tests == ["tests/test_notes.py"] + assert profile.dependency_files == ["requirements.txt"] + assert profile.app_frameworks == ["flask"] + assert profile.framework_in_dependencies is True + assert profile.runtime_version == "3.12" + + +def test_pyproject_configuration_and_custom_patterns(tmp_path): + write_file(tmp_path, "pyproject.toml", """ +[project] +name = "svc" +requires-python = ">=3.10,<3.12" +dependencies = ["fastapi"] +[project.optional-dependencies] +test = ["pytest", "httpx"] +[tool.pytest.ini_options] +testpaths = ["checks"] +python_files = ["check_*.py"] +""") + write_file(tmp_path, "checks/check_api.py", "def test_x():\n assert True\n") + write_file(tmp_path, ".python-version", "3.11.9\n") + _, profile = detect_framework(tmp_path) + + assert profile.config_file == "pyproject.toml" + assert profile.test_dir == "checks" + assert profile.file_patterns == ["check_*.py"] + assert profile.installable_project is True + assert profile.install_extras == ["test"] + assert profile.app_frameworks == ["fastapi"] + assert profile.runtime_version == "3.11" + + +def test_monorepo_picks_the_project_containing_the_finding(tmp_path): + write_file(tmp_path, "docs/requirements.txt", "mkdocs\n") + write_file(tmp_path, "services/api/requirements.txt", "flask\npytest\n") + write_file(tmp_path, "services/api/tests/conftest.py", "import pytest\n") + write_file(tmp_path, "services/api/tests/test_api.py", "def test_ok():\n assert True\n") + _, profile = detect_framework(tmp_path, "services/api/app.py") + assert profile.project_root == "services/api" + assert profile.test_dir == "tests" + + +def test_javascript_suites_are_reported_as_unsupported(tmp_path): + package = {"devDependencies": {"jest": "^29"}, "scripts": {"test": "jest"}} + write_file(tmp_path, "package.json", json.dumps(package)) + with pytest.raises(UnsupportedFrameworkError, match="`jest`.*not supported yet.*pytest"): + detect_framework(tmp_path) + + +def test_django_runner_without_pytest_is_unsupported(tmp_path): + write_file(tmp_path, "manage.py", "import django\n") + write_file(tmp_path, "requirements.txt", "django\n") + with pytest.raises(UnsupportedFrameworkError, match="Django's built-in test runner"): + detect_framework(tmp_path) + + +def test_repository_without_tests_is_unsupported(tmp_path): + write_file(tmp_path, "app.py", "print('hi')\n") + with pytest.raises(UnsupportedFrameworkError, match="no existing test suite was detected"): + detect_framework(tmp_path) + + +def test_node_modules_are_not_traversed(tmp_path): + write_file(tmp_path, "node_modules/pkg/conftest.py", "import pytest\n") + write_file(tmp_path, "node_modules/pkg/tests/test_x.py", "def test_x(): pass\n") + with pytest.raises(UnsupportedFrameworkError): + detect_framework(tmp_path) + + +# ── test paths ── + +@pytest.fixture +def profile(notes_repo): + return detect_framework(notes_repo)[1] + + +@pytest.mark.parametrize("path,problem", [ + ("tests/test_security_idor_note.py", None), + ("tests/security/test_idor.py", None), + ("", "no test file path"), + ("../tests/test_x.py", "without '..'"), + ("/tmp/test_x.py", "without '..'"), + ("tests\\test_x.py", "forward slashes"), + ("tests/test x.py", "may only contain"), + ("tests/conftest.py", "not conftest.py"), + ("tests/idor_checks.py", "would not be discovered"), + ("tests/test_x.txt", "must be a .py file"), + ("src/test_x.py", "existing test directory `tests/`"), +]) +def test_validate_test_path(profile, path, problem): + error = adapter.validate_test_path(profile, path) + if problem is None: + assert error is None + else: + assert problem in error + + +def test_suggested_path_never_collides(profile): + invariant = IdorSpec().extract_invariant(verified_idor_finding()) + taken = {"tests/test_security_idor_note.py", "tests/test_security_idor_note_2.py"} + assert adapter.suggest_test_path(profile, invariant, taken.__contains__) == "tests/test_security_idor_note_3.py" + + +# ── static policy ── + +def test_well_formed_regression_test_passes_policy(): + assert adapter.static_check(GOOD_TEST) == [] + + +@pytest.mark.parametrize("snippet,expected", [ + ("import requests\n", "makes real network requests"), + ("from urllib.request import urlopen\n", "makes real network requests"), + ("import subprocess\n", "spawns processes"), + ("import socket\n", "raw network sockets"), + ("import os\nos.system('id')\n", "runs shell commands"), + ("import time\ntime.sleep(1)\n", "sleeps"), + ("from time import sleep\n", "sleeps"), + ("import pytest\npytest.skip('later')\n", "skips the test"), + ("import pytest\n@pytest.mark.skip\ndef test_y():\n assert False\n", "could pass without running"), + ("import pytest\n@pytest.mark.xfail(strict=False)\ndef test_y():\n assert False\n", "could pass without running"), + ("from pytest import mark\n@mark.skipif(True, reason='x')\ndef test_y():\n assert False\n", "could pass without running"), + ("import unittest\n@unittest.skipIf(True, 'x')\ndef test_y():\n assert False\n", "could pass without running"), + ("def test_y():\n try:\n assert False\n except AssertionError:\n pass\n", "swallow the invariant check"), + ("def test_y():\n try:\n assert False\n except:\n pass\n", "swallow the invariant check"), + ("def pytest_runtest_makereport(item, call):\n pass\n", "defines pytest hook"), + ("import sys\nsys.exit(0)\n", "terminates the test process"), + ("eval('1')\n", "evaluates dynamic code"), + ("import atexit\n", "tamper with test results"), + ("TOKEN = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.c2lnbmF0dXJl'\n", "embeds a JSON Web Token"), +]) +def test_policy_violations(snippet, expected): + code = GOOD_TEST + "\n" + snippet + assert any(expected in v for v in adapter.static_check(code)), adapter.static_check(code) + + +def test_policy_requires_tests_and_assertions(): + assert "defines no test functions" in " ".join(adapter.static_check("x = 1\n")) + assert "contains no assert statements" in " ".join(adapter.static_check("def test_a():\n pass\n")) + assert adapter.static_check("def test_a(:\n")[0].startswith("syntax error on line 1") + + +# ── results ── + +def test_parse_results_distinguishes_assertions_crashes_errors_and_skips(tmp_path): + (tmp_path / "junit.xml").write_text(junit_xml({ + "test_owner_can_read_own_note": "passed", + "test_other_user_cannot_read_note": "failed", + "test_other_user_cannot_modify_note": "crashed", + "test_other_user_cannot_delete_note": "error", + "test_param[read]": "skipped", + })) + (tmp_path / "output.txt").write_text("Authorization: Bearer abc.def.ghi\n4 tests ran\n") + report = adapter.parse_results(tmp_path, 1, False) + + outcomes = {c.name: (c.outcome, c.assertion) for c in report.cases} + assert outcomes == { + "test_owner_can_read_own_note": ("passed", False), + "test_other_user_cannot_read_note": ("failed", True), + "test_other_user_cannot_modify_note": ("failed", False), + "test_other_user_cannot_delete_note": ("error", False), + "test_param[read]": ("skipped", False), + } + assert [c.base_name for c in report.cases][-1] == "test_param" + assert report.collection_error is None + assert "abc.def.ghi" not in report.output_tail + + +def test_parse_results_reports_collection_errors(tmp_path): + (tmp_path / "junit.xml").write_text(COLLECTION_ERROR_XML) + report = adapter.parse_results(tmp_path, 2, False) + assert "No module named 'notes'" in report.collection_error + assert report.cases == [] + + +def test_parse_results_without_results_file(tmp_path): + (tmp_path / "output.txt").write_text("ERROR: file or directory not found\n") + report = adapter.parse_results(tmp_path, 4, False) + assert "produced no results (exit code 4)" in report.collection_error + assert "file or directory not found" in report.collection_error + + +def test_parse_results_rejects_entity_declarations(tmp_path): + (tmp_path / "junit.xml").write_text( + ']>' + '' + ) + assert "DTD/entity" in adapter.parse_results(tmp_path, 0, False).collection_error + + +def test_parse_results_on_timeout(tmp_path): + report = adapter.parse_results(tmp_path, None, True) + assert report.timed_out and report.cases == [] + + +# ── sandbox image + command ── + +def test_dockerfile_installs_the_projects_own_test_dependencies(profile): + dockerfile = adapter.dockerfile(profile, "python:3.12-slim") + assert dockerfile.splitlines()[1] == "FROM python:3.12-slim" + assert 'COPY ["requirements.txt", "/workspace/requirements.txt"]' in dockerfile + assert 'RUN pip install --no-cache-dir -r "requirements.txt"' in dockerfile + assert 'COPY [".", "/workspace"]' in dockerfile + assert "chown -R 65534:65534 /workspace /openhack-results" in dockerfile + assert adapter.default_base_image(profile) == "python:3.12-slim" + + +def test_dockerfile_for_subproject_with_includes(tmp_path): + write_file(tmp_path, "api/requirements.txt", "flask\n") + write_file(tmp_path, "api/requirements-dev.txt", "-r requirements.txt\n-c constraints/pins.txt\npytest\n") + write_file(tmp_path, "api/constraints/pins.txt", "flask==3.0.3\n") + write_file(tmp_path, "api/setup.py", "from setuptools import setup\nsetup(name='api')\n") + write_file(tmp_path, "api/tests/test_a.py", "def test_a():\n assert True\n") + _, profile = detect_framework(tmp_path, "api/app.py") + assert profile.project_root == "api" + assert profile.dependency_files == ["requirements.txt", "requirements-dev.txt", "constraints/pins.txt"] + dockerfile = adapter.dockerfile(profile, "python:3.11-slim") + assert "WORKDIR /workspace/api" in dockerfile + assert 'COPY ["api/constraints/pins.txt", "/workspace/api/constraints/pins.txt"]' in dockerfile + assert 'pip install --no-cache-dir -e "."' in dockerfile + assert adapter.display_command(profile, "tests/test_x.py") == "cd api && python -m pytest tests/test_x.py" + + +def test_container_command_runs_one_file_with_junit_results(profile): + command = adapter.container_command(profile, "tests/test_security_idor_note.py") + assert command[:2] == ["sh", "-c"] + assert command[-1] == "tests/test_security_idor_note.py" + assert "--junitxml=/openhack-results/junit.xml" in command[2] + assert "--maxfail=100000" in command[2] + assert "> /openhack-results/output.txt 2>&1" in command[2] diff --git a/tests/test_regression_invariants.py b/tests/test_regression_invariants.py new file mode 100644 index 0000000..647937d --- /dev/null +++ b/tests/test_regression_invariants.py @@ -0,0 +1,136 @@ +"""Security-invariant extraction from verified findings and exploit evidence.""" + +import pytest + +from openhack.agents.session import Finding +from openhack.regression.evidence import sanitize_exploit_evidence +from openhack.regression.invariants import ( + IdorSpec, + MissingEvidenceError, + request_from_poc, + spec_for_finding, + supported_classes, + templatize_path, +) +from tests.regression_support import sandbox_result, verified_idor_finding + + +def test_idor_invariant_from_sandbox_exploit_request(): + invariant = IdorSpec().extract_invariant(verified_idor_finding()) + + assert invariant.vulnerability_class == "idor" + assert invariant.cwe == "CWE-639" + assert invariant.method == "GET" + assert invariant.path_template == "/api/notes/{note_id}" + assert invariant.example_path == "/api/notes/1" + assert invariant.object_param == "note_id" + assert invariant.param_location == "path" + assert invariant.resource == "note" + assert invariant.operation == "read" + assert invariant.source_location == "app.py:70" + # The invariant generalizes the witness: it is about every principal and + # identifier, and it states what must keep working. + assert "owned by another principal" in invariant.statement + assert "no matter which note_id" in invariant.statement + assert "401, 403 or 404" in invariant.denial + assert "owner can still read" in invariant.control + + +def test_invariant_evidence_is_redacted(): + invariant = IdorSpec().extract_invariant(verified_idor_finding()) + assert "eyJhbGci" not in invariant.evidence + assert "xyzzy-live-session-token" not in invariant.evidence + + +@pytest.mark.parametrize("method,operation", [ + ("PUT", "update"), ("PATCH", "update"), ("DELETE", "delete"), ("POST", "act on"), +]) +def test_operation_follows_http_method(method, operation): + result = sandbox_result(exploit_request={"method": method, "path": "/api/notes/9"}) + finding = verified_idor_finding(exploit_evidence=sanitize_exploit_evidence(result)) + assert IdorSpec().extract_invariant(finding).operation == operation + + +def test_nested_and_uuid_identifiers_are_templated(): + uuid = "3f2b8c1e-9d4a-4b6f-8e2a-1c5d7f9a0b3e" + template, param, resource = templatize_path(f"/api/users/42/documents/{uuid}") + assert template == "/api/users/{user_id}/documents/{document_id}" + assert param == "document_id" + assert resource == "document" + assert templatize_path("/api/categories/7")[2] == "category" + + +def test_query_parameter_identifier(): + result = sandbox_result(exploit_request={"method": "GET", "path": "/api/invoice?invoiceId=55&format=pdf"}) + invariant = IdorSpec().extract_invariant( + verified_idor_finding(exploit_evidence=sanitize_exploit_evidence(result)) + ) + assert invariant.object_param == "invoiceId" + assert invariant.param_location == "query" + assert invariant.resource == "invoice" + + +def test_body_identifier(): + result = sandbox_result(exploit_request={ + "method": "POST", "path": "/api/orders/cancel", "json_body": {"order_id": 77, "valid": True}, + }) + invariant = IdorSpec().extract_invariant( + verified_idor_finding(exploit_evidence=sanitize_exploit_evidence(result)) + ) + assert invariant.object_param == "order_id" + assert invariant.param_location == "body" + + +def test_falls_back_to_the_working_poc_when_the_request_is_missing(): + result = sandbox_result(exploit_request=None) + invariant = IdorSpec().extract_invariant( + verified_idor_finding(exploit_evidence=sanitize_exploit_evidence(result)) + ) + assert (invariant.method, invariant.path_template) == ("GET", "/api/notes/{note_id}") + + +@pytest.mark.parametrize("poc,expected", [ + ("requests.delete(f'{BASE}/api/notes/{note_id}', headers=h)", ("DELETE", "/api/notes/{note_id}")), + ("r = session.put(BASE_URL + '/api/notes/3', json={})", ("PUT", "/api/notes/3")), + ("curl -s -H 'Authorization: Bearer x' -X PATCH http://localhost:3000/api/notes/4", ("PATCH", "/api/notes/4")), + ("value = data.get('key')\nrequests.get('http://h:1/api/a/1')", ("GET", "/api/a/1")), + ("print('nothing to see')", ("", "")), +]) +def test_request_from_poc(poc, expected): + assert request_from_poc(poc) == expected + + +def test_finding_without_exploit_evidence_is_missing_evidence(): + finding = verified_idor_finding(exploit_evidence=None, source=None) + with pytest.raises(MissingEvidenceError, match="not verified by sandbox exploitation"): + IdorSpec().extract_invariant(finding) + + +def test_evidence_that_does_not_identify_the_request_is_missing_evidence(): + evidence = sanitize_exploit_evidence( + {"evidence": "It worked, I saw someone else's data.", "working_poc": "print('ok')"} + ) + with pytest.raises(MissingEvidenceError, match="does not identify the HTTP request"): + IdorSpec().extract_invariant(verified_idor_finding(exploit_evidence=evidence)) + + +@pytest.mark.parametrize("category", ["IDOR", "Insecure Direct Object Reference", "broken object level authorization"]) +def test_idor_categories_are_supported(category): + assert isinstance(spec_for_finding(Finding(category=category, severity="high", title="t", + description="d", file_path="a.py")), IdorSpec) + + +@pytest.mark.parametrize("category", ["XSS", "SQL Injection", "SSRF", "Authentication Bypass"]) +def test_other_classes_are_unsupported(category): + finding = Finding(category=category, severity="high", title="t", description="d", file_path="a.py") + assert spec_for_finding(finding) is None + assert supported_classes() == ["IDOR / broken object-level authorization"] + + +def test_generation_guidance_targets_the_invariant_not_a_payload(): + spec = IdorSpec() + guidance = spec.generation_guidance(spec.extract_invariant(verified_idor_finding())) + assert "TWO distinct principals" in guidance + assert "accept any of them" in guidance + assert "Never reuse tokens" in guidance + assert "GET /api/notes/{note_id}" in guidance diff --git a/tests/test_regression_lifecycle.py b/tests/test_regression_lifecycle.py new file mode 100644 index 0000000..d6d0ecf --- /dev/null +++ b/tests/test_regression_lifecycle.py @@ -0,0 +1,383 @@ +"""Regression tests inside the existing vulnerability lifecycle. + +discovery (hunters) → validation → sandbox exploit verification → Step 6 +regression tests, then report persistence, the --regression-tests flag, +configuration, and the TUI's findings view and /copy remediation prompt. +The LLM-backed scan stages are stubbed with canned results; the coordinator, +evidence capture and the regression pipeline are real. +""" + +import asyncio +import contextlib +import io +import json +import time +from types import SimpleNamespace + +import pytest + +import openhack.regression.pipeline as pipeline_mod +from openhack import config +from openhack.agents.coordinator import CoordinatorAgent +from openhack.agents.session import Finding, Session, TraceEntry +from openhack.config import settings +from openhack.regression import headless +from openhack.regression.pipeline import PipelineOptions +from openhack.regression.workspace import RevisionSpec +from openhack.tools.registry import ToolRegistry +from tests.regression_support import ( + FIX_BRANCH, + TEST_PATH, + FakeRunner, + ScriptedLLM, + git, + install_scan_stubs, + make_fixture_repo, + submit, + verified_idor_finding, +) + + +@pytest.fixture +def lifecycle(monkeypatch, tmp_path): + """The coordinator with stubbed discovery/validation/sandbox stages.""" + for key, value in { + "checkpoint_enabled": False, "feature_hunt_enabled": False, "sandbox_enabled": True, + "browser_verification_enabled": False, "regression_tests_enabled": True, + "regression_tests_fixed_ref": FIX_BRANCH, + }.items(): + monkeypatch.setattr(settings, key, value) + + fx = make_fixture_repo(tmp_path) + regression_llm = ScriptedLLM([submit()]) + runner = FakeRunner() + llms = install_scan_stubs(monkeypatch, regression_llm) + monkeypatch.setattr(pipeline_mod, "ContainerTestRunner", lambda limits=None: runner) + monkeypatch.setattr(pipeline_mod, "default_artifacts_root", lambda session: tmp_path / "artifacts") + + def scan(): + session = Session(str(fx["repo"]), persist_events=False) + agent = CoordinatorAgent(ScriptedLLM([]), ToolRegistry(target_dir=fx["repo"]), session) + return session, asyncio.run(agent.run_full_scan()) + + return SimpleNamespace(fx=fx, scan=scan, runner=runner, llm=regression_llm, llms=llms) + + +def test_verified_idor_produces_a_validated_regression_test_during_a_scan(lifecycle): + session, result = lifecycle.scan() + finding = session.findings[0] + + # Sandbox verification kept a redacted record of the exploit... + assert finding.source == "sandbox_verified" + request = finding.exploit_evidence["exploit_request"] + assert (request["method"], request["path"]) == ("GET", "/api/notes/1") + assert request["headers"]["Authorization"] == "[REDACTED]" + assert "eyJhbGci" not in json.dumps(finding.exploit_evidence) + # ...which Step 6 turned into a validated regression test. + assert finding.regression_test["status"] == "validated" + assert finding.regression_test["test_path"] == TEST_PATH + assert result["findings"][0]["regressionTest"]["status"] == "validated" + assert "regression_tests" in session.step_costs + steps = [e.content for e in session.trace if e.event_type == "step_start"] + assert any("Step 6: Security regression tests" in str(s) for s in steps) + complete = [e.content for e in session.trace if e.event_type == "step_complete" + and isinstance(e.content, dict) and e.content.get("step") == "regression_tests"] + assert complete[0]["statuses"] == {"validated": 1} + # The scanned working tree is the vulnerable revision; the fix comes from config. + assert len(lifecycle.runner.runs_for("vulnerable")) == 2 + assert len(lifecycle.runner.runs_for("remediated")) == 2 + + +def test_disabled_by_default_and_skipped_when_disabled(lifecycle, monkeypatch): + assert config.Settings.model_fields["regression_tests_enabled"].default is False + monkeypatch.setattr(settings, "regression_tests_enabled", False) + monkeypatch.setattr(pipeline_mod, "RegressionTestPipeline", + lambda *a, **k: pytest.fail("pipeline must not run when disabled")) + session, _ = lifecycle.scan() + + assert session.findings[0].regression_test is None + assert "regression_tests" not in session.step_costs + assert "regression_test" not in lifecycle.llms + # Exploit evidence is still recorded so a later --regression-tests run can use it. + assert session.findings[0].exploit_evidence is not None + + +def test_regression_step_failure_never_costs_the_scan_its_findings(lifecycle, monkeypatch): + async def explode(self, findings): + raise RuntimeError("docker exploded") + + monkeypatch.setattr(pipeline_mod.RegressionTestPipeline, "run", explode) + session, result = lifecycle.scan() + + assert result["status"] == "completed" + assert len(session.findings) == 1 + errors = [e.content for e in session.trace if e.event_type == "regression_test_error"] + assert errors and "docker exploded" in errors[0] + + +def test_misconfigured_regression_model_does_not_fail_the_scan(lifecycle, monkeypatch): + stubbed = CoordinatorAgent._create_llm_for_agent + + def create(self, agent_type): + if agent_type == "regression_test": + raise ValueError("unknown model 'nope'") + return stubbed(self, agent_type) + + monkeypatch.setattr(CoordinatorAgent, "_create_llm_for_agent", create) + session, result = lifecycle.scan() + + assert result["status"] == "completed" and len(session.findings) == 1 + errors = [e.content for e in session.trace if e.event_type == "regression_test_error"] + assert errors and "unknown model 'nope'" in errors[0] + assert session.step_costs["regression_tests"] == 0.0 + + +def test_unverified_findings_report_missing_evidence(lifecycle, monkeypatch): + monkeypatch.setattr(settings, "sandbox_enabled", False) + session, _ = lifecycle.scan() + status = session.findings[0].regression_test + assert status["status"] == "missing_evidence" + assert "enable sandbox verification" in status["reason"] + assert lifecycle.llm.calls == 0 + + +# ── reports ── + +def test_finding_round_trips_through_a_report(): + original = verified_idor_finding(regression_test={"status": "validated", "test_path": TEST_PATH}) + data = json.loads(json.dumps(original.to_dict())) + restored = Finding.from_dict(data) + + assert data["exploitEvidence"]["exploit_request"]["path"] == "/api/notes/1" + assert restored.id == original.id + assert restored.source == "sandbox_verified" + assert restored.exploit_evidence == original.exploit_evidence + assert restored.regression_test == {"status": "validated", "test_path": TEST_PATH} + assert restored.fix == original.fix and restored.line_number == 70 + + +def test_headless_report_records_the_scanned_revision(tmp_path, monkeypatch): + import openhack.headless_scan as headless_scan + + fx = make_fixture_repo(tmp_path) + monkeypatch.setattr(headless_scan, "SCANS_DIR", tmp_path / "scans") + session = Session(str(fx["repo"]), persist_events=False) + session.add_finding(verified_idor_finding(regression_test={"status": "validated"})) + path = headless_scan._write_report(session, str(fx["repo"]), "completed", time.time()) + report = json.loads(path.read_text()) + + assert report["repository"] == {"head": fx["vulnerable_sha"], "branch": "main", "dirty": False} + assert report["findings"][0]["regressionTest"] == {"status": "validated"} + + +def test_headless_status_lines(): + from openhack.headless_scan import format_regression_status + + finding = verified_idor_finding(regression_test={ + "status": "validated", "status_label": "generated and validated", "test_path": TEST_PATH, + "reason": "Fails on the vulnerable revision ...", "artifacts": {"patch": "/x/regression-test.patch"}, + }) + lines = format_regression_status(finding) + assert lines[0] == f"Regression test: generated and validated — {TEST_PATH}" + assert "Fails on the vulnerable revision" in lines[1] + assert "git apply" in lines[2] + assert format_regression_status(verified_idor_finding()) == [] + + +# ── openhack --regression-tests ── + +def _saved_scan(tmp_path, fx, finding, **repository): + scans = tmp_path / "scans" + scans.mkdir(exist_ok=True) + report = { + "scan_id": "a1b2c3d4-0000-4000-8000-000000000000", + "target_dir": str(fx["repo"]), + "status": "completed", + "repository": {"head": fx["vulnerable_sha"], "branch": "main", "dirty": False, **repository}, + "findings": [finding.to_dict()], + } + path = scans / f"{report['scan_id']}.json" + path.write_text(json.dumps(report)) + return path + + +@pytest.fixture +def cli_env(monkeypatch, tmp_path): + runner = FakeRunner() + llm = ScriptedLLM([submit()]) + monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path) + monkeypatch.setattr(headless, "SCANS_DIR", tmp_path / "scans") + monkeypatch.setattr(headless, "reload_settings", lambda: None) + monkeypatch.setattr("openhack.agents.llm.LLMClient", lambda *a, **k: llm) + monkeypatch.setattr(pipeline_mod, "ContainerTestRunner", lambda limits=None: runner) + monkeypatch.setattr(settings, "regression_tests_fixed_ref", None) + return SimpleNamespace(runner=runner, llm=llm) + + +def test_regression_tests_flag_validates_against_the_fix_and_updates_the_report(tmp_path, cli_env): + fx = make_fixture_repo(tmp_path) + report_path = _saved_scan(tmp_path, fx, verified_idor_finding()) + out = io.StringIO() + with contextlib.redirect_stdout(out): + code = asyncio.run(headless.run_regression_tests_for_report("a1b2c3d4", FIX_BRANCH)) + + assert code == 0 + report = json.loads(report_path.read_text()) + status = report["findings"][0]["regressionTest"] + assert status["status"] == "validated" + assert status["validation"]["vulnerable"]["resolved"] == fx["vulnerable_sha"] + assert status["validation"]["remediated"]["resolved"] == fx["fixed_sha"] + assert report["regression_tests"]["statuses"] == {"validated": 1} + printed = out.getvalue() + assert f"Vulnerable: git revision `{fx['vulnerable_sha']}`" in printed + assert f"Remediated: git revision `{FIX_BRANCH}`" in printed + assert "Regression test: generated and validated" in printed + + +def test_regression_tests_flag_reports_failures_with_a_nonzero_status(tmp_path, cli_env): + fx = make_fixture_repo(tmp_path) + _saved_scan(tmp_path, fx, verified_idor_finding()) + with contextlib.redirect_stdout(io.StringIO()): + # No fix revision and HEAD has not moved: the test can only be pending. + code = asyncio.run(headless.run_regression_tests_for_report("a1b2c3d4")) + assert code == 2 + + +def test_unknown_session(tmp_path, cli_env): + (tmp_path / "scans").mkdir() + out = io.StringIO() + with contextlib.redirect_stdout(out): + assert asyncio.run(headless.run_regression_tests_for_report("nope")) == 1 + assert "not found" in out.getvalue() + + +def test_choose_revisions(tmp_path, monkeypatch): + monkeypatch.setattr(settings, "regression_tests_fixed_ref", None) + fx = make_fixture_repo(tmp_path) + repo = fx["repo"] + clean = {"repository": {"head": fx["vulnerable_sha"], "dirty": False}} + + vulnerable, remediation, _ = headless.choose_revisions(clean, repo, None) + assert vulnerable == RevisionSpec.git(fx["vulnerable_sha"]) and remediation is None + + git(repo, "merge", "-q", "--ff-only", FIX_BRANCH) # the fix landed on main + _, remediation, notes = headless.choose_revisions(clean, repo, None) + assert remediation == RevisionSpec.git(fx["fixed_sha"]) and "using HEAD" in notes[-1] + + vulnerable, _, notes = headless.choose_revisions({"repository": {"head": "x", "dirty": True}}, repo, None) + assert vulnerable == RevisionSpec.worktree() and "uncommitted" in notes[0] + + _, remediation, _ = headless.choose_revisions(clean, repo, str(tmp_path)) + assert remediation.kind == "directory" + + +def test_cli_flag_usage_without_a_session(monkeypatch): + import openhack.__main__ as main_mod + + monkeypatch.setattr("sys.argv", ["openhack", "--regression-tests"]) + out = io.StringIO() + with contextlib.redirect_stdout(out): + main_mod.main() + assert "Usage: openhack --regression-tests [fixed-revision]" in out.getvalue() + + +# ── configuration ── + +def test_settings_can_be_enabled_from_the_environment(monkeypatch): + monkeypatch.setenv("REGRESSION_TESTS_ENABLED", "true") + monkeypatch.setenv("REGRESSION_TESTS_FIXED_REF", "fix/idor") + fresh = config._build_settings() + assert fresh.regression_tests_enabled is True + assert fresh.regression_tests_fixed_ref == "fix/idor" + + +def test_pipeline_options_from_settings(tmp_path): + stub = SimpleNamespace( + regression_tests_fixed_ref="fix/idor", regression_tests_max_attempts=0, + regression_tests_validation_runs=3, regression_tests_base_image="registry.local/python:3.12", + regression_tests_timeout=45, regression_tests_build_timeout=300, + ) + options = PipelineOptions.from_settings(stub, str(tmp_path), report_id="abc") + assert options.remediation == RevisionSpec.git("fix/idor") + assert options.max_attempts == 1 and options.validation_runs == 3 + assert options.base_image == "registry.local/python:3.12" + assert (options.limits.run_timeout, options.limits.build_timeout) == (45, 300) + assert options.report_id == "abc" and options.vulnerable == RevisionSpec.worktree() + + stub.regression_tests_fixed_ref = str(tmp_path) + assert PipelineOptions.from_settings(stub, str(tmp_path)).remediation.kind == "directory" + + +# ── TUI ── + +def _tui_app(): + from openhack.tui import OpenHackApp + + app = OpenHackApp.__new__(OpenHackApp) + app._invalidate = lambda: None + return app + + +def test_tui_config_accepts_regression_settings(monkeypatch): + import openhack.tui as tui + + saved = {} + monkeypatch.setattr(tui, "save_user_config", saved.update) + monkeypatch.setattr(tui, "reload_settings", lambda: None) + app = _tui_app() + app._cmd_config("regression_tests_enabled true") + assert saved == {"regression_tests_enabled": "true"} + assert app.last_status_line == "saved regression_tests_enabled" + assert any(key == "regression_tests_fixed_ref" for key, _ in tui._CONFIG_KEYS) + + +def test_tui_restores_regression_status_from_saved_reports(): + from openhack.tui import OpenHackApp + + original = verified_idor_finding(regression_test={"status": "remediation_unavailable"}) + loaded = OpenHackApp._findings_from_report({"findings": [original.to_dict()]})[0] + assert loaded.regression_test == {"status": "remediation_unavailable"} + assert loaded.exploit_evidence == original.exploit_evidence + assert loaded.source == "sandbox_verified" + + +@pytest.mark.parametrize("status,included,phrase", [ + ("validated", True, "fails on the vulnerable code and passes once"), + ("remediation_unavailable", True, "must pass after your fix"), + ("validation_failed", False, None), +]) +def test_copy_prompt_carries_the_regression_test(status, included, phrase): + from openhack.tui import OpenHackApp + + finding = verified_idor_finding(regression_test={ + "status": status, "test_path": TEST_PATH, "test_code": "def test_x():\n assert True\n", + }) + prompt = OpenHackApp._format_finding_for_agent(finding) + assert ("## Regression test" in prompt) is included + if included: + assert phrase in prompt + assert f"Add it unchanged at `{TEST_PATH}`" in prompt + assert "```python\ndef test_x():\n assert True\n```" in prompt + + +def test_tui_details_and_trace_show_regression_status(): + from openhack.tui import ScanState, _regression_test_fragments + + finding = verified_idor_finding(regression_test={ + "status": "validated", "status_label": "generated and validated", "test_path": TEST_PATH, + "reason": "Fails on the vulnerable revision and passes on the remediated revision.", + "run_command": f"python -m pytest {TEST_PATH}", "test_code": "def test_x():\n assert True\n", + "artifacts": {"patch": "/p/regression-test.patch"}, + }) + text = "".join(fragment[1] for fragment in _regression_test_fragments(finding)) + assert "REGRESSION TEST" in text and "✓ generated and validated" in text + assert TEST_PATH in text and "patch: /p/regression-test.patch" in text + assert _regression_test_fragments(verified_idor_finding()) == [] + + scan = ScanState(target="/repo") + scan.update_from_trace(TraceEntry( + timestamp=time.time(), agent="regression_tests", event_type="regression_test_result", + content={"title": "IDOR in app.py", "status": "validated", "label": "generated and validated"}, + )) + rendered = "".join(fragment[1] for _, line in scan.trace_lines for fragment in line) + assert "generated and validated" in rendered and "IDOR in app.py" in rendered diff --git a/tests/test_regression_pipeline.py b/tests/test_regression_pipeline.py new file mode 100644 index 0000000..b7c529a --- /dev/null +++ b/tests/test_regression_pipeline.py @@ -0,0 +1,512 @@ +"""The regression-test pipeline: generation, validation, feedback and statuses. + +Everything here is the real implementation (revision materialization, +framework detection, the generator agent and its tools, static policy, +evaluation, artifacts) except the LLM, which is scripted, and the container +runtime, which is replaced by FakeRunner writing pytest-format JUnit XML. +test_regression_e2e_docker.py runs the same flow against real Docker. +""" + +import asyncio +import json +import shutil +import subprocess +from types import SimpleNamespace + +import pytest + +from openhack.agents.llm import LLMResponse +from openhack.agents.session import Finding, Session +from openhack.regression.frameworks import CaseOutcome, RunReport +from openhack.regression.generator import CandidateTest +from openhack.regression.models import RegressionTestStatus as Status +from openhack.regression.pipeline import PipelineOptions, RegressionTestPipeline, evaluate_runs +from openhack.regression.workspace import RevisionSpec +from tests.conftest import write_file +from tests.regression_support import ( + FIX_BRANCH, + GOOD_CONTROL_TESTS, + GOOD_INVARIANT_TESTS, + GOOD_TEST, + TEST_PATH, + FakeRunner, + ScriptedLLM, + git, + make_fixture_repo, + read_file_call, + realistic_idor, + submit, + submit_weak, + verified_idor_finding, +) + +FIX = RevisionSpec.git(FIX_BRANCH) + + +def run_pipeline(tmp_path, responses, *, behavior=realistic_idor, remediation=FIX, + findings=None, repo=None, runner=None, **options): + fx = None + if repo is None: + fx = make_fixture_repo(tmp_path) + repo = fx["repo"] + session = Session(str(repo), persist_events=False) + llm = ScriptedLLM(responses) + runner = runner or FakeRunner(behavior) + opts = PipelineOptions(remediation=remediation, artifacts_root=tmp_path / "artifacts", **options) + pipeline = RegressionTestPipeline(llm, session, repo, opts, runner=runner) + findings = findings if findings is not None else [verified_idor_finding()] + results = asyncio.run(pipeline.run(findings)) + return SimpleNamespace(fx=fx, repo=repo, session=session, llm=llm, runner=runner, + pipeline=pipeline, findings=findings, results=results, result=results[0]) + + +def feedback_sent(llm: ScriptedLLM, request_index: int) -> str: + return next(m.content for m in reversed(llm.requests[request_index]) if m.role == "user") + + +# ── success ── + +def test_generates_and_validates_an_idor_regression_test(tmp_path): + run = run_pipeline(tmp_path, [read_file_call(), submit()]) + result = run.result + + assert result.status is Status.VALIDATED + assert result.attempts == 1 + assert result.vulnerability_class == "idor" + assert result.framework == "pytest" + assert result.test_path == TEST_PATH + assert result.run_command == f"python -m pytest {TEST_PATH}" + assert result.invariant_tests == GOOD_INVARIANT_TESTS + assert result.control_tests == GOOD_CONTROL_TESTS + assert result.invariant.path_template == "/api/notes/{note_id}" + assert result.test_code.startswith("# Security regression test generated by OpenHack") + assert GOOD_TEST in result.test_code + assert result.cost == pytest.approx(0.02) + + validation = result.validation + assert validation["runs_per_revision"] == 2 + assert validation["vulnerable"]["passed"] and validation["remediated"]["passed"] + assert validation["vulnerable"]["outcomes"]["test_other_user_cannot_read_note"] == "failed" + assert validation["vulnerable"]["outcomes"]["test_owner_can_read_own_note"] == "passed" + assert validation["remediated"]["outcomes"]["test_other_user_cannot_read_note"] == "passed" + assert validation["remediated"]["resolved"] == run.fx["fixed_sha"] + assert "Fails on the vulnerable revision" in result.reason + + # Two runs per revision, each a fresh container with only the new file added. + assert len(run.runner.runs_for("vulnerable")) == 2 + assert len(run.runner.runs_for("remediated")) == 2 + first = run.runner.runs[0] + assert list(first["files"]) == [TEST_PATH] + assert first["command"][-1] == TEST_PATH and first["workdir"] == "/workspace" + assert [tag.split("-")[-2] for tag, _ in run.runner.builds] == ["vulnerable", "remediated"] + assert "FROM python:3.12-slim" in run.runner.builds[0][1] + assert run.runner.images_removed + + # The generator really read the repository through its jailed tools. + tool_results = [m for m in run.llm.requests[1] if m.role == "tool"] + assert "def auth_headers" in tool_results[0].content + + +def test_result_is_attached_to_the_finding_and_traced(tmp_path): + run = run_pipeline(tmp_path, [submit()]) + finding = run.findings[0] + assert finding.regression_test["status"] == "validated" + assert finding.regression_test["status_label"] == "generated and validated" + assert finding.to_dict()["regressionTest"]["test_path"] == TEST_PATH + traced = [e.content for e in run.session.trace if e.event_type == "regression_test_result"] + assert traced == [{ + "title": finding.title, "status": "validated", "label": "generated and validated", + "reason": run.result.reason, "test_path": TEST_PATH, + }] + checks = [e.content["revision"] for e in run.session.trace if e.event_type == "regression_test_check"] + assert checks == ["vulnerable", "remediated"] + + +def test_artifacts_include_the_test_and_an_applicable_patch(tmp_path): + run = run_pipeline(tmp_path, [submit()]) + artifacts = run.result.artifacts + test_file = tmp_path / "artifacts" / run.session.id / "regression-tests" / run.findings[0].id[:8] / TEST_PATH + + assert artifacts["test_file"] == str(test_file) + assert test_file.read_text() == run.result.test_code + assert artifacts["repo_path"] == TEST_PATH + record = json.loads((test_file.parents[1] / "result.json").read_text()) + assert record["status"] == "validated" and record["artifacts"]["patch"] == artifacts["patch"] + + # The patch adds the test to the fix branch without touching anything else. + git(run.repo, "checkout", "-q", FIX_BRANCH) + subprocess.run(["git", "-C", str(run.repo), "apply", artifacts["patch"]], check=True) + assert (run.repo / TEST_PATH).read_text() == run.result.test_code + assert git(run.repo, "status", "--porcelain") == f"?? {TEST_PATH}" + + +def test_the_scanned_repository_is_never_modified(tmp_path): + run = run_pipeline(tmp_path, [submit(path="tests/test_notes.py"), submit(call_id="s2")]) + assert run.result.status is Status.VALIDATED + assert git(run.repo, "status", "--porcelain") == "" + + +# ── feedback loop ── + +def test_test_that_does_not_detect_the_vulnerability_is_rejected_and_revised(tmp_path): + run = run_pipeline(tmp_path, [submit_weak(), submit(call_id="s2")]) + + assert run.result.status is Status.VALIDATED + assert run.result.attempts == 2 + feedback = feedback_sent(run.llm, 1) + assert feedback.startswith("[VALIDATION FEEDBACK]") + assert "every invariant test PASSED on the VULNERABLE code" in feedback + assert "test_anonymous_cannot_read_note=passed" in feedback + # The weak test never got as far as the remediated revision. + assert all("anonymous" not in r["code"] for r in run.runner.runs_for("remediated")) + + +def test_gives_up_after_max_attempts(tmp_path): + run = run_pipeline(tmp_path, [submit_weak("a"), submit_weak("b")], max_attempts=2) + + assert run.result.status is Status.VALIDATION_FAILED + assert run.result.attempts == 2 + assert "does not detect the vulnerability" in run.result.reason + # Rejected tests are kept for review but never become artifacts. + assert "test_anonymous_cannot_read_note" in run.result.test_code + assert run.result.artifacts == {} + assert run.result.validation["vulnerable"]["passed"] is False + + +def test_policy_violations_are_fed_back_before_any_execution(tmp_path): + bad = GOOD_TEST + "\nimport requests\n" + run = run_pipeline(tmp_path, [submit(bad), submit(call_id="s2")]) + + assert run.result.status is Status.VALIDATED + feedback = feedback_sent(run.llm, 1) + assert "rejected before execution" in feedback and "makes real network requests" in feedback + assert all("import requests" not in r["code"] for r in run.runner.runs) + + +def test_only_invalid_tests_is_a_generation_failure(tmp_path): + bad = GOOD_TEST + "\nimport subprocess\n" + run = run_pipeline(tmp_path, [submit(bad, call_id="a"), submit(bad, call_id="b")], max_attempts=2) + assert run.result.status is Status.GENERATION_FAILED + assert "rejected before execution" in run.result.reason + assert run.runner.runs == [] and run.runner.builds == [] + + +def test_tests_embedding_credentials_are_rejected(tmp_path): + leaky = GOOD_TEST + "\nTOKEN = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.c2lnbmF0dXJl'\n" + run = run_pipeline(tmp_path, [submit(leaky), submit(call_id="s2")]) + assert run.result.status is Status.VALIDATED + assert "embeds a JSON Web Token" in feedback_sent(run.llm, 1) + assert "eyJhbGci" not in run.result.test_code + + +def test_existing_test_files_are_never_overwritten(tmp_path): + run = run_pipeline(tmp_path, [submit(path="tests/test_notes.py"), submit(call_id="s2")]) + feedback = feedback_sent(run.llm, 1) + assert "already exists" in feedback and "existing tests are never modified" in feedback + assert run.result.test_path == TEST_PATH + + +# ── validation failures ── + +def test_nondeterministic_tests_are_rejected(tmp_path): + def flaky(label, code, run_index): + outcomes = realistic_idor(label, code, run_index) + if run_index == 1: + outcomes["test_other_user_cannot_read_note"] = "passed" + return outcomes + + run = run_pipeline(tmp_path, [submit()], behavior=flaky, max_attempts=1) + assert run.result.status is Status.VALIDATION_FAILED + assert "nondeterministic" in run.result.reason + assert "test_other_user_cannot_read_note" in run.result.reason + + +def test_timeouts_are_validation_failures(tmp_path): + run = run_pipeline(tmp_path, [submit()], behavior=lambda *a: "timeout", max_attempts=1) + assert run.result.status is Status.VALIDATION_FAILED + assert "timed out after 180s" in run.result.reason + + +def test_collection_errors_are_reported_with_output(tmp_path): + run = run_pipeline(tmp_path, [submit(), submit(call_id="s2")], + behavior=lambda *a: "collection_error", max_attempts=2) + assert run.result.status is Status.VALIDATION_FAILED + assert "could not be collected or run" in run.result.reason + assert "No module named 'notes'" in feedback_sent(run.llm, 1) + + +def test_failing_control_test_means_the_failure_is_not_the_vulnerability(tmp_path): + def broken_setup(label, code, run_index): + outcomes = realistic_idor(label, code, run_index) + outcomes["test_owner_can_read_own_note"] = "failed" + return outcomes + + run = run_pipeline(tmp_path, [submit()], behavior=broken_setup, max_attempts=1) + assert run.result.status is Status.VALIDATION_FAILED + assert "control test(s) failed on the VULNERABLE code" in run.result.reason + + +def test_crashing_invariant_tests_are_not_accepted(tmp_path): + def crash(label, code, run_index): + outcomes = realistic_idor(label, code, run_index) + if label == "vulnerable": + outcomes["test_other_user_cannot_read_note"] = "crashed" + return outcomes + + run = run_pipeline(tmp_path, [submit()], behavior=crash, max_attempts=1) + assert run.result.status is Status.VALIDATION_FAILED + assert "unexpected exception rather than an assertion" in run.result.reason + + +def test_invariant_still_failing_on_the_fix_is_never_weakened_away(tmp_path): + def incomplete_fix(label, code, run_index): + outcomes = realistic_idor(label, code, run_index) + if label == "remediated": + outcomes["test_other_user_cannot_delete_note"] = "failed" + return outcomes + + run = run_pipeline(tmp_path, [submit(), submit(call_id="never-used")], behavior=incomplete_fix) + assert run.result.status is Status.VALIDATION_FAILED + assert "remediation is incomplete" in run.result.reason + assert "test_other_user_cannot_delete_note" in run.result.reason + assert run.llm.calls == 1 # no revision was requested + + +def test_setup_errors_on_the_fix_are_retried(tmp_path): + second = GOOD_TEST + "\n# revised setup\n" + + def setup_error_first(label, code, run_index): + outcomes = realistic_idor(label, code, run_index) + if label == "remediated" and "revised setup" not in code: + outcomes["test_owner_can_read_own_note"] = "error" + return outcomes + + run = run_pipeline(tmp_path, [submit(), submit(second, call_id="s2")], behavior=setup_error_first) + assert run.result.status is Status.VALIDATED + assert run.result.attempts == 2 + assert "errored or were skipped" in feedback_sent(run.llm, 1) + + +# ── generation failures ── + +def test_generator_that_never_submits(tmp_path): + talk = [LLMResponse(content="Looks fine to me.", finish_reason="stop")] * 4 + run = run_pipeline(tmp_path, talk, max_attempts=2) + assert run.result.status is Status.GENERATION_FAILED + assert run.result.reason == "the generator did not submit a test" + assert run.llm.calls == 4 + assert "You have not submitted a test" in feedback_sent(run.llm, 1) + + +def test_generator_errors_are_reported(tmp_path): + run = run_pipeline(tmp_path, [RuntimeError("upstream 500")]) + assert run.result.status is Status.GENERATION_FAILED + assert "the generator failed: upstream 500" in run.result.reason + + +def test_malformed_submissions_are_rejected_in_conversation(tmp_path): + malformed = submit() + malformed.tool_calls[0].arguments["invariant_tests"] = [] + run = run_pipeline(tmp_path, [malformed, submit(call_id="s2")]) + assert run.result.status is Status.VALIDATED + tool_reply = [m for m in run.llm.requests[1] if m.role == "tool"][-1].content + assert "invariant_tests" in tool_reply and "Submission rejected" in tool_reply + + +# ── statuses that need no LLM or sandbox ── + +def test_mixed_findings_each_get_a_status(tmp_path): + xss = Finding(category="XSS", severity="medium", title="XSS in note view", + description="d", file_path="app.py", validated=True) + unverified = verified_idor_finding(exploit_evidence=None, source=None, title="IDOR (static)") + verified = verified_idor_finding() + run = run_pipeline(tmp_path, [submit()], findings=[xss, unverified, verified]) + + assert [r.status for r in run.results] == [ + Status.UNSUPPORTED_VULNERABILITY, Status.MISSING_EVIDENCE, Status.VALIDATED, + ] + assert "XSS is not supported yet (supported: IDOR" in run.results[0].reason + assert "not verified by sandbox exploitation" in run.results[1].reason + assert all(f.regression_test for f in run.findings) + + +def test_nothing_eligible_needs_neither_llm_nor_docker(tmp_path): + xss = Finding(category="XSS", severity="medium", title="x", description="d", file_path="a.py") + run = run_pipeline(tmp_path, [], findings=[xss]) + assert run.result.status is Status.UNSUPPORTED_VULNERABILITY + assert run.llm.calls == 0 and run.runner.builds == [] and run.runner.runs == [] + + +def test_unsupported_test_framework(tmp_path): + repo = tmp_path / "no-tests" + shutil.copytree(make_fixture_repo(tmp_path)["repo"], repo, ignore=shutil.ignore_patterns("tests", "pytest.ini", ".git")) + (repo / "requirements.txt").write_text("flask\n") + run = run_pipeline(tmp_path, [], repo=repo, remediation=None) + assert run.result.status is Status.UNSUPPORTED_FRAMEWORK + assert "no existing test suite was detected" in run.result.reason + assert run.llm.calls == 0 + + +def test_sandbox_unavailable(tmp_path): + run = run_pipeline(tmp_path, [], runner=FakeRunner(available=False)) + assert run.result.status is Status.SANDBOX_ERROR + assert "Docker is required" in run.result.reason + assert run.llm.calls == 0 + + +def test_image_build_failure_is_a_sandbox_error(tmp_path): + run = run_pipeline(tmp_path, [submit()], runner=FakeRunner(build_error="pip: could not resolve flask")) + assert run.result.status is Status.SANDBOX_ERROR + assert "could not resolve flask" in run.result.reason + assert run.runner.images_removed + + +def test_cancelled_sessions_stop_generating(tmp_path): + fx = make_fixture_repo(tmp_path) + session = Session(str(fx["repo"]), persist_events=False) + session.cancelled = True + pipeline = RegressionTestPipeline(ScriptedLLM([]), session, fx["repo"], + PipelineOptions(remediation=FIX), runner=FakeRunner()) + result = asyncio.run(pipeline.run([verified_idor_finding()]))[0] + assert result.status is Status.GENERATION_FAILED and "cancelled" in result.reason + + +# ── remediation availability ── + +def test_without_a_fix_the_test_is_kept_pending(tmp_path): + run = run_pipeline(tmp_path, [submit()], remediation=None) + result = run.result + + assert result.status is Status.REMEDIATION_UNAVAILABLE + assert result.reproduces_vulnerability + assert "reproduces the vulnerability" in result.reason + assert f"openhack --regression-tests {run.session.id} " in result.reason + assert result.validation["remediated"] is None + assert run.runner.runs_for("remediated") == [] + assert (tmp_path / "artifacts").exists() and result.artifacts["patch"].endswith(".patch") + + +def test_fix_identical_to_the_vulnerable_code(tmp_path): + run = run_pipeline(tmp_path, [submit()], remediation=RevisionSpec.git("main")) + assert run.result.status is Status.REMEDIATION_UNAVAILABLE + assert "identical to the vulnerable revision" in run.result.reason + + +def test_unknown_fix_revision(tmp_path): + run = run_pipeline(tmp_path, [submit()], remediation=RevisionSpec.git("fix/typo")) + assert run.result.status is Status.REMEDIATION_UNAVAILABLE + assert "could not be prepared" in run.result.reason and "fix/typo" in run.result.reason + + +def test_pending_test_is_revalidated_without_another_llm_call(tmp_path): + pending = run_pipeline(tmp_path, [submit()], remediation=None) + finding = pending.findings[0] + assert finding.regression_test["status"] == "remediation_unavailable" + + session = Session(str(pending.repo), persist_events=False) + llm = ScriptedLLM([]) + runner = FakeRunner() + pipeline = RegressionTestPipeline( + llm, session, pending.repo, + PipelineOptions(vulnerable=RevisionSpec.git(pending.fx["vulnerable_sha"]), remediation=FIX, + artifacts_root=tmp_path / "artifacts2"), + runner=runner, + ) + result = asyncio.run(pipeline.run([finding]))[0] + + assert result.status is Status.VALIDATED + assert llm.calls == 0 and result.attempts == 0 + assert result.test_code == pending.result.test_code + + +def test_pending_test_already_committed_with_the_fix_is_accepted(tmp_path): + pending = run_pipeline(tmp_path, [submit()], remediation=None) + repo = pending.repo + git(repo, "checkout", "-q", FIX_BRANCH) + write_file(repo, TEST_PATH, pending.result.test_code) + git(repo, "add", TEST_PATH) + git(repo, "commit", "-q", "-m", "Add regression test") + git(repo, "checkout", "-q", "main") + + llm = ScriptedLLM([]) + pipeline = RegressionTestPipeline( + llm, Session(str(repo), persist_events=False), repo, + PipelineOptions(remediation=FIX, artifacts_root=tmp_path / "a2"), runner=FakeRunner(), + ) + result = asyncio.run(pipeline.run(pending.findings))[0] + assert result.status is Status.VALIDATED and llm.calls == 0 + + +def test_pending_test_failing_on_the_fix_reports_incomplete_remediation(tmp_path): + pending = run_pipeline(tmp_path, [submit()], remediation=None) + + def still_vulnerable(label, code, run_index): + outcomes = realistic_idor(label, code, run_index) + if label == "remediated": + outcomes["test_other_user_cannot_modify_note"] = "failed" + return outcomes + + llm = ScriptedLLM([]) + pipeline = RegressionTestPipeline( + llm, Session(str(pending.repo), persist_events=False), pending.repo, + PipelineOptions(remediation=FIX, artifacts_root=tmp_path / "a2"), runner=FakeRunner(still_vulnerable), + ) + result = asyncio.run(pipeline.run(pending.findings))[0] + assert result.status is Status.VALIDATION_FAILED + assert "remediation is incomplete" in result.reason and llm.calls == 0 + + +def test_stale_pending_test_is_regenerated_with_context(tmp_path): + pending = run_pipeline(tmp_path, [submit()], remediation=None) + stale_code = pending.result.test_code + + def stale(label, code, run_index): + outcomes = realistic_idor(label, code, run_index) + if code == stale_code: + return {name: "passed" for name in outcomes} + return outcomes + + llm = ScriptedLLM([submit(GOOD_TEST + "\n# regenerated\n", call_id="regen")]) + pipeline = RegressionTestPipeline( + llm, Session(str(pending.repo), persist_events=False), pending.repo, + PipelineOptions(remediation=FIX, artifacts_root=tmp_path / "a2"), runner=FakeRunner(stale), + ) + result = asyncio.run(pipeline.run(pending.findings))[0] + assert result.status is Status.VALIDATED and result.attempts == 1 + first_prompt = next(m.content for m in llm.requests[0] if m.role == "user") + assert "failed re-validation" in first_prompt and "Previous test" in first_prompt + + +# ── evaluate_runs ── + +def _report(**outcomes): + return RunReport(cases=[ + CaseOutcome(name, "tests.test_x", outcome, "AssertionError" if outcome == "failed" else "", + assertion=outcome == "failed") + for name, outcome in outcomes.items() + ], exit_code=0) + + +SUBMISSION = CandidateTest("tests/test_x.py", "", ["test_inv"], ["test_ctl"]) + + +@pytest.mark.parametrize("outcomes,expected", [ + ({"test_inv": "failed", "test_ctl": "passed", "test_extra": "passed"}, "neither declared invariant nor control"), + ({"test_inv": "failed"}, "declared tests were not collected: test_ctl"), + ({"test_inv": "failed", "test_ctl": "skipped"}, "errored or were skipped"), +]) +def test_evaluate_runs_requires_a_complete_declared_suite(outcomes, expected): + check = evaluate_runs([_report(**outcomes)], SUBMISSION, "vulnerable", True, 60) + assert not check.passed and expected in check.detail + + +def test_evaluate_runs_requires_a_control_test(): + submission = CandidateTest("tests/test_x.py", "", ["test_inv"], []) + check = evaluate_runs([_report(test_inv="failed")], submission, "vulnerable", True, 60) + assert not check.passed and "control test" in check.detail + assert evaluate_runs([_report(test_inv="failed")], submission, "vulnerable", False, 60).passed + + +def test_evaluate_runs_parametrized_tests_match_by_base_name(): + reports = [_report(**{"test_inv[read]": "failed", "test_inv[delete]": "failed", "test_ctl": "passed"})] + assert evaluate_runs(reports, SUBMISSION, "vulnerable", True, 60).passed diff --git a/tests/test_regression_workspace.py b/tests/test_regression_workspace.py new file mode 100644 index 0000000..db2c542 --- /dev/null +++ b/tests/test_regression_workspace.py @@ -0,0 +1,144 @@ +"""Revision workspaces: materializing vulnerable and remediated code safely.""" + +import os +import subprocess + +import pytest + +from openhack.regression import workspace +from openhack.regression.workspace import ( + RevisionSpec, + WorkspaceError, + git_info, + is_excluded_path, + materialize, + new_file_patch, +) +from tests.conftest import write_file +from tests.regression_support import FIX_BRANCH, FIXTURE_APP, git, make_fixture_repo + + +@pytest.fixture +def fixture_repo(tmp_path): + return make_fixture_repo(tmp_path) + + +def test_git_revisions_materialize_exact_commit_contents(fixture_repo, tmp_path): + repo = fixture_repo["repo"] + vulnerable = materialize(repo, RevisionSpec.git(fixture_repo["vulnerable_sha"]), tmp_path / "v") + fixed = materialize(repo, RevisionSpec.git(FIX_BRANCH), tmp_path / "f") + + assert vulnerable.resolved == fixture_repo["vulnerable_sha"] + assert fixed.resolved == fixture_repo["fixed_sha"] + assert (vulnerable.root / "app.py").read_text() == (FIXTURE_APP / "vulnerable" / "app.py").read_text() + assert (fixed.root / "app.py").read_text() == (FIXTURE_APP / "fixed_app.py").read_text() + assert (fixed.root / "tests" / "conftest.py").is_file() + assert vulnerable.fingerprint != fixed.fingerprint + assert fixed.label == f"{FIX_BRANCH} ({fixture_repo['fixed_sha'][:12]})" + assert vulnerable.label == fixture_repo["vulnerable_sha"][:12] + # The user's checkout is untouched. + assert git(repo, "status", "--porcelain") == "" + assert git(repo, "rev-parse", "--abbrev-ref", "HEAD") == "main" + + +def test_git_revisions_ignore_export_attributes(fixture_repo, tmp_path): + repo = fixture_repo["repo"] + write_file(repo, ".gitattributes", "tests export-ignore\napp.py export-subst\n") + git(repo, "add", ".gitattributes") + git(repo, "commit", "-q", "-m", "release tarball settings") + copy = materialize(repo, RevisionSpec.git("HEAD"), tmp_path / "c") + assert (copy.root / "tests" / "test_notes.py").is_file() + assert (copy.root / "app.py").read_text() == (repo / "app.py").read_text() + + +def test_identical_trees_share_a_fingerprint(fixture_repo, tmp_path): + repo = fixture_repo["repo"] + a = materialize(repo, RevisionSpec.git("main"), tmp_path / "a") + b = materialize(repo, RevisionSpec.worktree(), tmp_path / "b") + assert a.fingerprint == b.fingerprint + + +def test_worktree_snapshot_honors_gitignore_and_skips_credentials(fixture_repo, tmp_path): + repo = fixture_repo["repo"] + write_file(repo, ".gitignore", "build/\n") + write_file(repo, "build/artifact.py", "x = 1\n") + write_file(repo, "untracked_module.py", "y = 2\n") + write_file(repo, ".env", "SECRET_KEY=real-production-secret\n") + write_file(repo, ".env.example", "SECRET_KEY=change-me\n") + write_file(repo, "certs/server.key", "-----BEGIN PRIVATE KEY-----\n") + write_file(repo, "node_modules/left-pad/index.js", "module.exports = 1\n") + os.symlink("/etc/passwd", repo / "passwd_link") + + copy = materialize(repo, RevisionSpec.worktree(), tmp_path / "w") + files = {p.relative_to(copy.root).as_posix() for p in copy.root.rglob("*") if p.is_file()} + + assert "untracked_module.py" in files and ".env.example" in files and "app.py" in files + for absent in (".env", "certs/server.key", "build/artifact.py", "passwd_link"): + assert absent not in files + assert not any(f.startswith(("node_modules/", ".git/")) for f in files) + assert copy.resolved.startswith("working tree @ ") + + +def test_directory_revisions(tmp_path): + write_file(tmp_path / "fixed", "app.py", "print('fixed')\n") + write_file(tmp_path / "fixed", ".venv/lib/x.py", "") + spec = RevisionSpec.parse("fixed", base_dir=tmp_path) + assert spec.kind == "directory" + copy = materialize(tmp_path, spec, tmp_path / "out") + assert copy.file_count == 1 and (copy.root / "app.py").is_file() + + +def test_revision_spec_parse_defaults_to_git(): + assert RevisionSpec.parse("fix/idor-notes") == RevisionSpec.git("fix/idor-notes") + with pytest.raises(WorkspaceError): + RevisionSpec.parse(" ") + + +def test_unknown_git_revision_is_a_workspace_error(fixture_repo, tmp_path): + with pytest.raises(WorkspaceError, match="is not a commit"): + materialize(fixture_repo["repo"], RevisionSpec.git("no-such-branch"), tmp_path / "x") + + +def test_git_revision_outside_a_repository(tmp_path): + write_file(tmp_path / "plain", "app.py", "") + with pytest.raises(WorkspaceError, match="not a git repository"): + materialize(tmp_path / "plain", RevisionSpec.git("main"), tmp_path / "x") + + +def test_size_limits_are_enforced(fixture_repo, tmp_path, monkeypatch): + monkeypatch.setattr(workspace, "MAX_FILES", 2) + with pytest.raises(WorkspaceError, match="more than 2 files"): + materialize(fixture_repo["repo"], RevisionSpec.git("main"), tmp_path / "x") + + +def test_subdirectory_targets_use_the_matching_subtree(tmp_path): + repo = tmp_path / "mono" + write_file(repo, "services/api/app.py", "print('api')\n") + write_file(repo, "web/index.js", "1\n") + git(repo, "init", "-q", "-b", "main") + git(repo, "-c", "user.email=a@b.c", "-c", "user.name=a", "add", "-A") + git(repo, "-c", "user.email=a@b.c", "-c", "user.name=a", "commit", "-q", "-m", "init") + target = repo / "services" / "api" + assert git_info(target)["prefix"] == "services/api" + copy = materialize(target, RevisionSpec.git("HEAD"), tmp_path / "x") + assert {p.name for p in copy.root.iterdir()} == {"app.py"} + + +@pytest.mark.parametrize("path,excluded", [ + ("app.py", False), (".env.example", False), ("config/settings.py", False), + (".env", True), (".env.production", True), ("keys/deploy.pem", True), + ("home/.ssh/id_ed25519", True), (".aws/credentials", True), (".npmrc", True), + ("pkg.egg-info/PKG-INFO", True), (".openhack-sandbox-override-x.yml", True), +]) +def test_is_excluded_path(path, excluded): + assert is_excluded_path(path) is excluded + + +def test_new_file_patch_applies_with_git(fixture_repo): + repo = fixture_repo["repo"] + content = "def test_x():\n assert True" + patch = repo.parent / "add-test.patch" + patch.write_text(new_file_patch("tests/test_security_idor_note.py", content)) + subprocess.run(["git", "-C", str(repo), "apply", "--check", str(patch)], check=True) + subprocess.run(["git", "-C", str(repo), "apply", str(patch)], check=True) + assert (repo / "tests" / "test_security_idor_note.py").read_text() == content + "\n" From b2917d3347ef2ad62dedbcb4ab6023fd987c385b Mon Sep 17 00:00:00 2001 From: officialfrancismendoza Date: Sat, 14 Nov 2026 16:12:16 +0700 Subject: [PATCH 2/2] Updated with fixes from Greptile feedback (#41) --- docs/REGRESSION_TESTS.md | 46 +++++--- openhack/agents/coordinator.py | 4 +- openhack/headless_scan.py | 5 +- openhack/regression/frameworks.py | 110 +++++++++++++++--- openhack/regression/pipeline.py | 65 ++++++++--- openhack/regression/workspace.py | 27 ++++- openhack/sandbox/container_runner.py | 130 +++++++++++++++++++--- openhack/tui.py | 14 ++- tests/regression_support.py | 30 +++-- tests/test_regression_e2e_docker.py | 66 +++++++++++ tests/test_regression_frameworks.py | 91 +++++++++++++-- tests/test_regression_lifecycle.py | 35 +++++- tests/test_regression_pipeline.py | 74 ++++++++++++ tests/test_regression_sandbox_runner.py | 142 ++++++++++++++++++++++++ tests/test_regression_workspace.py | 16 +++ 15 files changed, 765 insertions(+), 90 deletions(-) create mode 100644 tests/test_regression_sandbox_runner.py diff --git a/docs/REGRESSION_TESTS.md b/docs/REGRESSION_TESTS.md index 17e21a9..ea144f2 100644 --- a/docs/REGRESSION_TESTS.md +++ b/docs/REGRESSION_TESTS.md @@ -125,9 +125,10 @@ and the patch path. `/copy` includes the test in the AI-fix prompt. **control tests** (legitimate access, expected to pass on both versions). 3. **Checks before anything runs.** The test must be a new file under your existing test directory that pytest will discover. It can never overwrite, - modify or delete an existing test. A static policy rejects skips and - xfails, swallowed assertions, network or subprocess use, dynamic code - execution, sleeps, pytest hooks, and embedded credentials. + modify or delete an existing test, or reuse the file of another finding's + test, so the patches for several findings apply together. A static policy + rejects skips and xfails, swallowed assertions, network or subprocess use, + dynamic code execution, sleeps, pytest hooks, and embedded credentials. 4. **Sandbox validation.** For each revision, OpenHack builds an image from a private copy of that revision plus your project's own test dependencies, then runs the test in a fresh locked-down container (by default twice per @@ -137,7 +138,12 @@ and the patch path. `/copy` includes the test in the AI-fix prompt. fixture, skip or error doesn't count; - on the **remediated** code, every test passes; - every declared test ran, and all runs of a revision produced identical - outcomes. + outcomes; + - every run ended with the exit status its results imply (pytest exits 1 + on the vulnerable code and 0 on the remediated code). A session that a + plugin or session fixture fails after the tests pass is rejected. + Coverage thresholds don't apply to these single-file runs: when + pytest-cov is installed, it runs with `--no-cov`. 5. **Feedback.** A rejected test is sent back to the generator with the precise reason and per-test outcomes, up to `regression_tests_max_attempts` times. One case is never retried: if an invariant test still fails its @@ -152,24 +158,32 @@ untrusted. They only ever execute inside a container started with: - `--network none`. Dependencies are installed during the image build, but the test run can't reach the network. -- No host mounts. The test goes in, and results come out, via `docker cp`. +- No host mounts. The test goes in via `docker cp`. Results come back as a + stream capped at 16 MB, and only regular files are written to the host, so + a symlink planted in the results never reaches it. A run whose results + exceed the cap is rejected. - A non-root user (`65534`), `--cap-drop ALL` and `no-new-privileges`. -- Memory, CPU and PID limits, plus a wall-clock timeout after which the - container is killed. +- Memory, CPU and PID limits, a 64 MB limit on any file the run writes, no + core dumps, and a wall-clock timeout after which the container is killed. +- The container is never attached and keeps no logs (`--log-driver none`), + so nothing the test prints is buffered on the host. - A fresh container per run, always removed afterwards. Images are removed when the run finishes. The private workspace copies leave out `.env` files (templates like `.env.example` are kept), private keys, `.npmrc`/`.pypirc`/`.netrc`, cloud -credential directories, symlinks and git submodules. Your checkout is never -modified. +credential directories, git submodules, and symlinks, including any path +through a symlinked directory. Your checkout is never modified. ## Results and artifacts Every finding gets a `regressionTest` entry in the scan report (`~/.openhack/scans/.json`). It holds the status, the reason, the invariant, the test path and code, the run command, and per-revision -outcomes. Verified findings also carry their redacted `exploitEvidence`. +outcomes. For validated and pending tests, `artifacts.repo_path` is the +test's path from the repository root. It differs from the test path when the +finding is in a subproject of a monorepo. Verified findings also carry their +redacted `exploitEvidence`. Validated and pending tests are written, owner-only, to `~/.openhack/scans/artifacts//regression-tests//`: @@ -200,9 +214,11 @@ artifacts. - **Vulnerability classes:** IDOR / broken object-level authorization (CWE-639). - **Test frameworks:** pytest (Python), including Flask, FastAPI, Starlette and - pytest-django projects. Requirements files (including `-r`/`-c` includes), - `pyproject.toml` test extras and installable projects are supported, and so - are monorepos: the project containing the finding is used. + pytest-django projects. Requirements files are supported, with `-r` + includes, `-c` constraints (which only constrain versions and are never + installed as requirements) and lines that install the project itself, such + as `-e .`. So are `pyproject.toml` test extras, installable projects and + monorepos: the project containing the finding is used. - **Not yet supported** (reported as unsupported): other vulnerability classes; Jest, Vitest, Mocha and other JavaScript runners; Go `testing`; JUnit; RSpec; PHPUnit; and Django's `manage.py test` runner without pytest. @@ -227,6 +243,10 @@ test framework, subclass `FrameworkAdapter` in is. A test runs inside the same process as pytest, so result integrity also relies on the policy and on cross-checking declared tests against reported outcomes. +- Docker has no portable way to cap a container's total disk use. Each file a + run writes is limited to 64 MB and the run to its timeout, but a hostile + test can still use disk inside Docker until it is killed and its container + removed. - During a scan, the vulnerable revision is the working tree that was scanned. - Only one test file is generated per finding, and existing tests are never edited. diff --git a/openhack/agents/coordinator.py b/openhack/agents/coordinator.py index 4ff5540..41f196c 100644 --- a/openhack/agents/coordinator.py +++ b/openhack/agents/coordinator.py @@ -38,7 +38,6 @@ from openhack.categories import normalize_category, normalize_severity from openhack.framework_detection import detect_frameworks from openhack.quality import run_quality_gates -from openhack.regression.evidence import sanitize_exploit_evidence # Static validator removed — line number correction in hunter, semantic validation by LLM from openhack.config import settings @@ -927,6 +926,9 @@ async def run_pass2(task_text, batch_idx): r.get("finding_index") for r in exploitable } + # Imported here: openhack.regression imports from this package. + from openhack.regression.evidence import sanitize_exploit_evidence + for r in exploitable: idx = r.get("finding_index") if idx is not None and idx < len(self.session.findings): diff --git a/openhack/headless_scan.py b/openhack/headless_scan.py index 23c0d92..0949267 100644 --- a/openhack/headless_scan.py +++ b/openhack/headless_scan.py @@ -48,8 +48,9 @@ def format_regression_status(finding: Finding) -> list[str]: if not isinstance(data, dict): return [] lines = [f"Regression test: {data.get('status_label') or data.get('status')}"] - if data.get("test_path") and data.get("status") in ("validated", "remediation_unavailable"): - lines[0] += f" — {data['test_path']}" + path = (data.get("artifacts") or {}).get("repo_path") or data.get("test_path") + if path and data.get("status") in ("validated", "remediation_unavailable"): + lines[0] += f" — {path}" if data.get("reason"): lines.append(f" {data['reason']}") patch = (data.get("artifacts") or {}).get("patch") diff --git a/openhack/regression/frameworks.py b/openhack/regression/frameworks.py index 308dcb7..87df2c9 100644 --- a/openhack/regression/frameworks.py +++ b/openhack/regression/frameworks.py @@ -51,7 +51,12 @@ class FrameworkProfile: test_dir: str file_patterns: list[str] config_file: Optional[str] = None + # Every file the dependency install reads (including -r/-c includes), and + # the subset installed as requirements. dependency_files: list[str] = field(default_factory=list) + requirement_files: list[str] = field(default_factory=list) + # A requirement installs from the project's own files (`-e .`, `./libs/x`). + requirements_need_source: bool = False installable_project: bool = False install_extras: list[str] = field(default_factory=list) fixtures: dict[str, str] = field(default_factory=dict) @@ -85,6 +90,8 @@ class RunReport: exit_code: Optional[int] = None timed_out: bool = False collection_error: Optional[str] = None + # The runner's exit status contradicts the per-test results. + session_error: Optional[str] = None output_tail: str = "" def outcomes(self) -> dict[str, str]: @@ -186,7 +193,8 @@ def _posix(path: Path | PurePosixPath | str) -> str: def _xml_is_safe(text: str) -> bool: - lowered = text[:4096].lower() + # The whole (size-capped) document: comments of any length may precede a DTD. + lowered = text.lower() return " bool: "requirements-test.txt", "requirements_test.txt", "requirements-tests.txt", "dev-requirements.txt", "test-requirements.txt", "requirements-testing.txt", ) +_ARCHIVE_SUFFIXES = (".whl", ".zip", ".tar.gz", ".tgz", ".tar.bz2") _TEST_EXTRAS = ("test", "tests", "testing", "dev") _APP_FRAMEWORKS = ( "flask", "django", "fastapi", "starlette", "quart", "aiohttp", "tornado", @@ -264,6 +273,29 @@ def _dotted(node: ast.AST) -> str: return "" +def _installs_from_project(requirements: str) -> bool: + """Whether requirements install from the project's own files. + + `-e .`, `./libs/shared`, `pkg @ file:...` or `--find-links ./wheels` need + the source tree in place before pip runs. + """ + for raw in re.sub(r"\\\r?\n", " ", requirements).splitlines(): + line = re.split(r"(?:^|\s)#", raw, maxsplit=1)[0].strip() + option = re.match(r"(?:-e|--editable|-f|--find-links)(?:\s*=\s*|\s*)(\S+)", line) + if not line or (option is None and line.startswith("-")): + continue # other pip options: -r, -c, --index-url, ... + if "file:" in line: + return True + target = option.group(1) if option else line.split()[0].split(";")[0] + if "://" in target or re.match(r"(?:git|hg|svn|bzr)\+", target): + continue # a remote URL or VCS checkout + if option or target.startswith((".", "/", "~")) or "/" in target or "\\" in target: + return True + if target.lower().endswith(_ARCHIVE_SUFFIXES): + return True + return False + + def _module_root_forbidden(module: str) -> Optional[str]: for name, why in _FORBIDDEN_MODULES.items(): if module == name or module.startswith(name + "."): @@ -287,10 +319,10 @@ def detect(self, repo_root: Path, hint_path: Optional[str] = None) -> Optional[F config_file, ini = self._pytest_config(project) test_files = [p for p in self._test_files(project, ini)] conftests = list(_iter_files(project, "conftest.py")) - deps = self._dependency_files(project) + requirement_files, deps = self._dependency_files(project) pyproject = self._load_pyproject(project) - dep_text = "\n".join(_read(project / d) for d in deps).lower() - dep_text += "\n" + json.dumps(pyproject).lower() + requirements_text = "\n".join(_read(project / d) for d in deps) + dep_text = requirements_text.lower() + "\n" + json.dumps(pyproject).lower() # Any pytest-ecosystem package (pytest, pytest-django, ...) counts. has_pytest_dep = bool(re.search(r"(? Optional[F file_patterns=self._patterns(ini), config_file=config_file, dependency_files=deps, + requirement_files=requirement_files, + requirements_need_source=_installs_from_project(requirements_text), installable_project=installable, install_extras=extras, fixtures=self._fixtures(project, conftests), @@ -417,26 +451,41 @@ def _test_dir(self, project: Path, ini: dict, test_files: list[Path]) -> str: return "tests" @staticmethod - def _dependency_files(project: Path) -> list[str]: - files: list[str] = [n for n in _REQUIREMENTS_NAMES if (project / n).is_file()] + def _dependency_files(project: Path) -> tuple[list[str], list[str]]: + """The requirement files to install, and every file the install reads. + + `-r other.txt` / `-c constraints.txt` includes are followed so the + image build has every file they reference. A constraints file is only + copied, never installed: it pins versions of packages the project may + not use at all, so installing it as requirements could fail a build + the project's own install passes. + """ + roots: list[str] = [n for n in _REQUIREMENTS_NAMES if (project / n).is_file()] req_dir = project / "requirements" if req_dir.is_dir(): - files += sorted(_posix(p.relative_to(project)) for p in req_dir.glob("*.txt")) - # Follow `-r other.txt` / `-c constraints.txt` includes so the image - # build sees every file the listed requirements reference. + roots += sorted( + _posix(p.relative_to(project)) for p in req_dir.glob("*.txt") + if "constraint" not in p.name.lower() + ) + files = list(roots) + constraints: set[str] = set() queue = list(files) while queue: current = queue.pop() base = PurePosixPath(current).parent for line in _read(project / current).splitlines(): - match = re.match(r"\s*(?:-r|--requirement|-c|--constraint)\s*=?\s*(\S+)", line) + match = re.match(r"\s*(-r|--requirement|-c|--constraint)\s*=?\s*(\S+)", line) if not match: continue - include = _posix(base / match.group(1)) - if include not in files and ".." not in include and (project / include).is_file(): + include = _posix(base / match.group(2)) + if ".." in include or not (project / include).is_file(): + continue + if match.group(1) in ("-c", "--constraint"): + constraints.add(include) + if include not in files: files.append(include) queue.append(include) - return files + return [f for f in roots if f not in constraints], files @staticmethod def _load_pyproject(project: Path) -> dict: @@ -616,13 +665,21 @@ def dockerfile(self, profile, base_image) -> str: "PIP_NO_INPUT=1 PIP_ROOT_USER_ACTION=ignore", f"WORKDIR {workdir}", ] - if profile.dependency_files: + install = "RUN pip install --no-cache-dir " + " ".join( + f"-r {json.dumps(d)}" for d in profile.requirement_files + ) + # Installing before the source is copied keeps the dependencies in a + # cached layer that the other revision's image can reuse. Requirements + # such as `-e .` install from the project's own files, so they wait. + early = bool(profile.requirement_files) and not profile.requirements_need_source + if early: for dep in profile.dependency_files: src = dep if root == "." else f"{root}/{dep}" lines.append(f"COPY {json.dumps([src, f'{workdir}/{dep}'])}") - flags = " ".join(f"-r {json.dumps(d)}" for d in profile.dependency_files) - lines.append(f"RUN pip install --no-cache-dir {flags}") + lines.append(install) lines.append('COPY [".", "/workspace"]') + if profile.requirement_files and not early: + lines.append(install) if profile.installable_project: target = "." + (f"[{','.join(profile.install_extras)}]" if profile.install_extras else "") lines.append( @@ -639,9 +696,13 @@ def container_command(self, profile, test_relpath) -> list[str]: # Output goes to a file so a noisy test can't flood the host, and the # repository's own pytest configuration (rootdir, conftest, plugins) # still applies. --maxfail overrides any `-x` in addopts so every - # declared test reports an outcome. + # declared test reports an outcome. A coverage threshold in addopts + # would fail a one-file session whose tests all pass, so pytest-cov's + # --no-cov is added (only when pytest-cov is installed, as it is + # otherwise an unknown option). script = ( - 'python -m pytest "$1" -p no:cacheprovider --maxfail=100000 ' + 'if python -c "import pytest_cov" 2>/dev/null; then set -- "$1" --no-cov; fi; ' + 'python -m pytest "$@" -p no:cacheprovider --maxfail=100000 ' f"-o junit_family=xunit2 --junitxml={RESULTS_DIR}/junit.xml " f"> {RESULTS_DIR}/output.txt 2>&1" ) @@ -708,6 +769,19 @@ def parse_results(self, results_dir: Path, exit_code: Optional[int], timed_out: report.cases.append(CaseOutcome(name, classname, outcome, message, assertion)) if not report.cases and report.collection_error is None: report.collection_error = f"no tests were collected. Output:\n{output[-2000:]}" + if report.collection_error is None: + # pytest exits 0 when every test passed and 1 when some failed. + # Anything else means the session itself failed or was altered + # (a plugin, a session fixture, or the project's configuration), + # even though the results file was written. + failed = any(c.outcome in ("failed", "error") for c in report.cases) + expected = 1 if failed else 0 + if exit_code != expected: + state = "some tests failed" if failed else "every test passed" + report.session_error = ( + f"pytest exited with code {exit_code} although {state} (expected {expected}), " + "so something outside the test cases failed or altered the session" + ) return report diff --git a/openhack/regression/pipeline.py b/openhack/regression/pipeline.py index 85c6e3e..faa8d51 100644 --- a/openhack/regression/pipeline.py +++ b/openhack/regression/pipeline.py @@ -96,6 +96,8 @@ class RevisionCheck: outcomes: dict[str, str] = field(default_factory=dict) failures: dict[str, str] = field(default_factory=dict) output_tail: str = "" + # The runner's output explains the problem better than per-test outcomes. + show_output: bool = False def to_dict(self, revision: MaterializedRevision) -> dict: return { @@ -118,15 +120,26 @@ def evaluate_runs( """Judge repeated runs of a candidate test against one revision. ``expect="vulnerable"``: controls pass and at least one invariant test - fails on an assertion. ``expect="remediated"``: every test passes. + fails on an assertion. ``expect="remediated"``: every test passes. Either + way every run must end with the exit status its results imply. """ first = reports[0] outcomes = first.outcomes() failures = {c.name: c.message for c in first.cases if c.outcome != "passed" and c.message} deterministic = all(r.outcomes() == outcomes for r in reports[1:]) - def result(passed: bool, detail: str, retryable: bool = True) -> RevisionCheck: - return RevisionCheck(passed, detail, retryable, deterministic, outcomes, failures, first.output_tail) + def result(passed: bool, detail: str, retryable: bool = True, + report: Optional[RunReport] = None) -> RevisionCheck: + tail = (report or first).output_tail + return RevisionCheck(passed, detail, retryable, deterministic, outcomes, failures, tail, + show_output=report is not None) + + def finished_cleanly(detail: str) -> RevisionCheck: + unclean = next((r for r in reports if r.session_error), None) + if unclean is not None: + return result(False, f"the test run did not finish cleanly: {unclean.session_error}", + report=unclean) + return result(True, detail) if any(r.timed_out for r in reports): return result(False, f"the test run timed out after {timeout}s (does it block, sleep or need the network?)") @@ -185,8 +198,7 @@ def result(passed: bool, detail: str, retryable: bool = True) -> RevisionCheck: f"invariant test(s) {', '.join(crashed)} failed with an unexpected exception rather than " "an assertion, so it is not the security property that failed", ) - return result( - True, + return finished_cleanly( f"{len(failed)} invariant test(s) failed on assertions while {len(control)} control test(s) passed", ) @@ -209,7 +221,7 @@ def result(passed: bool, detail: str, retryable: bool = True) -> RevisionCheck: "test(s) failed on the REMEDIATED code: " + ", ".join(c.name for c in failing) + ". The test setup must work against the fixed code too", ) - return result(True, f"all {len(first.cases)} test(s) passed") + return finished_cleanly(f"all {len(first.cases)} test(s) passed") def _feedback(stage: str, check: RevisionCheck) -> str: @@ -220,7 +232,7 @@ def _feedback(stage: str, check: RevisionCheck) -> str: )) for name, message in list(check.failures.items())[:6]: lines.append(f"--- {name} ---\n{message[-800:]}") - if not check.outcomes and check.output_tail: + if check.output_tail and (check.show_output or not check.outcomes): lines.append(f"Test output (tail):\n{check.output_tail[-1500:]}") lines.append( "Keep every invariant test that covers an operation on the object; fix setup or " @@ -229,6 +241,11 @@ def _feedback(stage: str, check: RevisionCheck) -> str: return "\n".join(lines) +def _project_path(profile: FrameworkProfile, rel: str) -> str: + """A path relative to the test project, made relative to the scanned directory.""" + return rel if profile.project_root == "." else f"{profile.project_root}/{rel}" + + def _with_provenance(code: str, invariant: SecurityInvariant) -> str: """Normalize line endings and credit the test's origin in a header comment.""" code = code.replace("\r\n", "\n") @@ -311,6 +328,9 @@ def __init__( self.runner = runner or ContainerTestRunner(self.options.limits) self.run_id = uuid4().hex[:10] self.git = git_info(self.target_dir) + # Test file of each accepted finding: two patches that add the same + # file could not both be applied. + self._claimed_paths: dict[str, str] = {} @property def total_cost(self) -> float: @@ -468,14 +488,13 @@ async def _process( content={"title": finding.title, "class": spec.key, "endpoint": f"{invariant.method} {invariant.path_template}"}, ) - root = profile.project_root - def repo_path(rel: str) -> str: - return rel if root == "." else f"{root}/{rel}" + def claimed_by_another_finding(rel: str) -> bool: + return self._claimed_paths.get(_project_path(profile, rel), finding.id) != finding.id def available(rel: str, stored_code: Optional[str] = None) -> bool: - path = repo_path(rel) - if vulnerable.exists(path): + path = _project_path(profile, rel) + if vulnerable.exists(path) or claimed_by_another_finding(rel): return False if remediated is not None and remediated.exists(path): # The developer may have committed our pending test alongside @@ -550,6 +569,11 @@ def outcome(status: RegressionTestStatus, reason: str) -> RegressionTestResult: path_error = adapter.validate_test_path(profile, candidate.path) if path_error: problems.append(path_error) + elif claimed_by_another_finding(candidate.path): + problems.append( + f"`{candidate.path}` is already the regression test for another finding; " + f"use a new file such as `{suggested}`" + ) elif not available(candidate.path, candidate.code if candidate_is_stored else None): problems.append( f"`{candidate.path}` already exists in the repository; existing tests are never " @@ -651,13 +675,15 @@ async def _validate( async def _run_once(self, image: str, adapter: FrameworkAdapter, profile: FrameworkProfile, candidate: CandidateTest) -> RunReport: root = profile.project_root - rel_in_repo = candidate.path if root == "." else f"{root}/{candidate.path}" workdir = "/workspace" if root == "." else f"/workspace/{root}" run = await self.runner.run_test( - image, {rel_in_repo: candidate.code}, + image, {_project_path(profile, candidate.path): candidate.code}, adapter.container_command(profile, candidate.path), workdir=workdir, ) try: + if run.results_error: + return RunReport(exit_code=run.exit_code, timed_out=run.timed_out, + collection_error=run.results_error) return adapter.parse_results(run.results_dir, run.exit_code, run.timed_out) finally: run.cleanup() @@ -690,14 +716,19 @@ def _accept( result.control_tests = list(candidate.control_tests) result.summary = candidate.summary result.validation = validation + self._claimed_paths[_project_path(profile, candidate.path)] = finding.id + parts = [p for p in (self.git.get("prefix", ""), profile.project_root, candidate.path) if p and p != "."] + # Kept even if the files below can't be written: it says where the + # test belongs in the repository. + result.artifacts = {"repo_path": PurePosixPath(*parts).as_posix()} try: - result.artifacts = self._write_artifacts(finding, result, profile) + result.artifacts = self._write_artifacts(finding, result, result.artifacts["repo_path"]) except OSError as exc: logger.warning(f"Could not write regression test artifacts: {exc}") return result def _write_artifacts(self, finding: Finding, result: RegressionTestResult, - profile: FrameworkProfile) -> dict[str, str]: + repo_path: str) -> dict[str, str]: root = self.options.artifacts_root or default_artifacts_root(self.session) session_dir = root / (self.options.report_id or self.session.id) art_dir = session_dir / "regression-tests" / finding.id[:8] @@ -707,8 +738,6 @@ def _write_artifacts(self, finding: Finding, result: RegressionTestResult, os.chmod(directory, 0o700) except OSError: pass - parts = [p for p in (self.git.get("prefix", ""), profile.project_root, result.test_path) if p and p != "."] - repo_path = PurePosixPath(*parts).as_posix() test_file = art_dir / repo_path patch = art_dir / "regression-test.patch" write_private_file(test_file, result.test_code or "") diff --git a/openhack/regression/workspace.py b/openhack/regression/workspace.py index a420e4a..47c23b3 100644 --- a/openhack/regression/workspace.py +++ b/openhack/regression/workspace.py @@ -202,16 +202,35 @@ def fingerprint(self) -> str: return digest.hexdigest() +def _regular_file(source: Path, rel: str) -> Optional[Path]: + """``source / rel`` if it is a regular file reached without any symlink. + + Symlinks are skipped because one pointing outside the tree would smuggle + host files into the build context. Every component is checked, not just + the last: git's index still lists the files of a tracked directory that + was replaced by a symlink. + """ + relpath = PurePosixPath(rel) + if relpath.is_absolute() or ".." in relpath.parts: + return None + path = source + for part in relpath.parts: + path = path / part + if path.is_symlink(): + return None + if not path.is_relative_to(source) or not path.is_file(): + return None + return path + + def _copy_tree_files(source: Path, relpaths: list[str], copier: _Copier) -> None: source = source.resolve() for rel in relpaths: rel = PurePosixPath(rel).as_posix() if is_excluded_path(rel): continue - path = source / rel - # Symlinks are skipped: one pointing outside the tree would otherwise - # smuggle host files into the build context. - if path.is_symlink() or not path.is_file(): + path = _regular_file(source, rel) + if path is None: continue with open(path, "rb") as stream: copier.add(rel, stream, executable=os.access(path, os.X_OK)) diff --git a/openhack/sandbox/container_runner.py b/openhack/sandbox/container_runner.py index ea498e9..7e56313 100644 --- a/openhack/sandbox/container_runner.py +++ b/openhack/sandbox/container_runner.py @@ -10,20 +10,24 @@ - no host mounts: code goes in through the image and ``docker cp``, results come back out the same way, so the container cannot write to the host; - unprivileged: non-root user, every capability dropped, no-new-privileges; -- bounded: memory, CPU and PID limits plus a wall-clock timeout, after which - the container is killed; +- bounded: memory, CPU, PID and file-size limits plus a wall-clock timeout, + after which the container is killed. The container is never attached and + keeps no logs, and results come back as a size-capped stream of regular + files, so nothing it writes can flood the host; - disposable: every run gets a fresh container that is always removed. """ from __future__ import annotations +import asyncio import logging import os import shutil +import tarfile import tempfile from dataclasses import dataclass, field -from pathlib import Path -from typing import Optional +from pathlib import Path, PurePosixPath +from typing import IO, Optional from uuid import uuid4 from .orchestrator import SandboxError, SandboxOrchestrator, SandboxTimeoutError @@ -32,6 +36,7 @@ LABEL = "openhack.regression=1" UNPRIVILEGED_USER = "65534:65534" +COPY_TIMEOUT = 60 @dataclass @@ -41,6 +46,10 @@ class ContainerLimits: memory: str = "1g" cpus: str = "1" pids: int = 256 + # Largest file a test run may write, and most bytes of results copied + # back to the host. + file_size: int = 64 * 1024 * 1024 + results_bytes: int = 16 * 1024 * 1024 @dataclass @@ -48,7 +57,8 @@ class ContainerRunResult: exit_code: Optional[int] timed_out: bool results_dir: Path - stderr: str = "" + # Why the results were discarded instead of copied back, if they were. + results_error: Optional[str] = None container: str = field(default="", repr=False) def cleanup(self) -> None: @@ -62,6 +72,31 @@ async def _run(cmd: list[str], timeout: int, check: bool = True): raise SandboxError("the Docker CLI was not found on PATH") from exc +def _extract_regular_files(archive: IO[bytes], dest: Path) -> Optional[str]: + """Write the regular files of a results archive under ``dest``. + + Links, devices and directories are never created, and no path may leave + ``dest``. Returns why the archive could not be read, or None. + """ + try: + with tarfile.open(fileobj=archive, mode="r:") as tar: + for member in tar: + relpath = PurePosixPath(member.name) + target = dest.joinpath(*relpath.parts) + if (not member.isreg() or not relpath.parts or relpath.is_absolute() + or ".." in relpath.parts or not target.is_relative_to(dest)): + continue + source = tar.extractfile(member) + if source is None: + continue + target.parent.mkdir(parents=True, exist_ok=True) + with source, open(target, "wb") as out: + shutil.copyfileobj(source, out) + except (tarfile.TarError, OSError) as exc: + return f"could not read the test results: {exc}" + return None + + class ContainerTestRunner: """Builds per-revision images and runs one test file per fresh container.""" @@ -77,6 +112,9 @@ def lockdown_flags(self) -> list[str]: "--memory-swap", limits.memory, "--cpus", str(limits.cpus), "--pids-limit", str(limits.pids), + "--ulimit", f"fsize={limits.file_size}:{limits.file_size}", + "--ulimit", "core=0", + "--log-driver", "none", "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--user", UNPRIVILEGED_USER, @@ -124,8 +162,9 @@ async def run_test( """Run ``command`` in a fresh locked-down container of ``image``. ``files`` (path relative to /workspace -> content) are copied in before - start; ``results_path`` is copied back out afterwards. The container is - removed whatever happens. + start; the regular files under ``results_path`` are copied back out + afterwards, up to ``results_bytes``. The container is removed whatever + happens. """ name = f"openhack-regression-{uuid4().hex[:12]}" results_dir = Path(tempfile.mkdtemp(prefix="openhack-results-")) @@ -149,19 +188,20 @@ async def run_test( exit_code: Optional[int] = None timed_out = False - stderr = "" + # Not attached, so nothing the test prints is buffered on the host. + await _run(["docker", "start", name], timeout=60) try: - proc = await _run( - ["docker", "start", "-a", name], - timeout=self.limits.run_timeout, check=False, - ) - exit_code = proc.returncode - stderr = (proc.stderr or "")[-2000:] + waited = await _run(["docker", "wait", name], timeout=self.limits.run_timeout) except SandboxTimeoutError: timed_out = True await self._quiet(["docker", "kill", name]) - await self._quiet(["docker", "cp", f"{name}:{results_path}/.", str(results_dir)]) - return ContainerRunResult(exit_code, timed_out, results_dir, stderr, name) + else: + try: + exit_code = int(waited.stdout.split()[-1]) + except (IndexError, ValueError) as exc: + raise SandboxError(f"unexpected `docker wait` output: {waited.stdout[:200]!r}") from exc + results_error = await self._copy_results(name, results_path, results_dir) + return ContainerRunResult(exit_code, timed_out, results_dir, results_error, name) except BaseException: shutil.rmtree(results_dir, ignore_errors=True) raise @@ -170,6 +210,64 @@ async def run_test( if created: await self._quiet(["docker", "rm", "-f", name]) + async def _copy_results(self, name: str, results_path: str, dest: Path) -> Optional[str]: + """Copy the regular files under ``results_path`` into ``dest``. + + The directory arrives as a tar stream that is cut off past + ``results_bytes``, so a test cannot fill the host's disk, and only + regular files are written: a symlink planted in the results would + otherwise make the host read one of its own files. Returns why the + results were discarded, or None. + """ + limit = self.limits.results_bytes + try: + proc = await asyncio.create_subprocess_exec( + "docker", "cp", f"{name}:{results_path}/.", "-", + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL, + ) + except FileNotFoundError as exc: + raise SandboxError("the Docker CLI was not found on PATH") from exc + stream = proc.stdout + assert stream is not None + + async def receive(archive: IO[bytes]) -> bool: + received = 0 + while chunk := await stream.read(1 << 16): + received += len(chunk) + if received <= limit: + archive.write(chunk) + elif received - len(chunk) <= limit and proc.returncode is None: + # Over the limit: stop the copy and discard what it already + # wrote. Reading on to EOF matters: before Python 3.12, + # wait() only returns once the pipe is drained. + proc.kill() + await proc.wait() + return received <= limit + + with tempfile.TemporaryFile() as archive: + complete: Optional[bool] = None + try: + complete = await asyncio.wait_for(receive(archive), timeout=COPY_TIMEOUT) + except asyncio.TimeoutError as exc: + raise SandboxError(f"copying the test results timed out after {COPY_TIMEOUT}s") from exc + finally: + if complete is None and proc.returncode is None: + try: + proc.kill() + except ProcessLookupError: + pass + if not complete: + return ( + f"the test run left more than {limit // (1024 * 1024)} MB in its results " + "directory, so the results were discarded; keep test output small" + ) + if proc.returncode != 0: + # No results directory to copy; the adapter reports missing results. + logger.debug(f"docker cp of {results_path} from {name} exited {proc.returncode}") + return None + archive.seek(0) + return _extract_regular_files(archive, dest) + async def remove_images(self) -> None: for tag in list(self._images): await self._quiet(["docker", "rmi", "-f", tag]) diff --git a/openhack/tui.py b/openhack/tui.py index 2036805..afa1676 100644 --- a/openhack/tui.py +++ b/openhack/tui.py @@ -1167,8 +1167,9 @@ def _regression_test_fragments(finding: Finding) -> list[tuple[str, str]]: style, mark = "class:trace.dim", "✗ " out = _section_header("Regression test") out += [("", "\n"), (style, mark + (data.get("status_label") or status))] - if data.get("test_path"): - out.append(("class:finding.path", f" {data['test_path']}")) + path = (data.get("artifacts") or {}).get("repo_path") or data.get("test_path") + if path: + out.append(("class:finding.path", f" {path}")) out.append(("", "\n")) if data.get("reason"): out.append(("class:trace.dim", f"{data['reason']}\n")) @@ -1205,9 +1206,16 @@ def _regression_test_prompt_lines(finding: Finding) -> list[str]: "fix yet, so it must pass after your fix." ) lang = "python" if path.endswith(".py") else "" + repo_path = (data.get("artifacts") or {}).get("repo_path") + if repo_path: + location = f"`{repo_path}` (relative to the repository root)" + else: + # The test path is relative to its project, which the run command names. + run = data.get("run_command") + location = f"`{path}` in its test project" + (f" (run it with `{run}`)" if run else "") return [ "## Regression test", "", intro, - f"Add it unchanged at `{path}` in the same change and do not weaken its assertions.", + f"Add it unchanged at {location} in the same change and do not weaken its assertions.", "", f"```{lang}", code.rstrip("\n"), "```", "", ] diff --git a/tests/regression_support.py b/tests/regression_support.py index 9cf3eed..f32c73c 100644 --- a/tests/regression_support.py +++ b/tests/regression_support.py @@ -33,10 +33,15 @@ def git(repo: Path, *args: str) -> str: ).stdout.strip() -def make_fixture_repo(tmp_path: Path) -> dict: - """Create the IDOR fixture as a git repo; returns paths and commit ids.""" +def make_fixture_repo(tmp_path: Path, customize: Optional[Callable[[Path], None]] = None) -> dict: + """Create the IDOR fixture as a git repo; returns paths and commit ids. + + ``customize(repo)`` can change the project's tooling before the first commit. + """ repo = tmp_path / "notes-app" shutil.copytree(FIXTURE_APP / "vulnerable", repo) + if customize is not None: + customize(repo) git(repo, "init", "-q", "-b", "main") git(repo, "config", "user.email", "dev@example.invalid") git(repo, "config", "user.name", "dev") @@ -364,7 +369,7 @@ def junit_xml(cases: dict[str, str], classname: str = "tests.test_security_idor_ "ModuleNotFoundError: No module named 'notes'" ) -Behavior = Callable[[str, str, int], Union[dict, str]] +Behavior = Callable[[str, str, int], Union[dict, tuple, str]] def realistic_idor(label: str, code: str, run_index: int) -> dict: @@ -380,7 +385,8 @@ def realistic_idor(label: str, code: str, run_index: int) -> dict: class FakeRunner: """Stands in for ContainerTestRunner. ``behavior(label, code, run_index)`` - returns {test: outcome}, or "timeout" / "collection_error" / "no_results".""" + returns {test: outcome}, ({test: outcome}, exit_code) to force pytest's exit + status, or "timeout" / "collection_error" / "no_results" / "oversized_results".""" def __init__(self, behavior: Behavior = realistic_idor, available: bool = True, build_error: Optional[str] = None): @@ -417,10 +423,20 @@ async def run_test(self, image, files, command, workdir="/workspace", results_pa (results / "junit.xml").write_text(COLLECTION_ERROR_XML) (results / "output.txt").write_text("ModuleNotFoundError: No module named 'notes'\n") return ContainerRunResult(2, False, results) + if outcome == "oversized_results": + return ContainerRunResult(1, False, results, results_error=( + "the test run left more than 16 MB in its results directory, so the results " + "were discarded; keep test output small" + )) + exit_code, output = None, "collected tests\n" + if isinstance(outcome, tuple): + outcome, exit_code = outcome + output += "INTERNALERROR> a plugin failed the session\n" (results / "junit.xml").write_text(junit_xml(outcome)) - (results / "output.txt").write_text("collected tests\n") - failed = any(o != "passed" for o in outcome.values()) - return ContainerRunResult(1 if failed else 0, False, results) + (results / "output.txt").write_text(output) + if exit_code is None: + exit_code = int(any(o in ("failed", "crashed", "error") for o in outcome.values())) + return ContainerRunResult(exit_code, False, results) async def remove_images(self) -> None: self.images_removed = True diff --git a/tests/test_regression_e2e_docker.py b/tests/test_regression_e2e_docker.py index 4dadd82..51a330f 100644 --- a/tests/test_regression_e2e_docker.py +++ b/tests/test_regression_e2e_docker.py @@ -233,6 +233,36 @@ def test_incomplete_fix_is_reported_not_weakened(tmp_path): assert result.artifacts == {} +def test_projects_with_editable_requirements_constraints_and_a_coverage_gate(tmp_path): + """Common real-world tooling must not stop validation: `-e .` in a + requirements file, a constraints file pinning a package the project never + installs (and that does not exist), and a coverage threshold in addopts + that a single-file run can never meet.""" + def tooling(repo: Path) -> None: + (repo / "requirements.txt").write_text("-c constraints.txt\nflask>=3.0,<4\n") + (repo / "constraints.txt").write_text("flask<4\nopenhack-unpublished-internal-package==1.0\n") + (repo / "requirements-dev.txt").write_text("-r requirements.txt\n-e .\npytest>=8.0\npytest-cov>=4\n") + (repo / "setup.py").write_text( + "from setuptools import setup\n\nsetup(name='notes-app', version='0.0.0', py_modules=['app'])\n" + ) + with open(repo / "pytest.ini", "a") as ini: + ini.write("addopts = --cov=app --cov-fail-under=100\n") + + fx = make_fixture_repo(tmp_path, customize=tooling) + repo = fx["repo"] + llm = ScriptedLLM([submit()]) + pipeline = RegressionTestPipeline( + llm, Session(str(repo), persist_events=False), repo, + PipelineOptions(remediation=RevisionSpec.git(FIX_BRANCH), base_image=BASE_IMAGE, + artifacts_root=tmp_path / "artifacts"), + ) + result = asyncio.run(pipeline.run([verified_idor_finding()]))[0] + + assert result.status is Status.VALIDATED, result.reason + assert result.attempts == 1 + assert {n for n, o in result.validation["vulnerable"]["outcomes"].items() if o == "failed"} == set(GOOD_INVARIANT_TESTS) + + def _probe_image(tmp_path: Path, runner: ContainerTestRunner) -> str: context = tmp_path / "probe" context.mkdir() @@ -274,6 +304,42 @@ def test_test_containers_are_locked_down(tmp_path): asyncio.run(runner.remove_images()) +def test_results_are_capped_and_links_never_reach_the_host(tmp_path): + mb = 1024 * 1024 + runner = ContainerTestRunner(ContainerLimits(run_timeout=60, file_size=4 * mb, results_bytes=mb)) + image = _probe_image(tmp_path, runner) + try: + script = ( + "ln -s /etc/hostname /openhack-results/output.txt; " + "ulimit -f > /openhack-results/fsize; " + "head -c 8000000 /dev/zero > /tmp/big; echo $? > /openhack-results/big_rc; " + "wc -c < /tmp/big > /openhack-results/big_size; " + "echo '' > /openhack-results/junit.xml" + ) + run = asyncio.run(runner.run_test(image, {}, ["sh", "-c", script])) + try: + assert run.results_error is None + # The planted symlink stays in the container. + assert sorted(p.name for p in run.results_dir.iterdir()) == ["big_rc", "big_size", "fsize", "junit.xml"] + assert (run.results_dir / "fsize").read_text().strip() == str(4 * mb // 512) + assert (run.results_dir / "big_rc").read_text().strip() != "0" # killed at the file-size limit + assert int((run.results_dir / "big_size").read_text()) == 4 * mb + finally: + run.cleanup() + + flood = asyncio.run(runner.run_test( + image, {}, ["sh", "-c", "head -c 3000000 /dev/zero > /openhack-results/flood"], + )) + try: + assert "more than 1 MB in its results directory" in flood.results_error + assert list(flood.results_dir.iterdir()) == [] + finally: + flood.cleanup() + assert _docker("ps", "-a", "--filter", f"name={flood.container}", "-q").stdout.strip() == "" + finally: + asyncio.run(runner.remove_images()) + + def test_hanging_tests_are_killed_at_the_timeout(tmp_path): runner = ContainerTestRunner(ContainerLimits(run_timeout=5)) image = _probe_image(tmp_path, runner) diff --git a/tests/test_regression_frameworks.py b/tests/test_regression_frameworks.py index b884beb..e9ba352 100644 --- a/tests/test_regression_frameworks.py +++ b/tests/test_regression_frameworks.py @@ -8,6 +8,7 @@ from openhack.regression.frameworks import ( PytestAdapter, UnsupportedFrameworkError, + _installs_from_project, detect_framework, ) from openhack.regression.invariants import IdorSpec @@ -220,14 +221,34 @@ def test_parse_results_without_results_file(tmp_path): assert "file or directory not found" in report.collection_error -def test_parse_results_rejects_entity_declarations(tmp_path): +@pytest.mark.parametrize("prolog", ["", ""]) +def test_parse_results_rejects_entity_declarations(tmp_path, prolog): (tmp_path / "junit.xml").write_text( - ']>' + f'{prolog}]>' '' ) assert "DTD/entity" in adapter.parse_results(tmp_path, 0, False).collection_error +@pytest.mark.parametrize("cases,exit_code,problem", [ + ({"test_a": "passed"}, 0, None), + ({"test_a": "failed", "test_b": "passed"}, 1, None), + ({"test_a": "error"}, 1, None), + # e.g. a coverage threshold or a plugin failing the session at shutdown + ({"test_a": "passed"}, 1, "exited with code 1 although every test passed (expected 0)"), + ({"test_a": "failed"}, 0, "exited with code 0 although some tests failed (expected 1)"), + ({"test_a": "failed"}, 3, "exited with code 3 although some tests failed"), +]) +def test_parse_results_checks_the_exit_status_against_the_results(tmp_path, cases, exit_code, problem): + (tmp_path / "junit.xml").write_text(junit_xml(cases)) + report = adapter.parse_results(tmp_path, exit_code, False) + assert report.collection_error is None + if problem is None: + assert report.session_error is None + else: + assert problem in report.session_error + + def test_parse_results_on_timeout(tmp_path): report = adapter.parse_results(tmp_path, None, True) assert report.timed_out and report.cases == [] @@ -237,10 +258,12 @@ def test_parse_results_on_timeout(tmp_path): def test_dockerfile_installs_the_projects_own_test_dependencies(profile): dockerfile = adapter.dockerfile(profile, "python:3.12-slim") - assert dockerfile.splitlines()[1] == "FROM python:3.12-slim" - assert 'COPY ["requirements.txt", "/workspace/requirements.txt"]' in dockerfile - assert 'RUN pip install --no-cache-dir -r "requirements.txt"' in dockerfile - assert 'COPY [".", "/workspace"]' in dockerfile + lines = dockerfile.splitlines() + assert lines[1] == "FROM python:3.12-slim" + assert 'COPY ["requirements.txt", "/workspace/requirements.txt"]' in lines + install = 'RUN pip install --no-cache-dir -r "requirements.txt"' + # Dependencies install before the source arrives, as a reusable layer. + assert lines.index(install) < lines.index('COPY [".", "/workspace"]') assert "chown -R 65534:65534 /workspace /openhack-results" in dockerfile assert adapter.default_base_image(profile) == "python:3.12-slim" @@ -248,19 +271,71 @@ def test_dockerfile_installs_the_projects_own_test_dependencies(profile): def test_dockerfile_for_subproject_with_includes(tmp_path): write_file(tmp_path, "api/requirements.txt", "flask\n") write_file(tmp_path, "api/requirements-dev.txt", "-r requirements.txt\n-c constraints/pins.txt\npytest\n") - write_file(tmp_path, "api/constraints/pins.txt", "flask==3.0.3\n") + write_file(tmp_path, "api/constraints/pins.txt", "flask==3.0.3\nsome-internal-package==1.0\n") write_file(tmp_path, "api/setup.py", "from setuptools import setup\nsetup(name='api')\n") write_file(tmp_path, "api/tests/test_a.py", "def test_a():\n assert True\n") _, profile = detect_framework(tmp_path, "api/app.py") assert profile.project_root == "api" assert profile.dependency_files == ["requirements.txt", "requirements-dev.txt", "constraints/pins.txt"] + assert profile.requirement_files == ["requirements.txt", "requirements-dev.txt"] dockerfile = adapter.dockerfile(profile, "python:3.11-slim") assert "WORKDIR /workspace/api" in dockerfile + # The constraints file is there for the -c include but is not installed. assert 'COPY ["api/constraints/pins.txt", "/workspace/api/constraints/pins.txt"]' in dockerfile + assert 'RUN pip install --no-cache-dir -r "requirements.txt" -r "requirements-dev.txt"\n' in dockerfile + assert '-r "constraints/pins.txt"' not in dockerfile assert 'pip install --no-cache-dir -e "."' in dockerfile assert adapter.display_command(profile, "tests/test_x.py") == "cd api && python -m pytest tests/test_x.py" +def test_constraints_files_in_a_requirements_directory_are_not_installed(tmp_path): + write_file(tmp_path, "pytest.ini", "[pytest]\n") + write_file(tmp_path, "requirements/base.txt", "-c constraints.txt\nflask\n") + write_file(tmp_path, "requirements/test.txt", "-r base.txt\npytest\n") + write_file(tmp_path, "requirements/constraints.txt", "flask==3.0.3\nsome-internal-package==1.0\n") + write_file(tmp_path, "tests/test_a.py", "def test_a():\n assert True\n") + _, profile = detect_framework(tmp_path) + assert profile.requirement_files == ["requirements/base.txt", "requirements/test.txt"] + assert "requirements/constraints.txt" in profile.dependency_files + assert '-r "requirements/constraints.txt"' not in adapter.dockerfile(profile, "python:3.12-slim") + + +def test_requirements_that_install_the_project_wait_for_its_source(tmp_path): + write_file(tmp_path, "requirements.txt", "flask\n") + write_file(tmp_path, "requirements-dev.txt", "-r requirements.txt\n-e .[test]\npytest\n") + write_file(tmp_path, "setup.py", "from setuptools import setup\nsetup(name='svc')\n") + write_file(tmp_path, "tests/test_a.py", "def test_a():\n assert True\n") + _, profile = detect_framework(tmp_path) + assert profile.requirements_need_source + lines = adapter.dockerfile(profile, "python:3.12-slim").splitlines() + install = 'RUN pip install --no-cache-dir -r "requirements.txt" -r "requirements-dev.txt"' + assert lines.index('COPY [".", "/workspace"]') < lines.index(install) + assert not any(line.startswith('COPY ["requirements') for line in lines) + + +@pytest.mark.parametrize("requirements,local", [ + ("-e .\n", True), + ("-e .[dev]\n", True), + ("--editable=./packages/core\n", True), + (".\n", True), + ("./libs/shared\n", True), + ("libs/shared[extra]\n", True), + ("notes @ file:///workspace/libs/notes\n", True), + ("-e file:.\n", True), + ("--find-links ./wheels\nnotes\n", True), + ("vendor/notes-1.0-py3-none-any.whl\n", True), + ("flask>=3.0,<4\npytest # see ./docs/testing.md\n", False), + ("notes @ https://example.com/notes-1.0-py3-none-any.whl\n", False), + ("-e git+https://github.com/example/notes.git#egg=notes\n", False), + ("-r base.txt\n-c constraints.txt\n--index-url https://pypi.org/simple\n", False), + ("-f https://download.pytorch.org/whl/torch_stable.html\ntorch\n", False), + ("django==4.2 \\\n --hash=sha256:0123abcd\n", False), + ("# -e .\n", False), +]) +def test_requirements_installing_from_the_project_are_recognized(requirements, local): + assert _installs_from_project(requirements) is local + + def test_container_command_runs_one_file_with_junit_results(profile): command = adapter.container_command(profile, "tests/test_security_idor_note.py") assert command[:2] == ["sh", "-c"] @@ -268,3 +343,5 @@ def test_container_command_runs_one_file_with_junit_results(profile): assert "--junitxml=/openhack-results/junit.xml" in command[2] assert "--maxfail=100000" in command[2] assert "> /openhack-results/output.txt 2>&1" in command[2] + # Coverage thresholds are switched off only where pytest-cov can parse --no-cov. + assert 'if python -c "import pytest_cov" 2>/dev/null; then set -- "$1" --no-cov; fi;' in command[2] diff --git a/tests/test_regression_lifecycle.py b/tests/test_regression_lifecycle.py index d6d0ecf..03ba1d6 100644 --- a/tests/test_regression_lifecycle.py +++ b/tests/test_regression_lifecycle.py @@ -183,6 +183,9 @@ def test_headless_status_lines(): assert "git apply" in lines[2] assert format_regression_status(verified_idor_finding()) == [] + finding.regression_test["artifacts"]["repo_path"] = f"services/api/{TEST_PATH}" + assert format_regression_status(finding)[0].endswith(f"— services/api/{TEST_PATH}") + # ── openhack --regression-tests ── @@ -356,10 +359,40 @@ def test_copy_prompt_carries_the_regression_test(status, included, phrase): assert ("## Regression test" in prompt) is included if included: assert phrase in prompt - assert f"Add it unchanged at `{TEST_PATH}`" in prompt + assert f"Add it unchanged at `{TEST_PATH}` in its test project" in prompt assert "```python\ndef test_x():\n assert True\n```" in prompt +def test_copy_prompt_places_a_subproject_test_from_the_repository_root(tmp_path): + """A monorepo finding: the test belongs in the project, not at the repository root.""" + import shutil + + from openhack.tui import OpenHackApp, _regression_test_fragments + from tests.regression_support import FIXTURE_APP + + repo = tmp_path / "monorepo" + shutil.copytree(FIXTURE_APP / "vulnerable", repo / "services" / "api") + (repo / "README.md").write_text("# monorepo\n") + finding = verified_idor_finding(file_path="services/api/app.py") + runner = FakeRunner() + pipeline = pipeline_mod.RegressionTestPipeline( + ScriptedLLM([submit()]), Session(str(repo), persist_events=False), repo, + PipelineOptions(artifacts_root=tmp_path / "artifacts"), runner=runner, + ) + result = asyncio.run(pipeline.run([finding]))[0] + + assert result.status.value == "remediation_unavailable" + assert result.test_path == TEST_PATH + assert result.artifacts["repo_path"] == f"services/api/{TEST_PATH}" + assert result.run_command == f"cd services/api && python -m pytest {TEST_PATH}" + assert list(runner.runs[0]["files"]) == [f"services/api/{TEST_PATH}"] + + prompt = OpenHackApp._format_finding_for_agent(finding) + assert f"Add it unchanged at `services/api/{TEST_PATH}` (relative to the repository root)" in prompt + details = "".join(fragment[1] for fragment in _regression_test_fragments(finding)) + assert f"services/api/{TEST_PATH}" in details + + def test_tui_details_and_trace_show_regression_status(): from openhack.tui import ScanState, _regression_test_fragments diff --git a/tests/test_regression_pipeline.py b/tests/test_regression_pipeline.py index b7c529a..94a4137 100644 --- a/tests/test_regression_pipeline.py +++ b/tests/test_regression_pipeline.py @@ -140,6 +140,42 @@ def test_artifacts_include_the_test_and_an_applicable_patch(tmp_path): assert git(run.repo, "status", "--porcelain") == f"?? {TEST_PATH}" +def test_repository_path_is_kept_when_artifacts_cannot_be_written(tmp_path, monkeypatch): + import openhack.regression.pipeline as pipeline_mod + + def disk_full(*args, **kwargs): + raise OSError("No space left on device") + + monkeypatch.setattr(pipeline_mod, "write_private_file", disk_full) + run = run_pipeline(tmp_path, [submit()]) + assert run.result.status is Status.VALIDATED + assert run.result.artifacts == {"repo_path": TEST_PATH} + + +def test_two_findings_never_add_the_same_test_file(tmp_path): + read_any = verified_idor_finding() + delete_any = verified_idor_finding(title="IDOR: delete any note") + # The second generator ignores its suggested path and reuses the first test's file. + responses = [submit(), submit(call_id="same-file"), + submit(path="tests/test_security_idor_note_2.py", call_id="new-file")] + run = run_pipeline(tmp_path, responses, findings=[read_any, delete_any]) + + first, second = run.results + assert first.status is Status.VALIDATED and second.status is Status.VALIDATED + assert first.test_path == TEST_PATH + assert second.test_path == "tests/test_security_idor_note_2.py" + feedback = feedback_sent(run.llm, 2) + assert f"`{TEST_PATH}` is already the regression test for another finding" in feedback + assert "such as `tests/test_security_idor_note_2.py`" in feedback + # The two patches apply together. + git(run.repo, "checkout", "-q", FIX_BRANCH) + for result in run.results: + subprocess.run(["git", "-C", str(run.repo), "apply", result.artifacts["patch"]], check=True) + assert git(run.repo, "status", "--porcelain").splitlines() == [ + f"?? {TEST_PATH}", "?? tests/test_security_idor_note_2.py", + ] + + def test_the_scanned_repository_is_never_modified(tmp_path): run = run_pipeline(tmp_path, [submit(path="tests/test_notes.py"), submit(call_id="s2")]) assert run.result.status is Status.VALIDATED @@ -235,6 +271,32 @@ def test_collection_errors_are_reported_with_output(tmp_path): assert "No module named 'notes'" in feedback_sent(run.llm, 1) +@pytest.mark.parametrize("revision,exit_code,expected", [ + # A plugin or session fixture failing the run after every test passed. + ("remediated", 1, "exited with code 1 although every test passed (expected 0)"), + ("vulnerable", 3, "exited with code 3 although some tests failed (expected 1)"), + ("vulnerable", 0, "exited with code 0 although some tests failed (expected 1)"), +]) +def test_runs_must_end_with_the_exit_status_their_results_imply(tmp_path, revision, exit_code, expected): + def unclean(label, code, run_index): + outcomes = realistic_idor(label, code, run_index) + return (outcomes, exit_code) if label == revision else outcomes + + run = run_pipeline(tmp_path, [submit(), submit(call_id="s2")], behavior=unclean, max_attempts=2) + assert run.result.status is Status.VALIDATION_FAILED + assert "did not finish cleanly" in run.result.reason and expected in run.result.reason + assert run.result.artifacts == {} + # The runner's own output explains a session failure, so it goes back to the generator. + feedback = feedback_sent(run.llm, 1) + assert "Test output (tail):" in feedback and "a plugin failed the session" in feedback + + +def test_oversized_results_are_rejected(tmp_path): + run = run_pipeline(tmp_path, [submit()], behavior=lambda *a: "oversized_results", max_attempts=1) + assert run.result.status is Status.VALIDATION_FAILED + assert "more than 16 MB in its results directory" in run.result.reason + + def test_failing_control_test_means_the_failure_is_not_the_vulnerability(tmp_path): def broken_setup(label, code, run_index): outcomes = realistic_idor(label, code, run_index) @@ -510,3 +572,15 @@ def test_evaluate_runs_requires_a_control_test(): def test_evaluate_runs_parametrized_tests_match_by_base_name(): reports = [_report(**{"test_inv[read]": "failed", "test_inv[delete]": "failed", "test_ctl": "passed"})] assert evaluate_runs(reports, SUBMISSION, "vulnerable", True, 60).passed + + +def test_evaluate_runs_requires_every_run_to_finish_cleanly(): + clean, unclean = _report(test_inv="passed", test_ctl="passed"), _report(test_inv="passed", test_ctl="passed") + unclean.session_error = "pytest exited with code 1 although every test passed (expected 0)" + unclean.output_tail = "FAIL Required test coverage of 90% not reached" + + check = evaluate_runs([clean, unclean], SUBMISSION, "remediated", True, 60) + assert not check.passed and check.retryable + assert check.detail.startswith("the test run did not finish cleanly: pytest exited with code 1") + assert check.show_output and "coverage" in check.output_tail + assert evaluate_runs([clean, clean], SUBMISSION, "remediated", True, 60).passed diff --git a/tests/test_regression_sandbox_runner.py b/tests/test_regression_sandbox_runner.py new file mode 100644 index 0000000..96aa16e --- /dev/null +++ b/tests/test_regression_sandbox_runner.py @@ -0,0 +1,142 @@ +"""The locked-down container runner, without a Docker daemon. + +`docker` is replaced at the process boundary: a stand-in `docker cp` streams a +crafted tar archive, so the size cap and the regular-files-only extraction run +for real. test_regression_e2e_docker.py covers the same paths against Docker. +""" + +import asyncio +import io +import sys +import tarfile +from types import SimpleNamespace + +import pytest + +from openhack.sandbox import container_runner +from openhack.sandbox.container_runner import ContainerLimits, ContainerTestRunner +from openhack.sandbox.orchestrator import SandboxTimeoutError + +MB = 1024 * 1024 + + +def _archive(*members) -> bytes: + """A tar archive from (name, type, payload) members.""" + buffer = io.BytesIO() + with tarfile.open(fileobj=buffer, mode="w") as tar: + for name, kind, payload in members: + info = tarfile.TarInfo(name) + if kind == "file": + data = payload if isinstance(payload, bytes) else payload.encode() + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + continue + info.type = {"dir": tarfile.DIRTYPE, "symlink": tarfile.SYMTYPE, "hardlink": tarfile.LNKTYPE}[kind] + info.linkname = payload or "" + tar.addfile(info) + return buffer.getvalue() + + +def _copy_results(monkeypatch, tmp_path, stream: bytes = b"", exit_code: int = 0, limits=None): + """Run _copy_results against a stand-in `docker cp` that writes ``stream``.""" + payload = tmp_path / "stream.bin" + payload.write_bytes(stream) + real_exec = asyncio.create_subprocess_exec + seen = [] + + async def docker_cp(*cmd, **kwargs): + seen.append(cmd) + script = ("import shutil, sys; shutil.copyfileobj(open(sys.argv[1], 'rb'), sys.stdout.buffer); " + "sys.exit(int(sys.argv[2]))") + return await real_exec(sys.executable, "-c", script, str(payload), str(exit_code), **kwargs) + + monkeypatch.setattr(container_runner.asyncio, "create_subprocess_exec", docker_cp) + dest = tmp_path / "results" + dest.mkdir() + error = asyncio.run(ContainerTestRunner(limits)._copy_results("openhack-regression-x", "/openhack-results", dest)) + assert seen == [("docker", "cp", "openhack-regression-x:/openhack-results/.", "-")] + return error, dest + + +def _written(dest): + return sorted(p.relative_to(dest).as_posix() for p in dest.rglob("*") if not p.is_dir()) + + +def test_only_regular_files_come_back(monkeypatch, tmp_path): + stream = _archive( + ("./", "dir", None), + ("./junit.xml", "file", ""), + # A planted link would make the host read its own file when results are parsed. + ("./output.txt", "symlink", "/etc/hostname"), + ("./hosts", "hardlink", "/etc/hosts"), + ("./logs/run.txt", "file", "nested output"), + ("../escape.txt", "file", "outside"), + ) + error, dest = _copy_results(monkeypatch, tmp_path, stream) + + assert error is None + assert _written(dest) == ["junit.xml", "logs/run.txt"] + assert (dest / "junit.xml").read_text() == "" + assert not (tmp_path / "escape.txt").exists() + + +def test_results_beyond_the_limit_are_discarded(monkeypatch, tmp_path): + stream = _archive(("./junit.xml", "file", ""), ("./output.txt", "file", b"x" * (2 * MB))) + error, dest = _copy_results(monkeypatch, tmp_path, stream, limits=ContainerLimits(results_bytes=MB)) + + assert "more than 1 MB in its results directory" in error + assert _written(dest) == [] + + +def test_missing_results_directory_leaves_nothing(monkeypatch, tmp_path): + error, dest = _copy_results(monkeypatch, tmp_path, b"", exit_code=1) + assert error is None and _written(dest) == [] + + +def test_unreadable_results_archive(monkeypatch, tmp_path): + error, dest = _copy_results(monkeypatch, tmp_path, b"this is not a tar archive" * 40) + assert error.startswith("could not read the test results") and _written(dest) == [] + + +def test_lockdown_flags_bound_files_and_keep_no_logs(): + flags = " ".join(ContainerTestRunner(ContainerLimits(file_size=4 * MB)).lockdown_flags()) + assert f"--ulimit fsize={4 * MB}:{4 * MB}" in flags + assert "--ulimit core=0" in flags and "--log-driver none" in flags + assert "--network none" in flags and "--cap-drop ALL" in flags + + +@pytest.fixture +def docker_calls(monkeypatch): + """Record docker commands; ``wait`` reports exit 3 unless told to time out.""" + calls, state = [], {"wait_times_out": False} + + async def run(cmd, timeout, check=True): + calls.append(cmd) + if cmd[1] == "wait" and state["wait_times_out"]: + raise SandboxTimeoutError("timed out") + return SimpleNamespace(stdout="3\n" if cmd[1] == "wait" else "", stderr="", returncode=0) + + async def no_results(self, name, results_path, dest): + return None + + monkeypatch.setattr(container_runner, "_run", run) + monkeypatch.setattr(ContainerTestRunner, "_copy_results", no_results) + return SimpleNamespace(calls=calls, state=state) + + +def test_containers_are_waited_on_not_attached(docker_calls): + run = asyncio.run(ContainerTestRunner().run_test("image", {"tests/test_x.py": "x"}, ["true"])) + run.cleanup() + + assert run.exit_code == 3 and not run.timed_out + assert [cmd[1] for cmd in docker_calls.calls] == ["create", "cp", "start", "wait", "rm"] + assert ["docker", "start", run.container] in docker_calls.calls + + +def test_timed_out_containers_are_killed_and_removed(docker_calls): + docker_calls.state["wait_times_out"] = True + run = asyncio.run(ContainerTestRunner().run_test("image", {}, ["sleep", "300"])) + run.cleanup() + + assert run.timed_out and run.exit_code is None + assert [cmd[1] for cmd in docker_calls.calls] == ["create", "cp", "start", "wait", "kill", "rm"] diff --git a/tests/test_regression_workspace.py b/tests/test_regression_workspace.py index db2c542..220f241 100644 --- a/tests/test_regression_workspace.py +++ b/tests/test_regression_workspace.py @@ -1,6 +1,7 @@ """Revision workspaces: materializing vulnerable and remediated code safely.""" import os +import shutil import subprocess import pytest @@ -79,6 +80,21 @@ def test_worktree_snapshot_honors_gitignore_and_skips_credentials(fixture_repo, assert copy.resolved.startswith("working tree @ ") +def test_tracked_directory_replaced_by_a_symlink_is_not_followed(fixture_repo, tmp_path): + repo = fixture_repo["repo"] + outside = tmp_path / "outside" + write_file(outside, "conftest.py", "HOST_SECRET = 'outside the checkout'\n") + write_file(outside, "test_notes.py", "HOST_SECRET = 'outside the checkout'\n") + shutil.rmtree(repo / "tests") + os.symlink(outside, repo / "tests") + # The index still lists the directory's files under the symlink. + assert "tests/conftest.py" in git(repo, "ls-files", "--cached").splitlines() + + copy = materialize(repo, RevisionSpec.worktree(), tmp_path / "w") + assert not (copy.root / "tests").exists() + assert (copy.root / "app.py").is_file() + + def test_directory_revisions(tmp_path): write_file(tmp_path / "fixed", "app.py", "print('fixed')\n") write_file(tmp_path / "fixed", ".venv/lib/x.py", "")