diff --git a/.evergreen/config.yml b/.evergreen/config.yml index 791dd332f0..8e219617c6 100644 --- a/.evergreen/config.yml +++ b/.evergreen/config.yml @@ -42,6 +42,7 @@ post: - func: "upload coverage" - func: "upload mo artifacts" - func: "upload test results" + - func: "upload fuzz artifacts" - func: "cleanup" tasks: diff --git a/.evergreen/generated_configs/functions.yml b/.evergreen/generated_configs/functions.yml index f27d11892b..eaa6a84ffb 100644 --- a/.evergreen/generated_configs/functions.yml +++ b/.evergreen/generated_configs/functions.yml @@ -301,6 +301,32 @@ functions: optional: "true" type: setup + # Upload fuzz artifacts + upload fuzz artifacts: + - command: ec2.assume_role + params: + role_arn: ${assume_role_arn} + type: setup + - command: archive.targz_pack + params: + target: fuzz-native-artifacts.tgz + source_dir: ./ + include: + - ./src/fuzz-scratch/** + - command: s3.put + params: + remote_file: ${build_variant}/${revision}/${version_id}/${build_id}/fuzz/${task_id}-${execution}-fuzz-native-artifacts.tar.gz + aws_key: ${AWS_ACCESS_KEY_ID} + aws_secret: ${AWS_SECRET_ACCESS_KEY} + aws_session_token: ${AWS_SESSION_TOKEN} + bucket: ${bucket_name} + local_file: fuzz-native-artifacts.tgz + permissions: public-read + content_type: ${content_type|application/x-gzip} + display_name: Fuzz Artifacts - Execution + optional: "true" + type: setup + # Upload mo artifacts upload mo artifacts: - command: ec2.assume_role diff --git a/.evergreen/generated_configs/tasks.yml b/.evergreen/generated_configs/tasks.yml index 00ac5416da..afa7dbf29f 100644 --- a/.evergreen/generated_configs/tasks.yml +++ b/.evergreen/generated_configs/tasks.yml @@ -208,27 +208,105 @@ tasks: # Fuzz tests - name: fuzz-regression commands: - - func: run tests - vars: - TEST_NAME: fuzz - SUB_TEST_NAME: regression - UV_PYTHON: "3.13" + - command: subprocess.exec + params: + binary: bash + args: + - .evergreen/scripts/install-dependencies.sh + working_dir: src + type: test + - command: subprocess.exec + params: + binary: uv + args: + - run + - --extra + - test + - python + - -m + - pytest + - test/test_fuzz_shared.py + - -m + - default + working_dir: src + type: test + - command: subprocess.exec + params: + binary: bash + args: + - fuzz/build_native.sh + working_dir: src + type: test + - command: subprocess.exec + params: + binary: bash + args: + - fuzz/run_native.sh + working_dir: src + env: + FUZZ_MAX_TIME: "0" + type: test tags: [fuzz, fuzz-regression, pr] - - name: fuzz + - name: fuzz-python-full commands: - func: run tests vars: TEST_NAME: fuzz SUB_TEST_NAME: fuzz UV_PYTHON: "3.13" - tags: [fuzz, fuzz-nightly] - - name: fuzz-capture + tags: [fuzz, fuzz-python] + - name: fuzz-native-full commands: - - func: run tests - vars: - TEST_NAME: fuzz - SUB_TEST_NAME: fuzz - UV_PYTHON: "3.13" + - command: subprocess.exec + params: + binary: bash + args: + - .evergreen/scripts/install-dependencies.sh + working_dir: src + type: test + - command: subprocess.exec + params: + binary: bash + args: + - fuzz/build_native.sh + working_dir: src + type: test + - command: subprocess.exec + params: + binary: bash + args: + - fuzz/run_native.sh + working_dir: src + include_expansions_in_env: + - FUZZ_MAX_TIME + type: test + tags: [fuzz, fuzz-native] + - name: fuzz-corpus-capture + commands: + - command: subprocess.exec + params: + binary: bash + args: + - .evergreen/scripts/install-dependencies.sh + working_dir: src + type: test + - command: subprocess.exec + params: + binary: bash + args: + - fuzz/build_native.sh + working_dir: src + type: test + - command: subprocess.exec + params: + binary: bash + args: + - fuzz/run_native.sh + - fuzz-scratch/corpus + working_dir: src + include_expansions_in_env: + - FUZZ_MAX_TIME + type: test - command: subprocess.exec params: binary: bash @@ -242,7 +320,7 @@ tasks: - AWS_SECRET_ACCESS_KEY - AWS_SESSION_TOKEN type: test - tags: [fuzz, fuzz-weekly] + tags: [fuzz, fuzz-corpus-capture] # Getdata tests - name: getdata diff --git a/.evergreen/generated_configs/variants.yml b/.evergreen/generated_configs/variants.yml index f624b89e6e..f14c4ab0d0 100644 --- a/.evergreen/generated_configs/variants.yml +++ b/.evergreen/generated_configs/variants.yml @@ -201,27 +201,17 @@ buildvariants: AUTH: auth # Fuzz tests - - name: fuzz-regression-rhel8 + - name: fuzzing-rhel8 tasks: - - name: .fuzz-regression - display_name: Fuzz Regression RHEL8 + - name: fuzz-regression + - name: fuzz-python-full + - name: fuzz-native-full + - name: fuzz-corpus-capture + batchtime: 10080 + display_name: Fuzzing RHEL8 run_on: - - rhel8.10-small - tags: [pr] - - name: fuzz-rhel8 - tasks: - - name: .fuzz-nightly - display_name: Fuzz RHEL8 - run_on: - - rhel8.10-small + - rhel8.7-large batchtime: 1440 - - name: fuzz-capture-rhel8 - tasks: - - name: .fuzz-weekly - display_name: Fuzz Capture RHEL8 - run_on: - - rhel8.10-small - batchtime: 10080 # Green framework tests - name: green-gevent-rhel8 diff --git a/.evergreen/scripts/capture-fuzz-corpus.sh b/.evergreen/scripts/capture-fuzz-corpus.sh index ad829e0c48..1e4b33692f 100755 --- a/.evergreen/scripts/capture-fuzz-corpus.sh +++ b/.evergreen/scripts/capture-fuzz-corpus.sh @@ -1,27 +1,32 @@ #!/bin/bash # PYTHON-6178: capture coverage-increasing inputs from a fuzz run and open # an automated PR growing fuzz/corpus/. Runs as the last command of the -# weekly "fuzz-capture" task, while the scratch corpus exists; manual -# `evergreen patch --variant fuzz-capture-rhel8 --task fuzz-capture` runs -# capture too. +# weekly fuzz-corpus-capture task, whose fuzzing run is native +# (PYTHON-6169). Manual `evergreen patch --variant fuzzing-capture-rhel8 +# --task fuzz-corpus-capture` runs capture too. set -eu -# Same environment as just.sh: venv on PATH for a modern Python. -. "$(dirname "${BASH_SOURCE:-$0}")/setup-dev-env.sh" - # No new units means no PR, and the github secrets flow is never touched. -uv run --no-sync python fuzz/capture_corpus.py +# The venv python directly: `uv run` re-syncs, which would clobber the +# instrumented extensions the replay validates against. capture_corpus.py +# is stdlib-only, so the venv needs nothing extra. +.venv/bin/python fuzz/capture_corpus.py if [ -z "$(ls -A fuzz-scratch/capture 2>/dev/null || true)" ]; then echo "No new fuzz corpus units; nothing to do." exit 0 fi -# The replay runs the atheris targets, so it must request the fuzz group. +# Replay the captured units natively: each unit as a file argument, so +# libFuzzer runs each exactly once under ASan. Same environment as +# run_native.sh. +ATHERIS_RUNTIME=$(.venv/bin/python -c 'import atheris; print(atheris.path())')/asan_with_fuzzer.so replay=(fuzz-scratch/capture/*) for target in fuzz_decode fuzz_decode_all fuzz_is_valid; do echo "Replaying captured units against ${target}..." - if ! uv run --group fuzz python "fuzz/${target}.py" "${replay[@]}" \ - -artifact_prefix="$PWD/fuzz-scratch/" -atheris_runs="${#replay[@]}" + if ! FUZZ_NATIVE=1 PYTHONMALLOC=malloc ASAN_OPTIONS="detect_leaks=0" \ + LD_PRELOAD="$ATHERIS_RUNTIME" \ + .venv/bin/python "fuzz/${target}.py" "${replay[@]}" \ + -artifact_prefix="$PWD/fuzz-scratch/" then echo "Captured unit fails ${target}; no corpus PR." >&2 exit 1 diff --git a/.evergreen/scripts/generate_config.py b/.evergreen/scripts/generate_config.py index 061f9bc0a6..27116bbad1 100644 --- a/.evergreen/scripts/generate_config.py +++ b/.evergreen/scripts/generate_config.py @@ -389,26 +389,26 @@ def create_doctests_variants(): def create_fuzz_variants(): - # Three variants for the three fuzz flows: the regression reproducers run - # on every PR, the time-boxed fuzzing for crash discovery runs nightly, - # and the weekly variant also captures the corpus (opens the automated - # [Fuzz Corpus] PR). The non-pr variants carry no "pr" tag, so PR patch - # builds never select them, while their default patchability keeps them - # manually runnable (`evergreen patch --variant fuzz-rhel8 --task fuzz`). - # The host needs CPython, which the rhel8 toolchain provides. + # One variant hosts all the fuzz flows (PYTHON-6169). A task's "pr" + # tag keeps it out of mainline builds and selects it into PR patch + # builds. The capture ref carries its own weekly batchtime, which + # overrides the variant's daily one (the kms tasks do the same). The + # host needs CPython, which the rhel8 toolchain provides. The large + # rhel8.7 distro matches the other drivers' fuzz jobs and fits + # libFuzzer's growing corpus. host = HOSTS["rhel8"] return [ create_variant( - [".fuzz-regression"], get_variant_name("Fuzz Regression", host), host=host, tags=["pr"] - ), - create_variant( - [".fuzz-nightly"], get_variant_name("Fuzz", host), host=host, batchtime=BATCHTIME_DAY - ), - create_variant( - [".fuzz-weekly"], - get_variant_name("Fuzz Capture", host), + [ + "fuzz-regression", + "fuzz-python-full", + "fuzz-native-full", + EvgTaskRef(name="fuzz-corpus-capture", batchtime=BATCHTIME_WEEK), + ], + get_variant_name("Fuzzing", host), host=host, - batchtime=BATCHTIME_WEEK, + run_on="rhel8.7-large", + batchtime=BATCHTIME_DAY, ), ] @@ -723,28 +723,67 @@ def create_no_orchestration_tasks(): def create_fuzz_tasks(): - # Deterministic regression test over the committed known-bug reproducers. - tags = ["fuzz", "fuzz-regression", "pr"] - test_vars = dict(TEST_NAME="fuzz", SUB_TEST_NAME="regression", UV_PYTHON="3.13") - test_func = FunctionCall(func="run tests", vars=test_vars) - tasks = [EvgTask(name="fuzz-regression", tags=tags, commands=[test_func])] + # The PR regression gate covers both oracles (PYTHON-6169): the + # python-side helper suite replays the reproducers through both bson + # implementations on the regular build, and the native replay runs the + # whole corpus under ASan. The pytest step runs before the instrumented + # build so the regular venv is still in place. + build_cmd = get_subprocess_exec(args=["fuzz/build_native.sh"]) + install_cmd = get_subprocess_exec(args=[".evergreen/scripts/install-dependencies.sh"]) + tasks = [ + EvgTask( + name="fuzz-regression", + tags=["fuzz", "fuzz-regression", "pr"], + commands=[ + install_cmd, + get_subprocess_exec( + binary="uv", + args=[ + "run", + "--extra", + "test", + "python", + "-m", + "pytest", + "test/test_fuzz_shared.py", + "-m", + "default", + ], + ), + build_cmd, + get_subprocess_exec(args=["fuzz/run_native.sh"], env=dict(FUZZ_MAX_TIME="0")), + ], + ) + ] - # Time-boxed fuzzing against the generated seed corpus, for crash - # discovery; corpus capture moved to the weekly fuzz-capture task. - tags = ["fuzz", "fuzz-nightly"] + # Time-boxed atheris fuzzing on mainline, for crash discovery. + tags = ["fuzz", "fuzz-python"] test_vars = dict(TEST_NAME="fuzz", SUB_TEST_NAME="fuzz", UV_PYTHON="3.13") test_func = FunctionCall(func="run tests", vars=test_vars) - tasks.append(EvgTask(name="fuzz", tags=tags, commands=[test_func])) + tasks.append(EvgTask(name="fuzz-python-full", tags=tags, commands=[test_func])) + + # Time-boxed native fuzzing (PYTHON-6169). Plain subprocess.exec: the + # "run tests" function would reinstall pymongo without sanitizer flags + # and clobber the instrumented build. + tasks.append( + EvgTask( + name="fuzz-native-full", + tags=["fuzz", "fuzz-native"], + commands=[ + install_cmd, + build_cmd, + get_subprocess_exec( + args=["fuzz/run_native.sh"], include_expansions_in_env=["FUZZ_MAX_TIME"] + ), + ], + ) + ) - # The weekly capture task fuzzes too (the capture reads the task-local - # fuzz-scratch/ corpus, so it must stay attached to a fuzzing run). - tags = ["fuzz", "fuzz-weekly"] - test_vars = dict(TEST_NAME="fuzz", SUB_TEST_NAME="fuzz", UV_PYTHON="3.13") - test_func = FunctionCall(func="run tests", vars=test_vars) - # PYTHON-6178: while the scratch corpus still exists, capture the new - # coverage-increasing inputs, replay them through every target so a - # unit that fails one is never published, and open an automated PR - # growing fuzz/corpus/. + # The capture fuzzes natively (PYTHON-6169): the instrumented build + # discovers C-extension coverage, and captured units are + # ASan-validated before publication. The run targets + # fuzz-scratch/corpus, where capture_corpus.py harvests (PYTHON-6178). + tags = ["fuzz", "fuzz-corpus-capture"] capture_cmd = get_subprocess_exec( args=[".evergreen/scripts/capture-fuzz-corpus.sh"], include_expansions_in_env=[ @@ -758,7 +797,21 @@ def create_fuzz_tasks(): "AWS_SESSION_TOKEN", ], ) - tasks.append(EvgTask(name="fuzz-capture", tags=tags, commands=[test_func, capture_cmd])) + tasks.append( + EvgTask( + name="fuzz-corpus-capture", + tags=tags, + commands=[ + install_cmd, + build_cmd, + get_subprocess_exec( + args=["fuzz/run_native.sh", "fuzz-scratch/corpus"], + include_expansions_in_env=["FUZZ_MAX_TIME"], + ), + capture_cmd, + ], + ) + ) return tasks @@ -1181,6 +1234,26 @@ def create_upload_mo_artifacts_func(): return "upload mo artifacts", cmds +def create_upload_fuzz_artifacts_func(): + # Retain libFuzzer crash-* reproducers (PYTHON-6169): they land in + # src/fuzz-scratch/ and no other post-task upload collects them. Outside + # fuzz tasks the include matches nothing, so optional keeps the upload + # a no-op. + archive_cmd = archive_targz_pack( + target="fuzz-native-artifacts.tgz", source_dir="./", include=["./src/fuzz-scratch/**"] + ) + display_name = "Fuzz Artifacts - Execution" + remote_file = ( + "${build_variant}/${revision}/${version_id}/${build_id}/fuzz/" + "${task_id}-${execution}-fuzz-native-artifacts.tar.gz" + ) + s3_artifacts = get_s3_put( + local_file="fuzz-native-artifacts.tgz", remote_file=remote_file, display_name=display_name + ) + cmds = [get_assume_role(), archive_cmd, s3_artifacts] + return "upload fuzz artifacts", cmds + + def create_fetch_source_func(): # Executes clone and applies the submitted patch, if any. cmd = git_get_project(directory="src") diff --git a/.evergreen/scripts/run_tests.py b/.evergreen/scripts/run_tests.py index 8f9802ffcb..9106b40924 100644 --- a/.evergreen/scripts/run_tests.py +++ b/.evergreen/scripts/run_tests.py @@ -149,33 +149,6 @@ def handle_fuzz() -> None: """Run the BSON fuzz targets (PYTHON-4232). Not pytest-based.""" targets = ["fuzz_decode", "fuzz_decode_all", "fuzz_is_valid"] - if SUB_TEST_NAME == "regression": - # Run the committed reproducers plus the seed corpus. - # Skip dotfiles (pathlib globbing matches them). - inputs = sorted( - str(p) for p in (ROOT / "fuzz" / "regression").glob("*") if not p.name.startswith(".") - ) - if not inputs: - raise RuntimeError("No fuzz regression inputs found in fuzz/regression/") - corpus_dir = os.environ.get("FUZZ_CORPUS_DIR", str(ROOT / "fuzz-scratch" / "corpus")) - # Fail fast on a missing or empty corpus; libFuzzer would silently skip it. - corpus_files = sorted( - str(p) for p in Path(corpus_dir).glob("*") if not p.name.startswith(".") - ) - if not corpus_files: - raise RuntimeError( - f"No fuzz seed corpus found in {corpus_dir}; was setup_tests.py run?" - ) - inputs.extend(corpus_files) - # Each input runs once: -atheris_runs equals the file count, so - # atheris exits cleanly after the last one. - runs = len(inputs) - for target in targets: - run_command( - f"{sys.executable} fuzz/{target}.py {' '.join(inputs)} -atheris_runs={runs}" - ) - return - # Time-boxed fuzzing against the generated seed corpus. corpus_dir = os.environ.get("FUZZ_CORPUS_DIR", str(ROOT / "fuzz-scratch" / "corpus")) # Fail fast: libFuzzer would burn the whole budget without the seeds. diff --git a/.evergreen/scripts/setup_tests.py b/.evergreen/scripts/setup_tests.py index cb0fb59c1e..9771e5d5a5 100644 --- a/.evergreen/scripts/setup_tests.py +++ b/.evergreen/scripts/setup_tests.py @@ -598,18 +598,15 @@ def handle_test_env() -> None: with zipfile.ZipFile(zip_path) as zf: zf.extractall(corpus_dir) zip_path.unlink() - if sub_test_name == "fuzz": - # PYTHON-6178 Also seed from the committed corpus of previously - # captured inputs, so the nightly and weekly runs build on prior - # discoveries instead of the spec seeds alone. Regression runs - # (PRs) keep running only the reproducers and the spec seed - # corpus. - committed_dir = ROOT / "fuzz" / "corpus" - if committed_dir.is_dir(): - for path in sorted(committed_dir.iterdir()): - if path.name.startswith("."): - continue - shutil.copyfile(path, corpus_dir / path.name) + # PYTHON-6178 Also seed from the committed corpus of previously + # captured inputs, so the run builds on prior discoveries instead + # of the spec seeds alone. + committed_dir = ROOT / "fuzz" / "corpus" + if committed_dir.is_dir(): + for path in sorted(committed_dir.iterdir()): + if path.name.startswith("."): + continue + shutil.copyfile(path, corpus_dir / path.name) # Manifest of every input this run starts from; capture_corpus.py # treats these digests as already-known, so only units the fuzzer # discovered during the run get captured. diff --git a/.evergreen/scripts/test_generate_config.py b/.evergreen/scripts/test_generate_config.py index 602e84e3e5..679d0b498c 100644 --- a/.evergreen/scripts/test_generate_config.py +++ b/.evergreen/scripts/test_generate_config.py @@ -1,7 +1,5 @@ """Sanity checks for the Evergreen config generation. -Also regression tests for the .evergreen script fixes in PYTHON-6167. - Run: pytest .evergreen/scripts/test_generate_config.py -m "" (-m "" clears the repo-wide marker filter.) Requires the generate-config hook's dependencies: pytest, pytest-asyncio, shrub.py, pyyaml. @@ -105,12 +103,7 @@ def test_generation_sanity(): def test_variants_select_tasks(): - """Check every variant selects at least one task. - - Every suite-family task is selected by at least one variant: a family - restructured without variant wiring would silently never run - (PYTHON-6167). - """ + """Check every variant selects at least one task.""" tasks = all_tasks() for variant in all_variants(): assert any(variant_selects(variant, task) for task in tasks), ( @@ -124,11 +117,7 @@ def test_variants_select_tasks(): def test_suite_families(): - """Check each per-suite family identifies its suite. - - The name and TEST_NAME identify the suite, and no family task mixes - min-deps with coverage (PYTHON-6167). - """ + """Check each per-suite family identifies its suite.""" for family, suite in SUITE_FAMILIES.items(): for task in [t for t in all_tasks() if family in (t.tags or [])]: where = f"{family} {task.name}" @@ -141,12 +130,7 @@ def test_suite_families(): def test_pr_tasks_pin_max_version(): - """Task-level pins: pr tasks pin MAX_VERSION. - - The "latest" nightly is unstable; the explicit 4.4 min-deps pin is the - exception. Variant-merged pins are checked by - test_pr_tasks_effectively_pin_max_version. - """ + """Task-level pins: pr tasks pin MAX_VERSION, except the 4.4 min-deps pin.""" offenders = [ (task.name, task_vars(task).get("VERSION")) for task in pr_tasks() @@ -159,11 +143,7 @@ def test_pr_tasks_pin_max_version(): def test_suite_families_have_pr_pins(): - """Run every suite family at least once on PR patches, with coverage. - - A restructure cannot then silently drop a family from the patch build - or the codecov report (PYTHON-6167). - """ + """Run every suite family at least once on PR patches, with coverage.""" for family in SUITE_FAMILIES: pinned = [ task @@ -176,12 +156,7 @@ def test_suite_families_have_pr_pins(): def test_pr_tasks_effectively_pin_max_version(): - """Effective pins: every pr task that runs a server resolves to MAX_VERSION. - - A pr task without its own VERSION var inherits the selecting variant's - version once variant expansions merge in. The explicit 4.4 min-deps - pin is the exception. - """ + """Effective pins: pr server tasks resolve to MAX_VERSION, except the 4.4 pin.""" tasks = [task for task in all_tasks() if "pr" in (task.tags or [])] offenders = [] for variant in all_variants(): @@ -202,15 +177,7 @@ def test_pr_tasks_effectively_pin_max_version(): def test_server_version_pr_tasks_selected_once(): - """A pr server-version task must be selected only by its matching variant. - - The variant must run the server version the task pins. The expected - family comes from create_server_version_variants(), not from the - selections: a variant missing its PR selector would otherwise drop - from both sides and the comparison would pass. Variants outside the - family must not select these tasks (the sanitizer variant pins - MAX_VERSION for its own mongod). - """ + """A pr server-version task must be selected only by its matching variant.""" sv_tasks = [task for task in pr_tasks() if "server-version" in (task.tags or [])] sv_variants = generate_config.create_server_version_variants() offenders = {} @@ -230,11 +197,7 @@ def test_server_version_pr_tasks_selected_once(): def test_pr_tasks_cover_version_boundaries(): - """PRs test the server version boundaries. - - The newest numbered server runs with every Python boundary, the min - server with its min-Python floor. - """ + """PRs test the server version boundaries.""" for version, pythons in ( ( generate_config_utils.MAX_VERSION, @@ -255,11 +218,7 @@ def test_pr_tasks_cover_version_boundaries(): def test_amazon2023_no_toolchain_variant_runs_on_prs(): - """Keep the no-toolchain variant on PR patches. - - The Amazon Linux host has no Python toolchain, so its no-toolchain - variant must keep running on PR patches (PYTHON-6167). - """ + """Keep the no-toolchain variant on PR patches.""" (variant,) = [v for v in all_variants() if "amazon2023" in v.name] assert "pr" in (variant.tags or []) selected = [task for task in all_tasks() if variant_selects(variant, task)] @@ -268,10 +227,7 @@ def test_amazon2023_no_toolchain_variant_runs_on_prs(): def test_server_version_rotated_tasks_keep_coverage(): - """Per-commit coverage for this family rides the rotated boundary-Python tasks. - - Not the pr tasks, which run only on MAX_VERSION. - """ + """Per-commit coverage for this family rides the rotated boundary-Python tasks.""" family = [task for task in all_tasks() if "server-version" in (task.tags or [])] cov = [task for task in family if task_vars(task).get("COVERAGE") == "1"] assert any("pr" not in (task.tags or []) for task in cov), ( @@ -294,11 +250,7 @@ def test_server_version_rotated_tasks_keep_coverage(): def test_numpy_win32_tasks_run_on_windows_only(): - """Keep the win32 numpy tasks on the windows variant. - - They use the 32-bit toolchain (IS_WIN32) and must be selected only by - the windows variant (PYTHON-6167). - """ + """Keep the win32 numpy tasks on the windows variant.""" win32_tasks = [task for task in all_tasks() if "test-numpy-win32" in (task.tags or [])] assert win32_tasks, "no win32 numpy tasks" for task in win32_tasks: @@ -317,11 +269,7 @@ def test_numpy_win32_tasks_run_on_windows_only(): def test_run_tests_env_carries_crypt_shared(): - """Check the run tests setup env carries TEST_CRYPT_SHARED. - - setup_tests.py reads it to wire the crypt_shared lib directory - (PYTHON-6167). - """ + """Check the run tests setup env carries TEST_CRYPT_SHARED.""" _, cmds = generate_config.create_run_tests_func() setup_cmd = cmds[0] includes = setup_cmd.params["include_expansions_in_env"] @@ -339,11 +287,7 @@ def test_pr_min_deps_tasks_also_run_coverage(): def test_standard_family_pr_budget(): - """Patch-build PR budget for test-standard pr tasks. - - At most 5 (the pre-pin baseline), at most 3 on Python 3.14+ (the - ubuntu22 compression filter). - """ + """Patch-build PR budget for test-standard pr tasks: at most 5, at most 3 on 3.14+.""" tasks = [task for task in pr_tasks() if "test-standard" in (task.tags or [])] assert len(tasks) <= 5, f"too many test-standard PR tasks: {[t.name for t in tasks]}" newer = [ @@ -358,12 +302,7 @@ def test_standard_family_pr_budget(): def test_pr_tasks_run_coverage(): - """Pr tasks that pin a server version run with COVERAGE=1. - - No-cov companions, infrastructure tasks (no VERSION), and the - encryption tasks (their suites exceed the coverage timeout on - macOS/Win64, PYTHON-6167) are exempt. - """ + """Pr tasks that pin a server version run with COVERAGE=1.""" offenders = [ task.name for task in pr_tasks() @@ -376,11 +315,7 @@ def test_pr_tasks_run_coverage(): def test_rotated_tasks_keep_nightly_coverage(): - """Batch coverage rides the rotation independently of the pr tasks. - - Rotated "latest" tasks and max-Python auth-aws tasks keep COVERAGE=1 - (min-deps excepted). - """ + """Batch coverage rides the rotation independently of the pr tasks.""" offenders = [] for task in all_tasks(): tags = task.tags or [] @@ -426,11 +361,7 @@ def test_rotated_tasks_keep_nightly_coverage(): def test_non_standard_cov_tasks_have_no_cov_companions(): - """Each non-standard coverage task also emits a no-cov companion. - - The macOS/Win64 encryption variants (which filter .cov) have a task to - activate in patch builds. - """ + """Each non-standard coverage task also emits a no-cov companion.""" no_cov = {task.name for task in all_tasks() if "test-non-standard-no-cov" in (task.tags or [])} for task in all_tasks(): if "test-non-standard-no-cov" in (task.tags or []): @@ -443,52 +374,95 @@ def test_non_standard_cov_tasks_have_no_cov_companions(): def test_fuzz_task_wiring(): """Test the fuzz task wiring. - Three fuzz flows: the pr-tagged regression variant runs the reproducers - on every PR; the nightly variant fuzzes for crash discovery; the weekly - variant also captures the corpus. The non-pr variants carry no "pr" tag, - so PR patch builds never select them, while their default patchability - keeps them manually runnable - (`evergreen patch --variant fuzz-rhel8 --task fuzz`). + Four flows in one Fuzzing variant. A task's "pr" tag keeps it out of + mainline builds and selects it into PR patch builds, so the regression + task gates PRs and the full flows run only on mainline. """ - tasks = [task for task in all_tasks() if "fuzz" in (task.tags or [])] - assert [task.name for task in tasks if "pr" in (task.tags or [])] == ["fuzz-regression"] - assert [task.name for task in tasks if "pr" not in (task.tags or [])] == [ - "fuzz", - "fuzz-capture", + tasks = {task.name: task for task in all_tasks() if "fuzz" in (task.tags or [])} + assert sorted(tasks) == [ + "fuzz-corpus-capture", + "fuzz-native-full", + "fuzz-python-full", + "fuzz-regression", + ] + assert sorted(task.name for task in tasks.values() if "pr" in (task.tags or [])) == [ + "fuzz-regression", ] variants = generate_config.create_fuzz_variants() - assert len(variants) == 3 - regression, nightly, capture_variant = variants - assert variant_selects(regression, tasks[0]) - assert "pr" in (regression.tags or []) - assert variant_selects(nightly, tasks[1]) - assert nightly.batchtime == generate_config_utils.BATCHTIME_DAY - assert variant_selects(capture_variant, tasks[2]) - assert capture_variant.batchtime == generate_config_utils.BATCHTIME_WEEK - # Webhook PR patch builds only select pr-tagged variants. - assert not nightly.tags - assert not capture_variant.tags - # The nightly fuzz task is crash discovery only: its last command is - # the "run tests" FunctionCall, with no capture command. - assert tasks[1].commands[-1].func == "run tests" + assert len(variants) == 1 + fuzzing = variants[0] + assert not fuzzing.tags + assert fuzzing.batchtime == generate_config_utils.BATCHTIME_DAY + # All four flows share the variant, with the capture ref's weekly + # batchtime overriding the variant's daily one. + assert [ref.name for ref in fuzzing.tasks] == [ + "fuzz-regression", + "fuzz-python-full", + "fuzz-native-full", + "fuzz-corpus-capture", + ] + capture_ref = fuzzing.tasks[-1] + assert capture_ref.batchtime == generate_config_utils.BATCHTIME_WEEK + for name, task in tasks.items(): + assert variant_selects(fuzzing, task), name + assert fuzzing.run_on == ["rhel8.7-large"] + # The python flow goes through the "run tests" function: time-boxed + # discovery on mainline. + assert tasks["fuzz-python-full"].commands[-1].func == "run tests" + # The regression task covers both oracles: the python-side helper suite + # on the regular build, then the whole corpus replayed under ASan. + regression = tasks["fuzz-regression"].commands + assert regression[0].params["args"] == [".evergreen/scripts/install-dependencies.sh"] + assert regression[1].params["binary"] == "uv" + assert regression[1].params["args"] == [ + "run", + "--extra", + "test", + "python", + "-m", + "pytest", + "test/test_fuzz_shared.py", + "-m", + "default", + ] + assert regression[2].params["args"] == ["fuzz/build_native.sh"] + regression_run = regression[3] + assert regression_run.params["args"] == ["fuzz/run_native.sh"] + assert regression_run.params["env"] == {"FUZZ_MAX_TIME": "0"} + # Script commands run bash from the src dir. + for cmd in (regression[0], regression[2], regression_run): + assert cmd.params["binary"] == "bash" + assert cmd.params["working_dir"] == "src" + # The native full flow reads the FUZZ_MAX_TIME expansion so a configured + # budget reaches it. + native_full = tasks["fuzz-native-full"].commands + assert native_full[0].params["args"] == [".evergreen/scripts/install-dependencies.sh"] + assert native_full[1].params["args"] == ["fuzz/build_native.sh"] + native_full_run = native_full[2] + assert native_full_run.params["args"] == ["fuzz/run_native.sh"] + assert "FUZZ_MAX_TIME" in native_full_run.params["include_expansions_in_env"] + assert "env" not in native_full_run.params # The capture subprocess bootstraps the comment-bot github app, whose # secrets live in AWS Secrets Manager: it needs the assumed-role # credentials (as resync_specs and backport-pr also pass them). - capture = tasks[2].commands[-1] + capture = tasks["fuzz-corpus-capture"].commands[-1] env_vars = capture.params["include_expansions_in_env"] for var in ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN"): assert var in env_vars, f"capture subprocess missing {var}" # The capture no longer keys off is_patch: manual patch runs must # capture too, and the weekly variant never runs in a PR build. assert "is_patch" not in env_vars + # The capture fuzzes natively into the corpus capture_corpus.py harvests. + capture_commands = tasks["fuzz-corpus-capture"].commands + assert capture_commands[0].params["args"] == [".evergreen/scripts/install-dependencies.sh"] + assert capture_commands[1].params["args"] == ["fuzz/build_native.sh"] + assert capture_commands[2].params["args"] == ["fuzz/run_native.sh", "fuzz-scratch/corpus"] + assert "FUZZ_MAX_TIME" in capture_commands[2].params["include_expansions_in_env"] + assert capture_commands[3] is capture def test_load_balancer_marker_selection(monkeypatch): - """The load balancer tasks select the load_balancer marker explicitly. - - pytest_conf.py only grants the implicit default markers to unmarked - tests (PYTHON-6167). - """ + """The load balancer tasks select the load_balancer marker explicitly.""" import run_tests monkeypatch.setattr(run_tests, "TEST_NAME", "load_balancer") @@ -502,11 +476,7 @@ def test_load_balancer_marker_selection(monkeypatch): def test_ensure_openssl3_escapes_persisted_values(monkeypatch, tmp_path): - """Reject DRIVERS_TOOLS paths carrying command substitution. - - A hostile path must not execute at write time or when the persisted - env.sh is sourced (PYTHON-6167). - """ + """Reject DRIVERS_TOOLS paths carrying command substitution.""" import subprocess import setup_tests @@ -535,11 +505,11 @@ def test_ensure_openssl3_escapes_persisted_values(monkeypatch, tmp_path): setup_tests.ensure_openssl3() - # The payload must not have executed at write time... + # The payload must not have executed at write time. assert not (Path.cwd() / "pwned.txt").exists() assert not (tmp_path / "pwned.txt").exists() - # ...nor when the persisted environment is sourced: the values round-trip - # literally. + # The exported values must round-trip literally through the persisted + # environment file. env = subprocess.run( # noqa: S603 ["/bin/bash", "-c", '. "$1" >/dev/null && env', "bash", str(env_file)], capture_output=True, @@ -553,11 +523,7 @@ def test_ensure_openssl3_escapes_persisted_values(monkeypatch, tmp_path): def test_crypt_shared_persisted_to_env(monkeypatch, tmp_path): - """Check the crypt_shared setup persists TEST_CRYPT_SHARED. - - The encryption tests use it to decide whether to run their crypt_shared - cases (PYTHON-6167). - """ + """Check the crypt_shared setup persists TEST_CRYPT_SHARED.""" import setup_tests import utils @@ -587,11 +553,7 @@ def test_crypt_shared_persisted_to_env(monkeypatch, tmp_path): def test_write_env_escapes_backslashes(monkeypatch, tmp_path): - """Check write_env escapes backslashes first. - - Substitution payloads and trailing backslashes must round-trip - literally when the file is sourced (PYTHON-6167). - """ + """Check write_env escapes backslashes first.""" import subprocess import utils @@ -624,11 +586,7 @@ def test_write_env_escapes_backslashes(monkeypatch, tmp_path): def test_read_env_unescapes_double_quoted_escapes(monkeypatch, tmp_path): - """Check read_env yields the value bash sourcing would. - - Double-quoted escapes unescape, single-quoted values stay literal - (PYTHON-6167). - """ + """Check read_env yields the value bash sourcing would.""" import subprocess import utils @@ -663,11 +621,7 @@ def test_read_env_unescapes_double_quoted_escapes(monkeypatch, tmp_path): def test_write_env_escapes_embedded_quotes(monkeypatch, tmp_path): - """Check write_env escapes embedded double quotes. - - Dropping them would lose data: a value read with read_env must - round-trip when persisted (PYTHON-6167). - """ + """Check write_env escapes embedded double quotes.""" import subprocess import utils @@ -700,10 +654,7 @@ def test_write_env_escapes_embedded_quotes(monkeypatch, tmp_path): def test_crypt_shared_escapes_backslashes(monkeypatch, tmp_path): - """Check the crypt_shared lib path persists literally. - - The trailing LD_LIBRARY_PATH expansion stays live (PYTHON-6167). - """ + """Check the crypt_shared lib path persists literally.""" import subprocess import setup_tests @@ -715,8 +666,8 @@ def test_crypt_shared_escapes_backslashes(monkeypatch, tmp_path): env_file = tmp_path / "test-env.sh" monkeypatch.setattr(utils, "ENV_FILE", env_file) monkeypatch.setattr(setup_tests, "ENV_FILE", env_file) - # The secrets service writes the path bash-escaped; read_env sees the - # literal, so persist its escaping. + # The secrets service writes the path bash-escaped, so persist its + # escaping for read_env to see the literal. escaped_payload = "\\$(touch cs-pwned.txt)" literal_payload = "$(touch cs-pwned.txt)" drivers_tools = tmp_path / "drivers-tools" @@ -767,12 +718,7 @@ def test_sync_option_env_override(monkeypatch): def test_sanitizer_task_wiring(): - """PYTHON-6048: one pr-tagged sanitizer task, selected by exactly one variant. - - The variant pins MAX_VERSION and runs on a large host for ASan's - memory headroom. VERSION stays off the task so it is exempt from the - pr COVERAGE rule (coverage under ASan is not useful). - """ + """One pr-tagged sanitizer task, selected by exactly one variant (PYTHON-6048).""" tasks = [task for task in all_tasks() if "sanitizer" in (task.tags or [])] assert len(tasks) == 1 task = tasks[0] @@ -789,3 +735,27 @@ def test_sanitizer_task_wiring(): assert len(variants) == 1 assert variants[0].run_on == ["rhel8.10-large"] assert (variants[0].expansions or {}).get("VERSION") == generate_config_utils.MAX_VERSION + + +def test_upload_fuzz_artifacts_func(): + """The fuzz artifacts upload archives crash reproducers and is optional.""" + name, cmds = generate_config.create_upload_fuzz_artifacts_func() + assert name == "upload fuzz artifacts" + archive = [cmd for cmd in cmds if cmd.command == "archive.targz_pack"] + assert len(archive) == 1 + assert archive[0].params["include"] == ["./src/fuzz-scratch/**"] + puts = [cmd for cmd in cmds if cmd.command == "s3.put"] + assert len(puts) == 1 + assert puts[0].params["optional"] == "true" + assert puts[0].params["local_file"] == "fuzz-native-artifacts.tgz" + # Wired into post hooks before cleanup, so it runs on task failure too. + config = Path(__file__).parents[2].joinpath(".evergreen/config.yml").read_text() + post = config.split("post:", 1)[1].split("tasks:", 1)[0] + assert '- func: "upload fuzz artifacts"' in post + assert post.index("upload fuzz artifacts") < post.index("cleanup") + + +def test_run_native_seeds_regression(): + """The native runner replays fuzz/regression/ reproducers under ASan.""" + script = Path(__file__).parents[2].joinpath("fuzz/run_native.sh").read_text() + assert "fuzz/regression" in script diff --git a/AGENTS.md b/AGENTS.md index b11b8c09da..cd101b41ba 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,7 +19,7 @@ Official Python driver for MongoDB. - `test/asynchronous/` — async test suite - `test/` — sync test suite (generated from `test/asynchronous/` by `just synchro`) and shared test suite - `test/unified_format/` — cross-driver spec tests (Unified Test Format) -- `fuzz/` — BSON fuzz tests (not pytest; see `fuzz/README.md`) +- `fuzz/` — BSON fuzz tests, including native ASan fuzzing (not pytest; see `fuzz/README.md`) Do not edit files in `pymongo/synchronous/` or mirrored files in `test/` directly: they are generated by `just synchro` from `pymongo/asynchronous/` and `test/asynchronous/`. A file in `test/` is mirrored if a file of the same name exists in `test/asynchronous/`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d16f95e5db..15d5c64572 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -450,16 +450,17 @@ The `fuzz/` directory holds coverage-guided fuzz tests for `bson` tests can only be run on Linux x86_64, the only platform with atheris wheels (CPython 3.12-3.14). -- Regression test (runs on every PR): - `just setup-tests fuzz regression` then `just run-tests`. +- Regression (runs on every PR): the `fuzz-regression` task runs the + python-side fuzz test suite and replays the whole corpus under ASan. + Local replays are covered in [fuzz/README.md](fuzz/README.md). - Time-boxed fuzzing for crash discovery (runs daily on Evergreen): `just setup-tests fuzz fuzz` then `just run-tests`. Set `FUZZ_MAX_TIME` (seconds, default 300) to change the per-target budget. -- Weekly capture (runs weekly on Evergreen): the `fuzz-capture` task also - fuzzes, then captures coverage-increasing inputs into `fuzz/corpus/` - via an automated PR (PYTHON-6178); see [fuzz/README.md](fuzz/README.md). +- Weekly capture (runs weekly on Evergreen): the `fuzz-corpus-capture` + task also fuzzes, then captures coverage-increasing inputs into + `fuzz/corpus/` via an automated PR (PYTHON-6178); see [fuzz/README.md](fuzz/README.md). To run that flow on demand, patch the task: - `evergreen patch --variant fuzz-capture-rhel8 --task fuzz-capture`. + `evergreen patch --variant fuzzing-rhel8 --task fuzz-corpus-capture`. ## Testing time-dependent operations diff --git a/fuzz/README.md b/fuzz/README.md index 979f4a7065..74f15641d5 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -39,23 +39,15 @@ The Evergreen fuzz tasks pin Linux CPython 3.13 and are unaffected. ### Regression inputs (deterministic) -`regression/` holds reproducers for known bugs. Running the targets -over them runs on Evergreen as the `fuzz-regression` sub-test on every PR: +`regression/` holds reproducers for known bugs. The native runs seed +them into the corpus, so every PR and mainline run replays them under ASan. +A local replay against the uninstrumented targets is: ```bash -just setup-tests fuzz regression -just run-tests -``` - -On every PR, the `fuzz-regression` task runs the committed reproducers and the full generated seed -corpus. - -Or without the justfile: - -```bash -uv run --group fuzz python fuzz/fuzz_decode.py fuzz/regression/* -atheris_runs=3 -uv run --group fuzz python fuzz/fuzz_decode_all.py fuzz/regression/* -atheris_runs=3 -uv run --group fuzz python fuzz/fuzz_is_valid.py fuzz/regression/* -atheris_runs=3 +runs="$(ls fuzz/regression | wc -l)" +uv run --group fuzz python fuzz/fuzz_decode.py fuzz/regression/* -atheris_runs="$runs" +uv run --group fuzz python fuzz/fuzz_decode_all.py fuzz/regression/* -atheris_runs="$runs" +uv run --group fuzz python fuzz/fuzz_is_valid.py fuzz/regression/* -atheris_runs="$runs" ``` When a target finds a bug, create a new ticket, add the reproducer as a new @@ -73,13 +65,12 @@ uv run python -m zipfile -e /tmp/fuzz-seed.zip /tmp/fuzz-corpus The builder also synthesizes seeds the spec corpus lacks: boundary-value documents and a ~500 KB stress document. Without a large seed, libFuzzer's -default mutation cap of 4096 bytes would keep the nightly away from +default mutation cap of 4096 bytes would keep the fuzzer away from long-string and many-field code paths. -Run the targets against the corpus. Time-boxed runs suit CI; this runs on -Evergreen as the `fuzz` sub-test, daily. The nightly `fuzz` task is crash -discovery only; the weekly `fuzz-capture` task fuzzes and captures the -corpus (below): +Run the targets against the corpus. Time-boxed runs suit CI; on Evergreen +this is the `fuzz-python-full` task, crash discovery only; the weekly +`fuzz-corpus-capture` task fuzzes and captures the corpus (below): ```bash just setup-tests fuzz fuzz @@ -95,14 +86,14 @@ uv run --group fuzz python fuzz/fuzz_decode.py /tmp/fuzz-corpus -max_total_time= Pass any [libFuzzer flags](https://llvm.org/docs/LibFuzzer.html#options) after the corpus directory. The `Failed to find function __sanitizer_*` startup warnings are benign libFuzzer symbol probes on uninstrumented runs; -native ASan-instrumented fuzzing is tracked separately (PYTHON-6169). +for instrumented native runs see "Native ASan fuzzing" below. ### Captured corpus (weekly) The weekly capture run seeds from the spec seed corpus plus every unit in `corpus/`, and libFuzzer writes each coverage-increasing ("interesting") input it discovers back into its corpus directory. After the targets -finish, the `fuzz-capture` task captures those new units, replays them +finish, the `fuzz-corpus-capture` task captures those new units, replays them through every target once so a unit that fails any target is never published (it stays in `fuzz-scratch/` for triage), and opens an automated "[Fuzz Corpus]" PR against main (PYTHON-6178). Later weeks @@ -139,15 +130,55 @@ The run count equals the file count: replaying individual files (not a corpus directory) performs no empty-input warmup, and letting the budget reach zero gives atheris a graceful exit so coverage.py can flush its report. +## Native ASan fuzzing (PYTHON-6169) + +Atheris instruments only Python code, so memory-safety bugs in +`bson/_cbsonmodule.c` are invisible to it. Rebuild the C extensions with +ASan and run the same three targets under libFuzzer. Requires Linux x86_64 +with a preinstalled clang (atheris ships Linux x86_64 wheels only); no +packages are installed: + +```bash +bash fuzz/build_native.sh # instrumented build into the project venv +FUZZ_MAX_TIME=60 bash fuzz/run_native.sh # time-boxed run over the seed corpus +FUZZ_MAX_TIME=0 bash fuzz/run_native.sh fuzz-scratch/corpus # replay a corpus, no mutation +``` + +The runner sets `FUZZ_NATIVE=1` (the targets skip atheris's own +libFuzzer), `LD_PRELOAD`s atheris's `asan_with_fuzzer.so`, and sets +`PYTHONMALLOC=malloc` so ASan has per-object redzones. Inputs are also +decoded through a sentinel-free `array.array`: `bytes` ends in CPython's +hidden NUL sentinel, which hides over-reads from ASan (the PYTHON-6110 +masking). Leak detection is off (`ASAN_OPTIONS=detect_leaks=0`), the +same as the sanitizer tests (PYTHON-6048). Like the weekly capture run, +the corpus seeds from the spec seed corpus plus the committed `corpus/` +and `regression/` units, replaying every known reproducer under ASan. + +Four Evergreen tasks run these scripts in one Fuzzing variant. On every +PR it runs the python-side regression suite and replays the whole corpus +natively (`fuzz-regression`, `FUZZ_MAX_TIME=0`: each unit runs once, +without mutation). On mainline +it runs the full time-boxed flows (`fuzz-python-full`, +`fuzz-native-full`). The `fuzz-corpus-capture` +task runs weekly, fuzzing natively into `fuzz-scratch/corpus` and +replaying the coverage-increasing inputs under ASan before opening the +automated [Fuzz Corpus] PR. Crash artifacts under `fuzz-scratch/` upload +as task artifacts, so an ASan finding keeps its reproducer. +`build_native.sh` installs pymongo non-editably so the targets load the +instrumented venv copy after the in-tree cleanup. A developer's `.venv` +stays non-editable until the next plain `uv sync`. + ## Files ``` build_corpus.py Seed corpus builder (mirrors the Go driver's build-oss-fuzz-corpus) +build_native.sh Rebuild the C extensions with ASan + libFuzzer instrumentation capture_corpus.py Weekly capture of new coverage-increasing inputs (PYTHON-6178) fuzz_decode.py Fuzz target: bson.decode() fuzz_decode_all.py Fuzz target: bson.decode_all() fuzz_is_valid.py Fuzz target: bson.is_valid() fuzz_shared.py Code shared by the fuzz targets +run_native.sh Run the targets against an instrumented build under libFuzzer corpus/ Captured coverage-increasing inputs; grown by automated weekly PRs regression/ Known bug reproducers; run with the seed corpus on PRs ``` diff --git a/fuzz/build_native.sh b/fuzz/build_native.sh new file mode 100755 index 0000000000..7c17e71071 --- /dev/null +++ b/fuzz/build_native.sh @@ -0,0 +1,117 @@ +#!/bin/bash +# Rebuild the C extensions with ASan + libFuzzer instrumentation and install +# the instrumented package into the project venv (PYTHON-6169). +# +# Requires Linux x86_64 (atheris wheel constraint) and a preinstalled clang. +# This script does not install packages. Run from the repository root: +# bash fuzz/build_native.sh +set -euo pipefail + +ROOT=$(git rev-parse --show-toplevel) +cd "$ROOT" + +PYVER="${FUZZ_NATIVE_PYTHON:-3.13}" + +# Task commands run in fresh shells: source the bootstrap's env.sh to find +# uv. Guarded: a local run without Evergreen setup skips it. +if [ -f .evergreen/scripts/env.sh ]; then + . .evergreen/scripts/env.sh +fi + +if [ "$(uname -s)" != "Linux" ] || [ "$(uname -m)" != "x86_64" ]; then + echo "ERROR: native fuzzing requires Linux x86_64 (atheris wheel constraint)." >&2 + exit 1 +fi + +CC="${CC:-clang}" +if ! command -v "$CC" > /dev/null 2>&1; then + echo "ERROR: clang not found ('$CC'). Native fuzzing needs a clang toolchain." >&2 + echo "Install clang on the host or image. This script does not install packages." >&2 + exit 1 +fi + +if ! command -v uv > /dev/null 2>&1; then + echo "ERROR: uv not found. Install uv or add its bin dir (PYMONGO_BIN_DIR," >&2 + echo '$HOME/.local/bin on Evergreen hosts) to PATH.' >&2 + exit 1 +fi + +# Sync the venv: atheris plus a non-editable pymongo install. Non-editable +# keeps the cleanup below from leaving the targets on the pure-Python +# fallback (PYTHON-6169). +uv sync --no-editable --group fuzz --python "$PYVER" + +# setuptools for the direct build_ext invocation below (uv venvs omit it). +uv pip install --python ".venv/bin/python" setuptools + +# Clear stale C artifacts: build_ext reuses them by mtime, and a plain +# same-version CPython build shares the ABI tag (as in PYTHON-6048). +rm -rf build +rm -f bson/*.so pymongo/*.so + +# Compile the extensions instrumented, directly and visibly: uv builds +# directory sources from a cached copy of the tree that contains the .so +# files built during `uv sync`, so a `uv pip install` can package the +# non-instrumented extensions without invoking the compiler (PYTHON-6169). +# Build failures and flag mismatches are then visible in the log. +export CC +export CFLAGS="-fsanitize=address,fuzzer-no-link -fno-omit-frame-pointer -g -O1" +export LDFLAGS="-fsanitize=address,fuzzer-no-link" +export LDSHARED="$CC -shared" +export PYMONGO_C_EXT_MUST_BUILD=1 +.venv/bin/python _setup.py build_ext -i + +# Overwrite the venv's C extensions with the instrumented ones, bypassing +# uv's wheel build and its cached, non-instrumented copy. +SITE_PACKAGES=$(ls -d .venv/lib/python3.*/site-packages) +cp -f bson/*.so "$SITE_PACKAGES/bson/" +cp -f pymongo/*.so "$SITE_PACKAGES/pymongo/" + +# The smoke import only proves the extension loads under the preloaded +# runtime; the nm symbol check is the instrumentation proof, demoted to a +# warning because -shared -fsanitize=address can hide __asan symbols from +# nm depending on linker mode. run_native.sh hard-fails on the same grep. +SO=$(ls "$SITE_PACKAGES"/bson/_cbson*.so) + +ATHERIS_DIR=$(.venv/bin/python -c 'import atheris; print(atheris.path())') +if [ ! -f "$ATHERIS_DIR/asan_with_fuzzer.so" ]; then + echo "ERROR: $ATHERIS_DIR/asan_with_fuzzer.so is missing. atheris could" >&2 + echo "not provide the runtime." >&2 + exit 1 +fi + +# Smoke: the instrumented extension must import under the preloaded runtime. +if ! FUZZ_NATIVE=1 LD_PRELOAD="$ATHERIS_DIR/asan_with_fuzzer.so" \ + ASAN_OPTIONS="detect_leaks=0" \ + .venv/bin/python -c "import bson; assert bson.has_c()"; then + echo "ERROR: the instrumented extension failed to import under the ASan runtime." >&2 + exit 1 +fi + +PATTERN="__asan|__sanitizer_cov|check_load_add|check_store_add" +if ! nm "$SO" 2>/dev/null | grep -E "$PATTERN" > /dev/null; then + echo "WARNING: $SO shows no ASan/sancov symbols with nm. The smoke import" >&2 + echo "passed, so the extension works, but instrumentation is unproven." >&2 + echo "--- diagnostics:" >&2 + file "$SO" >&2 || true + sha256sum "$SO" bson/_cbson*.so >&2 || true + nm "$SO" 2>&1 | head -40 >&2 || true + readelf -d "$SO" 2>&1 | head -15 >&2 || true +fi + +# Remove the in-tree copies: an instrumented extension here would break a +# plain `import bson` from the repo root (the targets load the site-packages +# copies). Left in place on an early exit above, where they help debugging. +rm -f bson/*.so pymongo/*.so + +# Smoke from a neutral cwd: with the in-tree copies gone, only the venv's +# site-packages copy can satisfy `bson.has_c()` (PYTHON-6169). +if ! (cd /tmp && FUZZ_NATIVE=1 LD_PRELOAD="$ATHERIS_DIR/asan_with_fuzzer.so" \ + ASAN_OPTIONS="detect_leaks=0" \ + "$ROOT/.venv/bin/python" -c "import bson; assert bson.has_c()"); then + echo "ERROR: post-cleanup import did not load the instrumented extension." >&2 + exit 1 +fi + +echo "Instrumented build installed: $SO" +echo "Preload runtime: $ATHERIS_DIR/asan_with_fuzzer.so" diff --git a/fuzz/corpus/00a8ed38b7f6231c0bece6d0b40696aaa5c69b42259bce4c42a0ae703bbebb5e b/fuzz/corpus/00a8ed38b7f6231c0bece6d0b40696aaa5c69b42259bce4c42a0ae703bbebb5e new file mode 100644 index 0000000000..69729c671e Binary files /dev/null and b/fuzz/corpus/00a8ed38b7f6231c0bece6d0b40696aaa5c69b42259bce4c42a0ae703bbebb5e differ diff --git a/fuzz/corpus/04e9d1c558aabd295b007fdae87ba3625f91af2ef1fe2769fc5a45c5cd604b2d b/fuzz/corpus/04e9d1c558aabd295b007fdae87ba3625f91af2ef1fe2769fc5a45c5cd604b2d new file mode 100644 index 0000000000..8103f94cd6 Binary files /dev/null and b/fuzz/corpus/04e9d1c558aabd295b007fdae87ba3625f91af2ef1fe2769fc5a45c5cd604b2d differ diff --git a/fuzz/corpus/0a0fefbd203ccd9cbc2969a2aa6f7bd8716ceee9994625ebfeee69d99bc70273 b/fuzz/corpus/0a0fefbd203ccd9cbc2969a2aa6f7bd8716ceee9994625ebfeee69d99bc70273 new file mode 100644 index 0000000000..893ecb152d Binary files /dev/null and b/fuzz/corpus/0a0fefbd203ccd9cbc2969a2aa6f7bd8716ceee9994625ebfeee69d99bc70273 differ diff --git a/fuzz/corpus/10a094396a1fdee8a8aef3a905b42f0131791beeaac64eb1be4c0fcabddc3b08 b/fuzz/corpus/10a094396a1fdee8a8aef3a905b42f0131791beeaac64eb1be4c0fcabddc3b08 new file mode 100644 index 0000000000..9aa3d6e507 Binary files /dev/null and b/fuzz/corpus/10a094396a1fdee8a8aef3a905b42f0131791beeaac64eb1be4c0fcabddc3b08 differ diff --git a/fuzz/corpus/14a7a5f29446b70bd41c02761705c22292974c287e16d18051781a7b7571454d b/fuzz/corpus/14a7a5f29446b70bd41c02761705c22292974c287e16d18051781a7b7571454d new file mode 100644 index 0000000000..c663eea96f Binary files /dev/null and b/fuzz/corpus/14a7a5f29446b70bd41c02761705c22292974c287e16d18051781a7b7571454d differ diff --git a/fuzz/corpus/18e4ce43f8200c7ad979a23b520599d07379dc5bcdcadc478df8ca747fbc19f4 b/fuzz/corpus/18e4ce43f8200c7ad979a23b520599d07379dc5bcdcadc478df8ca747fbc19f4 new file mode 100644 index 0000000000..91a0e0f78e Binary files /dev/null and b/fuzz/corpus/18e4ce43f8200c7ad979a23b520599d07379dc5bcdcadc478df8ca747fbc19f4 differ diff --git a/fuzz/corpus/1dd839ec29b73fa83028a709cceaa34da41889ef60b3b14859184b930ae2b2d1 b/fuzz/corpus/1dd839ec29b73fa83028a709cceaa34da41889ef60b3b14859184b930ae2b2d1 new file mode 100644 index 0000000000..9d937bd722 Binary files /dev/null and b/fuzz/corpus/1dd839ec29b73fa83028a709cceaa34da41889ef60b3b14859184b930ae2b2d1 differ diff --git a/fuzz/corpus/1ef582c6cb070409786a601765da1bd0dea1bc605a1dcbef0db9445ce6571f55 b/fuzz/corpus/1ef582c6cb070409786a601765da1bd0dea1bc605a1dcbef0db9445ce6571f55 new file mode 100644 index 0000000000..7c36d8d54f Binary files /dev/null and b/fuzz/corpus/1ef582c6cb070409786a601765da1bd0dea1bc605a1dcbef0db9445ce6571f55 differ diff --git a/fuzz/corpus/1f698578b48063648784d56553fb0dfb1a58f277e69df10e0947604c404e086c b/fuzz/corpus/1f698578b48063648784d56553fb0dfb1a58f277e69df10e0947604c404e086c new file mode 100644 index 0000000000..b3e3316555 Binary files /dev/null and b/fuzz/corpus/1f698578b48063648784d56553fb0dfb1a58f277e69df10e0947604c404e086c differ diff --git a/fuzz/corpus/1ff679f73f932f8d3f149022290f05c576aad3d5e24e29381fc24dc8dff8963a b/fuzz/corpus/1ff679f73f932f8d3f149022290f05c576aad3d5e24e29381fc24dc8dff8963a new file mode 100644 index 0000000000..a209bbd1e9 Binary files /dev/null and b/fuzz/corpus/1ff679f73f932f8d3f149022290f05c576aad3d5e24e29381fc24dc8dff8963a differ diff --git a/fuzz/corpus/26af2c5de2ea5e7169e9437be57a5a0795b9e9f64c796b26bcdff9f34b017f86 b/fuzz/corpus/26af2c5de2ea5e7169e9437be57a5a0795b9e9f64c796b26bcdff9f34b017f86 new file mode 100644 index 0000000000..7ac4076990 Binary files /dev/null and b/fuzz/corpus/26af2c5de2ea5e7169e9437be57a5a0795b9e9f64c796b26bcdff9f34b017f86 differ diff --git a/fuzz/corpus/27c245e2729f35688f6e0704187b311c84e28f382a5e1d53cd3e9dc5d2d29621 b/fuzz/corpus/27c245e2729f35688f6e0704187b311c84e28f382a5e1d53cd3e9dc5d2d29621 new file mode 100644 index 0000000000..2b930ba797 Binary files /dev/null and b/fuzz/corpus/27c245e2729f35688f6e0704187b311c84e28f382a5e1d53cd3e9dc5d2d29621 differ diff --git a/fuzz/corpus/2921a11f25dadaa24aa79a548e4e81508c2e5e56af2d833d65e2bcce448ce2f5 b/fuzz/corpus/2921a11f25dadaa24aa79a548e4e81508c2e5e56af2d833d65e2bcce448ce2f5 new file mode 100644 index 0000000000..19b3e940af Binary files /dev/null and b/fuzz/corpus/2921a11f25dadaa24aa79a548e4e81508c2e5e56af2d833d65e2bcce448ce2f5 differ diff --git a/fuzz/corpus/29e45c60eead7124431d4f99feb3acb3f3a074c4b93f38cdc2db0872dda63dde b/fuzz/corpus/29e45c60eead7124431d4f99feb3acb3f3a074c4b93f38cdc2db0872dda63dde new file mode 100644 index 0000000000..fb273cf609 Binary files /dev/null and b/fuzz/corpus/29e45c60eead7124431d4f99feb3acb3f3a074c4b93f38cdc2db0872dda63dde differ diff --git a/fuzz/corpus/2b39bf73b87a188c1da60ef4a06db212e9e70ec45cd3b549c8c830b77a5a4e42 b/fuzz/corpus/2b39bf73b87a188c1da60ef4a06db212e9e70ec45cd3b549c8c830b77a5a4e42 new file mode 100644 index 0000000000..92de40a236 Binary files /dev/null and b/fuzz/corpus/2b39bf73b87a188c1da60ef4a06db212e9e70ec45cd3b549c8c830b77a5a4e42 differ diff --git a/fuzz/corpus/2eb6fcf4152b3f3e7528142289daffbf819aacfae86428b028e271a14c67141b b/fuzz/corpus/2eb6fcf4152b3f3e7528142289daffbf819aacfae86428b028e271a14c67141b new file mode 100644 index 0000000000..1c0bc9d676 Binary files /dev/null and b/fuzz/corpus/2eb6fcf4152b3f3e7528142289daffbf819aacfae86428b028e271a14c67141b differ diff --git a/fuzz/corpus/30a637485bab4dd23c6e3679bc7c39ea070e719f35133407922d742cd9885e32 b/fuzz/corpus/30a637485bab4dd23c6e3679bc7c39ea070e719f35133407922d742cd9885e32 new file mode 100644 index 0000000000..c9c7909f33 Binary files /dev/null and b/fuzz/corpus/30a637485bab4dd23c6e3679bc7c39ea070e719f35133407922d742cd9885e32 differ diff --git a/fuzz/corpus/3354678ad45ee9ad9b85ea4b1164a1ccbb2197f60ec00de5360308941c0b7c60 b/fuzz/corpus/3354678ad45ee9ad9b85ea4b1164a1ccbb2197f60ec00de5360308941c0b7c60 new file mode 100644 index 0000000000..cbc8351590 Binary files /dev/null and b/fuzz/corpus/3354678ad45ee9ad9b85ea4b1164a1ccbb2197f60ec00de5360308941c0b7c60 differ diff --git a/fuzz/corpus/3458e85f1a812198dc622ad3ba8fce065ad26b4157a578fe0d6afa43ae10727b b/fuzz/corpus/3458e85f1a812198dc622ad3ba8fce065ad26b4157a578fe0d6afa43ae10727b new file mode 100644 index 0000000000..d6e766fe0f Binary files /dev/null and b/fuzz/corpus/3458e85f1a812198dc622ad3ba8fce065ad26b4157a578fe0d6afa43ae10727b differ diff --git a/fuzz/corpus/3abd48ab3b540094a62e7357f47c0c17ba0f95d91c50e3c394fc36cb4e7ac97d b/fuzz/corpus/3abd48ab3b540094a62e7357f47c0c17ba0f95d91c50e3c394fc36cb4e7ac97d new file mode 100644 index 0000000000..a2168fef60 Binary files /dev/null and b/fuzz/corpus/3abd48ab3b540094a62e7357f47c0c17ba0f95d91c50e3c394fc36cb4e7ac97d differ diff --git a/fuzz/corpus/3ee0d7c44a58950b18c1e01b912ed0e08549ff905fbf7010318a44d3e2efb8db b/fuzz/corpus/3ee0d7c44a58950b18c1e01b912ed0e08549ff905fbf7010318a44d3e2efb8db new file mode 100644 index 0000000000..7c4860275e Binary files /dev/null and b/fuzz/corpus/3ee0d7c44a58950b18c1e01b912ed0e08549ff905fbf7010318a44d3e2efb8db differ diff --git a/fuzz/corpus/44881562ca4aaa2d902c2b16d7bc4e53b903e7e7eb48285a4f273a8f9ad229b6 b/fuzz/corpus/44881562ca4aaa2d902c2b16d7bc4e53b903e7e7eb48285a4f273a8f9ad229b6 new file mode 100644 index 0000000000..83bce559f4 Binary files /dev/null and b/fuzz/corpus/44881562ca4aaa2d902c2b16d7bc4e53b903e7e7eb48285a4f273a8f9ad229b6 differ diff --git a/fuzz/corpus/4608d556b3650a5bc36def7cb5b449c459c78bad5af786b05fe4493c04bbd6e3 b/fuzz/corpus/4608d556b3650a5bc36def7cb5b449c459c78bad5af786b05fe4493c04bbd6e3 new file mode 100644 index 0000000000..2e73dc5ad2 Binary files /dev/null and b/fuzz/corpus/4608d556b3650a5bc36def7cb5b449c459c78bad5af786b05fe4493c04bbd6e3 differ diff --git a/fuzz/corpus/4b58e6d6c2fbd5b0446c3fae6914690345ba4ee05308b22ec3a8e5468e9d8d45 b/fuzz/corpus/4b58e6d6c2fbd5b0446c3fae6914690345ba4ee05308b22ec3a8e5468e9d8d45 new file mode 100644 index 0000000000..762672606c Binary files /dev/null and b/fuzz/corpus/4b58e6d6c2fbd5b0446c3fae6914690345ba4ee05308b22ec3a8e5468e9d8d45 differ diff --git a/fuzz/corpus/4c83cde2dcffb5d930e808134a2bc8b6da506626c68d25677dea9c2bc584c6a5 b/fuzz/corpus/4c83cde2dcffb5d930e808134a2bc8b6da506626c68d25677dea9c2bc584c6a5 new file mode 100644 index 0000000000..f36e94da07 Binary files /dev/null and b/fuzz/corpus/4c83cde2dcffb5d930e808134a2bc8b6da506626c68d25677dea9c2bc584c6a5 differ diff --git a/fuzz/corpus/4cf9165cb542be068f7d5cd54870118c856d077802cd0305497ca9d1556f76ed b/fuzz/corpus/4cf9165cb542be068f7d5cd54870118c856d077802cd0305497ca9d1556f76ed new file mode 100644 index 0000000000..1204ef6302 Binary files /dev/null and b/fuzz/corpus/4cf9165cb542be068f7d5cd54870118c856d077802cd0305497ca9d1556f76ed differ diff --git a/fuzz/corpus/4d597e0cdde7e51b5fe9de534c0af949904c54fb5f2a162d424cfd370cdcc2a3 b/fuzz/corpus/4d597e0cdde7e51b5fe9de534c0af949904c54fb5f2a162d424cfd370cdcc2a3 new file mode 100644 index 0000000000..bebc27b8bb Binary files /dev/null and b/fuzz/corpus/4d597e0cdde7e51b5fe9de534c0af949904c54fb5f2a162d424cfd370cdcc2a3 differ diff --git a/fuzz/corpus/4dec5656fb51d52b13de8894ee95bd3ad350c2abdd779117e5e332d485cdb5ef b/fuzz/corpus/4dec5656fb51d52b13de8894ee95bd3ad350c2abdd779117e5e332d485cdb5ef new file mode 100644 index 0000000000..f7685a4826 Binary files /dev/null and b/fuzz/corpus/4dec5656fb51d52b13de8894ee95bd3ad350c2abdd779117e5e332d485cdb5ef differ diff --git a/fuzz/corpus/547efc442bac57743e52ea913183aa0e38fba334992ba434d5e5f9970dd09655 b/fuzz/corpus/547efc442bac57743e52ea913183aa0e38fba334992ba434d5e5f9970dd09655 new file mode 100644 index 0000000000..9df1f78178 Binary files /dev/null and b/fuzz/corpus/547efc442bac57743e52ea913183aa0e38fba334992ba434d5e5f9970dd09655 differ diff --git a/fuzz/corpus/54a254ada5e25ab7c82c0d64a729585f220163143eb254d43b682a9dd25a0d98 b/fuzz/corpus/54a254ada5e25ab7c82c0d64a729585f220163143eb254d43b682a9dd25a0d98 new file mode 100644 index 0000000000..422e13bb0a Binary files /dev/null and b/fuzz/corpus/54a254ada5e25ab7c82c0d64a729585f220163143eb254d43b682a9dd25a0d98 differ diff --git a/fuzz/corpus/550db8b2a3e387483e67af51d0a4834e15650ac51325cd87163cc0cc00e316f2 b/fuzz/corpus/550db8b2a3e387483e67af51d0a4834e15650ac51325cd87163cc0cc00e316f2 new file mode 100644 index 0000000000..87a0405f02 Binary files /dev/null and b/fuzz/corpus/550db8b2a3e387483e67af51d0a4834e15650ac51325cd87163cc0cc00e316f2 differ diff --git a/fuzz/corpus/58586fb6a1333dfd3976a04998f1da3fc350d26674b67bf06712fc41beddbce9 b/fuzz/corpus/58586fb6a1333dfd3976a04998f1da3fc350d26674b67bf06712fc41beddbce9 new file mode 100644 index 0000000000..69df8efc4b Binary files /dev/null and b/fuzz/corpus/58586fb6a1333dfd3976a04998f1da3fc350d26674b67bf06712fc41beddbce9 differ diff --git a/fuzz/corpus/585d3a0bb706bcda05c26e268f78880b947ea68315c2ba11e18f6bf98ca2f862 b/fuzz/corpus/585d3a0bb706bcda05c26e268f78880b947ea68315c2ba11e18f6bf98ca2f862 new file mode 100644 index 0000000000..c90766f4f4 Binary files /dev/null and b/fuzz/corpus/585d3a0bb706bcda05c26e268f78880b947ea68315c2ba11e18f6bf98ca2f862 differ diff --git a/fuzz/corpus/59c9eebce707d38b4dda75ef3cf03e976f4567a73a4fde6db21d53a2670a3c5f b/fuzz/corpus/59c9eebce707d38b4dda75ef3cf03e976f4567a73a4fde6db21d53a2670a3c5f new file mode 100644 index 0000000000..c1dd5fa615 Binary files /dev/null and b/fuzz/corpus/59c9eebce707d38b4dda75ef3cf03e976f4567a73a4fde6db21d53a2670a3c5f differ diff --git a/fuzz/corpus/5a8bf664fc9b12ea2f22312b2ece5a126fed275146a000382349e5db083818e2 b/fuzz/corpus/5a8bf664fc9b12ea2f22312b2ece5a126fed275146a000382349e5db083818e2 new file mode 100644 index 0000000000..beac0dca6b Binary files /dev/null and b/fuzz/corpus/5a8bf664fc9b12ea2f22312b2ece5a126fed275146a000382349e5db083818e2 differ diff --git a/fuzz/corpus/608b8f2ae917c6ca89e1ba52e49a1cc15d6ae171fa3492af0d0ccbb61ce0483e b/fuzz/corpus/608b8f2ae917c6ca89e1ba52e49a1cc15d6ae171fa3492af0d0ccbb61ce0483e new file mode 100644 index 0000000000..c3772d3c4f Binary files /dev/null and b/fuzz/corpus/608b8f2ae917c6ca89e1ba52e49a1cc15d6ae171fa3492af0d0ccbb61ce0483e differ diff --git a/fuzz/corpus/61124b1d45b1ee030e250baed5f5a12519ea42e8c54a99164ae6e0924c58e065 b/fuzz/corpus/61124b1d45b1ee030e250baed5f5a12519ea42e8c54a99164ae6e0924c58e065 new file mode 100644 index 0000000000..1c340a00bf Binary files /dev/null and b/fuzz/corpus/61124b1d45b1ee030e250baed5f5a12519ea42e8c54a99164ae6e0924c58e065 differ diff --git a/fuzz/corpus/61a529a6f3c6735117e7f7828d516f23f58fab709224e5bf673d4c95ef75c186 b/fuzz/corpus/61a529a6f3c6735117e7f7828d516f23f58fab709224e5bf673d4c95ef75c186 new file mode 100644 index 0000000000..4235549ecd Binary files /dev/null and b/fuzz/corpus/61a529a6f3c6735117e7f7828d516f23f58fab709224e5bf673d4c95ef75c186 differ diff --git a/fuzz/corpus/622c5758150ecec7abbbc194240874a03c48062a21b941aaa3d16a37665f575f b/fuzz/corpus/622c5758150ecec7abbbc194240874a03c48062a21b941aaa3d16a37665f575f new file mode 100644 index 0000000000..8b985d12c0 Binary files /dev/null and b/fuzz/corpus/622c5758150ecec7abbbc194240874a03c48062a21b941aaa3d16a37665f575f differ diff --git a/fuzz/corpus/62f0ccc0696f0df78c94cfe6b1b45cd3c6f498d999c68a58afc0c86c8bc0354a b/fuzz/corpus/62f0ccc0696f0df78c94cfe6b1b45cd3c6f498d999c68a58afc0c86c8bc0354a new file mode 100644 index 0000000000..1526ecab3d Binary files /dev/null and b/fuzz/corpus/62f0ccc0696f0df78c94cfe6b1b45cd3c6f498d999c68a58afc0c86c8bc0354a differ diff --git a/fuzz/corpus/63c74f6e6f31c4f3e3ca5c000157240e6f76a8cb5bf59244f13bd297d2e0fc20 b/fuzz/corpus/63c74f6e6f31c4f3e3ca5c000157240e6f76a8cb5bf59244f13bd297d2e0fc20 new file mode 100644 index 0000000000..0fda3519f0 Binary files /dev/null and b/fuzz/corpus/63c74f6e6f31c4f3e3ca5c000157240e6f76a8cb5bf59244f13bd297d2e0fc20 differ diff --git a/fuzz/corpus/6764a91ba03c6615269acdac30c527da5a6170e411620ee72f49ffc3cf474c86 b/fuzz/corpus/6764a91ba03c6615269acdac30c527da5a6170e411620ee72f49ffc3cf474c86 new file mode 100644 index 0000000000..bbd49a3246 Binary files /dev/null and b/fuzz/corpus/6764a91ba03c6615269acdac30c527da5a6170e411620ee72f49ffc3cf474c86 differ diff --git a/fuzz/corpus/6c753ba035ff3f993ca23af998d25bf4f726ff993243666b3925eb8ee16f7390 b/fuzz/corpus/6c753ba035ff3f993ca23af998d25bf4f726ff993243666b3925eb8ee16f7390 new file mode 100644 index 0000000000..2800b35023 Binary files /dev/null and b/fuzz/corpus/6c753ba035ff3f993ca23af998d25bf4f726ff993243666b3925eb8ee16f7390 differ diff --git a/fuzz/corpus/7e81c8a995b00016a0dbe585e59c0486856725527c94fe2b71b9a3ab1f64eeb5 b/fuzz/corpus/7e81c8a995b00016a0dbe585e59c0486856725527c94fe2b71b9a3ab1f64eeb5 new file mode 100644 index 0000000000..5682a1a36a Binary files /dev/null and b/fuzz/corpus/7e81c8a995b00016a0dbe585e59c0486856725527c94fe2b71b9a3ab1f64eeb5 differ diff --git a/fuzz/corpus/affe6702b4fafff1487517c506ec0070a7c850df7a7552d08b3ddd4307337929 b/fuzz/corpus/affe6702b4fafff1487517c506ec0070a7c850df7a7552d08b3ddd4307337929 new file mode 100644 index 0000000000..fd46e3b39b Binary files /dev/null and b/fuzz/corpus/affe6702b4fafff1487517c506ec0070a7c850df7a7552d08b3ddd4307337929 differ diff --git a/fuzz/corpus/b52b5dd584355724b94b4d0f4a0f1985044df9781566ad34829279478e491689 b/fuzz/corpus/b52b5dd584355724b94b4d0f4a0f1985044df9781566ad34829279478e491689 new file mode 100644 index 0000000000..9f7e901be8 Binary files /dev/null and b/fuzz/corpus/b52b5dd584355724b94b4d0f4a0f1985044df9781566ad34829279478e491689 differ diff --git a/fuzz/corpus/b8eb862630c5df1737c028a8a4ec96b9b4274a0bc57f0f562aa134119884d402 b/fuzz/corpus/b8eb862630c5df1737c028a8a4ec96b9b4274a0bc57f0f562aa134119884d402 new file mode 100644 index 0000000000..c3dfa691c4 Binary files /dev/null and b/fuzz/corpus/b8eb862630c5df1737c028a8a4ec96b9b4274a0bc57f0f562aa134119884d402 differ diff --git a/fuzz/corpus/e1dfefdccbb352b20197a6d888dbcc52bfcc760a77f377918a52ba5c387bfb23 b/fuzz/corpus/e1dfefdccbb352b20197a6d888dbcc52bfcc760a77f377918a52ba5c387bfb23 new file mode 100644 index 0000000000..44aad0bc01 Binary files /dev/null and b/fuzz/corpus/e1dfefdccbb352b20197a6d888dbcc52bfcc760a77f377918a52ba5c387bfb23 differ diff --git a/fuzz/corpus/e63a9e3e469bd8d8738c26158ef506d16fc21bfeed745451c1378e97f1acad89 b/fuzz/corpus/e63a9e3e469bd8d8738c26158ef506d16fc21bfeed745451c1378e97f1acad89 new file mode 100644 index 0000000000..077142ada7 Binary files /dev/null and b/fuzz/corpus/e63a9e3e469bd8d8738c26158ef506d16fc21bfeed745451c1378e97f1acad89 differ diff --git a/fuzz/corpus/fc1c4703d93da4c1951b27498b798a9fd30d6acd4ad6abf61e1f61945e6a0358 b/fuzz/corpus/fc1c4703d93da4c1951b27498b798a9fd30d6acd4ad6abf61e1f61945e6a0358 new file mode 100644 index 0000000000..1219cb6f6f Binary files /dev/null and b/fuzz/corpus/fc1c4703d93da4c1951b27498b798a9fd30d6acd4ad6abf61e1f61945e6a0358 differ diff --git a/fuzz/fuzz_decode.py b/fuzz/fuzz_decode.py index 261059b349..cdc0f6187b 100755 --- a/fuzz/fuzz_decode.py +++ b/fuzz/fuzz_decode.py @@ -8,8 +8,13 @@ from __future__ import annotations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + import array + import atheris -from fuzz_shared import OTHER_ERRORS, load_pure_python_bson, main, normalize +from fuzz_shared import OTHER_ERRORS, input_views, load_pure_python_bson, main, normalize with atheris.instrument_imports(): # Load both implementations while import instrumentation is active so the @@ -23,7 +28,7 @@ _BOTH_IMPLS = _bson_c.has_c() -def _decode_with(bson_mod, data: bytes) -> dict | None: +def _decode_with(bson_mod, data: bytes | array.array) -> dict | None: """Run bson_mod.decode(data), returning the document or None on expected errors.""" try: return bson_mod.decode(data) @@ -33,45 +38,50 @@ def _decode_with(bson_mod, data: bytes) -> dict | None: @atheris.instrument_func def TestOneInput(data: bytes) -> None: - doc_c = _decode_with(_bson_c, data) - - # A successful decode must round-trip through encode(). - if doc_c is not None: - try: - _bson_c.encode(doc_c) - except Exception as exc: - raise AssertionError( - f"bson.encode() failed after bson.decode() succeeded: {exc!r}\n" - f"decoded document: {doc_c!r}" - ) from exc - - doc_pure = _decode_with(_bson_pure, data) - - if doc_pure is not None: - try: - _bson_pure.encode(doc_pure) - except Exception as exc: - raise AssertionError( - f"pure-Python bson.encode() failed after bson.decode() succeeded: {exc!r}\n" - f"decoded document: {doc_pure!r}" - ) from exc - - # Consistency check. - if _BOTH_IMPLS: - c_succeeded = doc_c is not None - pure_succeeded = doc_pure is not None - if c_succeeded != pure_succeeded: - raise AssertionError( - f"C extension and pure-Python bson.decode() disagree: " - f"C={'success' if c_succeeded else 'failure'}, " - f"pure={'success' if pure_succeeded else 'failure'} " - f"for input: {data!r}" - ) - if doc_c is not None and doc_pure is not None and normalize(doc_c) != normalize(doc_pure): - raise AssertionError( - f"C extension and pure-Python bson.decode() produced different " - f"documents: C={doc_c!r}, pure={doc_pure!r}, input: {data!r}" - ) + for view in input_views(data): + doc_c = _decode_with(_bson_c, view) + + # A successful decode must round-trip through encode(). + if doc_c is not None: + try: + _bson_c.encode(doc_c) + except Exception as exc: + raise AssertionError( + f"bson.encode() failed after bson.decode() succeeded: {exc!r}\n" + f"decoded document: {doc_c!r}" + ) from exc + + doc_pure = _decode_with(_bson_pure, view) + + if doc_pure is not None: + try: + _bson_pure.encode(doc_pure) + except Exception as exc: + raise AssertionError( + f"pure-Python bson.encode() failed after bson.decode() succeeded: {exc!r}\n" + f"decoded document: {doc_pure!r}" + ) from exc + + # Consistency check. + if _BOTH_IMPLS: + c_succeeded = doc_c is not None + pure_succeeded = doc_pure is not None + if c_succeeded != pure_succeeded: + raise AssertionError( + f"C extension and pure-Python bson.decode() disagree: " + f"C={'success' if c_succeeded else 'failure'}, " + f"pure={'success' if pure_succeeded else 'failure'} " + f"for input: {data!r}" + ) + if ( + doc_c is not None + and doc_pure is not None + and normalize(doc_c) != normalize(doc_pure) + ): + raise AssertionError( + f"C extension and pure-Python bson.decode() produced different " + f"documents: C={doc_c!r}, pure={doc_pure!r}, input: {data!r}" + ) if __name__ == "__main__": diff --git a/fuzz/fuzz_decode_all.py b/fuzz/fuzz_decode_all.py index e8a9812fc6..1a672e811b 100755 --- a/fuzz/fuzz_decode_all.py +++ b/fuzz/fuzz_decode_all.py @@ -8,8 +8,13 @@ from __future__ import annotations +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + import array + import atheris -from fuzz_shared import OTHER_ERRORS, load_pure_python_bson, main, normalize +from fuzz_shared import OTHER_ERRORS, input_views, load_pure_python_bson, main, normalize with atheris.instrument_imports(): # Load both implementations while import instrumentation is active so the @@ -23,7 +28,7 @@ _BOTH_IMPLS = _bson_c.has_c() -def _decode_all_with(bson_mod, data: bytes) -> list | None: +def _decode_all_with(bson_mod, data: bytes | array.array) -> list | None: """Run bson_mod.decode_all(data), returning the documents or None on expected errors.""" try: return bson_mod.decode_all(data) @@ -45,42 +50,43 @@ def _encode_all_with(bson_mod, docs) -> None: @atheris.instrument_func def TestOneInput(data: bytes) -> None: - docs_c = _decode_all_with(_bson_c, data) - if docs_c is not None: - _encode_all_with(_bson_c, docs_c) - - docs_pure = _decode_all_with(_bson_pure, data) - if docs_pure is not None: - _encode_all_with(_bson_pure, docs_pure) - - # Consistency checks. - if _BOTH_IMPLS: - c_succeeded = docs_c is not None - pure_succeeded = docs_pure is not None - - if c_succeeded != pure_succeeded: - raise AssertionError( - f"C extension and pure-Python bson.decode_all() disagree: " - f"C={'success' if c_succeeded else 'failure'}, " - f"pure={'success' if pure_succeeded else 'failure'} " - f"for input: {data!r}" - ) - - if docs_c is not None and docs_pure is not None and len(docs_c) != len(docs_pure): - raise AssertionError( - f"C extension decoded {len(docs_c)} document(s) but pure Python " - f"decoded {len(docs_pure)} document(s) for input: {data!r}" - ) - - if ( - docs_c is not None - and docs_pure is not None - and normalize(docs_c) != normalize(docs_pure) - ): - raise AssertionError( - f"C extension and pure-Python bson.decode_all() produced different " - f"documents for input: {data!r}" - ) + for view in input_views(data): + docs_c = _decode_all_with(_bson_c, view) + if docs_c is not None: + _encode_all_with(_bson_c, docs_c) + + docs_pure = _decode_all_with(_bson_pure, view) + if docs_pure is not None: + _encode_all_with(_bson_pure, docs_pure) + + # Consistency checks. + if _BOTH_IMPLS: + c_succeeded = docs_c is not None + pure_succeeded = docs_pure is not None + + if c_succeeded != pure_succeeded: + raise AssertionError( + f"C extension and pure-Python bson.decode_all() disagree: " + f"C={'success' if c_succeeded else 'failure'}, " + f"pure={'success' if pure_succeeded else 'failure'} " + f"for input: {data!r}" + ) + + if docs_c is not None and docs_pure is not None and len(docs_c) != len(docs_pure): + raise AssertionError( + f"C extension decoded {len(docs_c)} document(s) but pure Python " + f"decoded {len(docs_pure)} document(s) for input: {data!r}" + ) + + if ( + docs_c is not None + and docs_pure is not None + and normalize(docs_c) != normalize(docs_pure) + ): + raise AssertionError( + f"C extension and pure-Python bson.decode_all() produced different " + f"documents for input: {data!r}" + ) if __name__ == "__main__": diff --git a/fuzz/fuzz_is_valid.py b/fuzz/fuzz_is_valid.py index 5281c7e49e..4d9819e81f 100755 --- a/fuzz/fuzz_is_valid.py +++ b/fuzz/fuzz_is_valid.py @@ -9,7 +9,7 @@ from __future__ import annotations import atheris -from fuzz_shared import load_pure_python_bson, main +from fuzz_shared import input_views, load_pure_python_bson, main with atheris.instrument_imports(): # Load both implementations while import instrumentation is active so the @@ -25,29 +25,33 @@ @atheris.instrument_func def TestOneInput(data: bytes) -> None: + # is_valid() requires bytes (other buffers raise TypeError) and is a + # pure content predicate, so it runs on the raw input. decode() + # exercises every view, including the sentinel-free array.array copy + # that lets ASan see over-reads in native mode (PYTHON-6169). valid_c = _bson_c.is_valid(data) - - if valid_c: - try: - _bson_c.decode(data) - except Exception as exc: - # is_valid() performs a full decode and swallows every exception, - # so a True result guarantees decode() raises none. - raise AssertionError( - f"bson.is_valid() returned True but bson.decode() raised " - f"{type(exc).__name__}: {exc!r}\ninput: {data!r}" - ) from exc - valid_pure = _bson_pure.is_valid(data) - if valid_pure: - try: - _bson_pure.decode(data) - except Exception as exc: - raise AssertionError( - f"pure-Python bson.is_valid() returned True but bson.decode() " - f"raised {type(exc).__name__}: {exc!r}\ninput: {data!r}" - ) from exc + for view in input_views(data): + if valid_c: + try: + _bson_c.decode(view) + except Exception as exc: + # is_valid() performs a full decode and swallows every exception, + # so a True result guarantees decode() raises none. + raise AssertionError( + f"bson.is_valid() returned True but bson.decode() raised " + f"{type(exc).__name__}: {exc!r}\ninput: {data!r}" + ) from exc + + if valid_pure: + try: + _bson_pure.decode(view) + except Exception as exc: + raise AssertionError( + f"pure-Python bson.is_valid() returned True but bson.decode() " + f"raised {type(exc).__name__}: {exc!r}\ninput: {data!r}" + ) from exc if _BOTH_IMPLS and valid_c != valid_pure: raise AssertionError( diff --git a/fuzz/fuzz_shared.py b/fuzz/fuzz_shared.py index f4cde8aaae..4d659ae87c 100755 --- a/fuzz/fuzz_shared.py +++ b/fuzz/fuzz_shared.py @@ -3,16 +3,22 @@ from __future__ import annotations +import array import math import os import struct import sys +from typing import TYPE_CHECKING -import atheris +if TYPE_CHECKING: + from collections.abc import Iterator def load_pure_python_bson(): - """Re-import bson with the C extension blocked, then restore sys.modules.""" + """Re-import bson with the C extension blocked, then restore sys.modules. + + Raises RuntimeError if the pure-Python implementation cannot be loaded. + """ saved = { k: sys.modules.pop(k) for k in list(sys.modules) if k == "bson" or k.startswith("bson.") } @@ -64,8 +70,31 @@ def normalize(obj: object) -> object: return f"{type(obj).__name__}:{obj!r}" +def input_views(data: bytes) -> Iterator[object]: + """Yield the buffer views to decode for one fuzz input. + + Always yields the raw bytes. With FUZZ_NATIVE=1 (native ASan fuzzing, + PYTHON-6169) it also yields a sentinel-free array.array copy: bytes + ends in CPython's hidden NUL sentinel, which hides an over-read past + the buffer from ASan (the PYTHON-6110 masking). The array copy has no + sentinel and is exact-sized (a bare array.array(bytes) overallocates), + so the same over-read triggers ASan's redzone check. + """ + yield data + if os.environ.get("FUZZ_NATIVE") == "1": + # array.array(bytes) overallocates its buffer, leaving short + # over-reads inside addressable memory. A full slice of it + # allocates exactly len(data), putting the redzone right after. + yield array.array("B", data)[:] + + def main(test_one_input) -> None: """Set up atheris for a fuzz target and start fuzzing.""" + # Imported here so fuzz_shared remains importable without atheris, which + # test/test_fuzz_shared.py relies on. The fuzz targets import atheris + # themselves before calling main(). + import atheris + # FUZZ_NATIVE=1: libFuzzer is preloaded externally; skip atheris's own. internal_libfuzzer = os.environ.get("FUZZ_NATIVE") != "1" atheris.Setup(sys.argv, test_one_input, internal_libfuzzer=internal_libfuzzer) diff --git a/fuzz/run_native.sh b/fuzz/run_native.sh new file mode 100755 index 0000000000..10d4d06bab --- /dev/null +++ b/fuzz/run_native.sh @@ -0,0 +1,136 @@ +#!/bin/bash +# Run the BSON fuzz targets against an ASan-instrumented build under +# libFuzzer (PYTHON-6169). Expects fuzz/build_native.sh to have run. +# +# Optional argument: the corpus directory (default fuzz-scratch/ +# native-corpus, rebuilt from seeds each run; an explicit directory is +# kept, with the seeds added to it). The weekly capture passes +# fuzz-scratch/corpus, which capture_corpus.py harvests. +# +# FUZZ_MAX_TIME seconds per target, default 300. 0 replays every corpus +# unit once without mutating (the PR flow). Run from the repository root: +# bash fuzz/run_native.sh +set -euo pipefail + +# Canonical root: the containment check below compares real paths, so a +# symlinked checkout must resolve first. +ROOT=$(cd "$(git rev-parse --show-toplevel)" && pwd -P) +cd "$ROOT" + +PYTHON=".venv/bin/python" +SCRATCH="$ROOT/fuzz-scratch" +CORPUS="${1:-$SCRATCH/native-corpus}" +MAX_TIME="${FUZZ_MAX_TIME:-300}" + +# Relative arguments resolve against the repository root, the script's cwd. +case "$CORPUS" in + /*) ;; + *) CORPUS="$ROOT/$CORPUS" ;; +esac + +if [ ! -x "$PYTHON" ]; then + echo "ERROR: $PYTHON not found. Run fuzz/build_native.sh first." >&2 + exit 1 +fi + +# The venv's pymongo must be the instrumented one. The symbol pattern covers +# both instrumentation shapes: undefined/embedded __asan references and the +# .check_load_add/.check_store_add local labels clang emits for inline ASan +# checks (PYTHON-6169). grep without -q: with pipefail, grep -q's early exit +# SIGPIPEs nm on a large symbol table and the pipeline fails even on a match. +SO=$(ls .venv/lib/python3.*/site-packages/bson/_cbson*.so) +PATTERN="__asan|__sanitizer_cov|check_load_add|check_store_add" +if ! nm "$SO" 2>/dev/null | grep -E "$PATTERN" > /dev/null; then + echo "ERROR: $SO is not ASan-instrumented. Run fuzz/build_native.sh first." >&2 + exit 1 +fi + +# Canonicalize the corpus path (symlinks and ..) before any deletion: the +# containment check must see where the path really resolves (PYTHON-6169). +CORPUS=$("$PYTHON" -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$CORPUS") +case "$CORPUS" in + "$ROOT"/*) ;; + *) + echo "ERROR: corpus directory must live inside the repository." >&2 + exit 1 + ;; +esac +# Managed seed sources: copying the seeds into them would collide with +# themselves. +case "$CORPUS" in + "$ROOT"/fuzz/corpus | "$ROOT"/fuzz/regression) + echo "ERROR: pass a corpus directory, not a seed source." >&2 + exit 1 + ;; +esac + +# Build the seed corpus from the vendored spec data. build_corpus.py forces +# the pure-Python implementation, so it is safe under an instrumented venv. +# The default corpus is rebuilt from seeds every run; an explicit corpus is +# preserved, with the seeds added to it, so replaying never deletes locally +# discovered inputs. +mkdir -p "$CORPUS" "$SCRATCH" +if [ "$#" -eq 0 ]; then + # The reset is scoped to the scratch area: a symlink at the default + # corpus path must not redirect the deletion into tracked sources + # (PYTHON-6169). + case "$CORPUS" in + "$SCRATCH"/*) rm -rf "$CORPUS" ;; + *) + echo "ERROR: the default corpus path resolved outside fuzz-scratch." >&2 + echo "Remove the symlink or pass the corpus directory explicitly." >&2 + exit 1 + ;; + esac + mkdir -p "$CORPUS" +fi +ZIP="$SCRATCH/native-corpus-seed.zip" +"$PYTHON" fuzz/build_corpus.py "$ZIP" --data-dir test/bson_corpus +"$PYTHON" -m zipfile -e "$ZIP" "$CORPUS" +rm "$ZIP" +# Seed from the committed corpus and the regression reproducers too: the +# spec seeds, prior discoveries, and a deterministic ASan replay of every +# known bug (setup_tests.py seeds the other runs the same way). +for unit in "$ROOT"/fuzz/corpus/* "$ROOT"/fuzz/regression/*; do + if [ -f "$unit" ]; then + cp "$unit" "$CORPUS/" + fi +done +if [ -z "$(ls -A "$CORPUS")" ]; then + echo "ERROR: no seed corpus built in $CORPUS." >&2 + exit 1 +fi + +# Baseline manifest: capture_corpus.py treats these digests as +# already-known, so only units discovered during the run get captured +# (setup_tests.py writes the same manifest for the atheris runs). +MANIFEST="$(dirname "$CORPUS")/baseline.txt" +for unit in "$CORPUS"/*; do + sha256sum "$unit" +done | awk '{print $1}' > "$MANIFEST" + +# FUZZ_NATIVE=1: the targets read it and skip atheris's own libFuzzer, +# which comes preloaded below. PYTHONMALLOC=malloc: ASan needs per-object +# redzones and pymalloc has none, so the array.array over-reads are +# invisible under pymalloc. detect_leaks=0: LSan reports the targets' +# live objects as leaks (PYTHON-6048). +export FUZZ_NATIVE=1 +export PYTHONMALLOC=malloc +export ASAN_OPTIONS="detect_leaks=0" +ATHERIS_RUNTIME="$($PYTHON -c 'import atheris; print(atheris.path())')/asan_with_fuzzer.so" +export LD_PRELOAD="$ATHERIS_RUNTIME" + +# Write libFuzzer crash artifacts under the scratch dir. +for target in fuzz_decode fuzz_decode_all fuzz_is_valid; do + if [ "$MAX_TIME" -gt 0 ]; then + "$PYTHON" "fuzz/$target.py" "$CORPUS" \ + "-artifact_prefix=$SCRATCH/" \ + "-max_total_time=$MAX_TIME" -max_len=1048576 -print_final_stats=1 + else + # Replay-only (FUZZ_MAX_TIME=0, the PR flow): pass every corpus + # unit as a file argument, so libFuzzer runs each exactly once + # and exits. + "$PYTHON" "fuzz/$target.py" "$CORPUS"/* \ + "-artifact_prefix=$SCRATCH/" + fi +done diff --git a/test/test_fuzz_shared.py b/test/test_fuzz_shared.py new file mode 100644 index 0000000000..4c5a5b94bf --- /dev/null +++ b/test/test_fuzz_shared.py @@ -0,0 +1,132 @@ +"""Tests for the BSON fuzz target helpers (PYTHON-6169).""" + +from __future__ import annotations + +import array +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).parent.parent / "fuzz")) + +import fuzz_shared # type: ignore[import-not-found] + +# The PYTHON-6110 reproducer: a truncated Regex element whose flags string +# starts one byte past the document. +OVERREAD_INPUT = b"\x08\x00\x00\x00\x0b\x61\x00\x00" + + +# Explicit "default" markers: the collection hook auto-marks only unmarked +# modules, so parametrized tests would be deselected by the repo's +# default-marker filter. +@pytest.mark.default +@pytest.mark.parametrize("data", [b"", b"\x08\x00\x00\x00\x00", OVERREAD_INPUT]) +def test_input_views_bytes_by_default(monkeypatch, data): + """Without FUZZ_NATIVE, the only view is the raw bytes.""" + monkeypatch.delenv("FUZZ_NATIVE", raising=False) + views = list(fuzz_shared.input_views(data)) + assert len(views) == 1 + assert type(views[0]) is bytes + assert views[0] == data + + +@pytest.mark.default +@pytest.mark.parametrize("data", [b"", b"\x08\x00\x00\x00\x00", OVERREAD_INPUT]) +def test_input_views_native_adds_sentinel_free_array(monkeypatch, data): + """Also decode through a sentinel-free, exact-sized array under FUZZ_NATIVE=1.""" + monkeypatch.setenv("FUZZ_NATIVE", "1") + views = list(fuzz_shared.input_views(data)) + assert len(views) == 2 + assert type(views[0]) is bytes + assert type(views[1]) is array.array + assert views[1].typecode == "B" + assert views[1].tobytes() == data + # Exact allocation: array.array(bytes) overallocates its buffer, which + # masks short over-reads from ASan. + empty = sys.getsizeof(array.array("B")) + assert sys.getsizeof(views[1]) == empty + len(data) + + +def test_array_view_decodes_like_bytes(): + """Test that bson.decode() accepts an array view like bytes.""" + import bson + + doc = bson.encode({"a": "bc", "b": 123}) + assert bson.decode(array.array("B", doc)) == bson.decode(doc) + + +def test_overread_input_rejected_for_both_views(): + """Reject the PYTHON-6110 reproducer identically through both views.""" + import bson + + for view in (OVERREAD_INPUT, array.array("B", OVERREAD_INPUT)): + with pytest.raises(bson.InvalidBSON): + bson.decode(view) + + +@pytest.fixture +def fuzz_targets(monkeypatch): + """Import the fuzz target modules with a no-op atheris shim.""" + import contextlib + import types + + fake_atheris = types.ModuleType("atheris") + fake_atheris.instrument_imports = contextlib.nullcontext + fake_atheris.instrument_func = lambda func: func + monkeypatch.setitem(sys.modules, "atheris", fake_atheris) + + import fuzz_decode # type: ignore[import-not-found] + import fuzz_decode_all # type: ignore[import-not-found] + import fuzz_is_valid # type: ignore[import-not-found] + + return fuzz_decode, fuzz_decode_all, fuzz_is_valid + + +@pytest.mark.default +@pytest.mark.parametrize( + "data", + [ + b"", + b"\x05\x00\x00\x00\x00", # empty document + OVERREAD_INPUT, + bytes(bytearray(range(256))), # every byte value, all invalid + ], +) +def test_targets_handle_every_view(fuzz_targets, monkeypatch, data): + """Run every target's TestOneInput over both views.""" + monkeypatch.setenv("FUZZ_NATIVE", "1") + fuzz_decode, fuzz_decode_all, fuzz_is_valid = fuzz_targets + + fuzz_decode.TestOneInput(data) + fuzz_decode_all.TestOneInput(data) + fuzz_is_valid.TestOneInput(data) + + +def test_targets_accept_valid_documents_in_native_mode(fuzz_targets, monkeypatch): + """Round-trip a valid document through every view in native mode.""" + monkeypatch.setenv("FUZZ_NATIVE", "1") + fuzz_decode, fuzz_decode_all, fuzz_is_valid = fuzz_targets + + import bson + + data = bson.encode({"a": "bc", "b": 123, "c": [1, 2, 3]}) + fuzz_decode.TestOneInput(data) + fuzz_decode_all.TestOneInput(data) + fuzz_is_valid.TestOneInput(data) + + +def test_regression_files_replay_cleanly(fuzz_targets, monkeypatch): + """Replay every committed reproducer in fuzz/regression/decode__*.""" + monkeypatch.setenv("FUZZ_NATIVE", "1") + fuzz_decode, fuzz_decode_all, fuzz_is_valid = fuzz_targets + + regression = Path(__file__).parent.parent / "fuzz" / "regression" + paths = sorted(regression.glob("decode__*")) + assert paths, "no regression reproducers found" + + for path in paths: + data = path.read_bytes() + fuzz_decode.TestOneInput(data) + fuzz_decode_all.TestOneInput(data) + fuzz_is_valid.TestOneInput(data)