Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.

Expand Down Expand Up @@ -151,6 +154,7 @@ OpenHack runs the same pipeline as the TUI, prints progress to stdout, writes a
| `openhack --plan "<obj>"` | Draft a read-only attack plan |
| `openhack --sessions` | List all saved scans |
| `openhack --resume <id>` | Resume a scan from its last checkpoint |
| `openhack --regression-tests <id> [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 |
Expand Down Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions docs/EVENT_LOGGING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<session-id>/` 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/<session-id>/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

Expand Down
265 changes: 265 additions & 0 deletions docs/REGRESSION_TESTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
# 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:<version>-slim` | Base image for sandbox images (`<version>` 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 <session-id> 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, 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
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;
- 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
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 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, 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, 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/<session-id>.json`). It holds the status, the reason, the
invariant, the test path and code, the run command, and per-revision
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/<session-id>/regression-tests/<finding-id>/`:

- the test file, at its repository path;
- `regression-test.patch`, to apply from the repository root with
`git apply <patch>`;
- `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 <session-id> <fixed-revision>` |
| `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 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.

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.
- 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.

## 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/`.
Loading