diff --git a/.gitattributes b/.gitattributes index ebfb896..80bc4a9 100644 --- a/.gitattributes +++ b/.gitattributes @@ -24,5 +24,8 @@ *.mp4 binary *.mhl text +# Fuzz seeds are exact bytes: a CRLF or a stray encoding is the test case. +tests/fuzz_corpus/** binary + # Keep generated/vendored material out of language stats and diffs. docs/** linguist-documentation diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 783dfae..e8a1f52 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -91,24 +91,6 @@ jobs: - run: offloader info - run: pytest -q - fuzz: - name: property tests (soak) - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: "3.13" - cache: pip - - run: | - python -m pip install --upgrade pip - python -m pip install -e ".[dev]" - - name: Run the property tests at soak depth - # All three property modules: test_fuzz.py fuzzes what a filename can - # contain, test_fuzz_edges.py what a card can contain, and - # test_edge_cases.py the layers between the bytes and the paperwork. - run: pytest tests/test_fuzz.py tests/test_fuzz_edges.py tests/test_edge_cases.py --fuzz -q - build: name: build the distribution runs-on: ubuntu-latest diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml new file mode 100644 index 0000000..55e0225 --- /dev/null +++ b/.github/workflows/fuzz.yml @@ -0,0 +1,146 @@ +name: Fuzz + +# The soak: every property test at a deep example budget. Too slow for every +# pull request, where the ordinary suite already runs each property at 100 +# examples and replays the committed seed corpus. Here it runs nightly and on +# demand, on Linux and on Windows, whose paths, junctions and file locking are +# where a card offload is most likely to differ. +# +# Permissions are split as in markcopy's fuzz workflow: the job that runs +# untrusted-input tests holds a read-only token, and only the reporting job +# can write issues. + +on: + schedule: + - cron: "17 3 * * *" + workflow_dispatch: + inputs: + examples: + description: Examples per property (the --fuzz default is 3000) + required: false + default: "3000" + +permissions: + contents: read + +concurrency: + group: fuzz-${{ github.ref }} + cancel-in-progress: false + +env: + QT_QPA_PLATFORM: offscreen + PYTHONUTF8: "1" + +jobs: + soak: + name: soak / ${{ matrix.os }} + runs-on: ${{ matrix.os }} + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + steps: + - uses: actions/checkout@v4 + # Replaced by the test output below. If setup fails first, this is the + # log the artifact carries, so that platform still gets an issue. + - run: echo "The soak did not reach the tests." > soak.log + shell: bash + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + cache: pip + - run: | + python -m pip install --upgrade pip + python -m pip install -e ".[dev]" + + # Hypothesis replays every failing example it has saved before + # generating new ones, so a failure found one night is retried first + # the next. A per-run key with a prefix restore carries the newest + # database forward. + - uses: actions/cache@v4 + with: + path: .hypothesis + key: hypothesis-${{ matrix.os }}-${{ github.run_id }} + restore-keys: hypothesis-${{ matrix.os }}- + + - name: Run every property test at soak depth + shell: bash + env: + OFFLOADER_FUZZ_EXAMPLES: ${{ inputs.examples || '3000' }} + # The whole suite, so a new fuzz module needs no change here. + run: | + set -o pipefail + pytest --fuzz -q 2>&1 | tee soak.log + + - name: Keep the log and the example database + # Not `failure()`: a job that hits timeout-minutes ends cancelled. + if: ${{ !success() }} + uses: actions/upload-artifact@v4 + with: + name: soak-${{ matrix.os }} + path: | + soak.log + .hypothesis/ + retention-days: 30 + + report: + name: file the failure + needs: soak + # Any soak outcome but success, timeouts included. A run cancelled by + # hand files one too; close it if it says nothing. + if: ${{ always() && needs.soak.result != 'success' }} + runs-on: ubuntu-latest + permissions: + contents: read + issues: write + actions: read + steps: + - uses: actions/download-artifact@v4 + with: + pattern: soak-* + - name: Open or update an issue per failing platform + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + shopt -s nullglob + folders=(soak-*/) + if [ ${#folders[@]} -eq 0 ]; then + # Failed before the log existed: setup, install, or a timeout. + folders=("soak-unknown/") + fi + for folder in "${folders[@]}"; do + platform="${folder#soak-}"; platform="${platform%/}" + title="Fuzz failure: ${platform}" + { + echo "The nightly soak failed on \`${platform}\`: ${RUN_URL}" + echo + if [ -f "${folder}soak.log" ]; then + echo "Each falsifying example is printed with a \`@reproduce_failure\`" + echo "line that replays it locally. The log and the example database" + echo "are attached to the run as \`soak-${platform}\`." + echo + echo '```' + found=$(sed -n -E '/^(FAILED|E |Falsifying|@reproduce_failure)/p' "${folder}soak.log" | head -n 80) + if [ -n "${found}" ]; then + echo "${found}" + else + # No test failed: setup broke, or the job ran out of time. + tail -n 40 "${folder}soak.log" + fi + echo '```' + else + echo "No log was produced: the job failed before the tests ran or" + echo "timed out. Treat the harness as broken until the run says why." + fi + } > body.md + existing=$(gh issue list --state open --search "in:title \"${title}\"" \ + --json number,title --jq ".[] | select(.title == \"${title}\") | .number" | head -n 1) + if [ -n "${existing}" ]; then + gh issue comment "${existing}" --body-file body.md + else + gh issue create --title "${title}" --body-file body.md + fi + done diff --git a/.gitignore b/.gitignore index 416e834..7a0c047 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ dist/ .venv-build/ venv/ .pytest_cache/ +.hypothesis/ .coverage htmlcov/ *.log diff --git a/AGENTS.md b/AGENTS.md index 53ba7f7..c5db3cc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -135,9 +135,13 @@ python -m pytest -q Run the deeper property checks when relevant to safety or parser changes: ```powershell -python -m pytest tests/test_fuzz.py tests/test_fuzz_edges.py tests/test_edge_cases.py --fuzz -q +python -m pytest tests/test_fuzz.py tests/test_fuzz_edges.py tests/test_fuzz_parsers.py tests/test_fuzz_state.py tests/test_fuzz_engine.py tests/test_edge_cases.py --fuzz -q ``` +A module that starts reading outside input needs an entry in +`tests/fuzz_surfaces.json` in the same change: a fuzz target, or a stated gap. +See CONTRIBUTING's "Fuzz targets". + Build Python distributions when packaging changes: ```powershell @@ -161,8 +165,11 @@ reference outputs for formats and checksums over tests that mirror the writer. See CONTRIBUTING for existing synthetic BRAW/BWF fixtures and failure helpers. CI configuration is in [ci.yml](.github/workflows/ci.yml): cross-platform -tests, a Python minimum-version job, ffmpeg coverage, property-test soak, and -wheel/sdist validation. A configured job is not evidence of a passing run. +tests, a Python minimum-version job, ffmpeg coverage, and wheel/sdist +validation. The property-test soak runs nightly and on demand in +[fuzz.yml](.github/workflows/fuzz.yml) on Linux and Windows, and a failure +opens or updates a `Fuzz failure: ` issue. A configured job is not +evidence of a passing run. Report what was actually executed and any skips or environment limitations. ## Implementation, documentation, and releases diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ea8447..aaa321c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,37 @@ project uses [semantic versioning][semver]. ## [Unreleased] +### Fixed + +Found by `tests/test_fuzz_parsers.py` and `tests/test_fuzz_state.py`, which +fuzz the documents offloader reads back and the files it keeps between +runs. Each fix has the reproduction that found it. + +- **One damaged byte in a previous ASC MHL manifest cost the next one.** An + XML declaration reading `encoding="TF-8"` raised `LookupError`, and a + multi-byte encoding a `ValueError`, where the reader expected only a parse + error. The ASC MHL report then failed (recorded, not silent) instead of + starting a new generation. `verify` now reports such a manifest as one that + will not parse. +- **A deeply nested state file stopped the history loading.** `[[[[...` + raised `RecursionError`, which `read_json` did not treat as damage, so the + promise that a corrupt state file never stops an offload did not hold. +- **One overflowing count dropped a history record.** A `file_count` of + `1e400` made `int()` raise `OverflowError`, losing the record and the + duplicate-card warning its fingerprint provides. The count is now zero. +- **An iXML frame rate of `inf` reached the sound report.** `float()` accepts + `inf`, and a huge ratio overflows to it. Non-finite rates are now ignored, + like a zero or negative one. + ### Changed +- **The property-test soak runs nightly, on Linux and Windows.** It took + about 7 minutes on every pull request and ran on Linux only. `fuzz.yml` + now runs it on a schedule and on demand, keeps Hypothesis's database of + failing examples between runs, and opens or updates a `Fuzz failure: ` + issue with the reproduction when it fails. Pull requests still run every + property at the quick budget and replay the seed corpus. + - **Full verification is the default.** The read-back is the only mode that proves what is on the destination device, and the default should be the one whose "Verified" means the most. Applies to the engine's options, new diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9e476f4..d2df6c8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -38,7 +38,7 @@ pip install -e ".[dev]" ```sh pytest # run the full suite -pytest --fuzz # property tests at 3000 examples each, about 3 min +pytest --fuzz # property tests at 3000 examples each, about 7 min ruff check src tests pytest --cov=offloader --cov-report=term-missing ``` @@ -60,6 +60,44 @@ python tools/screenshots.py # rewrites docs/images/ It runs the real app against a throwaway config directory and invented volumes, so it neither reads your presets nor puts your drive labels in the README. +## Fuzz targets + +[`tests/fuzz_surfaces.json`](tests/fuzz_surfaces.json) lists every module +that reads or renders input offloader did not write, with the property tests +that fuzz it, or a `gap` saying what is not fuzzed yet. A module that starts +parsing card data, a manifest, a timeline or a state file comes with an entry +in the same change: a new target, or an honest gap. `tests/test_fuzz_surfaces.py` +fails on an unclassified module, a target that is not a `@given` test, a fuzz +test no surface claims, or a soak workflow that no longer runs on a schedule. + +The soak (`pytest --fuzz`, about 3000 examples per property) is too slow for +every pull request, so [`fuzz.yml`](.github/workflows/fuzz.yml) runs it +nightly on Linux and Windows, and on demand with a chosen example count +(`OFFLOADER_FUZZ_EXAMPLES` locally). Pull requests still run every property +at 100 examples and replay the seed corpus. A nightly failure opens or +updates a `Fuzz failure: ` issue with the falsifying examples and their +`@reproduce_failure` lines; paste one above the failing test to replay it, +then fix it as below. + +A target checks the answer, not just that nothing raised. Wrap the call in +`fuzz_oracle.bounded` (documented exceptions only, a time and memory ceiling) +and add the property only a correct parser satisfies: a round trip, a +reference implementation, or for anything that feeds a verdict, that a pass +is backed by a hash taken now. Use `fuzz_oracle.scaled(n)` for a per-test +example budget, so `--fuzz` still deepens it. + +Byte-level targets live in [`tests/fuzz_targets.py`](tests/fuzz_targets.py) +as `bytes -> None` functions, so the Hypothesis tests and the seed replay +state each property once. Their seeds are in `tests/fuzz_corpus//`, +generated from the unit-test builders by `python tests/make_fuzz_seeds.py` +(small, reproducible, never copied off a real card), and +`tests/test_fuzz_corpus.py` replays every one on each test run. + +A bug a target finds becomes three things in the same change: the fix, a +deterministic regression test, and the failing input, both as an `@example` +on the target that found it and as a `regress-` seed in +`make_fuzz_seeds.py`. Check that the test and the seed fail without the fix. + ## Testing without a card Almost nobody has a 27 GB BRAW clip, a sound cart and a failing card reader to diff --git a/README.md b/README.md index 6787e29..272af5c 100644 --- a/README.md +++ b/README.md @@ -638,12 +638,12 @@ Full verification only when every present destination was hashed. ```sh pip install -e ".[dev]" pytest # run the full suite -pytest --fuzz # same suite, 3000 examples per property (~3 min) +pytest --fuzz # same suite, 3000 examples per property (~7 min) ruff check src tests pytest --cov=offloader --cov-report=term-missing ``` -1383 tests at 87% line coverage. They cover formatting against the reference's +1454 tests at 87% line coverage. They cover formatting against the reference's exact strings, checksum vectors and streaming equivalence, copy/verify behaviour including simulated destination corruption, pause/resume/cancel concurrency, retry discrimination, BRAW container parsing, ffprobe parsing, @@ -662,7 +662,7 @@ real camera file when one is present. ### Property-based testing -Three modules use [Hypothesis][hyp] to assert invariants over generated input +Six modules use [Hypothesis][hyp] to assert invariants over generated input rather than over a handful of fixtures, each aimed at a different layer: - **`tests/test_fuzz.py`: what a filename can contain.** Names come off camera @@ -673,6 +673,35 @@ rather than over a handful of fixtures, each aimed at a different layer: atom headers lie, a tree that maps two sources onto one destination, a directory junction pointing at its own parent, a retry policy someone hand-edited into a preset. +- **`tests/test_fuzz_parsers.py`: what someone else wrote.** The iXML a + recorder put in a WAV, the ASC MHL a previous offload left behind, the + manifest `verify` is asked to vouch for, the `file:` URLs in a timeline. + Manifests are written by the test, not by `reports/`, and `verify` is + checked against hashes taken by the test: a report that passed must be + backed by a hash taken now, and a flipped byte, a deleted file, a dropped + digest or a hash marked failed must never pass. Every target also runs under + the shared oracle in `tests/fuzz_oracle.py`: only documented exceptions, a + time and memory ceiling per input, and no NaN or infinity in the result. +- **`tests/test_fuzz_state.py`: what is kept between runs.** The state file, + the history and the CLI's control file. Damaged content may be ignored but + never guessed at: a garbled control file never pauses or cancels a job, a + cancel stays final, claiming the control path never overwrites a file that + is not a control word, and a damaged history field costs that field, not + the record and its duplicate-card warning. + +The byte-level properties also replay a committed seed corpus +(`tests/fuzz_corpus/`) on every run, including the input behind every bug the +fuzzers have found, so those stay fixed without `--fuzz`. +- **`tests/test_fuzz_engine.py`: whole offloads under faults.** A random card + against destinations that may already hold a good copy, a stale one or a + same-size impostor, while source reads, writes, fsync or promotion fail + (transiently or for good), a staged copy is corrupted before its reread, or + the job is cancelled mid-flight. Checked against the bytes on disk: no + partial survives, every final file is the old one or exactly the source, a + different existing file survives unless replacing was asked for, nothing + marked Verified differs from the source, and a "Verified" job saw no fault + that kept failing. Planting a skipped checksum comparison or a no-op cleanup + in the engine fails it within the quick budget. - **`tests/test_edge_cases.py`: the layers between the bytes and the paperwork.** What ffprobe hands back, what a number formats to, what a digest compares equal to, what a name renders to. diff --git a/docs/release-plan.md b/docs/release-plan.md index ad02213..50c5fd8 100644 --- a/docs/release-plan.md +++ b/docs/release-plan.md @@ -52,7 +52,7 @@ tests or builds were run for this documentation task. | --- | --- | --- | | Product | Engine, CLI, Qt desktop app, reports, BRAW/BWF support, optional timeline import | Exercise the frozen application against representative workflows | | Version | One source in `src/offloader/_version.py` used by package metadata and the Windows bundle | Confirm the frozen release identity across all published assets | -| CI | Windows/macOS/Linux tests on Python 3.13, Linux Python 3.10, ffmpeg job, property-test soak, wheel/sdist build and metadata checks | Install built artifacts in fresh environments; build and smoke-test Windows desktop artifacts | +| CI | Windows/macOS/Linux tests on Python 3.13, Linux Python 3.10, ffmpeg job, nightly property-test soak on Linux and Windows, wheel/sdist build and metadata checks | Install built artifacts in fresh environments; build and smoke-test Windows desktop artifacts | | Distribution | Frozen bundle, NSIS installer path, source and bundle inventories, and checksums | Hardware-key signing, clean-machine installation, release workflow, and publication documentation | | Dependencies | Minimum versions and optional extras | Recorded build environment and pinned release dependency sets | | Media tools | ffmpeg/ffprobe discovered externally; copying works without them | Explicit installer dependency policy and useful missing-tool messaging | @@ -127,7 +127,7 @@ not elapsed time; set a public date after the first clean-machine pilot. | 1. Release foundation | Single version source; frozen scope; dependency pins; build instructions; chosen artifact names and repository | A clean checkout produces matching package/app/report versions; release identity is unambiguous | | 2. Windows package | PyInstaller spec and entry points; icon/version metadata; NSIS installer; third-party notices; media-tool status | GUI and CLI work on a clean Windows account without Python; reports render and manifests re-verify | | 3. Trust and installation | Signing integration; signature verification; safe active-job handling; install/upgrade/uninstall checks | Both executable and installer signatures validate; install lifecycle preserves user data and never interrupts a job | -| 4. Candidate qualification | All existing CI jobs green for the exact source commit; artifact smoke tests; integrity acceptance matrix below | Every gate has recorded evidence; no unexplained skips, false success, data loss, or blocking install defects | +| 4. Candidate qualification | All existing CI jobs green for the exact source commit, including a dispatched soak run; no open `Fuzz failure:` issue; artifact smoke tests; integrity acceptance matrix below | Every gate has recorded evidence; no unexplained skips, false success, data loss, or blocking install defects | | 5. Private pilot | Same candidate tested by 3 to 5 willing users on disposable copies of real media | At least 3 complete offload/re-verify workflows across 2 independent Windows machines; all blocking findings resolved and retested | | 6. Public beta | GitHub prerelease; verified asset downloads; quick start; known limits; support instructions; brief demo | A new user can install, run, locate the reports, and report a problem using the published instructions | | 7. Stabilize | Triage pilot/public reports; publish fixes with fresh versions; retain prior assets | At least one week of observation plus repeat acceptance evidence and no open integrity, installation, or recovery blockers before a normal release | diff --git a/src/offloader/ascmhl.py b/src/offloader/ascmhl.py index 851818f..a5c1f41 100644 --- a/src/offloader/ascmhl.py +++ b/src/offloader/ascmhl.py @@ -279,6 +279,21 @@ def next_sequence(root: Path) -> int: return max(used, default=0) + 1 +def parse_manifest(manifest: Path) -> ET.Element: + """The root element of a manifest file, or `ET.ParseError`. + + `ET.parse` has two more ways to say "this is not a manifest" than + `ParseError`, both from the XML declaration: an unknown encoding name is + a `LookupError` and a multi-byte one such as Shift-JIS is a `ValueError`. + One damaged byte in `encoding="UTF-8"` is enough to reach the first. They + are folded in here so every caller has one exception to catch. + """ + try: + return ET.parse(manifest).getroot() + except (LookupError, ValueError) as exc: + raise ET.ParseError(f"{manifest}: {exc}") from exc + + def read_manifest_hashes(manifest: Path) -> dict[str, dict[str, str]]: """{relative path: {algorithm tag: digest}} from an existing manifest. @@ -287,7 +302,7 @@ def read_manifest_hashes(manifest: Path) -> dict[str, dict[str, str]]: """ result: dict[str, dict[str, str]] = {} try: - root = ET.parse(manifest).getroot() + root = parse_manifest(manifest) except (ET.ParseError, OSError): return result diff --git a/src/offloader/config.py b/src/offloader/config.py index 90b9c7a..629b4ed 100644 --- a/src/offloader/config.py +++ b/src/offloader/config.py @@ -49,11 +49,12 @@ def read_json(path: Path, default: Any) -> Any: Config corruption must never stop someone offloading a card, so a bad file is treated as an empty one. That includes a file that is not valid UTF-8: `read_text` raises UnicodeDecodeError, which is a ValueError rather than an - OSError, and json.JSONDecodeError is a ValueError too. + OSError, and json.JSONDecodeError is a ValueError too. Deep nesting is a + RecursionError, which is neither, and one line of `[[[[` is enough. """ try: return json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError): + except (OSError, ValueError, RecursionError): return default diff --git a/src/offloader/history.py b/src/offloader/history.py index f797a8c..adee500 100644 --- a/src/offloader/history.py +++ b/src/offloader/history.py @@ -137,7 +137,7 @@ def text(key: str) -> str: def count(key: str) -> int: try: return int(data.get(key, 0)) - except (TypeError, ValueError): + except (TypeError, ValueError, OverflowError): # int(inf) return 0 # A JSON string here would otherwise be exploded character by diff --git a/src/offloader/ixml.py b/src/offloader/ixml.py index 38a28d7..9ae2ed7 100644 --- a/src/offloader/ixml.py +++ b/src/offloader/ixml.py @@ -162,6 +162,8 @@ def _ratio(value: str | None) -> float | None: rate = float(text) except (TypeError, ValueError): return None + # `float` accepts "inf" and "nan", and a huge ratio overflows to inf: none + # is a frame rate, and inf reaches `round()` in `timecode_of` as an error. return rate if math.isfinite(rate) and rate > 0 else None diff --git a/src/offloader/verify.py b/src/offloader/verify.py index 3ce5537..9d27ec8 100644 --- a/src/offloader/verify.py +++ b/src/offloader/verify.py @@ -29,7 +29,7 @@ from xml.etree import ElementTree as ET from . import longpath -from .ascmhl import ASCMHL_DIRNAME +from .ascmhl import ASCMHL_DIRNAME, parse_manifest from .ascmhl import NAMESPACE as ASCMHL_NAMESPACE from .ascmhl import directory_hashes as ascmhl_directory_hashes from .ascmhl import existing_manifests as ascmhl_existing_manifests @@ -318,7 +318,7 @@ def _entries(manifest: Path) -> Iterator[_Entry]: (``, namespaced, and living in an `ascmhl/` folder so its paths are relative to the folder above). """ - root = ET.parse(manifest).getroot() + root = parse_manifest(manifest) if root.tag == f"{{{ASCMHL_NAMESPACE}}}hashlist": yield from _ascmhl_entries(manifest, root) return @@ -607,7 +607,7 @@ def _ascmhl_root(manifest: Path) -> ET.Element | None: Classic MHL 1.1 has no concept of a directory hash, so there is nothing to re-check and nothing to read. """ - root = ET.parse(manifest).getroot() + root = parse_manifest(manifest) return root if root.tag == f"{{{ASCMHL_NAMESPACE}}}hashlist" else None @@ -1138,7 +1138,7 @@ def _recorded_at(manifest: Path) -> _dt.datetime | None: later. """ try: - root = ET.parse(manifest).getroot() + root = parse_manifest(manifest) except (OSError, ET.ParseError): return None return _recorded_at_root(root) diff --git a/tests/conftest.py b/tests/conftest.py index 3ef08f0..337dd93 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -153,8 +153,13 @@ def pytest_configure(config): "ci", max_examples=100, deadline=None, suppress_health_check=[HealthCheck.too_slow], ) + # The nightly job can ask for a different depth without a code change; + # `fuzz_oracle.scaled` budgets follow whatever this is. `print_blob` + # puts a `@reproduce_failure` line in the log, so a failure seen only in + # CI can be replayed locally from the issue it opens. settings.register_profile( - "fuzz", max_examples=3000, deadline=None, + "fuzz", max_examples=int(os.environ.get("OFFLOADER_FUZZ_EXAMPLES", "3000")), + deadline=None, print_blob=True, suppress_health_check=[HealthCheck.too_slow, HealthCheck.data_too_large], ) settings.load_profile("fuzz" if config.getoption("--fuzz") else "ci") diff --git a/tests/fuzz_corpus/ascmhl/failed-hash.mhl b/tests/fuzz_corpus/ascmhl/failed-hash.mhl new file mode 100644 index 0000000..5fe9daa --- /dev/null +++ b/tests/fuzz_corpus/ascmhl/failed-hash.mhl @@ -0,0 +1 @@ +2026-01-01T00:00:00ZA001/clip.braw0123456789abcdef \ No newline at end of file diff --git a/tests/fuzz_corpus/ascmhl/one-hash.mhl b/tests/fuzz_corpus/ascmhl/one-hash.mhl new file mode 100644 index 0000000..ad14d95 --- /dev/null +++ b/tests/fuzz_corpus/ascmhl/one-hash.mhl @@ -0,0 +1 @@ +2026-01-01T00:00:00ZA001/clip.braw0123456789abcdef \ No newline at end of file diff --git a/tests/fuzz_corpus/ascmhl/regress-encoding-shift-jis.mhl b/tests/fuzz_corpus/ascmhl/regress-encoding-shift-jis.mhl new file mode 100644 index 0000000..a72fb1a --- /dev/null +++ b/tests/fuzz_corpus/ascmhl/regress-encoding-shift-jis.mhl @@ -0,0 +1 @@ +2026-01-01T00:00:00ZA001/clip.braw0123456789abcdef \ No newline at end of file diff --git a/tests/fuzz_corpus/ascmhl/regress-encoding-tf8.mhl b/tests/fuzz_corpus/ascmhl/regress-encoding-tf8.mhl new file mode 100644 index 0000000..de65718 --- /dev/null +++ b/tests/fuzz_corpus/ascmhl/regress-encoding-tf8.mhl @@ -0,0 +1 @@ +2026-01-01T00:00:00ZA001/clip.braw0123456789abcdef \ No newline at end of file diff --git a/tests/fuzz_corpus/braw/moov-only.braw b/tests/fuzz_corpus/braw/moov-only.braw new file mode 100644 index 0000000..b077fbd Binary files /dev/null and b/tests/fuzz_corpus/braw/moov-only.braw differ diff --git a/tests/fuzz_corpus/braw/no-video.braw b/tests/fuzz_corpus/braw/no-video.braw new file mode 100644 index 0000000..e95eae2 Binary files /dev/null and b/tests/fuzz_corpus/braw/no-video.braw differ diff --git a/tests/fuzz_corpus/braw/regress-64bit-size-lie.braw b/tests/fuzz_corpus/braw/regress-64bit-size-lie.braw new file mode 100644 index 0000000..bc347ba Binary files /dev/null and b/tests/fuzz_corpus/braw/regress-64bit-size-lie.braw differ diff --git a/tests/fuzz_corpus/braw/video-trak.braw b/tests/fuzz_corpus/braw/video-trak.braw new file mode 100644 index 0000000..7021352 Binary files /dev/null and b/tests/fuzz_corpus/braw/video-trak.braw differ diff --git a/tests/fuzz_corpus/control/cancel-pending b/tests/fuzz_corpus/control/cancel-pending new file mode 100644 index 0000000..ba9a816 --- /dev/null +++ b/tests/fuzz_corpus/control/cancel-pending @@ -0,0 +1 @@ +cancel pending upload \ No newline at end of file diff --git a/tests/fuzz_corpus/control/cancel-upper b/tests/fuzz_corpus/control/cancel-upper new file mode 100644 index 0000000..e235793 --- /dev/null +++ b/tests/fuzz_corpus/control/cancel-upper @@ -0,0 +1 @@ +CANCEL \ No newline at end of file diff --git a/tests/fuzz_corpus/control/cancel-with-bom b/tests/fuzz_corpus/control/cancel-with-bom new file mode 100644 index 0000000..06e6417 --- /dev/null +++ b/tests/fuzz_corpus/control/cancel-with-bom @@ -0,0 +1 @@ +cancel \ No newline at end of file diff --git a/tests/fuzz_corpus/control/clip-bytes b/tests/fuzz_corpus/control/clip-bytes new file mode 100644 index 0000000..553a99f Binary files /dev/null and b/tests/fuzz_corpus/control/clip-bytes differ diff --git a/tests/fuzz_corpus/control/not-utf8 b/tests/fuzz_corpus/control/not-utf8 new file mode 100644 index 0000000..d263dd8 --- /dev/null +++ b/tests/fuzz_corpus/control/not-utf8 @@ -0,0 +1 @@ +ÿcancel \ No newline at end of file diff --git a/tests/fuzz_corpus/control/pause-crlf b/tests/fuzz_corpus/control/pause-crlf new file mode 100644 index 0000000..8c451e4 --- /dev/null +++ b/tests/fuzz_corpus/control/pause-crlf @@ -0,0 +1 @@ +pause diff --git a/tests/fuzz_corpus/control/run b/tests/fuzz_corpus/control/run new file mode 100644 index 0000000..f5bdd21 --- /dev/null +++ b/tests/fuzz_corpus/control/run @@ -0,0 +1 @@ +run diff --git a/tests/fuzz_corpus/history/bare-object.json b/tests/fuzz_corpus/history/bare-object.json new file mode 100644 index 0000000..2baf34b --- /dev/null +++ b/tests/fuzz_corpus/history/bare-object.json @@ -0,0 +1 @@ +{"fingerprint": "abc"} \ No newline at end of file diff --git a/tests/fuzz_corpus/history/destinations-string.json b/tests/fuzz_corpus/history/destinations-string.json new file mode 100644 index 0000000..63fa9b8 --- /dev/null +++ b/tests/fuzz_corpus/history/destinations-string.json @@ -0,0 +1 @@ +[{"fingerprint": "abc", "destinations": "F:/A001"}] \ No newline at end of file diff --git a/tests/fuzz_corpus/history/one-record.json b/tests/fuzz_corpus/history/one-record.json new file mode 100644 index 0000000..84191ab --- /dev/null +++ b/tests/fuzz_corpus/history/one-record.json @@ -0,0 +1 @@ +[{"fingerprint": "abc", "job_name": "A001", "destinations": ["F:/A001"], "file_count": 12, "status": "Verified"}] \ No newline at end of file diff --git a/tests/fuzz_corpus/history/regress-deep-nesting.json b/tests/fuzz_corpus/history/regress-deep-nesting.json new file mode 100644 index 0000000..0ce346b --- /dev/null +++ b/tests/fuzz_corpus/history/regress-deep-nesting.json @@ -0,0 +1 @@ +[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ \ No newline at end of file diff --git a/tests/fuzz_corpus/history/regress-overflowing-count.json b/tests/fuzz_corpus/history/regress-overflowing-count.json new file mode 100644 index 0000000..30a406e --- /dev/null +++ b/tests/fuzz_corpus/history/regress-overflowing-count.json @@ -0,0 +1 @@ +[{"fingerprint": "card-a", "file_count": 1e400}] \ No newline at end of file diff --git a/tests/fuzz_corpus/ixml/doctype-entity.xml b/tests/fuzz_corpus/ixml/doctype-entity.xml new file mode 100644 index 0000000..3a65b25 --- /dev/null +++ b/tests/fuzz_corpus/ixml/doctype-entity.xml @@ -0,0 +1 @@ +]>&a; \ No newline at end of file diff --git a/tests/fuzz_corpus/ixml/recorder.xml b/tests/fuzz_corpus/ixml/recorder.xml new file mode 100644 index 0000000..8bf9b94 --- /dev/null +++ b/tests/fuzz_corpus/ixml/recorder.xml @@ -0,0 +1,32 @@ + + + 1.5 + ChairsDoc + 12A + 3 + SR082226 + TRUE + wind on the boom + ABC123 + + 25/1 + 25/1 + NDF + 48000 + 0 + 1728000000 + + + 2 + + 1 + 1 + Boom + + + 2 + 2 + Lav 1 + + + diff --git a/tests/fuzz_corpus/ixml/regress-infinite-rate.xml b/tests/fuzz_corpus/ixml/regress-infinite-rate.xml new file mode 100644 index 0000000..c1fa904 --- /dev/null +++ b/tests/fuzz_corpus/ixml/regress-infinite-rate.xml @@ -0,0 +1,32 @@ + + + 1.5 + ChairsDoc + 12A + 3 + SR082226 + TRUE + wind on the boom + ABC123 + + inf + inf + NDF + 48000 + 0 + 1728000000 + + + 2 + + 1 + 1 + Boom + + + 2 + 2 + Lav 1 + + + diff --git a/tests/fuzz_corpus/ixml/regress-overflowing-ratio.xml b/tests/fuzz_corpus/ixml/regress-overflowing-ratio.xml new file mode 100644 index 0000000..083a768 --- /dev/null +++ b/tests/fuzz_corpus/ixml/regress-overflowing-ratio.xml @@ -0,0 +1,32 @@ + + + 1.5 + ChairsDoc + 12A + 3 + SR082226 + TRUE + wind on the boom + ABC123 + + 1e308/1e-308 + 1e308/1e-308 + NDF + 48000 + 0 + 1728000000 + + + 2 + + 1 + 1 + Boom + + + 2 + 2 + Lav 1 + + + diff --git a/tests/fuzz_corpus/riff/bext-only.wav b/tests/fuzz_corpus/riff/bext-only.wav new file mode 100644 index 0000000..66b3e3a Binary files /dev/null and b/tests/fuzz_corpus/riff/bext-only.wav differ diff --git a/tests/fuzz_corpus/riff/bwf-ixml-bext.wav b/tests/fuzz_corpus/riff/bwf-ixml-bext.wav new file mode 100644 index 0000000..d4f8126 Binary files /dev/null and b/tests/fuzz_corpus/riff/bwf-ixml-bext.wav differ diff --git a/tests/fuzz_corpus/riff/bwf-ixml-first.wav b/tests/fuzz_corpus/riff/bwf-ixml-first.wav new file mode 100644 index 0000000..137c549 Binary files /dev/null and b/tests/fuzz_corpus/riff/bwf-ixml-first.wav differ diff --git a/tests/fuzz_corpus/riff/lying-chunk-size.wav b/tests/fuzz_corpus/riff/lying-chunk-size.wav new file mode 100644 index 0000000..af56942 Binary files /dev/null and b/tests/fuzz_corpus/riff/lying-chunk-size.wav differ diff --git a/tests/fuzz_corpus/riff/regress-infinite-rate.wav b/tests/fuzz_corpus/riff/regress-infinite-rate.wav new file mode 100644 index 0000000..ba3d221 Binary files /dev/null and b/tests/fuzz_corpus/riff/regress-infinite-rate.wav differ diff --git a/tests/fuzz_corpus/state-json/history.json b/tests/fuzz_corpus/state-json/history.json new file mode 100644 index 0000000..b759cb9 --- /dev/null +++ b/tests/fuzz_corpus/state-json/history.json @@ -0,0 +1 @@ +[{"fingerprint": "abc", "job_name": "A001", "source": "E:/", "destinations": ["F:/A001"], "file_count": 12, "total_bytes": 3000000, "status": "Verified", "finished": "2026-08-22T10:00:00"}] \ No newline at end of file diff --git a/tests/fuzz_corpus/state-json/not-utf8.json b/tests/fuzz_corpus/state-json/not-utf8.json new file mode 100644 index 0000000..f3db0cf --- /dev/null +++ b/tests/fuzz_corpus/state-json/not-utf8.json @@ -0,0 +1 @@ +["ÿþ"] \ No newline at end of file diff --git a/tests/fuzz_corpus/state-json/regress-deep-nesting.json b/tests/fuzz_corpus/state-json/regress-deep-nesting.json new file mode 100644 index 0000000..0ce346b --- /dev/null +++ b/tests/fuzz_corpus/state-json/regress-deep-nesting.json @@ -0,0 +1 @@ +[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ \ No newline at end of file diff --git a/tests/fuzz_oracle.py b/tests/fuzz_oracle.py new file mode 100644 index 0000000..9429e40 --- /dev/null +++ b/tests/fuzz_oracle.py @@ -0,0 +1,95 @@ +"""The checks every parser fuzz target applies, whatever it parses. + +A fuzz target is only as good as its oracle. "It did not crash" catches a +fraction of what a hostile card can do; the rest is a parser that runs for a +minute, allocates a gigabyte, or returns an answer that is quietly wrong: a +frame rate of infinity that a report prints, or a verdict that says a file +matched when nobody hashed it. These helpers turn those into failures. + +Ported from the shared oracle in markcopy's fuzzing strategy, cut down to what +a Python parser can get wrong. +""" + +from __future__ import annotations + +import dataclasses +import enum +import math +import time +import tracemalloc +from collections.abc import Callable, Mapping +from pathlib import PurePath +from typing import Any, TypeVar + +from hypothesis import settings + +T = TypeVar("T") + +#: Per-input ceilings. Every input a target is fed is a few kilobytes, so a +#: parser that needs seconds or megabytes on one is doing something +#: proportional to a number it read from the input rather than to its length. +SECONDS = 3.0 +MEGABYTES = 64 + + +def scaled(examples: int) -> int: + """An example budget that grows with the active profile. + + A test that pins `max_examples` overrides the profile, so a bare + `@settings(max_examples=40)` stays at 40 under `--fuzz` and the soak never + goes deeper on it. This keeps `examples` as the quick-run budget and + multiplies it by however much larger the loaded profile is than the + default 100. + """ + return max(examples, examples * settings().max_examples // 100) + + +def bounded(fn: Callable[..., T], *args: Any, + allowed: tuple[type[BaseException], ...] = (), + seconds: float = SECONDS, megabytes: int = MEGABYTES, + **kwargs: Any) -> T | None: + """Call a parser and fail if it escapes its contract. + + Returns the result, or None when it raised one of `allowed`, the + exceptions its callers are documented to catch. Anything else propagates + and fails the test. Time and peak allocation are checked either way. + """ + tracing = tracemalloc.is_tracing() + if not tracing: + tracemalloc.start() + tracemalloc.reset_peak() + started = time.perf_counter() + try: + return fn(*args, **kwargs) + except allowed: + return None + finally: + elapsed = time.perf_counter() - started + _, peak = tracemalloc.get_traced_memory() + if not tracing: + tracemalloc.stop() + assert elapsed < seconds, f"{fn.__name__} took {elapsed:.1f}s on one input" + assert peak < megabytes * 2**20, ( + f"{fn.__name__} peaked at {peak / 2**20:.0f} MB on one input") + + +def assert_finite(value: Any, where: str = "result") -> None: + """No float anywhere in `value` is NaN or infinite. + + A parser that reads a number has to decide what an absurd one means. Left + undecided, `inf` reaches a report as text, or `round()` as an + OverflowError, far from the field that held it. + """ + if isinstance(value, float): + assert math.isfinite(value), f"{where} is {value!r}" + elif isinstance(value, (str, bytes, int, PurePath, enum.Enum)) or value is None: + return + elif dataclasses.is_dataclass(value) and not isinstance(value, type): + for field in dataclasses.fields(value): + assert_finite(getattr(value, field.name), f"{where}.{field.name}") + elif isinstance(value, Mapping): + for key, item in value.items(): + assert_finite(item, f"{where}[{key!r}]") + elif isinstance(value, (list, tuple, set, frozenset)): + for index, item in enumerate(value): + assert_finite(item, f"{where}[{index}]") diff --git a/tests/fuzz_surfaces.json b/tests/fuzz_surfaces.json new file mode 100644 index 0000000..511c68f --- /dev/null +++ b/tests/fuzz_surfaces.json @@ -0,0 +1,180 @@ +{ + "_comment": [ + "Every module that reads or renders input offloader did not write, and the", + "property tests that fuzz it. Enforced by tests/test_fuzz_surfaces.py: a", + "module in a policed folder must appear in exactly one table, every target", + "must be a Hypothesis test, and every Hypothesis test must be claimed here.", + "A surface with no target, or with part of it unfuzzed, says so in `gap`.", + "A gap is a known limit, not a protection: do not delete one without a", + "target that closes it." + ], + "policed": [ + "src/offloader", + "src/offloader/reports" + ], + "exempt": { + "src/offloader/gui": "Qt widgets. They read untrusted input only through engine, presets, volumes and history, which are listed here." + }, + "surfaces": { + "src/offloader/ascmhl.py": { + "targets": [ + "tests/test_fuzz_parsers.py::test_read_manifest_hashes_reports_exactly_what_was_written", + "tests/test_fuzz_parsers.py::test_read_manifest_hashes_on_damaged_xml" + ], + "gap": "The writer's hostile-name round trip in test_fuzz_edges.py is parametrized over fixed names, not generated." + }, + "src/offloader/braw.py": { + "targets": [ + "tests/test_fuzz_edges.py::test_braw_read_info_survives_arbitrary_bytes", + "tests/test_fuzz_edges.py::test_braw_read_info_survives_random_atom_trees", + "tests/test_fuzz_edges.py::test_braw_read_info_survives_truncated_video_traks", + "tests/test_fuzz_edges.py::test_find_moov_never_reads_past_the_end_of_the_file" + ] + }, + "src/offloader/companions.py": { + "targets": [], + "gap": "Matching card filenames to their proxies is example-tested only." + }, + "src/offloader/config.py": { + "targets": [ + "tests/test_fuzz_state.py::test_read_json_returns_the_value_or_the_default" + ] + }, + "src/offloader/engine.py": { + "targets": [ + "tests/test_fuzz_edges.py::test_flat_mode_never_silently_drops_a_file", + "tests/test_fuzz_edges.py::test_exclude_patterns_never_raise", + "tests/test_fuzz_state.py::test_control_read_means_a_word_or_no_opinion", + "tests/test_fuzz_state.py::test_a_damaged_control_file_never_changes_the_job", + "tests/test_fuzz_state.py::test_claim_never_overwrites_what_is_not_a_control_file", + "tests/test_fuzz_engine.py::test_an_offload_under_faults_keeps_the_safety_contract" + ], + "gap": "Source scanning is example-tested only. Faults are injected at the engine's I/O seams (open, read, write, fsync, replace, cache eviction), not below them; pause, paranoid rereads and concurrent instances are not in the fault plan." + }, + "src/offloader/hashers.py": { + "targets": [ + "tests/test_fuzz.py::test_chunked_hashing_matches_whole_buffer", + "tests/test_fuzz.py::test_hash_file_matches_in_memory" + ] + }, + "src/offloader/history.py": { + "targets": [ + "tests/test_fuzz_state.py::test_history_keeps_every_record_it_can_identify" + ] + }, + "src/offloader/installation.py": { + "targets": [], + "gap": "The install inventory JSON is example-tested only." + }, + "src/offloader/ixml.py": { + "targets": [ + "tests/test_fuzz_parsers.py::test_parse_ixml_on_any_text", + "tests/test_fuzz_parsers.py::test_parse_ixml_on_recorder_shaped_documents", + "tests/test_fuzz_parsers.py::test_read_sound_info_on_hostile_riff" + ] + }, + "src/offloader/longpath.py": { + "targets": [], + "gap": "Prefixing hostile card paths past MAX_PATH is example-tested only." + }, + "src/offloader/naming.py": { + "targets": [ + "tests/test_fuzz.py::test_sanitize_output_is_always_a_legal_filename", + "tests/test_fuzz.py::test_build_never_collides_with_taken_names", + "tests/test_fuzz.py::test_sequential_builds_are_all_distinct", + "tests/test_fuzz.py::test_index_token_pads_to_three_digits" + ] + }, + "src/offloader/presets.py": { + "targets": [ + "tests/test_fuzz.py::test_preset_round_trips_through_json", + "tests/test_fuzz.py::test_preset_from_dict_tolerates_garbage" + ], + "gap": "The preset file loader around from_dict is example-tested only." + }, + "src/offloader/probe.py": { + "targets": [ + "tests/test_edge_cases.py::test_parse_rate_never_raises_on_a_rational", + "tests/test_edge_cases.py::test_parse_rate_never_raises_on_junk" + ], + "gap": "Whole ffprobe JSON documents (_build) are example-tested only." + }, + "src/offloader/retry.py": { + "targets": [ + "tests/test_fuzz_edges.py::test_retry_never_asks_to_sleep_for_a_negative_time" + ] + }, + "src/offloader/thumbs.py": { + "targets": [], + "gap": "ffmpeg is called with an argument list, but the paths it is handed are not fuzzed." + }, + "src/offloader/timeline.py": { + "targets": [ + "tests/test_fuzz_parsers.py::test_url_to_path_on_any_text", + "tests/test_fuzz_parsers.py::test_windows_file_urls_round_trip", + "tests/test_fuzz_parsers.py::test_posix_file_urls_keep_their_root" + ], + "gap": "Timeline documents themselves (read_references over OTIO and FCP XML) are not fuzzed." + }, + "src/offloader/util.py": { + "targets": [ + "tests/test_fuzz.py::test_format_size_always_parses_back", + "tests/test_fuzz.py::test_format_size_is_monotonic", + "tests/test_edge_cases.py::test_format_size_promotes_negative_values_too", + "tests/test_fuzz.py::test_format_duration_shape", + "tests/test_fuzz.py::test_format_elapsed_shape", + "tests/test_fuzz.py::test_timecode_fields_stay_in_range", + "tests/test_fuzz.py::test_datetime_formats_never_crash" + ] + }, + "src/offloader/verify.py": { + "targets": [ + "tests/test_fuzz_parsers.py::test_verify_passes_exactly_when_it_should", + "tests/test_fuzz_parsers.py::test_verify_on_a_damaged_manifest_never_vouches_for_wrong_bytes" + ] + }, + "src/offloader/volumes.py": { + "targets": [], + "gap": "Volume labels and mount tables reported by the OS are example-tested only." + }, + "src/offloader/reports/csv_report.py": { + "targets": [ + "tests/test_fuzz.py::test_csv_keeps_its_column_count" + ] + }, + "src/offloader/reports/html.py": { + "targets": [ + "tests/test_fuzz.py::test_html_input_can_never_become_markup" + ] + }, + "src/offloader/reports/mhl.py": { + "targets": [ + "tests/test_fuzz.py::test_mhl_is_always_well_formed_xml" + ] + }, + "src/offloader/reports/pdf.py": { + "targets": [ + "tests/test_fuzz.py::test_pdf_survives_hostile_filenames", + "tests/test_fuzz.py::test_pdf_long_paths_stay_on_the_page", + "tests/test_fuzz.py::test_pdf_page_count_grows_with_content", + "tests/test_fuzz.py::test_pdf_handles_extreme_media_metadata" + ] + } + }, + "not_surfaces": { + "src/offloader/__init__.py": "Package metadata.", + "src/offloader/__main__.py": "Entry point.", + "src/offloader/_version.py": "Version literal.", + "src/offloader/cli.py": "Arguments come from the operator, not the card; documents are read through the surface modules.", + "src/offloader/installation_lock.py": "Takes a byte-range lock on a file it owns; reads no content.", + "src/offloader/integrity.py": "Evicts files from the cache; reads no structure.", + "src/offloader/models.py": "Dataclasses; parses nothing.", + "src/offloader/sysinfo.py": "Host facts from the OS, not from a card or a document.", + "src/offloader/windows_launch.py": "Launches an installed executable; takes no outside input.", + "src/offloader/reports/__init__.py": "Writer registry.", + "src/offloader/reports/fonts.py": "Bundled font lookup.", + "src/offloader/reports/icons.py": "Bundled drawings.", + "src/offloader/reports/layout.py": "PDF geometry; exercised by the PDF targets.", + "src/offloader/reports/paperwork.py": "Calls the writers and records their failures; renders nothing itself." + } +} diff --git a/tests/fuzz_targets.py b/tests/fuzz_targets.py new file mode 100644 index 0000000..2ede219 --- /dev/null +++ b/tests/fuzz_targets.py @@ -0,0 +1,152 @@ +"""Byte-level fuzz targets: one function per input surface, `bytes -> None`. + +Each target writes the bytes where the surface reads them, calls it under the +shared oracle and asserts what a correct reader must return. A violation is +an AssertionError, or whatever exception escaped the documented set. + +The same functions serve three callers, so a property is stated once: + +- the Hypothesis tests, which generate the bytes; +- `test_fuzz_corpus.py`, which replays every committed seed in + `tests/fuzz_corpus//` on every test run; +- a coverage-guided fuzzer, should one be added, which only needs a + `bytes -> None` callable and the corpus folder. +""" + +from __future__ import annotations + +import json +import tempfile +from collections.abc import Callable +from pathlib import Path + +from fuzz_oracle import assert_finite, bounded +from offloader import ascmhl, braw, config, engine, history, ixml +from offloader.models import SoundInfo + +#: What `braw.read_info` may raise: its caller catches OSError, nothing else. +BRAW_MAY_RAISE = (OSError,) + + +def _written(data: bytes, name: str): + """A temporary folder holding `data` at `name`; use as a context manager.""" + folder = tempfile.TemporaryDirectory() + (Path(folder.name) / name).write_bytes(data) + return folder, Path(folder.name) / name + + +def check_sound(info: SoundInfo | None) -> None: + assert info is None or isinstance(info, SoundInfo) + assert_finite(info, "SoundInfo") + # `timecode_of` is where a rate becomes arithmetic, so it is part of the + # parser's contract: whatever was accepted must be usable. + stamp = bounded(ixml.timecode_of, info, 48000) + assert stamp is None or isinstance(stamp, str) + + +def braw_file(data: bytes) -> None: + folder, path = _written(data, "clip.braw") + with folder: + assert_finite(bounded(braw.read_info, path, allowed=BRAW_MAY_RAISE), "BrawInfo") + + +def riff(data: bytes) -> None: + folder, path = _written(data, "take.wav") + with folder: + check_sound(bounded(ixml.read_sound_info, path)) + + +def ixml_text(data: bytes) -> None: + check_sound(bounded(ixml.parse_ixml, data.decode("utf-8", "replace"))) + + +def ascmhl_manifest(data: bytes) -> None: + folder, path = _written(data, "0001_card.mhl") + with folder: + result = bounded(ascmhl.read_manifest_hashes, path) + assert isinstance(result, dict) + for name, digests in result.items(): + assert isinstance(name, str) and name + assert digests and all(isinstance(d, str) for d in digests.values()) + + +_DEFAULT = object() + + +def state_json(data: bytes) -> None: + """`read_json` returns exactly what the file holds, or the default.""" + folder, path = _written(data, "state.json") + with folder: + result = bounded(config.read_json, path, _DEFAULT) + try: + expected = json.loads(data.decode("utf-8")) + except (ValueError, RecursionError): + assert result is _DEFAULT + else: + assert json.dumps(result) == json.dumps(expected) + + +def history_file(data: bytes) -> None: + """A damaged field costs that field, never the record: the record's + fingerprint is the duplicate-card warning for that card.""" + folder, path = _written(data, "history.json") + with folder: + loaded = bounded(history.History, path) + assert loaded is not None + for entry in loaded.entries: + assert isinstance(entry.file_count, int) + assert isinstance(entry.total_bytes, int) + assert all(isinstance(d, str) for d in entry.destinations) + assert isinstance(entry.describe(), str) + try: + records = json.loads(data.decode("utf-8")) + except (ValueError, RecursionError): + records = [] + identified = [r["fingerprint"] for r in records if isinstance(r, dict) + and isinstance(r.get("fingerprint"), str)] if isinstance(records, list) else [] + kept = [entry.fingerprint for entry in loaded.entries] + assert all(fingerprint in kept for fingerprint in identified), (identified, kept) + + +def control_word(data: bytes) -> str | None: + """What a control file means, decided independently of `FileControl.read`.""" + try: + word = data.decode("utf-8").replace("\r\n", "\n").strip().lower() + except UnicodeDecodeError: + return None + return word if word in engine.FileControl.STATES else None + + +def control_file(data: bytes) -> None: + """`read` means a whole word or no opinion; `claim` replaces an empty file + or a control word and leaves anything else byte for byte.""" + folder, path = _written(data, "offload.control") + with folder: + control = engine.FileControl(path, poll=0.05) + assert bounded(control.read) == control_word(data) + + try: + text = data.decode("utf-8").strip().lower() + except UnicodeDecodeError: + text = None + replaceable = (len(data) <= engine.FileControl.MAX_BYTES and text is not None + and (not text or text in engine.FileControl.STATES)) + try: + control.claim() + except engine.UnsafeControlFile: + assert not replaceable, f"refused a replaceable control file {data!r}" + assert path.read_bytes() == data, "a refused claim changed the file" + else: + assert replaceable, f"claim overwrote {data!r}" + assert path.read_bytes() == b"run\n" + + +TARGETS: dict[str, Callable[[bytes], None]] = { + "braw": braw_file, + "riff": riff, + "ixml": ixml_text, + "ascmhl": ascmhl_manifest, + "state-json": state_json, + "history": history_file, + "control": control_file, +} diff --git a/tests/make_fuzz_seeds.py b/tests/make_fuzz_seeds.py new file mode 100644 index 0000000..75c042e --- /dev/null +++ b/tests/make_fuzz_seeds.py @@ -0,0 +1,117 @@ +"""Write the seed corpus in `tests/fuzz_corpus//`. + + python tests/make_fuzz_seeds.py + +Seeds are generated from the same builders the unit tests use, never +collected from real cards: they are reproducible, small, licence-free and of +known origin. Each is a file named for what it is, replayed through +`fuzz_targets.TARGETS[]` on every test run by `test_fuzz_corpus.py`. + +A bug a target finds adds its input here (as `regress-`), beside the +fix and the deterministic regression test. Rerunning this script rewrites +the generated seeds and leaves any other file in the folder alone. +""" + +from __future__ import annotations + +import json +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) + +from bwf import bext_chunk, ixml_document, write_wav # noqa: E402 +from test_fuzz_edges import GOOD_MDHD, atom, braw_file, video_trak # noqa: E402 + +CORPUS = HERE / "fuzz_corpus" +#: Small seeds mutate faster; anything larger belongs in a unit-test fixture. +MAX_SEED_BYTES = 8192 + + +def _wav(**options) -> bytes: + with tempfile.TemporaryDirectory() as folder: + return write_wav(Path(folder) / "take.wav", frames=16, **options).read_bytes() + + +def _asc(body: str, encoding: str = "UTF-8") -> bytes: + return (f'' + '' + "2026-01-01T00:00:00Z" + f"{body}").encode() + + +ONE_HASH = ('A001/clip.braw' + '0123456789abcdef') + +SEEDS: dict[str, dict[str, bytes]] = { + "braw": { + "video-trak.braw": braw_file(video_trak(GOOD_MDHD, struct.pack(">II", 1, 1) * 2)), + "no-video.braw": braw_file(atom(b"trak", atom(b"mdia", atom(b"hdlr", bytes(12))))), + "moov-only.braw": atom(b"moov", b""), + "regress-64bit-size-lie.braw": atom(b"ftyp", b"braw") + + struct.pack(">I", 1) + b"moov" + struct.pack(">Q", 2 ** 40), + }, + "riff": { + "bwf-ixml-bext.wav": _wav(ixml=ixml_document(), bext=bext_chunk()), + "bwf-ixml-first.wav": _wav(ixml=ixml_document(), ixml_first=True), + "bext-only.wav": _wav(bext=bext_chunk()), + "lying-chunk-size.wav": b"RIFF" + struct.pack("", + "regress-infinite-rate.wav": _wav(ixml=ixml_document(rate="inf")), + }, + "ixml": { + "recorder.xml": ixml_document().encode(), + "doctype-entity.xml": b']>&a;', + "regress-infinite-rate.xml": ixml_document(rate="inf").encode(), + "regress-overflowing-ratio.xml": ixml_document(rate="1e308/1e-308").encode(), + }, + "ascmhl": { + "one-hash.mhl": _asc(ONE_HASH), + "failed-hash.mhl": _asc(ONE_HASH.replace("original", "failed")), + "regress-encoding-tf8.mhl": _asc(ONE_HASH, "TF-8"), + "regress-encoding-shift-jis.mhl": _asc(ONE_HASH, "shift_jis"), + }, + "state-json": { + "history.json": json.dumps([{ + "fingerprint": "abc", "job_name": "A001", "source": "E:/", + "destinations": ["F:/A001"], "file_count": 12, "total_bytes": 3_000_000, + "status": "Verified", "finished": "2026-08-22T10:00:00"}]).encode(), + "not-utf8.json": b'["\xff\xfe"]', + "regress-deep-nesting.json": b"[" * 3000, + }, + "history": { + "one-record.json": json.dumps([{ + "fingerprint": "abc", "job_name": "A001", "destinations": ["F:/A001"], + "file_count": 12, "status": "Verified"}]).encode(), + "bare-object.json": b'{"fingerprint": "abc"}', + "destinations-string.json": b'[{"fingerprint": "abc", "destinations": "F:/A001"}]', + "regress-deep-nesting.json": b"[" * 3000, + "regress-overflowing-count.json": b'[{"fingerprint": "card-a", "file_count": 1e400}]', + }, + "control": { + "run": b"run\n", + "pause-crlf": b"pause\r\n", + "cancel-upper": b"CANCEL", + "cancel-with-bom": b"\xef\xbb\xbfcancel", + "cancel-pending": b"cancel pending upload", + "not-utf8": b"\xffcancel", + "clip-bytes": bytes(range(256)) * 2, + }, +} + + +def main() -> None: + for target, seeds in SEEDS.items(): + folder = CORPUS / target + folder.mkdir(parents=True, exist_ok=True) + for name, data in seeds.items(): + assert len(data) <= MAX_SEED_BYTES, f"{target}/{name} is {len(data)} bytes" + (folder / name).write_bytes(data) + print(f"wrote {sum(map(len, SEEDS.values()))} seeds under {CORPUS}") + + +if __name__ == "__main__": + main() diff --git a/tests/test_fuzz.py b/tests/test_fuzz.py index 9f9fffa..1a23c5a 100644 --- a/tests/test_fuzz.py +++ b/tests/test_fuzz.py @@ -23,6 +23,7 @@ from hypothesis import given, settings from hypothesis import strategies as st +from fuzz_oracle import scaled from offloader import naming, util from offloader.hashers import ALGORITHMS, hash_file, new_hasher from offloader.models import ( @@ -238,7 +239,7 @@ def test_hash_file_matches_in_memory(payload: bytes, key: str, tmp_path_factory) # --------------------------------------------------------------------- PDF -@settings(max_examples=40, deadline=None) +@settings(max_examples=scaled(40), deadline=None) @given(names=st.lists(hostile_text, min_size=1, max_size=6), size=byte_sizes) def test_pdf_survives_hostile_filenames(names: list[str], size: int, tmp_path_factory): """No input may push text off the page or crash the writer.""" @@ -255,7 +256,7 @@ def test_pdf_survives_hostile_filenames(names: list[str], size: int, tmp_path_fa assert span["bbox"][3] <= layout.PAGE_HEIGHT + 1.0 -@settings(max_examples=25, deadline=None) +@settings(max_examples=scaled(25), deadline=None) @given(depth=st.integers(min_value=1, max_value=6), segment=st.integers(min_value=1, max_value=400)) def test_pdf_long_paths_stay_on_the_page(depth: int, segment: int, @@ -274,7 +275,7 @@ def test_pdf_long_paths_stay_on_the_page(depth: int, segment: int, assert span["bbox"][2] <= layout.PAGE_WIDTH + 1.0 -@settings(max_examples=20, deadline=None) +@settings(max_examples=scaled(20), deadline=None) @given(file_count=st.integers(min_value=0, max_value=30), destinations=st.integers(min_value=1, max_value=4)) def test_pdf_page_count_grows_with_content(file_count: int, destinations: int, @@ -290,7 +291,7 @@ def test_pdf_page_count_grows_with_content(file_count: int, destinations: int, assert f"Page {number}" in page.get_text() -@settings(max_examples=20, deadline=None) +@settings(max_examples=scaled(20), deadline=None) @given(width=st.integers(min_value=0, max_value=8000), height=st.integers(min_value=0, max_value=8000), fps=st.floats(min_value=0.01, max_value=1000, allow_nan=False, @@ -311,7 +312,7 @@ def test_pdf_handles_extreme_media_metadata(width: int, height: int, fps: float, # --------------------------------------------------------------------- CSV / MHL / HTML -@settings(max_examples=40, deadline=None) +@settings(max_examples=scaled(40), deadline=None) @given(names=st.lists(hostile_text, min_size=1, max_size=5)) def test_csv_keeps_its_column_count(names: list[str], tmp_path_factory): """A filename containing commas, quotes or newlines must not shift columns.""" @@ -326,7 +327,7 @@ def test_csv_keeps_its_column_count(names: list[str], tmp_path_factory): assert len(row) == len(header) -@settings(max_examples=40, deadline=None) +@settings(max_examples=scaled(40), deadline=None) @given(names=st.lists(hostile_text, min_size=1, max_size=5)) def test_mhl_is_always_well_formed_xml(names: list[str], tmp_path_factory): out = tmp_path_factory.mktemp("mhl") / "JobReport.mhl" @@ -367,7 +368,7 @@ def handle_starttag(self, tag, attrs): injecting_text = st.one_of(hostile_text, st.sampled_from(INJECTION_PAYLOADS)) -@settings(max_examples=40, deadline=None) +@settings(max_examples=scaled(40), deadline=None) @given(names=st.lists(injecting_text, min_size=1, max_size=5)) def test_html_input_can_never_become_markup(names: list[str], tmp_path_factory): """The real anti-injection property: whatever the filenames contain, the diff --git a/tests/test_fuzz_corpus.py b/tests/test_fuzz_corpus.py new file mode 100644 index 0000000..d769f66 --- /dev/null +++ b/tests/test_fuzz_corpus.py @@ -0,0 +1,36 @@ +"""Replay every committed seed through its fuzz target, on every test run. + +The Hypothesis targets only reach their deep budgets under `--fuzz`, which +runs in its own CI job. This is the quick tier: each seed in +`tests/fuzz_corpus//` goes through `fuzz_targets.TARGETS[]` +once, so a regression input, a target that no longer loads, or a seed that +has started failing breaks the ordinary suite. Ported from markcopy's +seed-replay test. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from fuzz_targets import TARGETS +from make_fuzz_seeds import CORPUS, MAX_SEED_BYTES + +SEEDS = sorted(path for path in CORPUS.glob("*/*") if path.is_file()) + + +@pytest.mark.parametrize("seed", SEEDS, ids=lambda p: f"{p.parent.name}/{p.name}") +def test_seed_passes_its_target(seed: Path): + assert seed.stat().st_size <= MAX_SEED_BYTES, "seeds stay small" + TARGETS[seed.parent.name](seed.read_bytes()) + + +def test_every_corpus_folder_is_a_target(): + folders = {path.name for path in CORPUS.iterdir() if path.is_dir()} + assert folders <= set(TARGETS), f"no target for {sorted(folders - set(TARGETS))}" + + +def test_every_target_has_seeds(): + seeded = {seed.parent.name for seed in SEEDS} + assert seeded == set(TARGETS), f"unseeded: {sorted(set(TARGETS) - seeded)}" diff --git a/tests/test_fuzz_edges.py b/tests/test_fuzz_edges.py index 27f100a..992e2e2 100644 --- a/tests/test_fuzz_edges.py +++ b/tests/test_fuzz_edges.py @@ -41,6 +41,8 @@ from hypothesis import HealthCheck, given, settings from hypothesis import strategies as st +import fuzz_targets +from fuzz_oracle import scaled from offloader import ascmhl, braw, engine, naming, retry from offloader.engine import OffloadOptions from offloader.hashers import hash_file @@ -138,15 +140,9 @@ def write_braw(directory: Path, payload: bytes, name: str = "clip.braw") -> Path @settings(deadline=None, suppress_health_check=[HealthCheck.too_slow]) @given(payload=st.binary(max_size=4096)) -def test_braw_read_info_survives_arbitrary_bytes(payload: bytes, tmp_path_factory): +def test_braw_read_info_survives_arbitrary_bytes(payload: bytes): """The cheapest fuzz there is: a .braw that is not BRAW at all.""" - target = write_braw(tmp_path_factory.mktemp("braw"), payload) - try: - braw.read_info(target) - except PARSER_MAY_RAISE: - pass - except Exception as exc: # noqa: BLE001 - pytest.fail(f"read_info raised {type(exc).__name__}: {exc}") + fuzz_targets.braw_file(payload) @settings(deadline=None, suppress_health_check=[HealthCheck.too_slow]) @@ -298,7 +294,7 @@ def test_destination_paths_are_injective_when_structure_is_preserved(tmp_path): assert landed == [1000, 2000] -@settings(max_examples=30, deadline=None, +@settings(max_examples=scaled(30), deadline=None, suppress_health_check=[HealthCheck.function_scoped_fixture, HealthCheck.too_slow]) @given(folders=st.lists(st.text(alphabet="ABCDEFG", min_size=1, max_size=3), diff --git a/tests/test_fuzz_engine.py b/tests/test_fuzz_engine.py new file mode 100644 index 0000000..220beca --- /dev/null +++ b/tests/test_fuzz_engine.py @@ -0,0 +1,332 @@ +"""Fuzz whole offloads: random cards, existing copies and injected faults. + +Every other fuzz target feeds one parser. This one runs `engine.run` end to +end, on a random card, against destinations that may already hold a good +copy, a stale one or a same-size impostor, while a fault plan fails source +reads, destination writes, fsync or promotion, corrupts a staged copy before +it is reread, or cancels the job at an arbitrary progress event. + +The oracle is the safety contract in AGENTS.md and docs/data-safety.md, +checked against the bytes on disk rather than against what the job says: + +- `run` raises nothing once its pre-flight checks pass, and finishes; +- the source is never changed; +- no `.offloader-partial` survives, and nothing else new appears; +- every final-named file holds either what was there before or exactly the + source's bytes: never a truncation, never a corrupt staged copy; +- a pre-existing different file survives unless `replace_existing`; +- a destination marked Verified or Copied holds the source's bytes, and one + marked Skipped at least has its size; +- a "Verified" job had every destination verified, was not cancelled, and + saw no fault that kept failing; +- no source file is silently missing from the job. + +Run longer sweeps with: pytest --fuzz tests/test_fuzz_engine.py +""" + +from __future__ import annotations + +import errno +import os +import random +import tempfile +import threading +from dataclasses import dataclass, field +from pathlib import Path + +import pytest +from hypothesis import HealthCheck, event, given, settings +from hypothesis import strategies as st + +from fuzz_oracle import scaled +from offloader import engine, longpath, retry +from offloader.models import FileStatus, VerificationMode + +CHUNK = 4096 +#: Long enough for a slow CI runner, short enough that a deadlock is a finding. +FINISH_WITHIN = 60.0 + +ENGINE = settings(max_examples=scaled(40), deadline=None, + suppress_health_check=[HealthCheck.too_slow, + HealthCheck.data_too_large]) + + +def _error(code: int, winerror: int, message: str) -> OSError: + """An OSError retry.py classifies the same way on every platform: when + `winerror` is set it alone decides.""" + exc = OSError(code, message) + exc.winerror = winerror + return exc + + +def transient() -> OSError: + return _error(errno.EIO, 1117, "simulated I/O device error") + + +def permanent() -> OSError: + return _error(errno.ENOSPC, 112, "simulated disk full") + + +@dataclass +class Fault: + kind: str # read | write | fsync | replace | corrupt | cancel + nth: int # fires on the nth operation of its kind + sticky: bool # and on every one after it + lasting: bool # a permanent error rather than a transient one + + def due(self, count: int) -> bool: + return count == self.nth or (self.sticky and count > self.nth) + + +@dataclass +class Plan: + faults: list[Fault] + counts: dict[str, int] = field(default_factory=dict) + fired: list[Fault] = field(default_factory=list) + lock: threading.Lock = field(default_factory=threading.Lock) + + def tick(self, kind: str) -> Fault | None: + """Count one operation of `kind`; the fault due on it, if any.""" + with self.lock: + count = self.counts[kind] = self.counts.get(kind, 0) + 1 + for fault in self.faults: + if fault.kind == kind and fault.due(count): + self.fired.append(fault) + return fault + return None + + def raise_if_due(self, kind: str) -> None: + fault = self.tick(kind) + if fault is not None: + raise permanent() if fault.lasting else transient() + + @property + def kept_failing(self) -> bool: + """A sticky fault fired: retries see it too, so something must fail.""" + return any(fault.sticky and fault.kind != "cancel" for fault in self.fired) + + +class _Faulty: + """A file handle whose reads or writes consult the plan first.""" + + def __init__(self, handle, plan: Plan, kind: str, fds: set[int]) -> None: + self._handle, self._plan, self._kind = handle, plan, kind + if kind == "write": + fds.add(handle.fileno()) + + def read(self, *args): + self._plan.raise_if_due("read") + return self._handle.read(*args) + + def write(self, data): + self._plan.raise_if_due("write") + return self._handle.write(data) + + def __getattr__(self, name): + return getattr(self._handle, name) + + def __enter__(self): + return self + + def __exit__(self, *exc): + self._handle.close() + return False + + +def _install(mp: pytest.MonkeyPatch, plan: Plan, card: Path, dests: list[Path]) -> None: + card = card.resolve() + dests = [d.resolve() for d in dests] + fds: set[int] = set() + open_binary, replace = longpath.open_binary, longpath.replace + evict, fsync = engine.integrity.evict_from_cache, os.fsync + + def under(path, roots) -> bool: + resolved = Path(os.path.abspath(str(path).removeprefix("\\\\?\\"))) + return any(resolved.is_relative_to(root) for root in roots) + + def faulty_open(path, mode="rb", *args, **kwargs): + handle = open_binary(path, mode, *args, **kwargs) + if "r" in mode and under(path, [card]): + return _Faulty(handle, plan, "read", fds) + if "w" in mode and under(path, dests): + return _Faulty(handle, plan, "write", fds) + return handle + + def faulty_fsync(fd): + if fd in fds: + plan.raise_if_due("fsync") + return fsync(fd) + + def faulty_replace(source, target): + if under(target, dests): + plan.raise_if_due("replace") + return replace(source, target) + + def corrupting_evict(path): + # The last moment before the verify reread: flipping a byte here is a + # write that landed wrong, which only a full reread can catch. + if str(path).endswith(engine.PARTIAL_SUFFIX) and plan.tick("corrupt"): + data = bytearray(Path(path).read_bytes()) + if data: + data[len(data) // 2] ^= 0xFF + Path(path).write_bytes(bytes(data)) + return evict(path) + + mp.setattr(engine, "CHUNK_SIZE", CHUNK) + mp.setattr(longpath, "open_binary", faulty_open) + mp.setattr(longpath, "replace", faulty_replace) + mp.setattr(os, "fsync", faulty_fsync) + mp.setattr(engine.integrity, "evict_from_cache", corrupting_evict) + + +# ----------------------------------------------------------------- strategies + +names = st.sampled_from(["A001_C001.mov", "A001_C002.mov", "CLIP/B002.braw", + "CLIP/B003.braw", "SOUND/T01.wav", "x"]) +#: (seed, size): bytes are drawn from a seeded generator, not by Hypothesis, +#: so a 16 KB clip does not cost 16 KB of shrinkable choices. +contents = st.tuples(st.integers(0, 2**32), st.integers(0, 4 * CHUNK + 7)) +cards = st.dictionaries(names, contents, min_size=1, max_size=4).filter( + lambda card: not ("x" in card and any(n.startswith("x/") for n in card))) + +#: What a destination already holds at a card file's path. +PRIOR = ["nothing", "same", "different", "same-size", "truncated"] + +faults = st.lists(st.builds( + Fault, + kind=st.sampled_from(["read", "write", "fsync", "replace", "corrupt", "cancel"]), + nth=st.integers(1, 8), sticky=st.booleans(), lasting=st.booleans()), + min_size=1, max_size=3) + + +def _bytes(seed: int, size: int) -> bytes: + return random.Random(seed).randbytes(size) + + +def _snapshot(root: Path) -> dict[str, bytes]: + return {p.relative_to(root).as_posix(): p.read_bytes() + for p in root.rglob("*") if p.is_file()} + + +# ---------------------------------------------------------------------- target + + +@ENGINE +@given(card=cards, destinations=st.integers(1, 2), prior=st.data(), + mode=st.sampled_from(list(VerificationMode)), skip_existing=st.booleans(), + replace_existing=st.booleans(), plan=faults) +def test_an_offload_under_faults_keeps_the_safety_contract( + card, destinations, prior, mode, skip_existing, replace_existing, plan): + if mode is not VerificationMode.FULL: + # Only a full reread can see a corrupt write; under the other modes it + # is a documented limit, not a property. + plan = [f for f in plan if f.kind != "corrupt"] + plan = Plan(plan) + + with tempfile.TemporaryDirectory() as folder, pytest.MonkeyPatch.context() as mp: + base = Path(folder) + source = {name: _bytes(*spec) for name, spec in card.items()} + for name, data in source.items(): + (base / "card" / name).parent.mkdir(parents=True, exist_ok=True) + (base / "card" / name).write_bytes(data) + + roots = [base / f"dest{i}" for i in range(destinations)] + before: list[dict[str, bytes]] = [] + for root in roots: + root.mkdir() + for name, data in source.items(): + kind = prior.draw(st.sampled_from(PRIOR), label=f"{root.name}/{name}") + old = {"same": data, "different": data[::-1] + b"old", + "same-size": bytes(len(data)), "truncated": data[: len(data) // 2], + }.get(kind) + if old is not None: + (root / name).parent.mkdir(parents=True, exist_ok=True) + (root / name).write_bytes(old) + before.append(_snapshot(root)) + + control = engine.JobControl() + events = 0 + + def progress(event) -> None: + nonlocal events + events += 1 + if plan.tick("cancel"): + control.cancel() + + options = engine.OffloadOptions( + destinations=roots, verification=mode, thumbnail_count=0, + extra_probe=False, skip_existing=skip_existing, + replace_existing=replace_existing, + retry=retry.RetryPolicy(attempts=3, delay=0)) + _install(mp, plan, base / "card", roots) + + outcome: dict = {} + + def offload() -> None: + try: + outcome["job"] = engine.run(base / "card", options, progress=progress, + control=control) + except BaseException as exc: # noqa: BLE001 - reported below + outcome["error"] = exc + + worker = threading.Thread(target=offload, daemon=True) + worker.start() + worker.join(FINISH_WITHIN) + mp.undo() + + assert not worker.is_alive(), f"run did not finish; faults fired: {plan.fired}" + if "error" in outcome: + raise AssertionError(f"run raised; faults fired: {plan.fired}") \ + from outcome["error"] + job = outcome["job"] + # Visible with --hypothesis-show-statistics: proof the plan reaches + # the engine, rather than every fault landing after the job ended. + for kind in sorted({fault.kind for fault in plan.fired}) or ["no fault"]: + event(f"fired: {kind}") + event(f"verdict: {job.final_status}") + _assert_contract(job, base, source, roots, before, plan, mode, + skip_existing, replace_existing) + + +def _assert_contract(job, base, source, roots, before, plan, mode, + skip_existing, replace_existing) -> None: + context = f"faults fired: {plan.fired}; verdict {job.final_status!r}" + + assert _snapshot(base / "card") == source, f"the source changed; {context}" + + for root, prior in zip(roots, before, strict=True): + after = _snapshot(root) + partials = [name for name in after if name.endswith(engine.PARTIAL_SUFFIX)] + assert not partials, f"left behind {partials}; {context}" + strays = set(after) - set(source) - set(prior) + assert not strays, f"unexpected files {strays}; {context}" + for name, data in after.items(): + assert data in (prior.get(name), source.get(name)), ( + f"{root.name}/{name} is neither the old file nor the source; {context}") + old = prior.get(name) + if old is not None and old != source[name] and not replace_existing: + assert data == old, f"{root.name}/{name} was replaced; {context}" + + listed = {Path(entry.source).resolve() for entry in job.files} + listed |= {Path(p).resolve() for p in job.not_attempted} + missing = [n for n in source if (base / "card" / n).resolve() not in listed] + assert not missing, f"silently omitted {missing}; {context}" + + statuses = [] + for entry in job.files: + name = Path(entry.source).resolve().relative_to((base / "card").resolve()).as_posix() + for destination in entry.destinations: + statuses.append(destination.status) + target = Path(destination.path) + if destination.status in (FileStatus.VERIFIED, FileStatus.COPIED): + assert target.read_bytes() == source[name], ( + f"{target} marked {destination.status.value} but differs; {context}") + elif destination.status is FileStatus.SKIPPED: + assert skip_existing and target.stat().st_size == len(source[name]) + + if job.final_status == "Verified": + assert mode is not VerificationMode.NONE + assert statuses and all(s is FileStatus.VERIFIED for s in statuses), context + assert len(job.files) == len(source), context + assert not job.cancelled, context + assert not plan.kept_failing, f"a fault kept failing and the job says Verified; {context}" diff --git a/tests/test_fuzz_parsers.py b/tests/test_fuzz_parsers.py new file mode 100644 index 0000000..30471e5 --- /dev/null +++ b/tests/test_fuzz_parsers.py @@ -0,0 +1,403 @@ +"""Fuzz targets for the parsers that read what someone else wrote. + +`test_fuzz.py` fuzzes filenames and `test_fuzz_edges.py` fuzzes the card. This +module fuzzes the documents offloader reads back: the iXML a recorder put in a +WAV, the ASC MHL a previous offload left behind, the manifest `verify` is +asked to vouch for, and the `file:` URLs in an editor's timeline. + +Each target pairs a generator with an oracle from `fuzz_oracle`. For the +manifest readers the oracle is differential: the manifest is written here, +independently of `reports/`, and the reader must report exactly what was +written. For `verify` it is the one property the product exists for: a +report that passed means every file it vouches for hashes, now, to the digest +the manifest recorded, checked against a hash taken here and not by +`hashers`. + +Run longer sweeps with: pytest --fuzz tests/test_fuzz_parsers.py +""" + +from __future__ import annotations + +import hashlib +import struct +import tempfile +import unicodedata +from pathlib import Path +from urllib.parse import quote +from xml.etree import ElementTree as ET +from xml.sax.saxutils import escape + +import pytest +import xxhash +from hypothesis import HealthCheck, example, given, settings +from hypothesis import strategies as st + +import fuzz_targets +from bwf import ixml_document +from fuzz_oracle import bounded, scaled +from fuzz_targets import check_sound +from offloader import ascmhl, ixml, timeline, verify + +QUICK = settings(max_examples=scaled(100), deadline=None, + suppress_health_check=[HealthCheck.too_slow]) +#: Targets that touch the filesystem per example. +SLOW = settings(max_examples=scaled(40), deadline=None, + suppress_health_check=[HealthCheck.too_slow]) + +#: Numbers a recorder should never write and a hand-edited file easily can. +ABSURD_NUMBERS = ["inf", "-inf", "nan", "INF/1", "1e308/1e-308", "0/0", "25/0", + "-25/1", "1e-320", "30000/1001", "25", ""] + +#: Independent reference hashes: not `offloader.hashers`, so a bug there +#: cannot make the oracle agree with it. +REFERENCE = { + "md5": lambda data: hashlib.md5(data).hexdigest(), + "sha256": lambda data: hashlib.sha256(data).hexdigest(), + "xxh64": lambda data: xxhash.xxh64(data).hexdigest(), + "xxh3": lambda data: xxhash.xxh3_64(data).hexdigest(), +} +#: The verify module's algorithm key for each tag above. +TAG_KEY = {"md5": "md5", "sha256": "sha256", "xxh64": "xxh64", "xxh3": "xxh3-64"} +KEY_TAG = {key: tag for tag, key in TAG_KEY.items()} + +xml_text = st.text( + st.characters(blacklist_categories=("Cs", "Cc")), max_size=40).map(escape) + + +# ---------------------------------------------------------------------- iXML + + +@QUICK +@given(text=st.text(max_size=2048)) +@example(text=ixml_document(rate="inf")) +def test_parse_ixml_on_any_text(text): + check_sound(bounded(ixml.parse_ixml, text)) + + +@QUICK +@given(project=xml_text, scene=xml_text, take=xml_text, note=xml_text, + rate=st.sampled_from(ABSURD_NUMBERS) | xml_text, + flag=st.sampled_from(["DF", "NDF", "df", ""]) | xml_text, + sample_rate=st.sampled_from(["48000", "0", "-1", "1e9", "nan"]) | xml_text, + samples=st.integers(min_value=0, max_value=2**64 - 1), + names=st.lists(xml_text, max_size=6)) +def test_parse_ixml_on_recorder_shaped_documents(project, scene, take, note, rate, + flag, sample_rate, samples, names): + document = ixml_document(project=project, scene=scene, take=take, note=note, + rate=rate, flag=flag, sample_rate=sample_rate, + samples_since_midnight=samples, track_names=names) + check_sound(bounded(ixml.parse_ixml, document)) + + +def test_an_infinite_timecode_rate_is_refused(): + """A rate of `inf` used to be accepted, then raise OverflowError in + `timecode_of`'s `round()`. `probe` swallowed that, but only after it had + stored the SoundInfo, so the infinite rate still reached the sound report.""" + for rate in ("inf", "INF/1", "1e308/1e-308"): + info = ixml.parse_ixml(ixml_document(rate=rate)) + assert info is not None and info.timecode_rate is None, rate + assert ixml.timecode_of(info, 48000) is None + + +def _riff_chunk(identifier: bytes, payload: bytes, declared: int | None) -> bytes: + size = len(payload) if declared is None else declared + return identifier + struct.pack(" str: + """The key two names collide on, on a case-insensitive or normalising + filesystem (NTFS, APFS).""" + return unicodedata.normalize("NFC", name).casefold() + + +asc_entries = st.lists(st.tuples( + relative_names, + st.lists(st.tuples(st.sampled_from(sorted(REFERENCE)), st.sampled_from(ACTIONS), + st.text("0123456789abcdefABCDEF", min_size=1, max_size=32)), + max_size=3), +), max_size=6, unique_by=lambda entry: entry[0]) + + +def asc_manifest(entries) -> bytes: + """An ASC MHL hashlist, written by hand rather than by `ascmhl`.""" + hashes = [] + for name, digests in entries: + inner = [f'{escape(name)}'] + for tag, action, digest in digests: + attribute = f' action="{action}"' if action else "" + inner.append(f"<{tag}{attribute}>{digest}") + hashes.append(f"{''.join(inner)}") + return (f'' + f'{"".join(hashes)}' + f"").encode() + + +def expected_hashes(entries) -> dict[str, dict[str, str]]: + """What the spec says a reader may use: never a hash marked failed.""" + result: dict[str, dict[str, str]] = {} + for name, digests in entries: + usable = {tag: digest for tag, action, digest in digests + if action != ascmhl.ACTION_FAILED} + if usable: + result.setdefault(name.strip(), {}).update(usable) + return result + + +@SLOW +@given(entries=asc_entries) +def test_read_manifest_hashes_reports_exactly_what_was_written(entries): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "0001_card.mhl" + path.write_bytes(asc_manifest(entries)) + assert bounded(ascmhl.read_manifest_hashes, path) == expected_hashes(entries) + + +#: XML declarations `ET.parse` refuses with something other than ParseError. +BAD_ENCODINGS = ["TF-8", "bogus", "shift_jis", "utf-32"] + + +def _with_encoding(document: bytes, encoding: str) -> bytes: + return document.replace(b'encoding="UTF-8"', f'encoding="{encoding}"'.encode(), 1) + + +@pytest.mark.parametrize("encoding", BAD_ENCODINGS) +def test_a_manifest_with_a_bad_encoding_reads_as_empty(tmp_path, encoding): + """One damaged byte in the declaration used to raise LookupError out of + the reader, failing the next ASC MHL generation instead of starting it.""" + path = tmp_path / "0001_card.mhl" + path.write_bytes(_with_encoding( + asc_manifest([("a.mov", [("md5", None, "00")])]), encoding)) + assert ascmhl.read_manifest_hashes(path) == {} + + +@pytest.mark.parametrize("encoding", BAD_ENCODINGS) +def test_verify_reports_a_bad_encoding_as_a_parse_error(tmp_path, encoding): + manifest = _write_case(tmp_path, {"a.mov": b"x"}, "md5", False, "none", 0) + manifest.write_bytes(_with_encoding(manifest.read_bytes(), encoding)) + with pytest.raises(ET.ParseError): + verify.verify_manifest(manifest, bypass_cache=False) + + +def _mutate(data: bytes, edits) -> bytes: + buffer = bytearray(data) + for position, kind, value in edits: + if not buffer: + break + at = position % len(buffer) + if kind == 0: + del buffer[at] + elif kind == 1: + buffer.insert(at, value) + else: + buffer[at] = value + return bytes(buffer) + + +#: Deletes the U of `encoding="UTF-8"` in either manifest form, which is +#: the edit that found the LookupError escaping `ET.parse`. +UTF8_TO_TF8 = (len(' bool: + folded = [_folded(name) for name in tree] + if len(set(folded)) != len(folded): + return False + # A name may not be both a file and a folder in the same tree. + return not any(other.startswith(name + "/") for name in folded for other in folded) + + +trees = st.dictionaries(relative_names, st.binary(min_size=1, max_size=256), + min_size=1, max_size=5).filter(_plausible_tree) + + +def _assert_sound(report: verify.VerifyReport, tag: str) -> None: + """The property `verify` exists for: a pass is backed by a hash taken now.""" + if not report.passed: + return + for verdict in report.verdicts: + if verdict.superseded_by is not None: + continue + assert verdict.path.is_file(), f"passed but {verdict.path} is not there" + actual = REFERENCE[tag](verdict.path.read_bytes()) + assert verdict.expected is not None + assert verdict.expected.lower() == actual, f"passed but {verdict.path} differs" + + +def _write_case(base: Path, tree: dict[str, bytes], tag: str, asc: bool, + mutation: str, victim: int) -> Path: + """The tree and a manifest of it, then one mutation.""" + root = base / "card" + for name, data in tree.items(): + (root / name).parent.mkdir(parents=True, exist_ok=True) + (root / name).write_bytes(data) + + names = sorted(tree) + target = names[victim % len(names)] + entries = [] + for name in names: + digest = REFERENCE[tag](tree[name]) + if name == target and mutation == "uppercase-digest": + digest = digest.upper() + recorded = [] if name == target and mutation == "drop-digest" else [digest] + entries.append((name, len(tree[name]), recorded)) + if mutation == "wrong-duplicate": + entries.append((target, len(tree[target]), ["0" * len(REFERENCE[tag](b""))])) + + if asc: + action = ascmhl.ACTION_FAILED if mutation == "mark-failed" else "original" + body = "".join( + f'{escape(name)}' + + "".join(f'<{tag} action="{action if name == target else "original"}">' + f"{d}" for d in digests) + + "" for name, size, digests in entries) + manifest = root / ascmhl.ASCMHL_DIRNAME / "0001_card_2026-01-01_000000Z.mhl" + manifest.parent.mkdir(parents=True) + manifest.write_text(f'{body}' + "", encoding="utf-8") + else: + body = "".join( + f"{escape(name)}{size}" + + "".join(f"<{tag}>{d}" for d in digests) + + "" for name, size, digests in entries) + manifest = root / "card.mhl" + manifest.write_text(f'' + f'{body}', + encoding="utf-8") + + path = root / target + if mutation == "flip-byte": + data = bytearray(tree[target]) + data[victim % len(data)] ^= 0xFF + path.write_bytes(bytes(data)) + elif mutation == "truncate": + path.write_bytes(tree[target][:-1]) + elif mutation == "delete": + path.unlink() + return manifest + + +@SLOW +@given(tree=trees, tag=st.sampled_from(sorted(REFERENCE)), asc=st.booleans(), + mutation=st.sampled_from(sorted(MUTATIONS)), victim=st.integers(min_value=0)) +def test_verify_passes_exactly_when_it_should(tree, tag, asc, mutation, victim): + if mutation == "mark-failed" and not asc: + mutation = "none" # classic MHL has no action attribute + with tempfile.TemporaryDirectory() as folder: + manifest = _write_case(Path(folder), tree, tag, asc, mutation, victim) + report = verify.verify_manifest(manifest, bypass_cache=False) + _assert_sound(report, tag) + assert report.passed is MUTATIONS[mutation], ( + f"{mutation}: passed={report.passed} {report.counts()}") + + +@SLOW +@given(tree=trees, tag=st.sampled_from(sorted(REFERENCE)), asc=st.booleans(), + edits=edits) +@example(tree={"a.mov": b"x"}, tag="md5", asc=False, edits=[UTF8_TO_TF8]) +def test_verify_on_a_damaged_manifest_never_vouches_for_wrong_bytes(tree, tag, asc, + edits): + with tempfile.TemporaryDirectory() as folder: + manifest = _write_case(Path(folder), tree, tag, asc, "none", 0) + manifest.write_bytes(_mutate(manifest.read_bytes(), edits)) + # The CLI reports a manifest that will not parse as an error, which + # is the right answer; anything else must still be a sound verdict. + report = bounded(verify.verify_manifest, manifest, bypass_cache=False, + allowed=(ET.ParseError,), seconds=10) + if report is not None: + _assert_sound(report, tag) + + +# ------------------------------------------------------------------ timeline + + +@QUICK +@given(url=st.text(max_size=200)) +def test_url_to_path_on_any_text(url): + result = bounded(timeline._url_to_path, url) + assert result is None or isinstance(result, Path) + scheme = bounded(timeline._url_scheme, url) + assert isinstance(scheme, str) and scheme == scheme.lower() + + +segments = st.lists(st.text(st.characters(whitelist_categories=("L", "N"), + whitelist_characters=" -_.%#&+"), + min_size=1, max_size=10).filter(lambda s: s.strip(" .")), + min_size=1, max_size=4) + + +@QUICK +@given(drive=st.sampled_from("CDEZ"), parts=segments, + form=st.sampled_from(["file:///", "file://localhost/", "FILE:///"])) +def test_windows_file_urls_round_trip(drive, parts, form): + url = form + quote(f"{drive}:/" + "/".join(parts)) + assert timeline._url_to_path(url) == Path(f"{drive}:/" + "/".join(parts)) + + +@QUICK +@given(parts=segments, form=st.sampled_from(["file://", "file://localhost"])) +def test_posix_file_urls_keep_their_root(parts, form): + """The leading slash of `/Volumes/...` is the path's root, not noise.""" + url = form + quote("/Volumes/" + "/".join(parts)) + result = timeline._url_to_path(url) + assert result is not None and result.anchor + assert result == Path("/Volumes/" + "/".join(parts)) diff --git a/tests/test_fuzz_state.py b/tests/test_fuzz_state.py new file mode 100644 index 0000000..e9db070 --- /dev/null +++ b/tests/test_fuzz_state.py @@ -0,0 +1,153 @@ +"""Fuzz targets for the files offloader keeps between runs. + +The state file, the history and the CLI's control file are all hand-editable, +all written by something other than this process at some point, and all read +at moments when failing would stop an offload: at startup, before a job, and +once per chunk during one. The contract for each is the same. Damaged +content may be ignored; it may not raise, may not be guessed at, and may not +cost the user something that was intact. + +Run longer sweeps with: pytest --fuzz tests/test_fuzz_state.py +""" + +from __future__ import annotations + +import json +import tempfile +from pathlib import Path + +import pytest +from hypothesis import HealthCheck, example, given, settings +from hypothesis import strategies as st + +import fuzz_targets +from fuzz_oracle import scaled +from offloader import config, engine, history + +FILES = settings(max_examples=scaled(100), deadline=None, + suppress_health_check=[HealthCheck.too_slow]) + +#: Any JSON value, including the NaN and Infinity Python's json writes. +json_values = st.recursive( + st.none() | st.booleans() | st.integers() | st.floats() | st.text(max_size=20), + lambda inner: st.lists(inner, max_size=4) + | st.dictionaries(st.text(max_size=12), inner, max_size=4), + max_leaves=20) + + +def _scratch(data: bytes, name: str = "state.json") -> tuple[tempfile.TemporaryDirectory, Path]: + folder = tempfile.TemporaryDirectory() + path = Path(folder.name) / name + path.write_bytes(data) + return folder, path + + +# ------------------------------------------------------------------ read_json + + +@FILES +@given(data=st.binary(max_size=512) + | json_values.map(lambda v: json.dumps(v).encode()) + | st.builds(lambda depth, bracket: bracket * depth, + st.integers(1, 200_000), st.sampled_from([b"[", b'{"a":']))) +@example(data=b"[" * 3000) +def test_read_json_returns_the_value_or_the_default(data): + fuzz_targets.state_json(data) + + +@pytest.mark.parametrize("opening", ["[", '{"a":']) +def test_deeply_nested_state_falls_back_to_the_default(tmp_path, opening): + """Deep nesting raised RecursionError, which is neither OSError nor + ValueError, out of `read_json`, so a damaged history.json stopped the + History from being built at all.""" + path = tmp_path / "history.json" + path.write_text(opening * 100_000, encoding="utf-8") + assert config.read_json(path, []) == [] + assert history.History(path).entries == [] + + +# -------------------------------------------------------------------- history + + +records = st.lists( + st.dictionaries( + st.sampled_from(["fingerprint", "job_name", "source", "destinations", + "file_count", "total_bytes", "status", "finished"]), + json_values, max_size=8) + | json_values, + max_size=6) + + +@FILES +@given(records=records) +@example(records=[{"fingerprint": "card-a", "file_count": float("inf")}]) +def test_history_keeps_every_record_it_can_identify(records): + """A damaged field costs that field, never the record: the record's + fingerprint is the duplicate-card warning for that card.""" + fuzz_targets.history_file(json.dumps(records).encode()) + + +@pytest.mark.parametrize("count", ["1e400", "-1e400"]) +def test_an_overflowing_count_costs_the_count_not_the_record(tmp_path, count): + """`int(inf)` raises OverflowError, which `count()` did not catch, so the + whole record was dropped along with its fingerprint.""" + path = tmp_path / "history.json" + path.write_text(f'[{{"fingerprint": "card-a", "file_count": {count}}}]', + encoding="utf-8") + entries = history.History(path).entries + assert [e.fingerprint for e in entries] == ["card-a"] + assert entries[0].file_count == 0 + + +# --------------------------------------------------------------- control file + + +control_bytes = ( + st.binary(max_size=80) + | st.builds(lambda pad, word, tail: (pad + word + tail).encode(), + st.sampled_from(["", " ", "\n", "", "\t"]), + st.sampled_from(["run", "pause", "cancel", "CANCEL", "Pause", + "cancel pending", "cancel\x00", "can cel"]), + st.sampled_from(["", "\n", "\r\n", " ", "\x00", "!"]))) + + +@FILES +@given(data=control_bytes) +def test_control_read_means_a_word_or_no_opinion(data): + fuzz_targets.control_file(data) + + +@FILES +@given(writes=st.lists(control_bytes, min_size=1, max_size=8)) +@example(writes=[b"cancel", b"pause"]) +def test_a_damaged_control_file_never_changes_the_job(writes): + """Only a whole control word moves the job. A cancel is final: a `pause` + written after it may show as the file's state, but the next checkpoint + still ends the job rather than holding it.""" + folder, path = _scratch(b"run\n", "offload.control") + with folder: + ticks = iter(range(1, 1000)) + control = engine.FileControl(path, poll=0.05, clock=lambda: next(ticks)) + state, cancelled = engine.FileControl.RUN, False + for data in writes: + path.write_bytes(data) + control.sync() + word = fuzz_targets.control_word(data) + if word is not None: + state = word + cancelled = cancelled or word == engine.FileControl.CANCEL + assert control.state == state + assert control.cancelled is cancelled + if cancelled: + with pytest.raises(engine.JobCancelled): + control.checkpoint() + else: + assert control.paused is (state == engine.FileControl.PAUSE) + + +@FILES +@given(existing=control_bytes | st.binary(min_size=65, max_size=200)) +def test_claim_never_overwrites_what_is_not_a_control_file(existing): + """The control path comes from a command line and a typo can name a clip. + Claiming may replace an empty file or a control word, and nothing else.""" + fuzz_targets.control_file(existing) diff --git a/tests/test_fuzz_surfaces.py b/tests/test_fuzz_surfaces.py new file mode 100644 index 0000000..99e5672 --- /dev/null +++ b/tests/test_fuzz_surfaces.py @@ -0,0 +1,110 @@ +"""Keep `fuzz_surfaces.json` honest. + +The manifest maps every module that reads or renders outside input to the +property tests that fuzz it, or records the gap. These checks make it +impossible to add a module, rename a target or add a fuzz file without the +manifest and the CI soak job hearing about it. They read files only; nothing +here runs a fuzzer. Ported from markcopy's `fuzzCoverage` test. +""" + +from __future__ import annotations + +import ast +import json +import re +from functools import cache +from pathlib import Path + +REPO = Path(__file__).resolve().parent.parent +MANIFEST = json.loads((REPO / "tests" / "fuzz_surfaces.json").read_text(encoding="utf-8")) +SURFACES: dict[str, dict] = MANIFEST["surfaces"] +NOT_SURFACES: dict[str, str] = MANIFEST["not_surfaces"] +HOW = "Add it to tests/fuzz_surfaces.json, under surfaces (with targets or a gap) " \ + "or not_surfaces (with a reason)." + + +@cache +def given_tests(test_file: str) -> frozenset[str]: + """Top-level test functions in `test_file` decorated with `@given`.""" + tree = ast.parse((REPO / test_file).read_text(encoding="utf-8")) + return frozenset( + node.name for node in tree.body + if isinstance(node, ast.FunctionDef) + and any(_is_given(decorator) for decorator in node.decorator_list)) + + +def _is_given(decorator: ast.expr) -> bool: + target = decorator.func if isinstance(decorator, ast.Call) else decorator + return (isinstance(target, ast.Name) and target.id == "given") or ( + isinstance(target, ast.Attribute) and target.attr == "given") + + +def fuzz_files() -> list[str]: + return sorted(path.relative_to(REPO).as_posix() + for path in (REPO / "tests").glob("test_*.py") if given_tests( + path.relative_to(REPO).as_posix())) + + +def test_every_module_in_a_policed_folder_is_classified(): + unlisted = [] + for folder in MANIFEST["policed"]: + for module in sorted((REPO / folder).glob("*.py")): + name = module.relative_to(REPO).as_posix() + if name not in SURFACES and name not in NOT_SURFACES: + unlisted.append(name) + assert not unlisted, f"unclassified: {unlisted}. {HOW}" + + +def test_no_module_is_both_a_surface_and_not_one(): + assert not set(SURFACES) & set(NOT_SURFACES) + + +def test_every_listed_path_exists(): + listed = [*SURFACES, *NOT_SURFACES, *MANIFEST["policed"], *MANIFEST["exempt"]] + missing = [name for name in listed if not (REPO / name).exists()] + assert not missing, f"listed but gone: {missing}" + + +def test_every_surface_has_a_target_or_a_stated_gap(): + bare = [name for name, entry in SURFACES.items() + if not entry.get("targets") and not entry.get("gap", "").strip()] + assert not bare, f"no target and no gap: {bare}" + + +def test_every_exclusion_gives_a_reason(): + unexplained = [name for name, reason in {**NOT_SURFACES, **MANIFEST["exempt"]}.items() + if not reason.strip()] + assert not unexplained + + +def test_every_target_is_a_hypothesis_test(): + wrong = [] + for name, entry in SURFACES.items(): + for target in entry.get("targets", []): + test_file, _, function = target.partition("::") + if not (REPO / test_file).is_file() or function not in given_tests(test_file): + wrong.append(f"{name}: {target}") + assert not wrong, f"not a @given test: {wrong}" + + +def test_every_hypothesis_test_is_claimed_by_a_surface(): + claimed = {target for entry in SURFACES.values() for target in entry.get("targets", [])} + orphans = [f"{test_file}::{function}" for test_file in fuzz_files() + for function in sorted(given_tests(test_file)) + if f"{test_file}::{function}" not in claimed] + assert not orphans, f"fuzz tests no surface claims: {orphans}. List each under " \ + "the module it fuzzes in tests/fuzz_surfaces.json." + + +def test_every_fuzz_file_runs_in_the_soak_job(): + """The nightly soak is the only place the deep budgets run. It runs the + whole suite; should it ever name files instead, a new fuzz module would + be left at the quick budget forever, so every one must then be named.""" + workflow = (REPO / ".github" / "workflows" / "fuzz.yml").read_text(encoding="utf-8") + assert "schedule:" in workflow, "the soak must run on a schedule" + soak = [line for line in workflow.splitlines() if re.search(r"pytest .*--fuzz", line)] + assert len(soak) == 1, "expected exactly one `pytest ... --fuzz` line in fuzz.yml" + if "tests/" not in soak[0]: + return + missing = [test_file for test_file in fuzz_files() if test_file not in soak[0]] + assert not missing, f"not in the soak job's pytest line: {missing}"