Skip to content

fix(B614): lower confidence for unresolvable weights_only; add torch.jit.load regression coverage - #1441

Open
DevamShah wants to merge 2 commits into
PyCQA:mainfrom
DevamShah:fix-b614-weights-only-fp
Open

DevamShah wants to merge 2 commits into
PyCQA:mainfrom
DevamShah:fix-b614-weights-only-fp

Conversation

@DevamShah

Copy link
Copy Markdown

Summary

Improves the B614 ("unsafe PyTorch load") check on two fronts, both reducing false positives:

  1. Suppress B614 when weights_only is a non-literal expression (a variable, attribute, subscript, call, etc.). When the value cannot be resolved statically, the check now gives the caller the benefit of the doubt rather than emitting a finding — mirroring the existing behaviour of B615 (huggingface_unsafe_download), which uses the same weights_only / non-literal handling.
  2. Regression coverage that torch.jit.load is not flagged (refs B614 False Positive when using torch.jit.load #1293). torch.jit.load uses TorchScript serialization, not pickle, and is correctly outside B614's matched set (torch.load / torch.serialization.load). The example file now documents this so the behaviour reported in B614 False Positive when using torch.jit.load #1293 is locked in by a test fixture.

Problem / motivation

  • Non-literal weights_only (the substantive fix): today torch.load(f, weights_only=flag) is flagged because the check only treats the literal True / "True" as safe. Real code frequently passes weights_only as a computed value (config flag, function arg), and flagging those is a false positive. B615 already solved the identical problem the same way; this brings B614 into line.
  • torch.jit.load (B614 False Positive when using torch.jit.load #1293): users reported B614 firing on torch.jit.load. On current main its qualified name (torch.jit.load) is not in B614's matched set, so it is already not flagged — this PR adds explicit example coverage so that stays true.

Change

  • bandit/plugins/pytorch_load.py: when the matched call (torch.load / torch.serialization.load) passes weights_only as a non-ast.Constant value, return without a finding. The existing weights_only == True/"True" safe-path and the genuine-unsafe path are unchanged. Uses the same context._context.get("call") keyword-inspection idiom as the merged B615 plugin.
  • examples/pytorch_load.py: adds non-triggering cases — torch.jit.load (with and without map_location) and a non-literal weights_only — alongside the existing genuinely-unsafe calls.

Trade-off (intentional, precedented)

Suppressing on a non-literal weights_only means torch.load(f, weights_only=flag) where flag is False at runtime will not be flagged (a false negative). This matches B615's deliberate "benefit of the doubt" stance for unresolvable arguments — favouring precision over recall for low-confidence static cases. The version-aware behaviour also requested in #1293 (treating weights_only as defaulting to True on torch ≥ 2.6) is intentionally out of scope here and left for a follow-up, since it requires version detection.

Testing / validation

  • tests/functional/test_functional.py::FunctionalTests::test_pytorch_load passes with the unchanged expectation (MEDIUM: 3, HIGH: 3) — the added cases correctly yield zero new findings.
  • Direct run on examples/pytorch_load.py: B614 fires only on the three genuinely-unsafe torch.load calls; it does not fire on torch.jit.load or the non-literal weights_only case.
  • Adjacent functional tests pass; no regressions.

@DevamShah

Copy link
Copy Markdown
Author

Re-verified this against current main today, since it has been sitting a while.

Branch state. Head 49b2147 sits directly on top of main at f8b9f1a ("Bump docker/login-action from 4.5.1 to 4.6.0", #1466) — no conflicts, no rebase needed. Nothing has touched B614 on main since 765f00d ("Limit B614 to torch.load deserializers", #1348), so the change still applies cleanly.

The false positive, minimal repro. weights_only passed as anything other than a literal is flagged, because the check only accepts the literal True/"True" as safe:

import torch

def load_checkpoint(path, weights_only=True):
    return torch.load(path, weights_only=weights_only)

On main (f8b9f1a):

>> Issue: [B614:pytorch_load] Use of unsafe PyTorch load
   Severity: Medium   Confidence: High
   Location: b614_repro.py:4:11

On this branch: No issues identified.

Precedent. This is the same defect and the same fix that #1358 ("Fix B615 false positive when revision is set via variable", 8f2f928) landed for huggingface_unsafe_download — inspect the raw AST keywords, and if the value is not an ast.Constant, give the caller the benefit of the doubt rather than treating unresolvable as missing. B614 has the identical gap for weights_only. One deliberate difference: I read the keywords off the public Context.node property (bandit/core/context.py:101) rather than context._context.get("call") as B615 does.

Behaviour matrix I actually ran (bandit -t B614 on this branch):

call result
torch.load(f, weights_only=cfg["wo"]) not flagged (was flagged on main)
torch.load(f, weights_only=cfg.safe) not flagged (was flagged on main)
torch.load(f, weights_only=False) flagged
torch.load(f, **kwargs) flagged
torch.load(f, weights_only=True) not flagged

The suppression is scoped to an explicit non-literal weights_only= keyword only — **kwargs and literal False are untouched. The trade-off is stated in the PR description: weights_only=flag where flag is False at runtime becomes a false negative, matching B615's stance.

Tests. python -m pytest tests/ -q: 274 passed on this branch, and 274 passed on main at f8b9f1a — identical, no regressions. examples/pytorch_load.py still yields exactly 3 findings (lines 10, 18, 22), unchanged from main, so the added example cases produce zero new findings. black --check --line-length=79 --target-version=py38 and flake8 are clean on bandit/plugins/pytorch_load.py. Local runs were on CPython 3.14.5, not the py310 tox target, so they are not a substitute for CI.

On torch.jit.load / #1293. To be precise about what this PR does and does not do: torch.jit.load is already not flagged on current main — #1348 narrowed B614's matched set to torch.load / torch.serialization.load, which excluded it. So that half of the PR is regression coverage only, pinning the behaviour in examples/pytorch_load.py so it cannot silently regress. The version-aware part of #1293 (treating weights_only as defaulting to True on torch >= 2.6) is still open and out of scope here.

Why it shows as blocked. mergeStateStatus is BLOCKED purely because reviewDecision is REVIEW_REQUIRED — no failing check and no conflict. readthedocs and pre-commit.ci are both green. The "Build and Test Bandit" and "Dependency Review" runs are sitting in action_required, waiting on a maintainer to approve the workflow run for the fork.

@ericwb — you reviewed and merged both #1348 (the B614 scoping) and #1358 (this exact fix for B615), so you have the most context here. Would you approve the workflow run and take a look? Happy to split the torch.jit.load example coverage into its own PR if you would rather keep the behavioural change isolated.

@noqt noqt left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NOQT independently tested current head 49b2147. There's a blocking false-negative regression in the new non-literal early return.

unsafe_flag = False
torch.load("model.pt", weights_only=unsafe_flag)

def load(path, weights_only=False):
    return torch.load(path, weights_only=weights_only)

Unchanged base f8b9f1a reports B614 at both call sites; this head reports neither. In a four-case probe containing those two unsafe cases plus matching True controls, base reported four findings and this head reported zero. So the change doesn't just avoid uncertain false positives—it also suppresses values that are locally and demonstrably unsafe.

Please keep the useful torch.jit.load regression, but don't treat every non-ast.Constant value as safe. The existing finding could remain; if precision is the goal, lower confidence for unresolved expressions or resolve simple assignments/defaults, and add both unsafe cases as regressions.

The targeted B614 functional test passes. The full functional module is 77/79 on both head and base with the same two Windows-only fixture failures; plugin flake8 and git diff --check pass. Minor: examples/pytorch_load.py:43 also adds E302 (one blank line before a top-level function instead of two).

B614 treated only a literal weights_only=True as safe, so
torch.load(path, weights_only=flag) was reported at HIGH confidence even
though nothing about the value is known statically.

An earlier revision of this change suppressed the finding entirely when
weights_only was a non-ast.Constant expression, following B615. That was
wrong: unlike B615's revision pin, weights_only is a boolean whose unsafe
value is frequently a local literal, so suppressing every non-constant
also silenced demonstrably unsafe calls such as

    unsafe = False
    torch.load(path, weights_only=unsafe)

Instead, keep reporting the call but drop its confidence from HIGH to
MEDIUM when weights_only is present and not an ast.Constant. No finding
is lost, and callers who do not want statically unresolvable results can
filter them with --confidence-level high. Calls with a literal
weights_only, with **kwargs, or with no weights_only at all keep HIGH
confidence.

Also adds example coverage that torch.jit.load (TorchScript, not pickle,
and outside B614's matched set since PyCQA#1348) is not flagged, pinning the
behaviour reported in PyCQA#1293.

Refs PyCQA#1293

Signed-off-by: devamshah <devamshah91@gmail.com>
@DevamShah
DevamShah force-pushed the fix-b614-weights-only-fp branch from 49b2147 to 2434052 Compare September 18, 2026 07:17
@noqt asked for both of his shapes as regressions. The shapes were right
but the values weren't: a name bound to bool(models) and a parameter
defaulting to True are not what he reported. Use his values -- a name
bound to False, and a parameter defaulting to False.

B614 does no dataflow, so the call site sees an ast.Name and an
ast.Name either way and both stay at MEDIUM confidence. Findings are
unchanged: five, three at HIGH and two at MEDIUM, matching the existing
test expectation.

Signed-off-by: devamshah <devamshah91@gmail.com>
@DevamShah

Copy link
Copy Markdown
Author

You're right, and thanks for actually running it — same numbers here, four findings on base and zero on that head. The B615 parallel I leaned on doesn't hold up. A revision pin is normally something you compute or look up, so benefit of the doubt is fair there, but weights_only is a boolean whose dangerous value is very often a literal sitting a few lines above the call, and treating every non-constant as safe threw that away.

Rewritten to keep the finding and only drop its confidence from HIGH to MEDIUM when weights_only is present and isn't an ast.Constant. Nothing is lost, and anyone who doesn't want unresolved results can filter with --confidence-level high. Your two cases are in examples/pytorch_load.py verbatim now — a name bound to False, and a parameter defaulting to False — and both come back flagged. The jit.load regression coverage stayed, and the E302 is gone.

Rebased onto 1d3053d. bandit -t B614 on the examples file gives five findings, three at high confidence and two at medium, which is what the functional expectation asserts; test_functional is 79/79 here on CPython 3.14, so I still can't say anything useful about your two Windows-only fixture failures. Retitling the PR too — it still says "suppress", which isn't what it does any more.

@DevamShah DevamShah changed the title fix(B614): suppress false positive on non-literal weights_only; add torch.jit.load regression coverage fix(B614): lower confidence for unresolvable weights_only; add torch.jit.load regression coverage Sep 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants