Every Python codebase has that one diff nobody wants to review: a new subprocess.Popen call that quietly grew a shell=True, a yaml.load() on a requests payload, an API token pasted straight into a test fixture. Code review catches some of it, but the failure mode is always the same — the reviewer sees a working feature and the risk hides inside a call whose signature they half-remember. Bandit exists to make that failure mode mechanical: it re-parses your Python into an AST, walks every node, and fires a targeted check the instant a call shape matches a known-dangerous pattern. It is the security gate behind a large share of Python CI setups, and its finding IDs (B101 for assert, B506 for yaml.load, B602 for subprocess with a shell) have become shorthand in review comments.

The project describes itself in one line in setup.cfg: “Security oriented static analyser for python code.” That brevity hides a genuinely interesting architecture. Bandit is not a giant pile of regexes. It is a small core — a visitor, a tester, a test registry — surrounded by dozens of independent plugin functions that are discovered at runtime through setuptools entry points, the same mechanism pip uses to expose console scripts. Understanding how those pieces connect makes the tool far more usable: you stop guessing why a check fired and start writing profiles and #nosec annotations with confidence.

This tour reads the source of PyCQA/bandit on its default main branch, following one file from entry to exit. The two diagrams below were generated from that tree: an overview of the moving parts, then a detail view of the rule-selection and execution machinery.

Bandit overview architecture: CLI, config, extension loader, manager, node visitor, test set, tester, plugins, blacklists, metrics and formatters

Overview of a bandit run: the CLI loads config and the extension manager, the manager walks files with an AST visitor, and matched plugin checks emit issues for the formatters.

Reading the overview from left to right:

  • main(), L134 — the 701-line CLI entry point that parses targets, severity and confidence thresholds, and the formatter choice before anything else runs.
  • BanditConfig, L25 — configuration loader that accepts YAML via yaml.safe_load or TOML from a tool.bandit table and exposes dotted get_option lookups.
  • Manager, L13 — wraps three stevedore ExtensionManager namespaces (bandit.plugins, bandit.formatters, bandit.blacklists) into one module-global MANAGER.
  • BanditManager, L32 — the orchestrator: file discovery, per-file parsing, #nosec tokenization, and final metric aggregation.
  • BanditTestSet, L14 — filters the plugin universe down to the active profile and indexes checks by AST node type.
  • BanditNodeVisitor, L16 — the AST walker that stamps parent/sibling links on nodes and dispatches typed visits.
  • BanditTester, L17 — runs the checks registered for the current node type and converts their return values into Issue objects.
  • subprocess_popen_with_shell_equals_true, L110 — one of six shell-injection checks (B602–B607) that share a single config block.
  • Issue, L79 — the finding record: severity, confidence, test id, column offsets and a CWE reference.

The detail diagram zooms into the middle of that flow, where most of the design actually lives.

Bandit detail architecture: file discovery, nosec tokenization, AST dispatch, test selection, plugin execution and reporting

Detail view: how manager.py drives the visitor, how the test set indexes checks by node type, and where the blacklist data tables plug in.

Why bandit parses instead of greps

A regex scanner has one fatal flaw: Python names are relative. yaml.load(d) is dangerous, but so is y.load(d) after import yaml as y, or load(d) after from yaml import load. BanditNodeVisitor.process solves this the honest way: it calls ast.parse(data) at L285 and hands the tree to generic_visit at L238, which recursively stamps every child with two private attributes — _bandit_parent and _bandit_sibling — so checks can inspect surrounding syntax without re-parsing.

The name-resolution machinery lives in the import visitors. visit_ImportFrom at L113 records every alias mapping, including the non-aliased case, so that from yaml import load still resolves load to the qualified name yaml.load. visit_Call at L80 then resolves each call’s qualified name through those aliases before running any checks registered for Call nodes. If you have ever wondered why bandit flags an obfuscated call that a linter missed, this alias table is the reason. The whole approach is possible because bandit builds on the cpython ast module — the same token stream the interpreter itself would consume.

The plugin contract: three decorators and an entry point

Every check is a plain function with up to three decorators from bandit/core/test_properties.py. checks() at L12 declares which AST node type the function wants (Call, Str, Assert, Import, FunctionDef, or the special File for whole-file checks). test_id() at L53 assigns the B-number users see in output, and takes_config() at L31 declares that the function receives a config block. accepts_baseline() at L67 marks formatters that can display baseline diffs.

The decorators feed directly into BanditTestSet._load_tests at L88, which appends each function into a dict keyed by node type. At scan time get_tests at L108 is a single dictionary lookup — there is no re-filtering per node. BanditTester.run_tests at L26 wraps the node context in a Context object (L48) and invokes the function, passing the config block only when the plugin declared one.

The plugin catalogue is worth studying as design. bandit/plugins/general_hardcoded_password.py splits one risk across three checks by AST shape: hardcoded_password_string (B105, L30) for Str literals, hardcoded_password_funcarg (B106, L150) for keyword arguments, and hardcoded_password_default (B107, L210) for function defaults — all matching against a shared RE_CANDIDATES regex at L13 that looks for names like passwd, token and secret. Compare that with assert_used (B101, L70), a one-function check on Assert nodes, and yaml_load (B506, L51). Same contract, wildly different amounts of logic.

From blacklist tables to a synthetic B001 plugin

Not every rule needs code. The bandit/blacklists/ package is two data tables: calls.py bans dangerous callables — eval (B307), pickle.loads (B301), hashlib.md5 (B303), urllib.urlopen (B310), random (B311), the whole XML family (B313–B320) — and imports.py bans dangerous modules — telnetlib (B401), pickle (B403), subprocess (B404), pycrypto (B413). Both expose a gen_blacklist() factory (calls.py L346, imports.py L234) loaded through the bandit.blacklists entry-point namespace.

The elegant trick is in BanditTestSet._load_builtins at L59: the blacklist entries are dressed up to look like an ordinary plugin by setting blacklisting.blacklist._test_id = "B001" alongside its _checks and _config at L82. Profile semantics get the same treatment — _get_filter at L27 expands a bare B001 in an include or exclude list to all blacklist IDs, preserving backwards compatibility documented in the comment at L37. Scoring then flows through constants.RANKING_VALUES at L9 — findings weigh UNDEFINED as 1, LOW 3, MEDIUM 5, HIGH 10 — accumulated per file by BanditTester at L99.

From decorators to distribution: the extension build

The deployment story is as instructive as the scan story. Bandit builds with pbr from a declarative setup.cfg, and its [entry_points] section is the real wiring diagram: three console scripts (bandit, bandit-config-generator, bandit-baseline at L47), two blacklist factories (L51), nine formatters — csv, json, txt, xml, html, sarif, screen, yaml, custom (L54) — and 42 plugin checks across 31 modules in bandit/plugins/ (L64). Because these are standard entry points, anything installed through pip — bandit itself or a third-party plugin package — is automatically visible to the extension loader.

The loader caches aggressively. extension_loader.py builds one MANAGER object at L114 and stores it as a module global, with a comment explaining why: entry-point discovery through pkg_resources is expensive, so it should happen exactly once per process. Plugin functions must carry _test_id or they are skipped with a warning (load_plugins at L37), which keeps a broken third-party plugin from crashing every scan. Formatters are selected from the same manager; the SARIF formatter alone is 374 lines, emitting the OASIS format that GitHub code scanning ingests. The orchestration side shows similar pragmatism: manager.py (499 lines) imports rich.progress and only renders a progress bar above PROGRESS_THRESHOLD = 50 files (L29, L273).

If you want to compare designs, this is the sharpest contrast with mypy: both walk the same AST, but mypy builds a type graph to reason about correctness, while bandit keeps only aliases and namespaces — a deliberately stateless design that makes plugins trivially isolated.

nosec, profiles and the baseline trick

The escape hatch is engineered as carefully as the checks. _parse_file at L301 runs tokenize over COMMENT tokens (L313) building a dict of line number to skipped test IDs, matched against the NOSEC_COMMENT regex at L27. Both bare # nosec and targeted # nosec B602 work, and BanditTester distinguishes them in its metrics: blanket suppression counts through note_nosec (L46 in metrics.py), targeted ones through note_skipped_test (L54) — so a rising nosec count is visible in the report instead of silently erasing findings.

Profiles are pure config: BanditConfig.get_option at L84 resolves dotted paths, _get_profile at L111 merges named profiles with --tests and --skips. The baseline workflow is the neatest trick: bandit/cli/baseline.py runs bandit twice via subprocess.check_output — once writing JSON to a temp file (L88), once with -b against it (L93) — and filter_results at L105 only reports files whose finding count changed, sidestepping unreliable line-number diffs.

Honest Limits

Bandit is a per-node checker, not a taint tracker. It knows eval(x) is dangerous; it cannot tell whether x is attacker-controlled three functions upstream. There is no cross-file data-flow analysis — context.py deliberately exposes only what one node and its alias table can answer. Severity and confidence are heuristic labels assigned per check, so B101 (assert) is LOW severity but appears in nearly every test suite; expect to profile it out rather than fix every instance. The blacklist model stops at the import/call level — import subprocess (B404) fires on a module most code legitimately needs, which is why it is LOW and often ignored. Line numbers drift with edits, which is exactly why the baseline mode counts findings per file instead of matching them. And the corpus of ninety-odd hand-written vulnerable snippets under examples/ doubles as the functional test fixture, so plugin behavior is only as good as those examples. None of this makes bandit weak — it makes it fast enough to run on every commit, which is the property that actually matters for a security gate. Treat it as the cheap first filter that catches the fifty classic Python footguns, and pair it with deeper analysis only where the threat model demands it.

Watch PyShine on YouTube

Contents