Metadata-Version: 2.4
Name: broadside-harness
Version: 0.5.0
Summary: Fail-closed network-safety kernel for authorized web application research
Author: Rafael Martinez
License: MIT
Project-URL: Homepage, https://github.com/TerminalsandCoffee/broadside
Project-URL: Repository, https://github.com/TerminalsandCoffee/broadside
Project-URL: Issues, https://github.com/TerminalsandCoffee/broadside/issues
Project-URL: Changelog, https://github.com/TerminalsandCoffee/broadside/releases/tag/v0.5.0
Requires-Python: >=3.12
Description-Content-Type: text/markdown
Requires-Dist: typer>=0.12
Requires-Dist: rich>=13
Requires-Dist: pydantic>=2
Requires-Dist: pyyaml>=6
Requires-Dist: httpx>=0.27
Requires-Dist: sqlalchemy>=2
Provides-Extra: dev
Requires-Dist: fastapi>=0.110; extra == "dev"
Requires-Dist: uvicorn>=0.27; extra == "dev"
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"

# Broadside

Broadside is an AI-assisted web application research framework for **explicitly
authorized** bug-bounty programs, owned targets, and local labs. Its fail-closed
network kernel validates authorization and scope before constructing a client,
then sends every request, redirect, retry, and replay through the same auditable
policy path.

> Status: Sprints 001-003 are shipped. Sprint 004's bounded static JavaScript
> extraction, Sprint 005's derive-only endpoint inventory, Sprint 006's
> experiment framework, and Sprint 007's offline diagnostic-exposure proposal
> producer are implementation-verified and merged into `main`.
> Sprint 008's bounded authorization-context experiment is implementation-verified
> on a separate local feature branch, not merged or released.
> GitHub Release `v0.5.0` already exists. The PyPI name `broadside` is taken by
> an unrelated package, so this project's distribution name is `broadside-harness`
> while the importable package and CLI stay `broadside`. This rename stays at
> `0.5.0` so a later publish can be `broadside-harness==0.5.0` matching that tag.
> Renaming the distribution does not publish a package.
> See the [roadmap](docs/ROADMAP.md) for the release boundary.

## Requirements and install

- Python 3.12 or newer

Install the PyPI distribution (when published) as `broadside-harness`. The
import remains `import broadside` and the console script remains `broadside`:

```bash
python -m pip install broadside-harness
broadside version
```

From a clone, install the same distribution in editable form:

```bash
python -m venv .venv
source .venv/bin/activate        # Windows PowerShell: .\.venv\Scripts\Activate.ps1
python -m pip install -e ".[dev]"
broadside version
```

The installed command reports `broadside 0.5.0`. Runtime dependencies are
`typer`, `rich`, `pydantic`, `pyyaml`, `httpx`, and `sqlalchemy`; the development
extra adds `fastapi`, `uvicorn`, `pytest`, and `pytest-asyncio`.

## Authorization, scope, and methods

Every scan, crawl, and replay requires the `--i-am-authorized` acknowledgment
and a supported platform:

```bash
broadside scan http://127.0.0.1:8765/ \
  --scope testdata/scope/lab_local.yml \
  --i-am-authorized \
  --platform self-hosted-lab
```

Supported platforms are `hackerone`, `bugcrowd`, `intigriti`, `vrp`, and
`self-hosted-lab`. The CLI platform must equal `program.platform` in the scope
file. These acknowledgments are runtime-only and are not persisted as legal
authorization. Programmatic authorization and insecure-proxy acknowledgments
are strict booleans: only the actual value `True` is accepted, never a truthy
string or integer.

Scope YAML is validated with unknown keys rejected. Empty host/IP allowlists
are invalid; exact domains do not imply subdomains; exclusions win; and ports
must be explicit. `methods` is an explicit allowlist selected from `GET`,
`HEAD`, `OPTIONS`, `POST`, `PUT`, `PATCH`, and `DELETE`. A method being supported
does not authorize it: for example, `POST` reaches transport only when the
current scope explicitly lists `POST`. The `scan` command itself remains a
single conservative `GET`; callers construct other `RequestIntent` values or
replay a stored template.

Every intent is also protected against virtual-host routing changes. A supplied
`Host` header must be exactly equivalent to the normalized URL authority
(including its effective port), and duplicate or conflicting Host spellings are
refused before transport. This Host guard applies to manual requests, redirects,
retries, and replay.

Example Sprint 002 additions to a scope file:

```yaml
methods: [GET, HEAD, POST]
limits:
  requests_per_second: 2.0
  concurrency: 2
  request_budget: 25
retry:
  max_retries: 2
  retry_transport_errors: false
  status_codes: [502, 503, 504]
evidence:
  retain_raw: false
```

See `testdata/scope/` for complete fixtures and `testdata/urls/cases.yaml` for
golden URL normalization cases.

## Bounded HTML crawling

`crawl` walks authorized HTML pages without changing the single-request `scan`
or stored-template `replay` commands. Its command surface is:

```bash
broadside crawl http://127.0.0.1:8765/crawl/ \
  --scope testdata/scope/lab_local.yml \
  --i-am-authorized \
  --platform self-hosted-lab \
  --database broadside.db \
  --evidence-root evidence \
  --max-depth 3 \
  --max-pages 100 \
  --queue-capacity 256 \
  --workers 4
```

The shared `--allow-insecure-proxy-tls` acknowledgment is also available when
the scope selects an insecure explicit proxy. `--max-depth` accepts 0–20,
`--max-pages` 1–10,000, `--queue-capacity` 1–4,096 per BFS frontier, and
`--workers` 1–32. These are execution bounds, not authorization grants. Page
slots are claimed when work enters a frontier and are never recycled; the
summary reports admitted, submitted, and parsed pages separately from actual
kernel-reserved requests.

`scope.yml` is the only navigation authorization policy. Sprint 003 does not
fetch or consult `robots.txt` or sitemaps, does not probe them at startup, and
does not interpret their contents. Recognizable or explicitly declared
robots/sitemap references are recorded as `ROBOTS_SITEMAP_DEFERRED` and never
scheduled. Only ordinary `a[href]` and `area[href]` navigation candidates may
be queued after pure classification and exact execution re-gating. Forms and
their submit overrides, scripts, frames, refresh targets, styles, images, and
other resource references are record-only: Broadside will never submit forms
or fetch targets merely because they appear as resources. Out-of-scope
references are recorded in redacted form and are not fetched.

Scheduling is level-by-level BFS. The coordinator alone owns page admission,
canonical deduplication, stable parent/link ordering, current and next bounded
frontiers, and persistence. Bounded workers submit body-free `GET` intents with
purpose `crawl` through the same `ScopedHTTPClient` used by scan and replay;
workers never enqueue children or own a network client. There is no crawl
resume/export/daemon state.

Only terminal 2xx `text/html` responses are parsed, with media type parameters
removed and case ignored. There is no MIME sniffing and XHTML/XML is skipped.
Crawl consumption supports identity and gzip only; unsupported or stacked
encodings, unsupported charsets, corrupt gzip, non-HTML media, and over-limit
bodies are recorded as skips and are never partially parsed. Supported charset
labels are UTF-8, US-ASCII, ISO-8859-1, and Windows-1252; absent means UTF-8.

The fixed per-response limits are 2,097,152 encoded bytes and 1,048,576 decoded
bytes, enforced while the kernel consumes the stream. Extraction retains at
most 1,024 discoveries, 64 forms, 64 fields per form and 1,024 fields per
document; candidate URLs are limited to 8,192 UTF-8 bytes and stored
descriptions to 256 Unicode characters with an explicit truncation marker.
An oversized crawl seed is a configuration error (exit 1), checked both before
normalization and against its canonical URL before persistence or admission.
Limit metadata says when counts are incomplete rather than claiming an unseen
total.

The kernel closes the HTTP response before delivering a private transient HTML
lease to a worker. Releasing that lease only drops its bounded bytes and exact
resolution URL; it performs no network work. Raw retention remains off by
default. When explicitly enabled, only complete bounded bodies may enter the
existing evidence store. Public summaries, SQLite rows, console output, and
reports remain redacted. Response metadata records `body_complete` and an
optional `body_stop_reason`, so an unread or interrupted representation is not
reported as a complete empty body.

## Bounded static JavaScript extraction

`broadside crawl` can additionally produce bounded, provenance-bearing static
observations from external `<script src>` bodies discovered during the HTML
walk. It is off by default and opt-in only:

```bash
broadside crawl http://127.0.0.1:8765/js/ \
  --scope testdata/scope/lab_local.yml \
  --i-am-authorized \
  --platform self-hosted-lab \
  --extract-js \
  --max-js-assets 100 \
  --js-queue-capacity 256
```

`--extract-js` is the explicit opt-in; supplying `--max-js-assets` (1–10,000) or
`--js-queue-capacity` (1–4,096) without it is a configuration error (exit 1),
even when the value equals the default. JavaScript work reuses the existing
`--workers` setting and there is no JavaScript URL argument, file input, or
resume flag. Only classic and module scripts with a nonblank external `src`
found in a fully parsed page are eligible; inline scripts, import maps,
`javascript:` URLs, non-JavaScript `type` values, and blank `src` are
record-only and never fetched.

The HTML and JavaScript phases never overlap. Each budget-safe HTML batch closes
every response stream, then the JavaScript queue drains on the same shared
run budget before the next HTML batch, so an enabled run may visit fewer pages.
With JavaScript disabled the crawl is byte-for-byte page-only. Every JavaScript
GET uses the same `ScopedHTTPClient`, carries the fixed `javascript` tag and
provenance across redirects and retries, and re-gates on every hop; there is no
second HTTP client. Only complete terminal 2xx `text/javascript` or
`application/javascript` bodies (UTF-8 or US-ASCII, identity or gzip) are
parsed, with media-type parameters stripped.

The extractor is a bounded standard-library lexer plus token recognizers — it
**does not execute JavaScript**, evaluate expressions, render a browser, or
resolve modules. It yields closed, deduplicated **static observations** only:
`fetch`/XHR/axios calls, WebSocket URLs, API-route candidates, GraphQL
operations and variable names, query parameters, feature flags, environment
references, import references, source-map references, and potential-secret
markers. Each observation is a `static_pattern`, not a verified endpoint or a
proof that a code path runs, and extracted endpoints, WebSockets, GraphQL
operations, imports, and maps are never followed. Relative references stay
unresolved rather than being resolved against the script origin. Extraction is
skip-never-partial: any cap, decode, or parse failure yields zero observations
for that asset, and its stop reason is recorded with `extraction_complete=false`.

Source maps are reference-only. A `sourceMappingURL` directive is recorded as a
redacted reference only; Broadside **does not fetch source maps**, decode inline
maps, or retrieve original sources. Potential-secret findings are heuristic review markers
stored as **category and location** only — `SENSITIVE_ASSIGNMENT`,
`PRIVATE_KEY`, `JWT_LIKE`, or `TOKEN_LIKE` — with no value, excerpt, prefix,
digest, or masked sample, and are never turned into requests, credentials, or
templates. **JavaScript bodies are never retained** as evidence even when scope
`evidence.retain_raw` is enabled; opted-in HTML evidence is unchanged.

## Offline endpoint inventory

Sprint 005 derives a bounded inventory of **endpoint candidates** from one
finalized scan's stored metadata. It does not fetch URLs, open sockets, probe
authentication, reconstruct secrets, or invent body keys. Identity is
source-anchored `(scan_run_id, source_kind, source_id)` with kinds `request`,
`crawl_discovery`, and `js_observation` — not redacted-URL or private-hash
identity. CLI counts are candidate counts.

Primary command (no `--i-am-authorized`; the database must already exist):

```bash
broadside inventory --database broadside.db [--scan-run-id ID] [--replace]
```

Optional end-of-crawl hook, after collection handles close, using the same
builder against persisted rows. It requires an explicit filesystem `--database`
path (not `:memory:` or a missing flag). Default crawl behavior is unchanged:

```bash
broadside crawl http://127.0.0.1:8765/crawl/ \
  --scope testdata/scope/lab_local.yml \
  --i-am-authorized \
  --platform self-hosted-lab \
  --database broadside.db \
  --build-inventory
```

Schema version 5 is additive and creates seven inventory tables (19 user tables
total). Missing paths never create a database. Without `--replace`, an existing
inventory for the selected scan is refused. This command surface is
implementation-verified and included in the prepared `0.5.0` package;
tagging and publication remain separately gated.

## Control/test experiments

`experiment run` executes one strict JSON spec through the existing authorized
kernel. The first version accepts only body-free GET/HEAD/OPTIONS pairs on the
same origin with distinct canonical URLs and the same method. Specs cannot
supply headers, sessions, bodies, executable comparison code, or their own
approval. Unknown keys, duplicate JSON keys, files over 64 KiB, URLs over 8 KiB,
and invalid pairing are rejected before a client is constructed.

Start the deterministic lab (`broadside lab serve`) in another terminal, then
run the checked-in example from the repository root (single-line commands work
in Bash and PowerShell):

```text
broadside experiment run testdata/experiments/status_pair.json --scope testdata/scope/lab_local.yml --i-am-authorized --platform self-hosted-lab --database experiments.db
```

The example repeats a 404 control and a 200 test twice. It demonstrates the
framework, **not a vulnerability**. Each repetition sends control then test with
fresh request IDs and the corresponding `control`/`experiment` purpose. All
redirects and retries are re-gated and consume the same run budget. Preflight
requires enough budget for the direct pairs; redirects/retries can still exhaust
it. The first failed/refused/incomplete arm stops the run.

Choose `metadata_difference` to compare status plus a normalized media-type
category, or `status_pair` with distinct `control_status` and `test_status`.
Two to five repetitions are required. Each arm's metadata must be consistent
across repetitions. Body text, arbitrary header values, timing, body similarity,
and security impact are not compared. Matching expectations produce
`inconclusive` / `OBSERVED_DIFFERENCE`; stable absent expectations produce
`rejected`; unstable or incomplete execution remains `inconclusive`.

Response consumption is capped at 2 MiB encoded and 1 MiB decoded per hop,
supports identity/gzip, and closes streams under the kernel's concurrency limit.
Truncated, oversized, or unsupported representations cannot support validation.
Raw retention stays opt-in; only complete bounded bodies may be retained.

Schema-v6 records link hypothesis → experiment → ordered observations → actual
request/response rows. Existing redirect/retry ancestry supplies the evidence
graph, including refused audit nodes without invented request rows. No raw spec,
body content, arbitrary narrative, or header values enter experiment summaries.
`source_request_ids` can link a hypothesis to up to 16 existing requests; these
references never become executable URLs or credentials.

Use the run UUID printed by the command to inspect the SQLite evidence. After
reviewing a real reproducible difference and independently confirming security
impact, a human can record one immutable, offline attestation:

```text
broadside experiment review RUN_UUID --database experiments.db --verdict validated --impact-confirmed
```

Do not validate the demonstration fixture: its status difference has no
demonstrated security impact. To reject a completed experiment instead, use
`--verdict rejected` without the impact flag. Validation requires at least two
complete, reproducible, matching pairs backed by stored responses. Reviews make
no requests, do not overwrite earlier reviews, and do not create findings,
severity ratings, or report submissions. Human attestation is not independent
machine proof of impact. A missing database is refused without creating it.

Run exits: `0` completed execution (including inconclusive/rejected), `2`
interrupted execution, `1` invalid configuration or storage failure. Review exits
`0` on success and `1` on refusal. There is no resume, body matcher, session
resolver, mutation experiment, or automatic experiment generation from inventory.

### Sprint 008 authorization-context experiments

The version-2 `authorization` spec selects exactly one target and two distinct
closed roles (`unauthenticated`, `user`, `peer_user`, or `privileged`), at least
one authenticated. Each authenticated context imports one bearer token or
cookie header from a local, available terminal with input echo disabled.
Redirected stdin, CLI arguments, environment variables, files, browser
sessions, and custom authentication headers are not credential sources. Imports
are bounded to 8,192 ASCII bytes each, 16,384 combined, and at most 32 cookie
pairs. Credentials live only in the run's private memory lease; Broadside has
no persistent vault or automatic credential refresh. Memory-only does not
guarantee zeroization of Python, HTTP-library, or OS copies.

With `broadside lab serve --host 127.0.0.1 --port 8765` in another terminal,
run this secret-free example from the repository root. Through hidden terminal
input, enter `control-test-token` for control, then `peer-test-token` for test.
These are fixed synthetic lab-only bearer values;
there is no per-context visible prompt, and values never belong in the command
or spec. Native Windows/POSIX terminal adapters have deterministic mocked
coverage; live native-TTY manual smoke was unavailable for this verification.
The checked-in scope is literal-loopback lab mode, allows only
GET/HEAD/OPTIONS, and sets `retain_raw: false`:

```text
broadside experiment run testdata/experiments/authz.json --scope testdata/scope/lab_local.yml --database authz.db --platform self-hosted-lab --i-am-authorized --approve-authz
```

Both `--i-am-authorized` and the separate per-run `--approve-authz` gate are
required before credential import or network construction. A v2 run refuses
`retain_raw: true`; it writes no raw evidence or request templates. An existing
database must be quiescent/checkpointed before import: nonempty WAL or rollback
journals, unsafe sidecars, or detected file changes fail closed. Broadside
does not automatically checkpoint or clean them, nor claim filesystem tamper
resistance. Atomic start rechecks source evidence after import. Ordinary old
`auth_context_ref` strings remain inert metadata, not credential capabilities.

V2 sends one ordered control/test sequence for two to five repetitions (four
to ten requests at most) through the existing kernel. It uses one client and
run budget; every attempted request is re-gated. The request set is fixed:
body-free GET/HEAD/OPTIONS only, no automatic redirect follow, retry, login,
refresh, object enumeration, or cookie adoption from responses. HTTPS requires
verified TLS. HTTP is permitted only for literal `127.0.0.1` or `[::1]` with
`lab_mode: true`; DNS names do not grant that exception. An insecure TLS proxy
is refused outside lab mode. Response consumption is capped at 2 MiB encoded
and 1 MiB decoded, identity/gzip only; an incomplete response cannot support
validation. Supported HTTPX/HTTPcore transport diagnostics are suppressed only
during this authorization path, not globally; arbitrary in-process hooks that
capture raw objects before filtering are outside that boundary.

The fixture expects 200/200 on `/sprint008/account`. Equal status codes are
only observations, not proof of body equivalence, object ownership, or
security impact: this example remains inconclusive. There is no automatic
vulnerability verdict. A human must independently inspect the evidence,
verify the two context identities and security impact, and then choose whether
an offline review is justified. The command shape is:

```text
broadside experiment review RUN_UUID --database authz.db --verdict validated --impact-confirmed --contexts-confirmed
```

Replace `RUN_UUID` with the run ID from execution. The two review flags are
human attestations, not instructions to auto-validate the lab's 200/200 pair.
Do **not** validate the demonstration fixture merely because it completed or
matched its declared statuses. Validated review requires complete,
reproducible matching evidence and both attestations; review makes no network
request, is immutable, and creates no finding or report. Offline redacted
evidence cannot reconstruct exact targets or credentials. Encoding is not
stored, so a bounded incomplete `CONTENT_DECODING_FAILED` row is failure
metadata, not independent proof of decoded content.

## Diagnostic-exposure proposals

`diagnostic propose` is an offline producer. It reads one operator-selected
completed source pair from an **existing schema-v6/v7 database** (read-only; it
never migrates or creates a database) and writes one ordinary Sprint 006
`ExperimentSpec`. It does not construct an HTTP client, run the experiment, or
invoke human review. Schema-v7 authorization-run sources are excluded; it
never turns credential-bearing evidence into a proposal or v2 run.

Source collection is a separate, explicitly authorized workflow. Record a local
lab pair first, for example with `broadside experiment run` against
`broadside lab serve`, then inspect the completed scan and request IDs in
SQLite. Replace the illustrative UUIDs below with those **actual same-scan**
evidence IDs; the values from the test helper are not preexisting evidence.

```json
{
  "version": 1,
  "source_scan_id": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaa0001",
  "control": {
    "request_id": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaa0002",
    "url": "http://127.0.0.1:8765/sprint007/missing"
  },
  "candidate": {
    "request_id": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaa0003",
    "url": "http://127.0.0.1:8765/sprint007/exposed/diagnostics"
  }
}
```

Bindings are strict JSON: version 1 only, no unknown fields or duplicate keys,
UUIDs and absolute HTTP(S) URLs, at most 65,536 bytes. Queries (including a
bare `?`), fragments, userinfo, redaction markers, percent-encoded or
brace-template paths, dot segments, and repeated slashes are rejected rather
than rewritten. Paths may use `/`, ASCII letters/digits, `-`, `_`, and `.`.
Each selected request must have exactly one matching template. The candidate
path must be `/diagnostics` or end with `/diagnostics`; the control must not.

```text
broadside diagnostic propose binding.json --database lab.db --scope testdata/scope/lab_local.yml --output diagnostic-proposal.json
```

Inspect the proposal file, then run it only with explicit authorization and
the same source database:

```text
broadside experiment run diagnostic-proposal.json --scope testdata/scope/lab_local.yml --i-am-authorized --platform self-hosted-lab --database lab.db
```

The exported spec is `safety=read_only`, `repetitions=2`, `boundary=representation`,
and `status_pair` 404/200. Preflight requires a request budget of at least four
nominal sends; retries and redirects still consume the existing run budget.
Proposal files contain the operator-supplied URLs in plaintext: they are local
request inputs, not redacted audit artifacts. The command refuses to overwrite
an existing output path or symlink.

Exit codes: `0` wrote a proposal, `2` valid but ineligible pair (unsupported
route, unexpected source statuses, credential-bearing source, and similar
skip reasons — these are not findings), `1` malformed binding, storage, scope,
or export error. Console output is fixed outcomes and UUIDs, never URLs or
record contents.

A matched execution remains **inconclusive**. Status differences cannot
distinguish synthetic internal diagnostics from a public health page or a
login/documentation page that also returns 200. Only the existing separate
human review can attest impact. This command surface is implementation-verified
and included in the prepared `0.5.0` package, still untagged and unpublished.

## Request bodies

`RequestIntent.body` accepts the pure `BodySpec` union; no public model exposes
an HTTPX type. The helpers provide deterministic bytes and content types for:

- `RawBodySpec` (`bytes`, with an optional media type)
- `JsonBodySpec` (canonical compact UTF-8 JSON)
- `FormBodySpec` (ordered URL-encoded fields)
- `MultipartBodySpec` (ordered parts and a content-derived deterministic
  `multipart/form-data` boundary)

```python
from uuid import uuid4

from broadside.models import FormBodySpec, FormField, HTTPMethod, RequestIntent

intent = RequestIntent(
    request_id=uuid4(),
    method=HTTPMethod.POST,
    url="http://localhost:8765/echo",
    body=FormBodySpec(fields=(FormField(name="mode", value="safe"),)),
)
```

Conflicting caller-supplied `Content-Type` values are rejected. Multipart names,
filenames, and content types reject header-line injection. Body bytes never
appear in audit, console, template metadata, or reports; raw request bodies exist
only when evidence retention is explicitly enabled.

## Cookies and redaction

Cookie behavior is explicit-header-only. No cookie jar is merged into later
requests, redirects, retries, or replay. A caller may deliberately provide a
`Cookie` header, but it is redacted from outward metadata and captured templates
record an unresolved secret reference instead of its value. Response
`Set-Cookie` is likewise redacted and never becomes request state.

Authorization headers, proxy authorization, API keys, cookie values, declared
secret headers/query fields, sensitive query values, and bodies are redacted
before persistence or presentation. Raw evidence is the sole opt-in exception.

## Explicit proxy / Burp configuration

Ambient proxy environment variables are ignored because the only production
HTTPX client is created with `trust_env=False`. To use Burp or another proxy,
configure its URL explicitly in scope YAML:

```yaml
proxy:
  url: http://127.0.0.1:8080   # proxy.url; http or https, no credentials
  tls_insecure: true
```

`proxy.tls_insecure: true` sets `verify=False` on the entire proxy-configured
HTTPX client. With the HTTP Burp proxy shown above, there is no TLS proxy leg;
the consequence is that certificate verification is disabled for HTTPS target
requests sent through Burp. Outside `lab_mode`, the run is rejected before
transport construction unless the operator adds the explicit acknowledgment:

```bash
broadside scan https://target.example/ \
  --scope scope.yml \
  --i-am-authorized \
  --platform hackerone \
  --allow-insecure-proxy-tls
```

The proxy URL may not contain userinfo, a non-root path, query, or fragment.
Only the normalized proxy host and whether client certificate verification is
enabled are audited; proxy credentials are unsupported. Treat
`--allow-insecure-proxy-tls` as acceptance that proxied HTTPS targets are no
longer authenticated by their certificates, not as a narrow exception for a
proxy certificate.

## Retries, redirects, and budgets

`retry.max_retries` defaults to `0` and is bounded from 0 through 3. Status-code
retries default to 502/503/504; transport-error retries are separately opt-in.
Every attempt gets a new request ID, consumes the per-run request budget, waits
for the same token bucket and concurrency semaphore, and re-enters the complete
scope/method/Host policy gate before transport.

Retry lineage is separate from redirect lineage. `attempt_index` begins at 0;
later attempts link to the original attempt through `retry_of_request_id`.
`parent_request_id` is reserved for redirect ancestry. Redirect following is
disabled inside HTTPX; each `Location` becomes a new intent that is normalized
and re-gated. Cross-origin redirects drop secret-bearing headers and auth
context.

## Request corpus and replay

Each admitted non-replay logical hop automatically creates one secret-free row
in the `request_templates` table for its `attempt_index == 0` request. Retry
attempts do not create duplicate templates; their `retry_of_request_id` points
back to the first attempt. A redirect is a separately admitted logical hop and
therefore can create its own attempt-zero template. Replay requests, including
their redirects and retries, never create templates. A template records
redacted request metadata, provenance, content type and digest, and unresolved
secret references. It never contains raw secret values. A body artifact
reference is captured only when it points to the exact retained `request.body`
beneath the configured evidence root and matches the expected digest.

Replay requires the same current scope, authorization, platform, proxy/TLS
acknowledgment, budget, rate, concurrency, and Host checks as any fresh request:

```bash
broadside replay TEMPLATE_UUID \
  --database broadside.db \
  --scope scope.yml \
  --evidence-root evidence \
  --i-am-authorized \
  --platform self-hosted-lab
```

Replay is intentionally lossy. It restores only this positive safe-header
allowlist: `Accept`, `Accept-Encoding`, `Accept-Language`, `Cache-Control`,
`Content-Type`, `If-Match`, `If-Modified-Since`, `If-None-Match`, `If-Range`,
`If-Unmodified-Since`, `Pragma`, `Range`, and `User-Agent`. `Host`, hop-by-hop
headers, forwarding/routing headers, method-override headers, and all unknown or
custom headers are not restored. HTTPX derives Host from the already normalized
URL, and the kernel still enforces Host equivalence for every intent.

No secret resolver exists for replay. A template containing `secret_refs`
or `auth_context_ref` fails closed rather than prompting, reading the
environment, or inventing credentials. Sprint 008's separate, private
authorization approval/handle path does not activate these old references.
Replay bodies also fail closed unless
the configured evidence root exists, is not a symlink/reparse point, contains
the artifact lexically and after resolution, and the regular file matches its
stored SHA-256 digest.

## Response and evidence behavior

Broadside requests gzip support and consumes each response while holding its
concurrency slot. For an unread gzip response, it retains the encoded bytes and
validates/decompresses them once with the standard library. Valid gzip records
`content_decoded_by_broadside: true`; malformed or truncated gzip is preserved
unchanged with that flag false. Already-decoded responses are never decompressed
again. Other encodings use HTTPX's normal decoding. Body size and opt-in evidence
describe the resulting bytes, and the original `Content-Encoding` is retained.

TLS metadata is best-effort: protocol version, cipher, certificate subject and
issuer, expiry, and ALPN are stored only when the HTTP transport exposes them.
Plain HTTP and transports without those extensions store `null`; missing TLS
metadata is not an error.

Raw evidence remains off by default. When `evidence.retain_raw` is true, the
evidence root is created and validated before transport construction. Root,
run, request, and existing artifact paths reject symlinks/reparse points and
non-directory/non-file substitutions; generated identifiers are constrained;
and the resolved request directory must remain under the trusted root.

## Database migration

Opening a version-1 through version-6 Broadside SQLite database through the
standard database path upgrades it transactionally and in place to schema
version 7. Version 2's request corpus remains intact. The version-3 migration
adds exactly `crawl_runs`, `crawl_pages`, and
`crawl_discoveries`, plus `responses.body_complete` and nullable
`responses.body_stop_reason`. Crawl rows keep redacted page/discovery metadata
and separate admitted/submitted/parsed/request counters; request rows remain the
source of truth for distinct retry (`retry_of_request_id`) and redirect
(`parent_request_id`) ancestry. Discoveries link to the terminal request that
provided the parsed document; the crawl page retains its logical root request.

Schema version 4 is additive on top of version 3 and adds exactly three tables —
`js_runs`, `js_assets`, and `js_observations` — plus nullable `js_asset_id` and
`js_disposition` columns on `crawl_discoveries` and `resource_tag`/`script_type`
inside the existing allowlisted discovery metadata. A JavaScript run is created
only for an enabled crawl and stores the immutable options snapshot, the
`static-v1` extractor rule version, status, and bounded counters. `js_assets`
records one admitted asset slot each (including unsent or cancelled work) with
redacted requested/terminal URLs; `js_observations` holds the closed, redacted
per-document observations and stores no raw JavaScript. Existing rows stay
null/unknown for the new metadata and are never upgraded into executable script
work. Version 5 adds seven inventory tables: `inventory_runs`, `endpoints`,
`endpoint_parameters`, `endpoint_provenance`, `tech_signals`,
`auth_flow_sketches`, and `id_relation_candidates`. Version 6 adds `hypotheses`,
`experiments`, `experiment_observations`, and `experiment_reviews` (23 user tables
total). Version 7 additively adds four authorization tables and nullable,
checked `responses.authz_media_category`, for 27 user tables total. Historical
v1 experiment models and stored evidence are not relabeled as authenticated.
Offline inventory accepts existing version-4, version-5, version-6, and version-7
databases and upgrades older accepted versions to current; it never creates a
missing database. Reopening a current
database is a no-op; unknown older versions and future
versions are refused. Back up important databases before any migration as normal
operational practice.

## Local lab

```bash
broadside lab serve --host 127.0.0.1 --port 8765
```

The deterministic lab binds only to loopback and supplies redirect, gzip, slow,
cookie, echo, retry, bounded crawl, `/js/` script-extraction fixtures
(including a redirect/retry script chain and references that must never be
fetched), synthetic `/sprint007/` diagnostic-looking JSON fixtures, and fixed
synthetic `/sprint008/` authorization-context fixtures.
Lab requests use the same
application and `ScopedHTTPClient` path as production. The optional pinned OWASP
Juice Shop lab remains available on port 3000; its [setup guide](labs/juice-shop/README.md)
uses the ready-made `testdata/scope/lab_juice_shop.yml` scope.

## Current limitations

- The crawler handles bounded HTML structure plus opt-in static extraction from
  external scripts; no JavaScript execution, browser rendering, source-map
  fetching, non-script asset traversal, robots/sitemap processing, or resume
- Endpoint inventory is derive-only from stored metadata: no live endpoint
  fetch, exact URL identity recovery, auth probing, robots/sitemaps, body-key
  invention, cookie-name recovery, or secret reconstruction
- Static JavaScript observations and inventory rows are candidates, not verified
  endpoints, and are never followed; potential-secret markers are
  category/location review hints
- No general vulnerability plugin runtime, exploit PoCs, or payload fuzzing;
  the built-in diagnostic-exposure producer only emits a reviewable spec
- Experiments compare bounded response metadata only; a human must attest
  security impact before any validated verdict
- Diagnostic proposals do not execute themselves or distinguish sensitive from
  benign HTTP 200 pages; Sprint 008 authz runs are a separate explicit mode
- No cookie jar, general session manager, browser automation, vault, or replay
  secret resolver; Sprint 008 credentials are run-local and terminal-imported
- No LLM networking, alternate HTTP client, or shell-out networking
- No report generation; templates are request-corpus records, not findings
- Replay cannot restore arbitrary/custom headers or resolve credentials
- TLS metadata may be unavailable; raw evidence is local, opt-in, and sensitive

## Tests and documentation

```bash
pytest -W error
```

The suite denies non-loopback sockets globally and otherwise uses injected
transports or ephemeral loopback servers.

- [Architecture](docs/ARCHITECTURE.md)
- [Roadmap](docs/ROADMAP.md)
- [Threat model](docs/THREAT_MODEL.md)
- [Sprint 002 design](docs/superpowers/specs/2026-09-04-broadside-sprint-002-design.md)
- [Sprint 003 crawler design](docs/superpowers/specs/2026-09-04-broadside-sprint-003-crawler-design.md)
- [Sprint 004 JavaScript design](docs/superpowers/specs/2026-09-05-broadside-sprint-004-javascript-design.md)
- [Sprint 005 endpoint intelligence design](docs/superpowers/specs/2026-09-12-broadside-sprint-005-endpoint-intelligence-design.md)
- [Sprint 006 experiment framework design](docs/superpowers/specs/2026-09-16-broadside-sprint-006-experiments-design.md)
- [Sprint 007 diagnostic-exposure design](docs/superpowers/specs/2026-09-16-broadside-sprint-007-diagnostic-exposure-design.md)
