Rules reference#
Each rule has:
- A code, short identifier like
SAFE101, shown in the output. Use this to search docs or issues. - A name, the key used in config files.
- An enabled flag, set to
falseto turn the rule off. - A severity,
"error"blocks the commit;"warning"is informational. - A language scope, most rules apply to Python, JavaScript, and TypeScript; a few are language-specific (see below).
- Rule-specific options documented below.
For top-level config keys (mode, ignore, per_file_ignores, …) see the Configuration file. For inline / file-level suppression see Suppression mechanisms. JavaScript projects may also want to set a runtime preset so rule defaults match the deployment target (browser / Deno / Cloudflare Workers / Bun).
Language coverage#
Currently supported#
- Python (
.py,.pyw). Per-framework defaults (taint sinks, nullable methods, and which of the sharedSAFE905-909framework rules are active) are switchable via the[tool.safelint.python] framework = "..."preset (vanilla/django/flask/fastapi), with an orthogonalpydantic = trueaxis. - JavaScript (
.js,.mjs,.cjs), source analysis is runtime-agnostic and runs identically against Node.js, browser, Deno, Cloudflare Workers, Bun, and any WASM-hosted JS engine (QuickJS-WASM, Boa, etc.). Per-runtime defaults (the lists of tracked acquirers, sinks, sources, global namespaces, etc.) are switchable via the[tool.safelint.javascript] runtime = "..."preset, the source-language rules themselves don't change. - TypeScript (
.ts,.tsx), and AssemblyScript (.as, TypeScript-syntax language compiling to WebAssembly, parsed by the same grammar). Reuses the JavaScript rule implementations end-to-end (TS compiles to JS at runtime; AST is a superset), with TS-specific handling for type-only constructs the JS rules wouldn't otherwise recognise (generic type parameters,ascasts, non-null assertions,declare globalambient declarations, etc.). Shares the JavaScript runtime presets, TS doesn't get its own runtime config because TS source executes in the same runtimes JS does. See TypeScript for the full language reference. - Java (
.java), new in v2.1.0. 20 rules apply (the 15 cross-language core plus the 5 also registered for Python / JS / TS) plus 4 Spring Boot framework-specific structural rules (SAFE901-904) target Spring annotation patterns. Per-framework defaults (sinks, nullable methods, structural rule enablement) are switchable via the[tool.safelint.java] framework = "..."preset (vanilla/spring-boot). See Java for the full language reference. - Rust (
.rs), new in v2.2.0. 15 of the cross-language rules port cleanly plus 11 Rust-only rules cover Rust-idiom-specific patterns (panic-in-non-test, lock poisoning,unsafeblock documentation, truncatingascasts, silentErrarms, dangerousmem::*ops, needlessmut, unchecked arithmetic on integer parameters, broad.unwrap()outside tests, interior-mutablestatics, plus the empty-Err/ unlogged-ErrRust analogues ofempty_except/logging_on_error). 7 rules deliberately skipped for Rust because their semantics don't translate cleanly (Rust has no try/catch /globalkeyword, RAII / Drop covers resource cleanup, and macros are opaque to the rule-8 dynamic-execution check). Recognises both inline#[cfg(test)] mod testsand Cargotests/<stem>.rsintegration-test conventions. See Rust for the full language reference. - Go (
.go), new in v2.5.0. 17 cross-language rules apply (the 14 all-language core plus SAFE302 / SAFE309 / SAFE401, which Go shares with Python / JS / TS / Java / PHP but Rust skips) and 2 Go-only rules cover Go-idiom patterns: SAFE209 (empty_error_check, the emptyif err != nil {}swallow) and SAFE211 (panic_calls_outside_tests). SAFE601 (missing_assertions) was registered for Go in v2.16.0: Go has no production assertion idiom, so the rule only makes sense there as the "tests must assert something" guard thattest_functions_onlynow gives by default, counting the*testing.Tfailure API and testify by receiver. 6 rules deliberately skipped for Go because their semantics don't translate cleanly (no try/catch, noglobalkeyword, novarhoisting, no chained-nullable idiom). Headline Go adaptations: the barefor {}infinite loop (SAFE501), the siblingfoo_test.goconvention (SAFE701 / SAFE702), the_ = f()explicit-discard exemption (SAFE802), and thedefer x.Close()resource form (SAFE401). See Go for the full language reference. -
PHP (
.php), new in v2.6.0. 21 rules apply and only 2 are skipped (SAFE201bare_exceptand SAFE305wide_scope_declaration), the widest rule coverage of any non-Python language because PHP ports the largest share of the existing rule set. PHP is the first non-Python home for SAFE301 (global_state): PHP has a literalglobalkeyword, so the rule fires onglobal $config;-style declarations exactly as it does on Python. PHP also has try/catch (SAFE202 / SAFE203 apply),evaland dynamic-call surfaces (SAFE309), and resource lifecycles (SAFE401). Headline PHP highlights: the@-operator error-suppression idiom, superglobal taint sources ($_GET/$_POST/$_REQUEST/ etc.) feeding SAFE801, and thebreak N;/continue N;multi-level loop forms. Per-framework defaults are switchable via the[tool.safelint.php] framework = "..."preset (vanilla/laravel), which enables the sharedSAFE905-909framework rules. See PHP for the full language reference. -
C (
.c,.h), new in v2.7.0. Holzmann's original target language. 21 rules apply: the 16 cross-language ports plus 5 new C-family rules (the "homecoming", shared with C++) that express clauses every other language adapts away - SAFE106 (nonlocal_jumps,goto/setjmp), SAFE310 (dynamic_allocation, themallocfamily), SAFE311 (complex_macro) and SAFE312 (conditional_compilation) for the preprocessor, and SAFE313 (restricted_pointers). SAFE106 is the only one enabled by default (warning severity, becausegoto errcleanup is idiomatic); the other four are opt-in..hheaders are linted as C. 7 rules are skipped: SAFE201/202/203, SAFE301 and SAFE305 (semantics don't translate) plus SAFE401 and SAFE803 (documented gaps - C cleanup and nil analysis need flow analysis). See C for the full language reference. - C++ (
.cpp,.cxx,.cc,.hpp,.hxx,.hh), new in v2.8.0. Builds on C: the five C-family rules widen to C and C++, plus C++ gains itstry/catch/throwrules (SAFE201 catch-all, SAFE202, SAFE203) and two new C++-only rules - SAFE315 (raw_new_delete) and SAFE316 (dangerous_casts). 26 rules apply. Plain.hheaders are linted as C; use.hpp/.hxx/.hhfor C++ headers. See C++ for the full language reference.
Planned#
No languages are currently on the near-term roadmap. SafeLint's registry-driven architecture (see Adding a language) makes each new language incremental, community contributions are welcome.
Rule scope (current languages)#
| Scope | Count | Codes |
|---|---|---|
| Cross-language (all nine: Python, JavaScript, TypeScript, Java, Rust, Go, PHP, C, C++) | 14 | SAFE101, SAFE102, SAFE103, SAFE104, SAFE105 (no_recursion), SAFE303, SAFE304, SAFE501, SAFE601 (missing_assertions, Go added in 2.16.0), SAFE603 (blanket_suppression), SAFE701, SAFE702, SAFE801, SAFE802 (apply to all nine). |
| Python / JS / TS / Java / Rust / PHP (not Go, not C, not C++) | 1 | SAFE803 (null_dereference); no chained-nullable idiom in Go, and C / C++ nil analysis needs flow analysis (documented gap). |
| Python / JS / TS / Java / Go / PHP / C / C++ (not Rust) | 2 | SAFE302 (global_mutation), SAFE309 (dynamic_code_execution). Rust's analogues are SAFE307 + SAFE602 (mutable statics) and an opaque token-tree limitation for rule 8. C / C++ fire on file-scope (and, for C++, namespace-scope) mutable declarations (SAFE302) and dlopen / dlsym (SAFE309). |
| Python / JS / TS / Java / Go / PHP (not Rust, not C, not C++) | 1 | SAFE401 (resource_lifecycle). Rust and C++ use Drop / RAII; C cleanup (goto err, explicit fclose / free) needs flow analysis the rule does not do (documented gap - allocation discipline is C's SAFE310, C++'s is SAFE310 / SAFE315). |
| Python / JS / TS / Java / PHP / C++ (not Rust, not Go, not C) | 2 | SAFE202 (empty_except), SAFE203 (logging_on_error). C++ gains try / catch; C has no try/catch. Neither Rust nor Go has try/catch; Rust's analogues are SAFE206 / SAFE207, and Go's empty-if err != nil swallow is covered by SAFE209. |
| Python + PHP | 1 | SAFE301 (global_state); both have a literal global keyword, JS / TS / Java / Rust / Go / C / C++ do not. |
| Python + C++ | 1 | SAFE201 (bare_except); Python's bare except: and C++'s catch (...) catch-all. JS / TS / Java catches always bind the error, and Rust / Go / PHP / C have no bare-catch equivalent. |
| JavaScript-family-only (JS and TS) | 1 | SAFE305 (wide_scope_declaration); Python / Java / Rust / Go / PHP have no var / let / const distinction. |
| Java + Spring Boot only | 4 | SAFE901 (spring_field_injection), SAFE902 (spring_missing_transactional), SAFE903 (spring_unvalidated_input), SAFE904 (spring_async_checked_exception); all default-disabled under vanilla, default-enabled by the spring-boot framework preset. |
| Python / PHP framework presets only | 5 | SAFE905 (debug_mode_enabled), SAFE906 (mass_assignment), SAFE907 (unvalidated_request_input), SAFE908 (csrf_protection_disabled), SAFE909 (hardcoded_secret); all default-disabled, enabled by the Python / PHP framework presets (Django / Laravel enable all five; Flask enables SAFE905 + SAFE907 + SAFE909; FastAPI enables SAFE905 + SAFE907; pydantic = true enables SAFE906). The non-Java analogue of the Spring SAFE9xx rules. |
| Rust-only | 11 | SAFE110 (needless_mut), SAFE112 (unchecked_arithmetic_on_input), SAFE204 (panic_macros_outside_tests), SAFE205 (lock_poisoning_ignored), SAFE206 (silent_result_discard, the Rust analogue of SAFE202), SAFE207 (unlogged_error_branch, the Rust analogue of SAFE203), SAFE208 (result_unwrap_outside_tests), SAFE306 (dangerous_mem_ops), SAFE307 (interior_mutable_static), SAFE308 (truncating_as_cast), SAFE602 (undocumented_unsafe); all default-disabled. |
| Go-only | 2 | SAFE209 (empty_error_check, the Go analogue of SAFE206), SAFE211 (panic_calls_outside_tests, the Go analogue of SAFE204); both default-disabled. |
| C-family (C and C++) | 5 | SAFE106 (nonlocal_jumps, goto / setjmp; enabled at warning severity), SAFE310 (dynamic_allocation; on C++ also new / delete), SAFE311 (complex_macro), SAFE312 (conditional_compilation), SAFE313 (restricted_pointers; smart pointers exempt on C++); the last four default-disabled. The Power-of-Ten clauses (rules 1, 3, 8, 9) every other language adapts away. |
| C++-only | 2 | SAFE315 (raw_new_delete), SAFE316 (dangerous_casts); both default-disabled. Modern-C++ ownership / type-safety idioms (3xx band). |
The engine's per-language dispatch automatically skips rules whose language tuple doesn't include the active file's language. There's no manual configuration to do, drop a .py file in a JS / TS project (or vice versa) and the right rules fire on each.
At a glance#
The table below is generated from the live rule registry (safelint.rules.ALL_RULES) and the per-rule defaults in safelint.core.config.DEFAULTS, it can't drift from the implementation. Click any code to jump to the detailed section below.
| Code | Name | Default severity | Enabled by default |
|---|---|---|---|
SAFE101 |
function_length |
error | yes |
SAFE102 |
nesting_depth |
error | yes |
SAFE103 |
max_arguments |
error | yes |
SAFE105 |
no_recursion |
warning | yes |
SAFE201 |
bare_except |
error | yes |
SAFE202 |
empty_except |
error | yes |
SAFE301 |
global_state |
warning | yes |
SAFE302 |
global_mutation |
error | yes |
SAFE305 |
wide_scope_declaration |
warning | yes |
SAFE501 |
unbounded_loops |
warning | yes |
SAFE104 |
complexity |
error | yes |
SAFE303 |
side_effects_hidden |
error | yes |
SAFE304 |
side_effects |
warning | yes |
SAFE309 |
dynamic_code_execution |
warning | no |
SAFE203 |
logging_on_error |
warning | yes |
SAFE401 |
resource_lifecycle |
error | yes |
SAFE702 |
test_coupling |
warning | no |
SAFE701 |
test_existence |
warning | no |
SAFE601 |
missing_assertions |
warning | no |
SAFE603 |
blanket_suppression |
warning | no |
SAFE801 |
tainted_sink |
error | no |
SAFE802 |
return_value_ignored |
warning | no |
SAFE803 |
null_dereference |
error | no |
SAFE901 |
spring_field_injection |
warning | no |
SAFE902 |
spring_missing_transactional |
error | no |
SAFE903 |
spring_unvalidated_input |
error | no |
SAFE904 |
spring_async_checked_exception |
warning | no |
SAFE905 |
debug_mode_enabled |
warning | no |
SAFE906 |
mass_assignment |
error | no |
SAFE907 |
unvalidated_request_input |
warning | no |
SAFE908 |
csrf_protection_disabled |
error | no |
SAFE909 |
hardcoded_secret |
error | no |
SAFE110 |
needless_mut |
warning | no |
SAFE112 |
unchecked_arithmetic_on_input |
warning | no |
SAFE204 |
panic_macros_outside_tests |
warning | no |
SAFE205 |
lock_poisoning_ignored |
warning | no |
SAFE206 |
silent_result_discard |
warning | no |
SAFE207 |
unlogged_error_branch |
warning | no |
SAFE208 |
result_unwrap_outside_tests |
warning | no |
SAFE306 |
dangerous_mem_ops |
error | no |
SAFE308 |
truncating_as_cast |
warning | no |
SAFE602 |
undocumented_unsafe |
warning | no |
SAFE307 |
interior_mutable_static |
warning | no |
SAFE209 |
empty_error_check |
warning | no |
SAFE211 |
panic_calls_outside_tests |
warning | no |
SAFE106 |
nonlocal_jumps |
warning | yes |
SAFE310 |
dynamic_allocation |
warning | no |
SAFE311 |
complex_macro |
warning | no |
SAFE312 |
conditional_compilation |
warning | no |
SAFE313 |
restricted_pointers |
warning | no |
SAFE315 |
raw_new_delete |
warning | no |
SAFE316 |
dangerous_casts |
warning | no |
Engine-internal codes#
A few codes are emitted by the engine directly rather than by registered BaseRule subclasses. They don't have their own config section and follow the global ignore list. Inline # nosafe: SAFE0xx works for codes emitted after parsing (such as SAFE004, see below) but not for SAFE000, because parse errors are raised before the engine has a chance to read suppression directives off the tree.
SAFE000: parse#
What it flags: Tree-sitter parse errors (syntax errors, broken indentation, missing tokens). The violation carries the offending token's column as a zero-width caret so editors can mark the precise location.
Always severity error. Cannot be configured per-rule.
On C and C++ the message names the preprocessor instead of advising you to check syntax. safelint parses the source as written, so an #ifdef spanning part of a construct or a macro standing in for a declarator is unparseable even though the file compiles; on four real projects this is 25-54% of files, and each one is dropped from every other rule. The generic "check syntax near this location" would be a false accusation at that rate. See Parse coverage: the preprocessor limit for the measurements and what to do about it. (Since 2.17.2.)
Inline # nosafe: SAFE000 does not work. Parse errors are raised by SafetyEngine._lint_parsed_source before it parses inline suppression directives off the Tree-sitter tree (see the early-return at the parse-error check). The only way to silence SAFE000 is the global ignore list, which is read at engine init from your config file:
Use this when you genuinely don't want parse errors surfaced (rare, usually you do want to know when a file failed to parse).
SAFE004: unused_suppression (added in 1.8.0)#
What it flags: A # nosafe directive on a line where no violation actually fired, i.e. the suppression is stale (e.g. left over after a refactor that removed the offending code).
Severity is fixed at warning. Disable globally via ignore = ["SAFE004"] if your workflow involves many transient suppressions you'd rather not police. Per-file ignores do not apply to SAFE004: like SAFE000, it's an engine-internal code gated solely on the global ignore list (configuring it inside per_file_ignores will surface a typo-guard warning and otherwise do nothing). Self-referential # nosafe: SAFE004 is special-cased; a directive that only mentions SAFE004 is always considered "used" to avoid recursion.
Test code is skipped by six rules#
Changed in 2.15.0 (#198), extended in 2.17.0 (#208). Six rules skip files they recognise as test code: SAFE101 function_length, SAFE203 logging_on_error, SAFE302 global_mutation, SAFE304 side_effects, SAFE401 resource_lifecycle and, since 2.17.0, SAFE901 spring_field_injection. The first five are enabled by default and SAFE901 is enabled by the spring-boot preset, so this changes what an untuned run reports.
The reason is measured rather than aesthetic. Those six put the overwhelming majority of their findings in test files, where the pattern they flag is conventional:
# tests/test_requests.py
def test_session():
s = requests.Session() # SAFE401: a session scoped to one test
print(render(result)) # SAFE304: observing output IS the test
On Requests that shape was 91 of SAFE401's 94 findings, and the three in library code - including a genuine unclosed zipfile.ZipFile in utils.py - were buried under them. A rule users learn to ignore protects nothing.
SAFE901 joined on the same evidence and is the starkest case of it: on Spring PetClinic, written by the Spring team as the reference example, all 17 of its findings were in test classes, 63% of the project's whole default output, and field injection in a test is what Spring's own documentation and samples use. See SAFE901 for why the reasoning inverts inside a test.
| Option | Default | Description |
|---|---|---|
skip_test_code |
true |
Skip files recognised as test code |
test_dirs |
["tests", "test", "__tests__", "spec"] |
Directories whose contents are test code, matched as a path-component subsequence |
A file is test code when it is under a test_dirs entry, or its filename uses a convention nothing but a test uses: foo.test.ts / foo.spec.js (JS/TS), FooTest.java / FooTests.java / FooIT.java, FooTest.php, and a _test stem suffix everywhere else - foo_test.go, foo_test.rs, foo_test.py, foo_test.c / foo_test.cpp.
A bare test_ prefix is deliberately not enough. Production modules use it - safelint's own src/safelint/rules/test_coverage.py is a rule implementation, and TestDataFactory.java under src/main/java is a factory - so excluding on it would silently drop six rules on real source files. Python tests are still covered, because tests/test_foo.py matches on the directory. This is stricter than the detection test_functions_only (SAFE601) and SAFE701/702 use, which answer the opposite question and can afford the looser signal.
Turn it off for the strict reading, per rule:
# pyproject.toml
[tool.safelint.rules.resource_lifecycle]
skip_test_code = false
# ... or tell safelint where your tests actually live
[tool.safelint.rules.side_effects]
test_dirs = ["tests", "integration", "examples"]
test_dirs entries are project-root-relative, and the project root is the directory holding your config - discovered by walking up from each file, the same way config itself is resolved. So safelint check /path/to/repo works from anywhere, and a monorepo with per-package configs is anchored per package. With no config discoverable, the working directory is the fallback. An absolute entry is matched as given.
Structural rules#
These check the shape of your functions. They are cheap to run and always go first.
SAFE101: function_length#
What it flags: Functions longer than max_lines (interpreted under the configured count_mode). Cross-language.
Long functions are hard to read, test, and reason about. The Holzmann rule says a function should fit on one printed page.
| Option | Default | Description |
|---|---|---|
enabled |
true |
Turn rule on/off |
severity |
"error" |
"error" or "warning" |
max_lines |
60 |
Maximum allowed function size (units depend on count_mode) |
count_mode |
"lines" |
How to measure size: "lines" (raw source lines incl. blanks/comments, Holzmann's original framing), "logical_lines" (lines minus blanks and pure-comment lines, less game-able), or "statements" (count Python statement nodes, robust to formatting, equivalent to ruff's PLR0915). Added in 1.8.0. |
skip_test_code |
true |
Skip files recognised as test code - see above. Added in 2.15.0. |
test_dirs |
["tests", "test", "__tests__", "spec"] |
Directories treated as test code. Added in 2.15.0. |
[tool.safelint.rules.function_length]
enabled = true
severity = "error"
max_lines = 60
count_mode = "lines" # default; alternatives: "logical_lines", "statements"
When switching to "statements", lower max_lines accordingly, a function with 60 source lines typically corresponds to ~25–35 statement nodes. Pick a value that matches the spirit of "function fits on a page" for your codebase.
SAFE102: nesting_depth#
What it flags: Functions with control-flow nested more than max_depth levels deep. Cross-language.
Deep nesting (if inside for inside if inside while…) makes code hard to follow and test. Two levels is enough for most real functions.
with and try are not nesting levels. The rule exists to keep decisions shallow, and a resource or error-handling wrapper adds indentation without adding a branch:
with open(path) as fh: # depth 0
for row in fh: # depth 1
if row: # depth 2 - clears the default cap
handle(row)
The reason this matters more than tidiness is actionability: a developer told to reduce nesting in with session: for x: if y: has no good move short of restructuring resource handling, which is a worse outcome than the nesting it was flagged for. So the finding was unactionable even where the count was literally correct.
This extends a principle the rule already applied: Java's synchronized block and Rust's unsafe block were never nesting steps, for exactly this reason. Removed in 2.15.0 (#166) from Python (with, try), Java (try, try-with-resources), JavaScript / TypeScript (try), PHP (try) and C++ (try). Rust, Go and C had none to remove, so all nine languages now agree. switch and match remain steps - they branch.
else if is not a nesting level. A flat if / else if / else if chain branches once, so it scores depth 1 in every language:
function f(x) {
if (x === 1) { doA(); }
else if (x === 2) { doB(); }
else if (x === 3) { doC(); } // depth 1, not 3
}
Python and PHP always behaved this way, since their grammars name elif / elseif separately. The other seven languages express the same idea structurally - the continuation if sits under an else_clause, or is the enclosing if's alternative child - and were corrected in 2.15.0. Three shapes still count, because they really are another level: else { if (..) } written with braces, else while (x); (legal C), and a nested if inside an else if body.
| Option | Default | Description |
|---|---|---|
enabled |
true |
Turn rule on/off |
severity |
"error" |
"error" or "warning" |
max_depth |
2 |
Maximum allowed nesting depth of branching constructs (if, for, while, switch / match) |
SAFE103: max_arguments#
What it flags: Functions with more than max_args parameters. Cross-language.
Too many arguments usually means a function is doing too much, or needs a config object. self and cls are excluded from the count. *args and **kwargs each count as one parameter; they bring real callers, just an unbounded number of them, so they cannot be free.
| Option | Default | Description |
|---|---|---|
enabled |
true |
Turn rule on/off |
severity |
"error" |
"error" or "warning" |
max_args |
7 |
Maximum number of parameters (excluding self/cls; *args/**kwargs each count as one) |
SAFE104: complexity#
What it flags: Functions with cyclomatic complexity above max_complexity. Cross-language.
Cyclomatic complexity counts the number of independent paths through a function. It starts at 1 and goes up by 1 for every if, elif, for, while, except, ternary expression, and/or operator, and comprehension condition. A score above 10 means the function has too many possible paths to test reliably.
A match / switch construct adds one, not one per arm. (Since 2.18.0; see #181.) McCabe measures hand-written control flow, and a dispatch table is not that: the arms are value comparisons, or in Rust a compiler-checked exhaustive match, with no fall-through and no ordering dependency. Adding a variant is a compile error rather than a silent gap, so a twenty-arm lookup carries a cognitive load nearer 1 than 20.
Counting each arm made dispatch tables the dominant finding on real code. Measured across two large Rust projects: match_arm alone was 50% of every counted decision point in astral-sh/ty, and 54% of ruff's 656 SAFE104 findings fell to at or under the threshold once arms stopped counting individually, every one of them a lookup table where "split into smaller functions" was not applicable advice.
An arm carrying a guard still adds one, because a guard can fall through to a later arm: exhaustiveness proves nothing about it and the reader has to follow a real condition. That applies to Rust (n if cond =>), Java 21 pattern guards (case Integer i when i > 0) and Python (case X if cond, counted as the ordinary if_clause it parses to). Go, PHP and C arms are value comparisons with no guard form.
This applies uniformly to all nine languages. Before 2.18.0 the behaviour was inconsistent in both directions: Rust, Go, Java, JavaScript, PHP and C counted every arm, while Python counted its match as nothing at all, so the same dispatch table scored 0 in one language and N in another. Python now counts the construct like everywhere else, which makes it marginally stricter.
| Option | Default | Description |
|---|---|---|
enabled |
true |
Turn rule on/off |
severity |
"error" |
"error" or "warning" |
max_complexity |
10 |
Maximum cyclomatic complexity (McCabe score) |
SAFE105: no_recursion#
What it flags: Functions that call themselves directly. Cross-language.
Holzmann's Power of Ten rule 1 ("restrict all code to very simple control flow constructs") bans recursion outright: recursion without a guaranteed bound makes the call stack an unbounded resource, so worst-case depth (and therefore termination and memory behaviour) cannot be proven by inspection. An explicit loop with a worklist makes the bound visible.
The rule fires on direct self-recursion - a function whose body contains a call to its own name, either bare (fact(n - 1)) or self-qualified (self.walk(...) in Python / Rust, this.walk(...) in JS / TS / Java). A call on a different receiver (other.walk(...)) does not fire. In JavaScript and TypeScript the name may come from the const / let / var binding holding a function expression, so const fact = (n) => n * fact(n - 1) reports since 2.17.1 (see below). Indirect / mutual recursion (a calls b calls a) stays out of scope: it needs a call graph.
Enabled by default at warning severity (mirrors unbounded_loops), so intentional recursion (tree walks, divide-and-conquer) does not block a local run. Annotate deliberate recursion with # nosafe: SAFE105 (or the language's comment form) and a one-line justification.
JavaScript and TypeScript: recursion through a binding#
An arrow_function has no name of its own; the name sits on the binding that holds it. Until 2.17.1 the rule matched only the function's own name, so it was silent on the form most of the ecosystem uses to declare a function while firing correctly on function fact() {} beside it:
const fact = (n) => (n <= 1 ? 1 : n * fact(n - 1)); // reports since 2.17.1
function fact(n) { return n <= 1 ? 1 : n * fact(n - 1); } // always reported
Only a variable declarator lends its name to this route, and only for a bare call. The three binding forms look alike and do not behave alike, which is why the distinction is drawn rather than assumed:
| Shape | Bare call | this.-qualified call |
|---|---|---|
const fact = (n) => ... |
reported - a lexical binding, so fact(...) is the function |
not reported - an arrow takes this from the enclosing scope, so this.fact is some other object's property |
{ walk: (n) => ... } |
not reported - an object property is not a lexical binding, so a bare walk(...) cannot reach it; it resolves to an outer binding of that name, or raises ReferenceError if there is none |
not reported - an arrow takes this from the enclosing scope, so the receiver is not the object being built and cannot be shown to be this function |
class T { fact = (n) => ... } |
not reported - nor is a class field a lexical binding, so the same resolution applies as for an object property | genuine recursion, and not yet reported; see the note below |
A class field's this.-qualified recursion is a known gap
class T { fact = (n) => n * this.fact(n - 1) } really does recurse, and the rule does not report it. Reaching it means matching the enclosing class against the receiver, so that a sibling object's this.fact(...) is not mistaken for it; that is a separate piece of work from naming the function. Recorded rather than left to be rediscovered.
The ordinary guards still apply, and they are what keeps the widening honest: a call whose callee is a member access is never a bare call, so const trim = (s) => s.trim() and const getComputedStyle = (el) => window.getComputedStyle(el) stay clean although the names match. A nested binding of the same name shadows the outer one, so const walk = (n) => { const walk = (m) => m; return walk(n); } is clean too. A key that is not statically spelled ({ [walk]: ... }) lends no name at all, since the verdict would rest on a variable whose value is unknown.
Measured across the JavaScript and TypeScript validation corpora: 91 new findings across 35 functions, none removed. The functions are what the rule exists to find, among them mergeDeep (a deep merge whose depth is its input's), hasAdditionalProperties (a recursive JSON-schema walk), Vue's setScopeId and recursiveGetSubtree over the vnode tree, and axios's visit over an arbitrarily nested object. Note the two units: the rule reports one finding per call site, so a function with four self-calls is four findings.
Only JavaScript and TypeScript. Java puts a lambda in a variable_declarator too, and the node type is spelled the same in both grammars, so the route is gated by language rather than left to match for free: a Java lambda cannot call its own variable before the assignment completes, which would be a different claim needing its own evidence.
What counts as "its own name"#
A name match alone is not a self-call, so the rule rules a call out whenever the source text settles the question. These need no type information and so cannot hide genuine recursion:
- A same-named nested function rebinds the name, so a bare call in the enclosing body reaches the nested one (every language). A
self/this-qualified call still fires. - Rust: a bare
name(..)inside animplortraitbody cannot reach the method, which needsself.name()orType::name(..). A function-localuserebinds the name for its enclosing block, souse std::os::unix::fs::symlink;insidefn symlinksilences the bare call within that block (and only within it); anasalias binds the alias, not the path's last segment. - Java: the argument count must fit the signature, with the explicit receiver parameter (
void tick(Outer Outer.this, int n)) discounted since it is never passed, and varargs exempt because a fixed-arity comparison proves nothing there. Beyond arity, two facts rule a call out: an argument cast toObjectwhere the parameter is notObject(remove((Object) array, index)insideremove(boolean[], int), withjava.lang.Objectrecognised as the same type); and an element of the array parameter at that same position, by index or through a for-each variable (append(lhs[i], ..)insideappend(Object[] lhs, ..)).
Overloaded Java methods#
What the source text cannot settle is a call that an overloaded sibling could also accept. Resolving it needs the declared types of the arguments, which means a classpath:
void expectContents(E... elements) { expectContents(asList(elements)); }
void expectContents(Collection<E> expected) { ... }
asList(elements) returns something safelint cannot type, so either method could be the target. safelint reports the call, with a message that says so rather than asserting recursion:
SAFE105 Function "expectContents" calls "expectContents", which is overloaded in this type, so
the target cannot be resolved without type information; if it is this method, recursion
has no guaranteed stack bound (Power of Ten rule 1) - refactor to an explicit loop or
worklist
Dropping these instead would silence genuine recursion in any method that happens to be overloaded, which is the more dangerous error for this rule: real recursion passes plain identifiers and so carries none of the signals above.
The hedge is decided per call, from the argument count: a type holding f(int) and f(int, int) has an overloaded name, but a one-argument call inside f(int) has only one candidate, so that message is unhedged. A varargs sibling counts as a rival for any count from its fixed prefix upwards.
Inheritance is not resolved
Only declarations on the enclosing type are known, so an unhedged message means "no rival in this type", not "no rival anywhere". A same-named method inherited from a superclass can also win resolution; seeing that would need the supertype's source, which again means a classpath.
| Option | Default | Description |
|---|---|---|
enabled |
true |
Turn rule on/off |
severity |
"warning" |
"error" or "warning" |
SAFE106: nonlocal_jumps#
What it flags: goto statements and setjmp / longjmp family calls. C and C++, new in v2.7.0 (widened to C++ in v2.8.0). This is Holzmann's rule 1 ("restrict all code to very simple control flow constructs") expressed literally - C and C++ are the registered languages with goto / setjmp.
goto and the setjmp / longjmp non-local-jump pair bypass structured control flow, so worst-case control paths cannot be reasoned about by inspection. The rule fires on every goto_statement and every call to a configured non-local-jump function (setjmp / longjmp / sigsetjmp / siglongjmp).
Enabled by default at warning severity. The paper bans goto outright, but the goto err cleanup chain is pervasive, idiomatic C; shipping it as a non-blocking warning surfaces every jump without breaking --fail-on=error builds. Annotate a sanctioned cleanup with // nosafe: SAFE106.
| Option | Default | Description |
|---|---|---|
enabled |
true |
Turn rule on/off |
severity |
"warning" |
"error" or "warning" |
nonlocal_jump_calls_c |
["setjmp", "longjmp", "sigsetjmp", "siglongjmp"] |
Call names treated as non-local jumps alongside goto (C, .c / .h) |
nonlocal_jump_calls_cpp |
["setjmp", "longjmp", "sigsetjmp", "siglongjmp"] |
Same, for C++ (.cpp / .cxx / .cc / .hpp / .hxx / .hh) - resolved independently of the C key |
# pyproject.toml
[tool.safelint.rules.nonlocal_jumps]
nonlocal_jump_calls_c = ["setjmp", "longjmp", "sigsetjmp", "siglongjmp"]
nonlocal_jump_calls_cpp = ["setjmp", "longjmp", "sigsetjmp", "siglongjmp"] # C++ uses its own key
# safelint.toml
[rules.nonlocal_jumps]
nonlocal_jump_calls_c = ["setjmp", "longjmp", "sigsetjmp", "siglongjmp"]
nonlocal_jump_calls_cpp = ["setjmp", "longjmp", "sigsetjmp", "siglongjmp"] # C++ uses its own key
Error handling rules#
These check that exceptions are handled clearly and not swallowed silently.
SAFE201: bare_except#
What it flags: except: clauses with no exception type. Python and C++ - Python's except: and C++'s catch (...) catch-all (its first non-Python home). JavaScript catch clauses always bind the caught error (and don't have the KeyboardInterrupt / SystemExit hijack hazard), so there's no equivalent hazard to flag on JS files; SAFE202 + SAFE203 cover the related JS concerns.
A bare except: catches everything including KeyboardInterrupt and SystemExit, which are signals, not bugs. Always specify the exception type you expect.
| Option | Default | Description |
|---|---|---|
enabled |
true |
Turn rule on/off |
severity |
"error" |
"error" or "warning" |
Bad:
Good:
SAFE202: empty_except#
What it flags: except / catch blocks whose body is effectively a no-op. Cross-language.
except E: passexcept E: continueexcept E: ...(Ellipsis)except E: 0/None/True/False(constant literals)except E: "TODO"/""(string-as-comment idiom)
An empty except block silently swallows the error. The caller has no idea something went wrong. Broadened in 1.8.0, earlier versions only matched a literally empty body which Tree-sitter doesn't actually produce for valid Python, so the rule was effectively dead code.
Multi-statement bodies are not flagged even if every statement looks trivial, two consecutive no-ops suggest some intentional structure and would generate false positives.
| Option | Default | Description |
|---|---|---|
enabled |
true |
Turn rule on/off |
severity |
"error" |
"error" or "warning" |
SAFE203: logging_on_error#
What it flags: except / catch blocks that handle an error without any logging call. Cross-language.
If you catch an exception and do something with it but never log it, the error is invisible. This rule requires at least one call to a logger method inside the handler, unless the handler propagates the failure instead.
What counts as not swallowing it#
A handler that re-raises is not swallowing anything, and demanding a log there actively hurts: you get two reports of one failure, the second at the wrong altitude. The test is whether every exit path leaves by raising, so all of these are clean:
except ValueError as err:
raise RuntimeError("bad") from err # the idiomatic add-context re-raise
except ValueError as exc:
print(f"failed: {exc}") # report, then propagate
raise
except ValueError as err:
if recoverable(err):
raise Retry() from err # every arm raises, so nothing is lost
else:
raise
Containment is deliberately not the test - this body really does swallow, and still reports:
Throwing a fresh error needs a closer look in the C-family languages, which have no automatic chaining. One that carries the caught value along is the local spelling of raise ... from err, and is clean:
catch (IOException e) {
throw new ConfigException("loading " + path, e); // clean: original attached
}
One that does not still discards the original and still wants logging: throw new Error("x") with no mention of the binding. So does throw makeError(e) in JavaScript, TypeScript, Java and PHP, because a factory's return value need not be a wrapper; C++ constructs the thrown value with a plain call (throw std::runtime_error(e.what())), so there it does count. Python needs none of this - a raise inside an except chains the active exception automatically, so the original stays reachable either way.
Where the finding points#
When only some arms propagate, the violation anchors at the arm that falls through rather than at the except line:
except ValueError:
if a:
raise
elif b:
raise
else:
cleanup() # <- reported here: "this path leaves the handler without
# logging or re-raising"
On a handler with several arms, "something in here leaks" leaves you to work out which. When the handler falls through as a whole, the clause stays the anchor - there the handler as a unit is the problem. So does a branching handler where no arm raises: the per-path wording says the other paths re-raise, and saying that where nothing raises would be a false statement about the code.
| Option | Default | Description |
|---|---|---|
enabled |
true |
Turn rule on/off |
severity |
"warning" |
"error" or "warning" |
log_methods |
see below | (Python.) Call names that count as making the failure visible |
log_methods_javascript / _typescript / _java / _php / _cpp |
see below | The same, per language |
skip_test_code |
true |
Skip files recognised as test code - see above. Added in 2.15.0. |
test_dirs |
["tests", "test", "__tests__", "spec"] |
Directories treated as test code. Added in 2.15.0. |
Names are matched with the receiver discarded, so $logger->notice($e) resolves to notice and console.print_exception() to print_exception.
Python's list adds print, print_exception and print_exc to the logger names: a script or CLI legitimately prints its own failure, and Rust's SAFE207 - the documented analogue of this rule - has always accepted println / eprintln / print on the same reasoning. Java's list deliberately does not, because System.out.println inside a catch block is the anti-pattern this rule exists to find, not a fix for it.
[tool.safelint.rules.logging_on_error]
enabled = true
severity = "warning"
log_methods = ["debug", "info", "warning", "error", "exception", "critical", "print"]
log_methods_java = ["severe", "fine", "warning", "error"]
Python, Bad:
Python, Good:
JavaScript, Bad:
JavaScript, Good:
State and purity rules#
These check for use of global variables and unexpected side effects in functions.
SAFE301: global_state#
What it flags: Functions that declare the global keyword. Python and PHP (the two languages with a literal global declaration form). JavaScript has no global read-only declaration form; on JS this rule would always be a strict subset of SAFE302 (global_mutation), so it isn't separately registered. JS users get the same protection from SAFE302 alone.
Using global means a function reads or writes shared state outside its own scope. This makes functions hard to test and creates hidden dependencies between parts of your code. Pass values as arguments instead.
| Option | Default | Description |
|---|---|---|
enabled |
true |
Turn rule on/off |
severity |
"warning" |
"error" or "warning" |
SAFE302: global_mutation#
What it flags: shared module / global mutable state. Cross-language (Python, JavaScript, TypeScript, Java), the intent (Holzmann rule 6: declare data at the smallest possible scope) is the same, but the syntactic shape differs per language.
Python: by default, functions that declare global x and then assign to x. With strict = true, any global declaration is flagged regardless of whether a write follows. This is stricter than SAFE301. The default behaviour is more nuanced than ruff's PLW0603 (which fires on any global); set strict = true if your team's policy is to ban the keyword entirely.
JavaScript: function-body writes, assignment_expression, augmented_assignment_expression, or update_expression (++ / --), whose target is a member_expression or subscript_expression rooted in a configured global namespace. The receiver chain is walked leftward, process.env.NODE_ENV = '...', process.env['NODE_ENV'] = '...', and process.exitCode++ all resolve to process and fire. Bracket-notation writes (globalThis['x'] = 1, window["config"] = {}) work the same way as dot access. The default namespace list (global_namespaces_javascript) is ["globalThis", "window", "global", "self", "process"]; runtime presets adjust this (browser drops process, adds document; Deno adds Deno, drops window and process). Module-level (top-of-file) writes do NOT fire, that's setup, not the bug pattern. Reading a global (return globalThis.env;) does NOT fire, only writes.
A write is also skipped when the root name is shadowed by a local declaration, since the write then targets the local and not the global:
function Headers() {
const self = this; // a local alias for `this`
return function set(key, value) {
self[key] = value; // writes to the local - not reported
};
}
That pre-arrow idiom is how JavaScript carried this into a nested function for years, and it appears three times in Axios's lib/core/AxiosHeaders.js. Reporting it made a library's ordinary self-reference indistinguishable from a genuine window.XMLHttpRequest = null. Recognised binding forms are a const / let / var declarator, a function parameter (including the TypeScript typed form and an arrow function's single unparenthesised parameter), and a catch binding, in any enclosing scope up to and including module scope. A destructured binding (const { self } = x) is not recognised, which leaves such a write reported as before rather than risking a silenced global mutation.
Java (added in 2.4.0): non-final static field declarations. This is declaration-site detection, not write-site: a mutable static field IS the smallest-scope violation regardless of where it is written, and a single tree walk over field declarations has near-zero false positives (the same shape PMD's MutableStaticState flags). static final fields are clean, even when the referent is interiorly mutable (static final List<String> CACHE = new ArrayList<>()) - detecting interior mutability would need type resolution safelint does not do, so it is a documented exclusion. Instance fields and local variables never fire. Interface fields are implicitly public static final and so are never flagged. This fulfils the Java SAFE302 work previously deferred in the language docs. Rust is not covered by SAFE302: static mut is unsafe-gated (SAFE602's territory) and safe interior-mutable statics are covered by SAFE307 (interior_mutable_static). Go (added in 2.5.0): declaration-site detection on every package-level var, including sentinel errors (var ErrNotFound = errors.New(...)) - the rule does not special-case the initialiser, so treat sentinels as immutable by suppressing with a per-file ignore or //nosafe if desired. const declarations and block-scoped var / := inside functions are clean.
| Option | Default | Description |
|---|---|---|
enabled |
true |
Turn rule on/off |
severity |
"error" |
"error" or "warning" |
strict |
false |
(Python only.) When true, fire on every global declaration even without a subsequent write, mirrors ruff's PLW0603. Added in 1.8.0. |
global_namespaces_javascript |
see above | (JavaScript only.) Receiver names that count as "global namespace", function-body assignments rooted in any of these fire. Added in 1.13.0. |
skip_test_code |
true |
Skip files recognised as test code - see above. Added in 2.15.0. |
test_dirs |
["tests", "test", "__tests__", "spec"] |
Directories treated as test code. Added in 2.15.0. |
[tool.safelint.rules.global_mutation]
enabled = true
severity = "error"
strict = false # Python: ban global keyword outright when true
global_namespaces_javascript = ["globalThis", "window", "process"] # JavaScript: tighten or relax the namespace list
Python, Bad:
COUNTER = 0
def bump():
global COUNTER
COUNTER += 1 # SAFE302 - function-body write to module-level state
Python, Good:
JavaScript, Bad:
// Bad, function-body write to a global namespace
function setupCache() {
globalThis.cache = new Map(); // SAFE302
process.env.READY = "true"; // SAFE302
}
JavaScript, Good:
// Good, encapsulate state, return rather than mutate
function buildCache() {
return new Map();
}
const cache = buildCache(); // module-level setup is fine; not flagged
SAFE303: side_effects_hidden#
What it flags: Functions with "pure-sounding" names that perform I/O. Cross-language.
A function named calculate_total (Python) or calculateTotal (JavaScript) implies it just computes and returns a value. If it secretly calls open() / print() / input() (Python) or console.log / fetch / fs.readFile (JavaScript), it is hiding a side effect. This is a core Holzmann risk, callers cannot reason about the function's behaviour. The prefix-match check is case-insensitive on the lowercased function name, so it works equally on snake_case (Python convention) and camelCase (JavaScript convention).
| Option | Default | Description |
|---|---|---|
enabled |
true |
Turn rule on/off |
severity |
"error" |
"error" or "warning" |
io_functions |
["open", "print", "input", "subprocess"] |
Call names considered I/O |
pure_prefixes |
see below | Function name prefixes that imply purity |
Default pure_prefixes: calculate, compute, get, check, validate, is, has, find, parse, transform, convert, format, build, resolve, detect
[tool.safelint.rules.side_effects_hidden]
enabled = true
severity = "error"
io_functions = ["open", "print", "input", "subprocess"]
pure_prefixes = ["calculate", "compute", "get", "check", "validate", "is", "has"]
SAFE304: side_effects#
What it flags: Any function that calls an I/O primitive and is not named to signal that fact. Cross-language.
Broader than SAFE303, applies to all functions, not just pure-named ones. A function named process_order that calls print() should be renamed to log_order or refactored to use dependency injection.
| Option | Default | Description |
|---|---|---|
enabled |
true |
Turn rule on/off |
severity |
"warning" |
"error" or "warning" |
io_functions |
["open", "print", "input"] |
(Python.) Call names considered I/O |
io_functions_javascript |
see below | (JavaScript.) Call names considered I/O. Runtime presets ([tool.safelint.javascript] runtime) adjust this default. Added in 1.13.0. |
io_name_keywords |
see below | Functions whose names contain these words are exempt (cross-language) |
skip_test_code |
true |
Skip files recognised as test code - see above. Added in 2.15.0. |
test_dirs |
["tests", "test", "__tests__", "spec"] |
Directories treated as test code. Added in 2.15.0. |
Default io_name_keywords: print, log, write, read, save, load, send, fetch, export, import. The substring check is case-insensitive, so it matches writeData (camelCase) the same way as write_data (snake_case).
Default io_functions_javascript (Node, the default): ["log", "error", "warn", "info", "debug", "fetch", "readFile", "writeFile", "readFileSync", "writeFileSync"]. The browser / deno / cloudflare-workers presets swap in different verbs, see JavaScript runtime presets.
Rust: write! targets and receiver-blind method names#
Two Rust-specific behaviours, both changed in 2.15.0.
write! / writeln! are checked against their target. write! is not an I/O function in Rust; it expands to write_fmt on its first argument, which may implement std::io::Write (I/O) or std::fmt::Write (a string buffer, no I/O). Where the first argument is a plain binding, its declaration decides:
impl fmt::Display for X {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "hello") // not reported - Formatter parameter
}
}
let mut s = String::new();
write!(&mut s, "x").unwrap(); // not reported - String buffer
writeln!(std::io::stdout(), "x"); // reported - genuine I/O
A parameter whose type's base name is String exactly or ends in Formatter, or a local initialised from String::new / String::with_capacity / String::from / format!, is treated as a non-I/O target. The base name is taken after stripping generic arguments, references, lifetimes, mut / dyn and path segments. The Formatter match is a suffix rather than an exact comparison because domain formatters follow the XFormatter convention (Ruff's PyFormatter); String is exact because StringWriter may implement std::io::Write. Anything else (a path expression, a call, an unknown binding) keeps reporting, so the unresolved case stays a finding. On ripgrep write! / writeln! were 34 of 83 SAFE304 findings, 16 inside fn fmt.
read, status, spawn, output and recv left the Rust SAFE304 default. Call names are resolved with the receiver discarded, so as bare method names these matched whatever they were called on, and Rust's standard library spends those verbs on non-I/O operations that are pervasive in ordinary code: RwLock::read and Mutex::write for locks, mpsc::Receiver::recv for channels, tokio::spawn for tasks, and status / output as accessors on any domain type. They remain in SAFE303's list, where the function's own name must also signal purity, which is the same split Go's list already uses for Get / Query / Exec. Add any of them back via io_functions_rust if your codebase uses them for real I/O.
[tool.safelint.rules.side_effects]
enabled = true
severity = "warning"
io_functions = ["open", "print", "input"] # Python list
io_functions_javascript = ["log", "error", "warn", "fetch", "writeFile"] # JavaScript list (overrides the runtime preset)
io_name_keywords = ["print", "log", "write", "read", "save", "load", "send", "fetch"]
Python, Bad:
def process_order(order):
print(f"processing {order}") # SAFE304 - non-io-named function calls I/O
return order
Python, Good:
JavaScript, Bad:
function processOrder(order) {
console.log(`processing ${order}`); // SAFE304 - non-io-named function calls I/O
return order;
}
JavaScript, Good:
function logOrder(order) { // name contains ``log``, exempt
console.log(`processing ${order}`);
return order;
}
SAFE305: wide_scope_declaration#
What it flags: var declarations whose function-scope hoisting is observable - that is, where replacing var with let would change what the code does. JS-family only (JavaScript and TypeScript, including .tsx / .as): var carries the same hazard in TypeScript, while Python has no var / let / const distinction.
var is function-scoped: a var declared inside one branch of an if is visible throughout the entire enclosing function (and at module top, throughout the module), because the declaration is hoisted to the top of its containing function. let and const are block-scoped: they only exist inside the { ... } they're declared in. The rule's intent matches Holzmann Power-of-Ten Rule 6 ("declare variables at the smallest possible scope") translated to JS's actual scope-control mechanism.
Changed in 2.16.0. The rule used to report every var. That inverted its own value: on Express 1748 of 1960 default findings (89%, across 136 of 141 files) were SAFE305, so the handful of vars whose hoisting actually bites were indistinguishable from the rest, and the other ten rules were drowned out (#201). A module-scope var path = require("node:path") has no observable difference from const; there is nothing to fix, so there is nothing to report.
Five shapes are reported, each with its own message naming the hazard:
| Shape | Why let differs |
|---|---|
| Used outside the block it is declared in (read or assigned) | let would be a ReferenceError; the hoisting is what makes the use work |
| Read before its declaration in the same execution scope | var yields undefined; let rejects it (TDZ) |
| Declared in a loop and captured by a closure inside it | every var closure shares one binding and sees the final value; let gives each iteration its own |
Re-declares a name already bound in an overlapping scope (an earlier var, or a parameter) |
at the same scope let / const reject the duplicate outright; from a nested block they bind a separate shadowing variable instead of the one already there, so assignments stop being visible outside the block. Either way the fix is a rename, not a keyword swap |
Declared in one switch clause and read from a later one (2.17.1) |
entering the switch at the reading clause skips the declaration, so var reads undefined while let / const throw Cannot access 'w' before initialization. The fix is to declare it above the switch |
Deliberately silent on everything else, including a var at function top level used only within that function, a loop counter used only inside its loop, and a var declared and used in the same block. A read from inside a nested function does not count as a read-before-declaration, because the closure runs after the declaration has executed. A reference inside a nested function that binds the same name is that function's own binding and is ignored.
The first three shapes need a reference to be observable, so a var nothing ever touches is not reported. A redeclaration is reported regardless: let rejects the duplicate whether or not anything reads the name, so it blocks the conversion either way.
Two bindings of one name only count as a redeclaration when their block scopes overlap - one contains the other, or either is at function top level. Disjoint blocks never collide, and the name belongs to whichever block it sits in:
function f(a, b) {
for (var i = 0; i < a.length; i++) { use(a[i]); } // NOT reported
for (var i = 0; i < b.length; i++) { use(b[i]); } // `let` is legal in both
}
if (c) { var x = 1; } else { var x = 2; } is the same case. An inner block is contained by the outer one, so if (c) { var x = 1; if (d) { var x = 2; } } does report.
A switch is one scope, not one per case: the braces of the switch open the scope that every case and the default share. So two var y in different cases of the same switch are a redeclaration (as let they are a SyntaxError), while two different names across cases are not.
Only a binding that merges with the var counts as a redeclaration: another var declarator, or one of the function's own parameters. A let / const in a nested block, a catch parameter and a class name each create their own binding that let is free to shadow, so none of these is reported:
function f() {
var err = null;
try { run(); } catch (err) { log(err); } // catch binds its own `err`
return err; // `let err` above parses fine
}
function g(c) {
var x = 1;
if (c) { const x = 2; use(x); } // ...and so does this
return x;
}
New in 2.17.1. Because the switch is one scope, a var declared in one clause and read from a later one is its own shape (#255). The other four each miss it for a different reason: the declaration comes first in source order, so it is not a read-before-declaration, and both sites share the one switch scope, so it is not an escape. What makes it a hazard is execution order:
function f(k) {
switch (k) {
case 1: var w = 1; break;
case 2: use(w); break; // k === 2 never ran case 1
}
}
As var that reads undefined; as let it throws. default: counts in both directions, since it is a clause like any other. No fall-through analysis is involved and none would help: a clause carrying a label is directly reachable whenever the discriminant matches it, so the hazard holds whether or not the declaring clause ends in break, and the discriminant's value is exactly what cannot be known here. A read in the same clause is fine, and a read in an earlier one is already reported as a read before the declaration.
If a var both crosses clauses and leaves the switch entirely, the escape message is shown, because it describes the more pressing half.
The fix is a keyword swap for one shape only. Swapping var for let in place changes behaviour in three of the five, which is the point of reporting them but is not a drop-in replacement. Each line below was run against node:
| Shape | What the fix is |
|---|---|
| Used outside the block | move the declaration above the block, then let / const. Swapping the keyword where it stands gives ReferenceError: w is not defined, because the binding no longer exists at the use |
| Read before its declaration | the read is the bug: move it after the declaration. Swapping the keyword turns a silent undefined into ReferenceError: Cannot access 'w' before initialization, which makes the hazard visible rather than fixing it |
| Captured by a closure in a loop | a genuine one-token swap. let gives each iteration its own binding, so the closures print 0,1,2 instead of 3,3,3 - the behaviour changes, and that change is the fix |
| Re-declares a name in an overlapping scope | rename one of them |
Declared in one switch clause, read from a later one |
declare it above the switch |
Use let where the binding is reassigned later and const where it is not. The rule fires once per variable_declaration node, so a multi-binding form like var x = 1, y = 2; produces a single violation (the line is the unit of fix, not each bound name).
If you want the old behaviour - every var reported, as a codemod trigger for a "modernise this codebase" pass - the rule does not provide it; use a linter rule built for that (eslint no-var), which is what it was competing with.
| Option | Default | Description |
|---|---|---|
enabled |
true |
Turn rule on/off |
severity |
"warning" |
"error" or "warning" |
Bad:
var path = require("node:path"); // NOT reported - `const` behaves identically
function f(items) {
if (items.length > 0) {
var first = items[0]; // SAFE305 - read outside its block, below
}
return first; // accidentally accessible, exactly the bug
}
function g(items) {
for (var i = 0; i < items.length; i++) { // SAFE305 - captured in a loop
setTimeout(function () {
console.log(i); // every closure shares one `i` and logs items.length
});
}
}
function doubleAndReturnLastIndex(arr) {
for (var i = 0; i < arr.length; i++) { // SAFE305 - i leaks out of the loop
arr[i] = i * 2;
}
return i; // i is still accessible, that's the bug
}
Good:
function f(items) {
if (items.length > 0) {
const first = items[0]; // block-scoped to the if
return first;
}
return undefined;
}
function doubleEach(arr) {
for (let i = 0; i < arr.length; i++) { // i is block-scoped to the loop
arr[i] = i * 2;
}
}
SAFE309: dynamic_code_execution#
What it flags: runtime code generation and reflection. Python, JavaScript, TypeScript, Java. Disabled by default.
Holzmann's rule 8 restricts the preprocessor because textual code generation defeats static analysis: a tool cannot reason about code that does not exist until runtime. The modern equivalent is eval / exec-style execution and reflection. SAFE309 is structural, it flags the construct wherever it appears, with no dataflow. That is the difference from SAFE801 (tainted_sink), which fires only when user input demonstrably reaches one of these sinks. The two are complementary and may both fire on the same line; an untainted eval(config_string) still destroys analysability, which is what rule 8 cares about.
Per-language defaults (call names):
- Python (
dynamic_exec_calls):eval,exec,compile,__import__. Only bare calls andbuiltins.-qualified calls fire, somodel.eval()(a method call) does not.getattr/setattrare deliberately excluded (far too common, and they do not generate code). - JavaScript / TypeScript (
dynamic_exec_calls_javascript):eval,Function(bothnew Function(...)and the bareFunction(...)call),execScript. A bare-identifier callee is required, soobj.eval()does not fire.setTimeout/setIntervalwith a string first argument (the implicit-eval form) are deliberately not in the defaults: flagging everysetTimeoutwould be noise, and detecting only the string-argument form is not worth the complexity for a near-extinct idiom; add them via the config list if your codebase still uses the string form. - Java (
dynamic_exec_calls_java):forName(Class.forName),invoke(Method.invoke),eval(JSR-223ScriptEngine),defineClass,loadClass. Matched by method name regardless of receiver, so a user-definedforNamewould also match (acceptable for an off-by-default rule).
Rust is excluded: its rule-8 analogue is the macro system, whose bodies parse as opaque token trees (a documented limitation shared with SAFE801), and panic-family macros already have SAFE204. Go (added in 2.5.0): Go has no eval; the rule-8 surface is reflection (reflect Call / CallSlice / MethodByName) and plugin loading (plugin Open / Lookup), via dynamic_exec_calls_go. Matching is by bare method name, so Open also matches os.Open - narrow the list if noisy.
| Option | Default | Description |
|---|---|---|
enabled |
false |
Turn rule on/off |
severity |
"warning" |
"error" or "warning" |
dynamic_exec_calls |
see above | (Python) call names that count as dynamic execution |
dynamic_exec_calls_javascript |
see above | (JS / TS) call / constructor names |
dynamic_exec_calls_java |
see above | (Java) reflection method names |
# pyproject.toml
[tool.safelint.rules.dynamic_code_execution]
enabled = true
severity = "warning"
# Per-language call lists (each replaces that language's default):
dynamic_exec_calls = ["eval", "exec", "compile", "__import__"] # Python (bare key)
dynamic_exec_calls_javascript = ["eval", "Function", "execScript"] # JS / TS (TS inherits via fallback)
dynamic_exec_calls_java = ["forName", "invoke", "defineClass", "loadClass"] # Java
# standalone safelint.toml (same keys, no [tool.safelint] prefix)
[rules.dynamic_code_execution]
enabled = true
SAFE310: dynamic_allocation#
What it flags: Calls to the heap-allocation / free family. C and C++, new in v2.7.0 (widened to C++ in v2.8.0). Holzmann's rule 3 ("do not use dynamic memory allocation after initialisation") expressed literally - on C++ it additionally flags new / delete expressions.
Fires on every call to a configured allocator (malloc / calloc / realloc / aligned_alloc / free / strdup). Disabled by default - embedded and safety-critical projects opt in; most application C uses the heap freely. Pre-allocate fixed pools / arenas at init and hand out slots to satisfy the rule.
| Option | Default | Description |
|---|---|---|
enabled |
false |
Turn rule on/off |
allocation_calls_c |
["malloc", "calloc", "realloc", "aligned_alloc", "free", "strdup"] |
Allocator call names (C, .c / .h) |
allocation_calls_cpp |
["malloc", "calloc", "realloc", "aligned_alloc", "free", "strdup"] |
Allocator call names for C++ (.cpp / .cxx / ...) - resolved independently of the C key. C++ additionally flags new / delete expressions structurally (not configurable) |
# pyproject.toml
[tool.safelint.rules.dynamic_allocation]
enabled = true
allocation_calls_c = ["malloc", "calloc", "realloc", "aligned_alloc", "free", "strdup", "xmalloc"]
allocation_calls_cpp = ["malloc", "calloc", "realloc", "aligned_alloc", "free", "strdup", "xmalloc"] # C++ uses its own key; new / delete are always flagged
# safelint.toml
[rules.dynamic_allocation]
enabled = true
allocation_calls_c = ["malloc", "calloc", "realloc", "aligned_alloc", "free", "strdup", "xmalloc"]
allocation_calls_cpp = ["malloc", "calloc", "realloc", "aligned_alloc", "free", "strdup", "xmalloc"] # C++ uses its own key; new / delete are always flagged
SAFE311: complex_macro#
What it flags: Preprocessor macros that are not simple, complete syntactic units. C and C++, new in v2.7.0 (widened to C++ in v2.8.0). Holzmann's rule 8 ("limit the preprocessor to header files and simple macros").
Fires on function-like macros that use token pasting (##) or variadic __VA_ARGS__, and on object-like macros whose replacement text is not a balanced syntactic unit (heuristic: unbalanced () / {} / [], ignoring brackets inside string and character literals). Mutually recursive macro definitions (the paper's third banned construct) are not detected; that needs macro-table analysis. Disabled by default.
SAFE312: conditional_compilation#
What it flags: #if / #ifdef / #ifndef directives beyond the include-guard idiom. C and C++, new in v2.7.0 (widened to C++ in v2.8.0). Holzmann's rule 8 again: each conditional-compilation directive doubles the number of build configurations that must be tested (2^n versions from n flags).
An #ifndef X + #define X pair (a header include guard) is exempt; the matching #define must be the first substantive statement of the block, with comments (e.g. an SPDX / licence header) and #pragma lines (a belt-and-braces #pragma once) allowed in between. Every other #if / #ifdef / #ifndef fires. Disabled by default. Prefer runtime configuration over compile-time flags.
SAFE313: restricted_pointers#
What it flags: Declarators with more than one level of pointer indirection (int **p) and function-pointer declarators (void (*fp)(int)). C and C++, new in v2.7.0 (widened to C++ in v2.8.0; smart pointers exempt on C++). Holzmann's rule 9 ("limit pointer use to a single dereference, and do not use function pointers") expressed literally. The check is syntactic (declarator shape only): a pointer level hidden behind a typedef or a macro is not counted - the paper's no-hidden-dereference clause needs type resolution and is a documented gap.
Disabled by default - it is deliberately strict (char **argv fires too). Opt in for the highest-assurance profiles; collapse multi-level pointers behind a struct or out-parameter, and replace function pointers with tagged dispatch.
C++ idiom rules#
Two C++-only rules capture modern-C++ ownership / type-safety idioms that have no analogue in the other languages. Both are disabled by default. New in v2.8.0.
SAFE315: raw_new_delete#
What it flags: Every new and delete expression. C++-only. The modern-ownership rule: prefer std::make_unique / std::make_shared and RAII so a scoped owner releases memory automatically and cannot be forgotten on an early return or exception. std::make_unique / std::make_shared contain no new expression and never fire; a raw new inside a std::unique_ptr<T>(new T) argument still fires (prefer make_unique).
It overlaps the widened SAFE310 (dynamic_allocation) by design: SAFE310 is the Holzmann no-allocation-after-init posture (embedded / safety-critical), SAFE315 the ownership posture (leak safety). Enabling both double-reports a raw new, the same intentional overlap as SAFE205 / SAFE208.
SAFE316: dangerous_casts#
What it flags: reinterpret_cast and const_cast expressions. C++-only. These defeat the type / const system: reinterpret_cast reinterprets a bit pattern with no checking, const_cast strips const (undefined behaviour if the underlying object is truly const). static_cast and dynamic_cast are compiler-checked and stay clean. The named casts parse as a call_expression whose callee is a template_function, so the rule matches on the template callee name.
The flagged list is configurable via dangerous_casts_cpp - narrow it, or add static_cast if your profile forbids all named casts.
# pyproject.toml
[tool.safelint.rules.dangerous_casts]
enabled = true
dangerous_casts_cpp = ["reinterpret_cast", "const_cast"]
# safelint.toml
[rules.dangerous_casts]
enabled = true
dangerous_casts_cpp = ["reinterpret_cast", "const_cast"]
Resource safety rules#
SAFE401: resource_lifecycle#
What it flags: Resource-acquisition calls that aren't wrapped in a cleanup-guaranteed scope. Cross-language with language-specific scope semantics.
Python: the call must appear inside a with statement (with open(path) as f:). Bare assignments without with fire even when paired with manual f.close(), Python's idiom is context-manager-first.
JavaScript: the call must appear inside a try block whose try_statement has a finally_clause somewhere up the AST ancestor chain. Heuristic-only: the rule doesn't verify that the finally block actually closes the specific resource. Captures the most common "I created a stream and didn't think about cleanup at all" leak. JavaScript's newer using declarations (Stage 3 / Node 22+) aren't yet recognised as a safe form; for now, wrap inside try { ... } finally { ... }.
| Option | Default | Description |
|---|---|---|
enabled |
true |
Turn rule on/off |
severity |
"error" |
"error" or "warning" |
tracked_functions |
(see below) | (Python.) Calls that must be inside a with block. Replaces the default list when set. |
extend_tracked_functions |
[] |
(Python.) Appended to the default list, use this when you want to add custom functions without losing the defaults. Added in 1.8.0. |
cleanup_patterns |
["close", "commit", "rollback", "release", "shutdown"] |
(Python.) Acceptable cleanup method names as an alternative |
tracked_functions_javascript |
(see below) | (JavaScript.) Calls that must be inside a try { ... } finally { ... }. Runtime presets ([tool.safelint.javascript] runtime) adjust this default. Added in 1.13.0. |
skip_test_code |
true |
Skip files recognised as test code - see above. Added in 2.15.0. |
test_dirs |
["tests", "test", "__tests__", "spec"] |
Directories treated as test code. Added in 2.15.0. |
Default tracked_functions (Python, expanded in 1.8.0):
tracked_functions = [
"open", "connect", "session", "Session", # files, DBs, HTTP
"Lock", "RLock", "Semaphore", # synchronisation
"Pool", "ThreadPoolExecutor", "ProcessPoolExecutor", # work pools
"socket", "mmap", # network / memory
"TemporaryFile", "NamedTemporaryFile", "TemporaryDirectory",
"ZipFile", "TarFile", # archives
]
Default tracked_functions_javascript (Node, the default runtime):
tracked_functions_javascript = [
"createReadStream", "createWriteStream", "openSync", # fs
"createServer", "createConnection", "connect", # net / DB drivers
"createWorker", # worker pools
]
The browser / deno / cloudflare-workers presets swap in different lists, see JavaScript runtime presets.
# Add custom Python acquirers without losing the defaults
[tool.safelint.rules.resource_lifecycle]
extend_tracked_functions = ["acquire_widget", "rent_db_handle"]
# Replace the JS tracked list entirely (overrides the runtime preset)
[tool.safelint.rules.resource_lifecycle]
tracked_functions_javascript = ["openSync", "createServer", "myCustomAcquirer"]
Python, Bad:
f = open("data.txt") # SAFE401 - not in a with block
data = f.read()
f.close() # won't run if f.read() raises
Python, Good:
JavaScript, Bad:
function readData(path) {
const stream = fs.createReadStream(path); // SAFE401 - not wrapped in try/finally
return processStream(stream);
}
JavaScript, Good:
function readData(path) {
let stream;
try {
stream = fs.createReadStream(path);
return processStream(stream);
} finally {
if (stream) stream.close();
}
}
Loop safety rules#
SAFE501: unbounded_loops#
What it flags: while loops that may run forever. Cross-language.
Two cases are flagged:
- Literal-
truecondition with nobreakinside, applies to bothwhile True:(Python) andwhile (true)(JavaScript). Guaranteed infinite loop unless something inside the body breaks out. - Non-comparison condition, applies to Python only (
while x:wherexisn't a comparison expression). JS idioms likewhile (queue.length)andwhile (token)are commonly bounded, so the heuristic stays Python-only, flagging them on JS files would produce too much noise.
What counts as leaving the loop#
A break is not the only exit, and the rule recognises three others. Each was a measured false-positive source before 2.15.0.
A return. It ends the enclosing function and so leaves every loop inside it:
In Rust this is the more common shape, because ?-propagation forces it - you cannot ? out of a loop with a break - and on ripgrep it accounted for every SAFE501 finding the rule produced. The gap was present in all nine languages.
A return inside a nested loop does not clear the outer one. The inner loop may run zero times, in which case the return is never reached and the outer loop really is unbounded:
loop {
for x in items { // if `items` is empty ...
return; // ... this never runs; the outer loop still reports
}
}
A return inside a nested function or closure belongs to that function and likewise does not count.
A goto out of the loop (C and C++). Counted only when the target label sits outside the loop body; a jump to an in-loop label is intra-loop control flow.
A break or return inside a Rust macro body. tree-sitter parses a macro's arguments as an opaque token_tree, so statements inside are never typed nodes - in loop { select! { .. break; .. } } the break exists only as an anonymous token. The rule looks for those keyword tokens directly, so crossbeam::select! and tokio::select! bodies are read correctly. A macro carrying no exit keyword still reports, so loop { println!("x"); } is unaffected, and because a token tree is still tokenised the word break inside a string literal does not count.
| Option | Default | Description |
|---|---|---|
enabled |
true |
Turn rule on/off |
severity |
"warning" |
"error" or "warning" |
Python, Bad:
Python, Good:
JavaScript, Bad:
JavaScript, Good:
Documentation rules#
SAFE601: missing_assertions#
What it flags: Functions with fewer than min_assertions assertions. Cross-language.
Based on Holzmann rule 5: the paper asks for an assertion density averaging a minimum of two assertions per function. The rule defaults to min_assertions = 1 (any assertion satisfies it) to keep noise low; paper-strict projects set min_assertions = 2. Disabled by default because many functions legitimately have no assertions (e.g. simple data transformations).
Two further clauses of the paper's rule 5 are intentionally out of scope: assertions must be side-effect free (safelint does not analyse assertion expressions for effects), and a trivially-true assertion (assert True) counts toward the threshold even though the paper disallows assertions a static checker can prove never fail. Both need analysis machinery (effect inference, constant propagation) that does not fit a structural rule; review remains the guard there.
Python counts the AST assert_statement (built-in keyword) and calls to a configured set of assertion-method names (assertion_calls), so unittest / Django TestCase bodies that assert only via self.assertEqual(...) / self.assertRaises(...) and pytest bodies using pytest.raises(...) / pytest.warns(...) are recognised instead of being flagged as assertion-less. The default set covers the unittest assert* surface (assertEqual, assertTrue, assertRaises, assertIn, assertIsNone, fail, ...) plus pytest's raises / warns; call_name strips the receiver, so self.assertEqual and pytest.raises match on the bareword. Add project-specific assertion helpers through extend_assertion_calls.
Since 2.16.0 the default also covers two families that are not unittest's but are just as standard:
unittest.mock-assert_called,assert_called_once,assert_called_with,assert_called_once_with,assert_any_call,assert_has_calls,assert_not_called, and theassert_awaited*mirrors.mockis in the standard library, so a test whose only assertion isclient.get.assert_called_once_with(...)is asserting; it used to read as assertion-free. On the Django codebase this was measured against, 55 of 100 flagged test functions asserted only this way.- Django
SimpleTestCase/TestCase-assertContains,assertRedirects,assertTemplateUsed,assertNumQueries,assertRaisesMessage,assertFormError,assertJSONEqual,assertHTMLEqual,assertInHTML,assertQuerySetEqualand the rest of that API. Unconditional rather than gated behind[python] framework = "django": every name is spelledassert*and nothing else defines them, so counting one as an assertion is right in any project, and a false-positive fix should not depend on the preset being set. A name added here can only ever suppress a finding, never raise one.
Matching is by call name only (receiver stripped) in the assertion_calls_* lists - the same allowlist approach every other language's SAFE601 detector and tainted_sink.sanitizers use, and the reason a bare project helper (verify_invariant(x)) counts. Go is the exception, and in two directions: assertion_receivers_go matches on the receiver instead of the name, and the shipped *testing.T failure methods are counted only on a testing-typed receiver, because Errorf and Error would otherwise be credited to fmt.Errorf(...) and err.Error(). The tradeoff: a production call whose name coincides with a configured entry (a helper literally named fail / raises) is also credited, so SAFE601 may under-report an assertion-less function. This is a false-negative on an opt-in advisory rule, and test_functions_only (below, on by default) confines the rule to test functions, where these names are unambiguously assertions.
JavaScript has no built-in assert keyword, so the rule walks for calls to a configured set of assertion-function names, Node's assert module (assert, ok, equal, strictEqual, deepEqual, match, ...), console.assert, and test-framework idioms (expect for Jest / Chai-via-expect, should for Should.js, vi.expect for Vitest). Configure via assertion_calls_javascript.
Scoping to test functions only. Default since 2.16.0. test_functions_only is on, so the rule reads SAFE601 as "a test must actually assert something": production code that validates by raising, and fixtures / setUp / helper methods that legitimately have no assertions, are skipped, while a test that asserts nothing - a genuinely broken test - still fires.
It was off until 2.16.0, which enforced the paper's intent literally (assertions in every function) and made SAFE601 56-92% of all output on four real codebases: 557 of 987 findings on a Python service (every one in a non-test file, across 126 production modules), 157 of 233 on spring-petclinic, 154 of 232 on a JavaScript app, 624 of 679 on a Rust binary. A getter, a trait conversion and a migration hook assert nothing by design, so the findings that mattered were indistinguishable from the ones that did not. Set test_functions_only = false for the paper reading.
How a test is identified. Three routes, because the languages do not agree on what marks a test. The first two also require the file to be a test file (under test_dirs, or matching the language's test-filename convention - the same definition SAFE701 / SAFE702 use), since a production test_connection() helper is not a test. A marker stands on its own, which is what makes Rust's colocated tests reachable at all.
| Route | Languages | Config key | Example |
|---|---|---|---|
| Name prefix | all | test_function_prefixes |
def test_parses_empty(): ... |
| Registration callback | JavaScript, TypeScript, Go | test_registration_calls |
it("rejects a short password", () => { ... }) |
| Attribute / annotation | Rust, Java | test_markers |
#[test] fn empty_input_is_zero() { ... } |
- Name prefix is per language, because the conventions differ in case as well as shape:
["test"]everywhere,["Test", "Fuzz"]for Go, whose toolchain requiresTestXxx.BenchmarkXxxandExampleXxxare deliberately out: a benchmark has no assertion to make, and an example asserts through its// Output:comment, which is not a call. - Registration callback (since 2.16.0) covers the shape that has no name of its own. Default
["it", "test"]for the JS family and["Run", "Fuzz"]for Go. Matching is against the whole callee chain, so the bareit(...), the modifiersit.only/test.skip/it.concurrent/it.failing, the parametrisedit.each(table)(...), node:test'st.test(...)and Go'st.Run(...)/f.Fuzz(...)are all covered by those names. The finding is then named by the registration call's first string argument:Test "rejects a short password" has no assertions, rather thanFunction "<anonymous>".describeis deliberately not a registration call - see the delegation note below. - Attribute / annotation (since 2.16.0) covers Rust and Java, where the name is free prose. Defaults
["test", "rstest"]and["Test", "ParameterizedTest", "RepeatedTest", "TestTemplate", "TestFactory"].@TestFactorywas excluded in 2.16.0 and is back since 2.17.0: a factory's assertions live inside theDynamicTestlambdas it returns, the counters stopped at nested functions, and including it therefore reported every well-written factory. #252 counts a test's callbacks, and a factory is a test, so the exclusion no longer buys anything - a factory whose lambdas assert is clean, and one that asserts nothing is reported rather than invisible. Zero new findings on commons-lang's four factories. A qualified marker matches on its trailing segment, so#[tokio::test],#[actix_web::test],#[rstest::rstest]and@org.junit.jupiter.api.Testneed no entry of their own, and stacked attributes (#[test]under#[should_panic]) are read as the separate items they are.#[cfg(test)]is not a marker: it marks test context, and a#[cfg(test)] fn helper()is test support rather than a test case.@BeforeEach/@AfterEachare likewise absent.
A function that registers tests is not reported. Since 2.16.0. A Mocha / Jest describe block, and a Go table-driven TestXxx whose assertions all live in t.Run subtests, assert nothing in their own bodies. Each callback they register is checked on its own merit, and the registering function is skipped rather than reported. A matching name with no callback argument does not qualify: t.Run with no function, or a production runner.test(value), still leaves its enclosing function answerable for its own assertions.
What counts as the test's own assertion. Changed in 2.17.0. Two things count inside a function the rule has identified as a test, and neither counts anywhere else:
- A call whose name starts with an
assertion_call_prefixesentry (assertby default), so a project's own helper counts without being listed. A large suite grows these by the hundred -assertIllegalArgumentException,assertEqualCharNodes,assertMapEquals- and exact-name matching read every test whose only assertion went through one as assertion-free: 53% of commons-lang's findings and 34% of Guava's. Restricted to tests deliberately: inside a test anassert-prefixed call is an assertion, while a production method namedassertValid()is nobody's assertion and is never credited. To go back to exact names alone, set the key for the language you mean:assertion_call_prefixes = []covers Python, and every other language needs its own suffixed key (assertion_call_prefixes_java = [],_rust,_go,_javascript,_php; TypeScript takes either its own or the JavaScript one it inherits). The bare key is Python's throughout safelint, and it is kept out of the other languages' lookup chain so one list cannot silently widen all nine. In Rust the prefix is the one route that reaches a plain call, becauseassertion_calls_rustholds macro names and a function namedpanicis not an assertion; a helperfn assert_roundtrip(...)is. -
An assertion inside a callback written inline in the test - an Express route handler, a promise continuation, a
forEachlambda. The counters otherwise stop at nested functions, which is right for an ordinary function (it must not be credited for an inner definition's asserts) and wrong for a test, since whatever a test's callbacks assert, the test asserts. On Express this was 10 of 89 findings. The skip still applies to every function that is not a test.The boundary is the test's own syntax tree, not the call: a callback defined elsewhere and passed by name (or, in C, through a function pointer) is not inside the test and its assertions are not counted. C has no nested function, closure or lambda at all, so this route reaches nothing there.
The trade: an inner definition inside a test now credits the test even if nothing calls it, because "passed to someone else" and "defined and never used" are the same tree shape. A test carrying a dead assertion helper is rare, and the finding would be about dead code rather than about assertions.
| Option | Default | Description |
|---|---|---|
enabled |
false |
Disabled by default, opt-in |
severity |
"warning" |
"error" or "warning" |
min_assertions |
1 |
Minimum assertions per function; set 2 for the paper's density. Added in 2.4.0. |
assertion_calls |
(see default Python list above) | (Python; _<lang> for the others.) Assertion call names counted in addition to any assert keyword. Replaces the default list. Added in 2.12.0. |
extend_assertion_calls |
[] |
Names appended to the resolved list instead of replacing it. Per language through the same key chain (extend_assertion_calls_javascript, ..., and TypeScript inherits the JavaScript one). Mirrors resource_lifecycle's extend_tracked_functions. Added in 2.16.0. |
assertion_receivers |
[], ["assert", "require"] for Go |
Receivers whose every call counts as an assertion. Go only by default: testify exposes dozens of assertion functions per package, so a name list would go stale and collide with ordinary method names. Added in 2.16.0. |
assertion_call_prefixes |
["assert"] |
(Python; _<lang> for the others.) Call-name prefixes counted as an assertion inside a test only, so a project's own assert* helper needs no entry. Set the language's own key to [] for exact names alone; the bare key here reaches Python only. An empty-string entry is dropped rather than matching every name. Added in 2.17.0. |
test_functions_only |
true |
Restrict the rule to functions identifiable as tests (see above). Default changed from false in 2.16.0. Added in 2.12.0. |
test_function_prefixes |
["test"], ["Test", "Fuzz"] for Go |
Name prefixes marking a function as a test. Per language since 2.16.0. Added in 2.12.0. |
test_registration_calls |
["it", "test"] (JS / TS), ["Run", "Fuzz"] (Go), [] elsewhere |
Calls that register a test by taking its body as a callback. Added in 2.16.0. |
test_markers |
["test", "rstest"] (Rust), ["Test", "ParameterizedTest", "RepeatedTest", "TestTemplate", "TestFactory"] (Java; TestFactory added in 2.17.0), [] elsewhere |
Attributes / annotations that mark a function as a test case, whatever it is named and wherever it lives. Added in 2.16.0. |
test_dirs |
["tests", "test", "__tests__", "spec"] |
Directories marking a file as a test file, matched as a path-component subsequence (same key and default as SAFE701 / 702). Added in 2.12.0. |
assertion_calls and extend_assertion_calls are alternatives in practice. They are not mutually exclusive, but setting both appends to the replaced list, not to the defaults: with assertion_calls = ["assertEqual"] and extend_assertion_calls = ["verify_invariant"] the resolved list is exactly those two names, and the other 65 defaults are gone. Pick extend_* to add to the defaults, or assertion_calls to state the whole list yourself.
A relative test_dirs entry is anchored at the file's own project root (the nearest directory above it holding a safelint.toml or a pyproject.toml with a [tool.safelint] section), falling back to the working directory when there is none. So ["tests"] matches a monorepo's per-package test trees at any depth, while a checkout that happens to live under ~/tests/ is not read as all test code. A project with no safelint config of its own therefore needs safelint run from its root for a relative entry to match; an absolute entry is always anchored exactly as given.
Java, Rust, PHP, C, and C++ have their own assertion_calls_<lang> lists (see each language page). Go uses assertion_calls_go (Error, Errorf, Fatal, Fatalf, Fail, FailNow - the *testing.T / B / F failure API) plus assertion_receivers_go.
Known limits.
- The receiver is stripped before matching, so a production call whose name coincides with a configured entry is credited as an assertion: a
log.Fatal(...)inside a Go test, or a helper literally namedfail. That is a false negative on an opt-in advisory rule, and distinguishing the two would need type information the rule does not have. - A helper named anything other than
assert*still has to be named.assertion_call_prefixescovers the dominant convention across Java, Python, JavaScript and Go, not every project's; a suite whose helpers arecheck*orverify*either adds that prefix or lists the names throughextend_assertion_calls_<lang>. - An assertion reached through a function the test calls by name, rather than defines or passes inline, is not credited: the rule is intra-procedural and does not follow a call into another function's body. A test whose only assertion lives in a shared
assertValidResponse(response)helper defined elsewhere is covered by the prefix route above, by its name alone - not because the rule looked inside it.
assertion_calls_rust covers the insta snapshot macros (assert_snapshot, assert_debug_snapshot, assert_json_snapshot and the rest of that family) and assert_matches / debug_assert_matches since 2.15.0. Snapshot testing is the dominant assertion idiom in modern Rust suites, and without those names a test whose only assertion is a snapshot read as having none: on Ruff, 557 of 5412 sampled findings were #[test] functions that do assert, against 82 genuinely assertion-free ones.
# pyproject.toml
[tool.safelint.rules.missing_assertions]
enabled = true
severity = "warning"
min_assertions = 2 # Holzmann rule 5 density; default is 1
extend_assertion_calls = ["verify_invariant"] # Python; APPENDS, so the 66 defaults stay
# assertion_calls = ["assertEqual", "assertTrue"] # ...or REPLACE them with exactly this list
assertion_calls_javascript = ["assert", "expect", "should"]
extend_assertion_calls_java = ["assertIllegalArgumentException"] # your own assert* helpers
# Scoped to tests by default. Set false for the paper's reading (every function):
# test_functions_only = false
test_function_prefixes = ["test", "should"] # per language; Go defaults to ["Test", "Fuzz"]
test_registration_calls_javascript = ["it", "test", "scenario"] # your own wrapper
test_markers_rust = ["test", "rstest", "my_test"]
assertion_receivers_go = ["assert", "require", "must"]
test_dirs = ["tests", "test", "__tests__", "spec"]
# standalone safelint.toml (same keys, no [tool.safelint] prefix)
[rules.missing_assertions]
enabled = true
min_assertions = 2
extend_assertion_calls = ["verify_invariant"]
test_registration_calls_javascript = ["it", "test", "scenario"]
test_markers_java = ["Test", "ParameterizedTest", "MyFrameworkTest"]
# test_functions_only = false
Python, Bad:
def transfer(amount, src, dst): # SAFE601 - no assert statements
src.balance -= amount
dst.balance += amount
Python, Good:
def transfer(amount, src, dst):
assert amount > 0
assert src.balance >= amount
src.balance -= amount
dst.balance += amount
JavaScript, Bad:
function transfer(amount, src, dst) { // SAFE601 - no assertion calls
src.balance -= amount;
dst.balance += amount;
}
JavaScript, Good:
function transfer(amount, src, dst) {
assert(amount > 0);
assert(src.balance >= amount);
src.balance -= amount;
dst.balance += amount;
}
SAFE603: blanket_suppression#
What it flags: un-scoped suppressions of other analysers. Cross-language (all nine registered languages). Disabled by default.
Holzmann's rule 10 ("compile with all warnings enabled and heed every warning") has a modern failure mode: not disabling warnings at the compiler, but silencing an entire analyser from inside the source. SAFE603 flags the blanket forms while leaving scoped suppressions alone, because a scoped suppression is a deliberate, auditable decision about one rule.
Per language, the blanket forms that fire (and the scoped forms that stay clean):
- Python (comments): bare
noqa(no: codelist),type: ignorewith no[code]qualifier,pylint: disable=all. Scoped (noqa: E501,type: ignore[arg-type],pylint: disable=line-too-long) is clean. - JavaScript / TypeScript (comments):
eslint-disable/eslint-disable-line/eslint-disable-next-linewith no rule list,@ts-nocheck,@ts-ignore.@ts-expect-erroris clean (it self-polices: it errors when the suppressed error no longer occurs). A rule-listedeslint-disable no-consoleis clean. - Java (annotations):
@SuppressWarnings("all")and@SuppressWarnings({..., "all"}). Scoped (@SuppressWarnings("unchecked")) is clean. - Rust (attributes):
#[allow(clippy::all)],#[allow(warnings)], and their inner#![...]forms. Scoped (#[allow(dead_code)],#[allow(clippy::too_many_arguments)]) is clean. - Go (comments): golangci-lint's bare
//nolint(all linters) and Staticcheck's bare//lint:ignore(no check list). Both are machine-readable directives recognised only in the tight form with no space after//(//nolint, not// nolint), so a prose// nolint herecomment is left alone. Scoped (//nolint:errcheck,//lint:ignore SA1000 reason) is clean. - PHP: the
@error-suppression operator (@file_get_contents(...)) - PHP's headline blanket-suppression hazard - plus barephpcs:ignore/phpcs:disable,@phpstan-ignore-line/@phpstan-ignore-next-line, and@psalm-suppress all. Scoped forms (phpcs:ignore Squiz.Foo,@phpstan-ignore <id>,@psalm-suppress SomeIssue) are clean. - C / C++ (comments): clang-tidy's bare
// NOLINT/// NOLINTNEXTLINE. Scoped// NOLINT(bugprone-foo)is clean.
SAFE603 never flags safelint's own # nosafe / # safelint: ignore directives, those are policed by SAFE004 (unused suppression). Directive-looking text inside a string literal is not flagged either, the detectors scan comment / annotation / attribute nodes, not string contents.
| Option | Default | Description |
|---|---|---|
enabled |
false |
Disabled by default, opt-in |
severity |
"warning" |
"error" or "warning" |
Test coverage rules#
These are disabled by default. Enable them in CI to enforce test discipline.
SAFE701: test_existence#
What it flags: Source files that have no corresponding test file. Cross-language.
The expected test filename pattern is language-aware:
- Python, looks for
test_<stem>.py(e.g.src/mymodule/foo.pypairs withtest_foo.py). - JavaScript, looks for
<stem>.test.<ext>(Jest convention) or<stem>.spec.<ext>(Mocha / Karma convention) across all registered JS extensions (.js/.mjs/.cjs). For examplesrc/app/foo.jspairs withfoo.test.jsorfoo.spec.js.
The rule searches under the configured test_dirs for any of these patterns. Test files themselves (files under a test_dirs entry, or files whose names already match the pattern) are skipped; the rule doesn't ask a test to have its own test.
| Option | Default | Description |
|---|---|---|
enabled |
false |
Disabled by default, opt-in |
severity |
"warning" |
"error" or "warning" |
test_dirs |
["tests"] |
Directories to search for test files |
[tool.safelint.rules.test_existence]
enabled = true
severity = "warning"
test_dirs = ["tests", "test"]
SAFE702: test_coupling#
What it flags: Source files that were changed without a corresponding change to their test file. Cross-language.
If you modify src/foo.py, you must also modify tests/test_foo.py in the same commit. For JavaScript, modifying src/foo.js requires updating foo.test.js or foo.spec.js. This enforces the discipline that source changes come with test updates. Same filename patterns as SAFE701. Unlike SAFE701, this requires the test file to exist; if it does not, SAFE701 fires instead.
| Option | Default | Description |
|---|---|---|
enabled |
false |
Disabled by default, opt-in |
severity |
"warning" |
"error" or "warning" |
test_dirs |
["tests"] |
Directories to search for test files |
Dataflow rules#
These combine AST analysis with intra-procedural taint tracking. They are more expensive than structural rules and disabled by default. Enable them when you need deeper security or correctness guarantees.
SAFE801: tainted_sink#
What it flags: User-controlled input (function parameters, input() calls in Python, prompt() / confirm() / getItem() in JS, etc.) flowing into dangerous functions like eval, exec, subprocess (Python) or eval / Function / child_process (JavaScript) without being sanitized first. Cross-language.
The rule tracks data flow through assignments: if x = user_data then x is tainted. If y = x + "_suffix" then y is tainted too. Calling eval(y) then triggers a violation. Passing the value through a configured sanitizer (e.g. escape(x)) clears the taint.
Taint is scoped to the block that declares a binding. Changed in 2.17.1. A nested block that rebinds a name used to overwrite the function-wide entry, so the outer binding came back from the block without its taint (#250):
let input = std::env::var("CMD").unwrap(); // tainted
{ let input = "safe"; } // used to clear the entry
cmd.arg(input); // tainted - was NOT reported
The same flat map was wrong in the other direction too, reporting a sink that reads a clean outer binding after an inner block tainted the name. Both are fixed in Rust, JavaScript / TypeScript, C, C++ and Go - every language where a nested block may rebind a name already in scope.
Three languages are deliberately unchanged, and the reason matters if you are reading a finding in one of them. Python has no block scope. PHP's locals are function-scoped, so an inner if (...) { $c = "safe"; } genuinely overwrites the outer $c and the flat model is the correct one. Shadowing a local in a nested block is a compile error in Java. JavaScript var is likewise still function-scoped and hoisted: an inner-block var really does rebind the function-wide name, which is the hazard SAFE305 exists to report, so only let and const are scoped.
A binding declared in a loop or control-statement header is scoped to that statement rather than to a block, since the body is its sibling rather than its parent: a for (let p = 0; ...) head binding ends with the loop, and Go's if cmd := get(); c { } else { ... } binding stays in scope through the else.
Only declaring forms are scoped. A plain x = value inside a block writes through to the binding already in scope, so its taint survives the block, as it must.
Two wordings, by what the analysis actually traced. Changed in 2.16.0. Taint is seeded from two places that are not equally good evidence, so the message now says which one a finding rests on:
| Message | What it means |
|---|---|
Tainted variable "x" flows into dangerous sink "s" |
A recognised source was traced to the sink: input(), $_GET['q'], os.Getenv, a framework request accessor. Untrusted data genuinely reaches s. |
Parameter-derived value "x" reaches dangerous sink "s" |
Only a function parameter was seeded. The sink is real, but nothing in this function shows a request can reach it; the question is what callers pass. |
Seeding every parameter is what makes an intra-procedural analysis useful, and it is also why a helper that takes an argument and calls a dangerous builtin reports whether or not it is reachable from a request. Both kinds still report, and the parameter kind is worth reading: it is how an injection arrives once a caller is attacker-facing. What changed is that it no longer claims to have traced untrusted input.
The distinction follows the flow rather than the spelling. A value derived from a parameter stays
parameter-derived (built = "sh -c " + cmd); mixing a parameter with a source escalates to the
stronger wording (cmd = prefix + input()); and reassigning overwrites the origin along with the
taint, in both directions. A closure capturing a source-tainted local inherits the stronger wording
through the capture.
If you want to review only the traced-source findings first, filter on the message prefix in
--format json; there is no separate rule code, because both are the same hazard seen with
different amounts of evidence.
Taint propagates through projections of a tainted base, uniformly across all languages. Request-driven web code almost never passes a bare tainted parameter to a sink; the data arrives behind an attribute, a subscript, or a method call on the request object. All three keep the taint:
- Attribute / member access -
request.data,req.body,$request->inputstays tainted (the receiver's taint dominates; the attribute name itself is a lookup, not data). - Subscript / index -
request.GET["q"],req.query['q'],argv[1]stays tainted (the base carries the taint, not the index). - Method call on a tainted receiver -
request.GET.get("q"),input.trim(),req->param("q")stays tainted even with no tainted positional arguments. This receiver step is part of the conservativeassume_taint_preserving = trueposture (see below), so it is off when that flag isfalse. The sanitizer check runs first, soescape(request.data)still clears. - Assignment to a sink-named property -
element.innerHTML = taintedis reported, as are theelement["innerHTML"] = taintedsubscript spelling andelement.innerHTML += tainted. Writing the property is the injection, so the target is matched with the same sanitizer and property-typed semantics as a call. Write-sinks live in their ownassignment_sinkslist (assignment_sinks_<lang>, bare for Python), NOT the flatsinkslist: outside JavaScript those hold function names, so reusing them would report every field calledquery/args/loadas an injection. OnlyinnerHTMLships as a default (JavaScript, inherited by TypeScript); addouterHTML/srcdocor a project-specific setter yourself. Supported in all nine languages on their native member shapes. A computed subscript key (results[key] = tainted) is not matched - its spelling names no property - while a quoted one (o["danger"]) is. Added in 2.14.0.
So under a framework preset (which adds request-injection sinks like Django RawSQL / mark_safe, Flask render_template_string, Laravel whereRaw), an idiomatic RawSQL(request.GET["q"]) is detected, not just the rare direct-parameter RawSQL(request).
| Option | Default | Description |
|---|---|---|
enabled |
false |
Disabled by default, opt-in |
severity |
"error" |
"error" or "warning" |
sinks |
see below | Call names considered dangerous |
sanitizers |
see below | Call names that clear taint |
sources |
see below | Call names that inject taint (in addition to parameters) |
assume_taint_preserving |
true |
How unknown calls (neither sanitizer nor source) propagate taint. Added in 1.8.0. |
receiver_sinks |
Java: openConnection, openStream |
Sinks whose payload is the receiver, not an argument (see below). Added in 2.12.1. |
assignment_sinks |
JavaScript: innerHTML |
Sinks that are written to rather than called (el.innerHTML = tainted). Separate from sinks because those are function names. Added in 2.14.0. |
sanitizer_properties |
{} |
Table of sanitiser name -> the safety properties it establishes (e.g. escape = ["html_escaped"]). Opt-in; see Property-typed sanitisers. Added in 2.13.0. |
sink_properties |
{} |
Table of sink name -> the single safety property it requires (e.g. RawSQL = "sql_escaped"). Opt-in; see Property-typed sanitisers. Added in 2.13.0. |
Receiver vs argument payload. When a sink is called as a method on a tainted receiver (x.execute(...)), whether that is an injection depends on where the payload is. For most sinks the payload is an argument (conn.execute(sql)), so a tainted receiver passed only constant arguments - conn.execute("SELECT 1") where conn merely derives from user input - is not flagged (the receiver conveys no user data into the sink). Some sinks, though, carry their payload in the receiver itself - url.openConnection(proxy) is SSRF even when proxy is clean. List those in receiver_sinks (per-language receiver_sinks_<lang>, bare receiver_sinks for Python) and they fire on a tainted receiver regardless of arguments. A receiver_sinks entry must also appear in the matching sinks list. Defaults ship Java's URL SSRF methods (openConnection, openStream).
Changed in 2.16.0: a sink not listed in receiver_sinks no longer reports on a tainted receiver when the call happens to have no arguments. That used to fire, on the reasoning that a no-argument call must be carrying its payload in the receiver. It need not, and the false positives were substantial: $folder->query()->unseen()->get() on a php-imap folder builds an IMAP search, takes no arguments, and was reported as SQL injection - 6 of 10 SAFE801 findings on FreeScout, none substantiated (#158). Declaring the sink in receiver_sinks is now the only evidence accepted. If you relied on the old behaviour for a sink whose payload genuinely is its receiver, add it to receiver_sinks_<lang>.
Default sinks: eval, exec, compile, system, popen, Popen, run, call, check_output, execute
Default sanitizers: escape, sanitize, clean, validate, quote, encode, bleach
Default sources: input, readline, recv, recvfrom, read
[tool.safelint.rules.tainted_sink]
enabled = true
severity = "error"
sinks = ["eval", "exec", "system", "execute"]
sanitizers = ["escape", "sanitize", "quote"]
sources = ["input", "readline"]
assume_taint_preserving = true # default; set false for taint-dropping mode
# Sinks whose payload is the receiver, not an argument (fire on a tainted
# receiver regardless of arguments). Each entry must ALSO appear in the matching
# per-language sinks list (sinks_java here): receiver_sinks only changes how an
# already-registered sink treats its receiver, it does not register a new sink.
# Per-language keys: receiver_sinks_java, receiver_sinks_go, etc.
sinks_java = ["openConnection", "openStream"]
receiver_sinks_java = ["openConnection", "openStream"]
Property-typed sanitisers (sanitizer_properties / sink_properties)#
By default a sanitiser clears taint for every sink - convenient, but imprecise: an HTML escaper does not make a value safe for SQL, yet listing escape in sanitizers clears it for a RawSQL sink too (a false negative). The property-typed contract makes clearing per sink:
sanitizer_propertiesmaps a sanitiser to the safety properties it establishes (e.g.escape = ["html_escaped"]).sink_propertiesmaps a sink to the single property it requires (e.g.RawSQL = "sql_escaped").- A property-typed sanitiser clears a sink only when it establishes that sink's required property. It is path-sensitive: the clear survives an intermediate variable (
safe = escape(x); html_render(safe)is clean, whilerun_sql(safe)still fires). - Only the flat
sanitizerslist clears a sink with no declared property; a property-typed sanitiser never does (establishinghtml_escapeddoes not make a value safe foreval).
A property-typed sanitiser's clear does not survive an intervening unknown call, including a benign-looking wrapper: html_sink(str(escape(u))) and html_sink(escape(u).strip()) both report, because an unknown call may equally well decode its input. The flat sanitizers list does not behave this way - it short-circuits before descending - so the precise form is deliberately the stricter one. Wrap-then-sanitise (escape(str(u))) avoids it.
The mechanism is opt-in and backward compatible: both tables ship empty, and the flat sanitizers list stays universal (clears every sink, as before), so no existing config changes meaning. Move a sanitiser into sanitizer_properties only when you want the tighter, context-specific behaviour. Both keys are per-language (bare for Python, _<lang> suffix otherwise).
Pydantic's validating entry points (model_validate, model_validate_json, parse_obj_as) are a natural schema_validated provider. They are not a shipped default (the contract ships empty, so it adds no cost until you opt in); add them yourself when you declare a schema_validated-requiring sink. They must NOT go in the flat sanitizers list - a schema-validated string is still injectable into a SQL / shell / template sink.
Note the example sets sanitizers = [] so the escapers are governed only by their declared properties; leaving escape in the flat sanitizers list would clear every sink universally (the default behaviour).
pyproject.toml:
[tool.safelint.rules.tainted_sink]
enabled = true
sinks = ["RawSQL", "eval"]
sanitizers = [] # escape / sqlquote are property-typed below, not universal
sanitizer_properties = { escape = ["html_escaped"], sqlquote = ["sql_escaped"] }
sink_properties = { RawSQL = "sql_escaped" } # eval declares no property
safelint.toml:
[rules.tainted_sink]
enabled = true
sinks = ["RawSQL", "eval"]
sanitizers = []
sanitizer_properties = { escape = ["html_escaped"], sqlquote = ["sql_escaped"] }
sink_properties = { RawSQL = "sql_escaped" }
With the above, RawSQL(escape(user_input)) fires (HTML escaping does not satisfy sql_escaped), RawSQL(sqlquote(user_input)) is cleared (matching property), and eval(...) fires for either escaper because eval declares no property and property-typed sanitisers never clear a no-property sink (add a name to the flat sanitizers list for that).
assume_taint_preserving modes (1.8.0)#
Most real codebases pass tainted data through internal helper functions before it reaches a sink. The assume_taint_preserving config flag controls how those unknown calls (i.e. calls whose name isn't in sources or sanitizers) are analysed.
The naming says it directly: when assume_taint_preserving = true, the analyser assumes any unknown call preserves the taint of its arguments, the more conservative stance, fewer false negatives, more false positives:
true(default), conservative / taint-preserving. An unknown call's result is tainted iff any of its arguments are tainted.eval(user_input)fires (direct flow).eval(wrap(user_input))also fires (taint flows through the unknownwrap). Cost: false positives whenwrapis in fact safe.false, taint-dropping (less conservative, weaker detection). Unknown calls always drop taint.eval(user_input)still fires (direct flow).eval(wrap(user_input))does not fire, the unknownwrapresets taint, even if it does in fact pass user input through. Use when your codebase has many internal-only wrappers and you'd rather miss a flow than chase down false positives.
Note the asymmetry: false is the less conservative setting (fewer reports, more chance of missing real issues), not "stricter". The trade-off is fundamental to intra-procedural analysis, there's no way to know whether wrap actually preserves the taint without inlining it. Switch modes based on which failure mode hurts more in your codebase.
Python, Bad:
Python, Good:
def run_query(user_input):
safe = sanitize(user_input)
cursor.execute(safe) # sanitizer clears taint - no violation
JavaScript, Bad:
function runQuery(userInput) {
eval(userInput); // SAFE801 - tainted param reaches eval()
}
function buildFn(userInput) {
return new Function(userInput); // SAFE801 - Function constructor is a sink too
}
JavaScript, Good:
function runQuery(userInput) {
const safe = sanitize(userInput);
someApi.run(safe); // sanitizer clears taint - no violation
}
SAFE802: return_value_ignored#
What it flags: Calls to functions whose return value signals success or failure, where the return value is discarded. Cross-language.
Calling subprocess.run(["rm", "-rf", path]) as a bare statement (not assigning the result) means you never check whether the command succeeded. Same with sock.send(), which returns the number of bytes actually sent and may send fewer than asked - that is why sendall exists.
| Option | Default | Description |
|---|---|---|
enabled |
false |
Disabled by default, opt-in |
severity |
"warning" |
"error" or "warning" |
flagged_calls |
see below | Call names whose return value must not be discarded |
Default flagged_calls: run, call, check_output, send, sendfile, replace
Note: SAFE802 matches the call name without its receiver, so
asyncio.run(main())andapp.run(workers=4)both matchruneven though discarding their result is the universal idiom. Keep that in mind when adding entries.
The Python list was trimmed twice in 2.15.0 (#156); it had been ported from C/POSIX semantics, where checking the return code is correct and necessary, without adjusting for Python's. Two groups left it:
| removed | why |
|---|---|
remove, unlink, rename, makedirs, mkdir, rmdir |
They return None, so the rule demanded a check of a value that cannot exist. The os.* forms all return None; the pathlib forms return either None (Path.unlink, Path.mkdir, Path.rmdir) or a Path that nothing acts on (Path.rename, Path.replace). Because matching ignores the receiver, these also covered list.remove and every other method of the name. |
write, seek, truncate |
They return a byte count, a file position and a result nobody reads. On Django these were 404 of the 614 findings left after the six above went, so they were the larger half of the problem. |
What stayed, and why: send and sendfile, which return a byte count and may transfer fewer bytes than asked; run / call / check_output, because subprocess.run returns a CompletedProcess whose returncode matters; and replace, which is deliberately ambiguous - str.replace and Path.replace both return a value worth keeping, os.replace does not. sendall is not on the list: it returns None and raises on error, so it exists precisely so the short-write check is unnecessary.
All of them are defaults, not hard-coded: list a name in flagged_calls to bring it back. The C defaults (flagged_calls_c) are unchanged - there the return code genuinely is the point.
[tool.safelint.rules.return_value_ignored]
enabled = true
severity = "warning"
flagged_calls = ["run", "call", "check_output", "send", "sendfile", "replace"]
Python, Bad:
subprocess.run(["deploy.sh"]) # SAFE802 - return value discarded
sock.send(payload) # SAFE802 - a short send is silently accepted
f.write(data) does not fire on the default list: write was removed in 2.15.0, because discarding the byte count is idiomatic Python (see the table above). Add "write" to flagged_calls if your codebase treats it as significant.
Python, Good:
result = subprocess.run(["deploy.sh"])
if result.returncode != 0:
raise RuntimeError("Deploy failed")
JavaScript, Bad:
fs.writeFile("out.txt", data, cb); // SAFE802 - the returned Promise is discarded
stream.write(buf); // SAFE802 - backpressure signal ignored
JavaScript, Good:
SAFE803: null_dereference#
What it flags: Chained attribute access or subscript directly on a call that can return None (Python) / null or undefined (JavaScript), without a guard. Cross-language.
dict.get() returns None when the key is absent. Calling .strip() on the result without checking for None first will raise AttributeError at runtime. Same with ORM methods like session.scalar() or cursor.fetchone().
| Option | Default | Description |
|---|---|---|
enabled |
false |
Disabled by default, opt-in |
severity |
"error" |
"error" or "warning" |
nullable_methods |
see below | Method names whose return value may be None |
Default nullable_methods: get, pop, find, next, first, one_or_none, scalar, scalar_one_or_none, fetchone
[tool.safelint.rules.null_dereference]
enabled = true
severity = "error"
nullable_methods = ["get", "pop", "find", "fetchone", "first"]
Python, Bad:
name = config.get("username").strip() # SAFE803 - .get() can return None
row = cursor.fetchone().value # SAFE803 - fetchone() can return None
Python, Good:
# Or supply a literal fallback. Not reported: the key being absent now yields
# the fallback rather than None, so the common dereference is safe.
name = config.get("username", "").strip()
Python fallback arguments. get, pop and next take a fallback as their
second argument (getattr as its third, if you add it to nullable_methods).
The finding is dropped when that slot holds a literal whose value is
non-None by construction: a dict, list, set or tuple display, a string, a
number, a bool, ..., a comprehension, a generator expression or a lambda.
d.get(k, {}).x is the Python safe-navigation idiom, and reporting it fired the
rule hardest on the code written to be safe.
The check is syntactic and one-directional, so anything opaque still reports:
d.get(k, None).x # the fallback IS None
d.get(k, (None)).x # ...grouping does not change that
d.get(k, fallback).x # a name is opaque; it may well BE None
d.get(k, compute()).x # ...as may a call's return value
d.get(k, a or b).x # an or-chain falls through to its last operand
d.get(*args).x # a splat hides the positional count
d.get(k, **kw).x # ...as does a keyword splat
d.get(k, default=f).x # a keyword argument is not positional
Grouping is peeled before the check, so d.get(k, ({})).x is recognised as the
dict literal it is and stays quiet.
Known limits. A literal fallback does not prove the call cannot return
None, and SAFE803 keeps no model of what values a mapping or an iterator
holds:
- a mapping that stores
Noneunder the key returnsNonewhatever the default is, sod.get(k, {}).xon{"k": None}raises and is not reported; next(it, {})yields whatever the iterator produced, which may beNone.
Deciding either needs value tracking the rule does not do. The alternative is to
report every defaulting lookup, which is the noise this behaviour exists to
remove, so both misses are accepted deliberately. Guard with an explicit
comparison where the values themselves may be None.
The suppression is scoped to the names above, not to any call with two
arguments: session.find("Model", 42).name and cursor.fetchone(1, 2).value
take arguments that are not fallbacks and still report. JavaScript is unaffected
- Map.prototype.get ignores a second argument rather than returning it, so
treating it as a fallback there would hide a real null dereference.
JavaScript, Bad:
const text = document.getElementById("title").textContent; // SAFE803 - getElementById can return null
const first = users.find(u => u.id === id).name; // SAFE803 - .find() can return undefined
JavaScript, Good:
// Optional chaining, the modern guard
const text = document.getElementById("title")?.textContent;
const first = users.find(u => u.id === id)?.name;
// Or explicit check (catches both null and undefined via loose !=)
const el = document.getElementById("title");
if (el != null) {
process(el.textContent);
}
Java + Spring Boot rules#
SAFE9xx rules are Java-only structural checks for common Spring Boot misuses. All four are disabled by default and enabled together by the spring-boot framework preset ([tool.safelint.java] framework = "spring-boot"). They do not fire on Python / JavaScript / TypeScript files even if explicitly enabled; rule dispatch is gated on file language.
SAFE901: spring_field_injection#
What it flags: A class field annotated with @Autowired (or the fully-qualified @org.springframework.beans.factory.annotation.Autowired). Java only.
Spring's reference documentation recommends constructor injection over field injection: constructor-injected dependencies are immutable (final), testable without reflection, fail fast on missing beans at construction time, and surface obvious circular dependencies as compile errors. Field-injected dependencies hide all of those properties.
Test classes are skipped. Added in 2.17.0. Field injection in a test is the pattern Spring's own reference documentation and sample code use, and the argument for constructor injection does not carry over: the framework instantiates a @SpringBootTest class itself, so there is no constructor the user controls in the ordinary way, and the usual case for constructor injection is substantially about making a class easy to unit-test, which inverts when applied to the test. Measured on Spring PetClinic, written by the Spring team as the reference example: 17 findings, all 17 in test classes and 63% of the project's whole default output, with none in production code. The three Java test-filename conventions (*Test.java, *Tests.java, *IT.java) account for every one, so no annotation detection is needed. skip_test_code and test_dirs are the same keys, with the same meaning, as the #198 rules read. They are resolved per rule, so a project with non-standard test directories sets test_dirs under spring_field_injection as well: the engine passes each rule only its own configuration section, and there is no project-wide test_dirs. Set skip_test_code = false for the strict reading.
| Option | Default | Description |
|---|---|---|
enabled |
false (vanilla) / true (spring-boot preset) |
Toggle the rule |
severity |
"warning" |
"error" or "warning" |
skip_test_code |
true |
Skip files identified as test code. Added in 2.17.0. |
test_dirs |
["tests", "test", "__tests__", "spec"] |
Directory names counted as test code, matched at any depth. Added in 2.17.0. |
Bad:
Not flagged (a test class, by filename):
// OwnerControllerTests.java
class OwnerControllerTests {
@Autowired
private VetRepository vets; // the pattern Spring's own samples use
}
Good:
@Service
public class OrderService {
private final InventoryClient inventory;
public OrderService(InventoryClient inventory) {
this.inventory = inventory;
}
}
SAFE902: spring_missing_transactional#
What it flags: A @Service or @Component method that performs two or more Spring Data repository writes (save / saveAll / saveAndFlush / delete / deleteAll / deleteAllInBatch / deleteAllById / deleteAllByIdInBatch / deleteById / update) without @Transactional on the method or the enclosing class. Java only.
Multi-write methods without @Transactional run each write in its own short-lived transaction; a failure between writes leaves the database in a partially-updated state. Single-write methods are exempt because the implicit per-statement transaction is sufficient.
Receiver-name heuristic: detection is constrained to method invocations whose receiver name (lowercased) contains repo / dao / jdbctemplate, e.g. userRepo.save(...), productDao.update(...), jdbcTemplate.update(...). Without this guard, call_name() strips the receiver and unrelated calls like file.delete() / cache.delete() / restTemplate.delete(...) would be counted. Rename a service-managed field if your convention is userStore / userManager / etc., or add the matching pattern via [tool.safelint.rules.spring_missing_transactional] configuration in a future release (currently the pattern set is fixed at the source level).
| Option | Default | Description |
|---|---|---|
enabled |
false (vanilla) / true (spring-boot preset) |
Toggle the rule |
severity |
"error" |
"error" or "warning" |
Bad:
@Service
public class OrderService {
public void placeOrder(Order order) {
orderRepo.save(order);
inventoryRepo.update(order.itemId(), -1); // SAFE902: 2 writes, no @Transactional
}
}
Good:
@Service
public class OrderService {
@Transactional
public void placeOrder(Order order) {
orderRepo.save(order);
inventoryRepo.update(order.itemId(), -1);
}
}
SAFE903: spring_unvalidated_input#
What it flags: A @RestController or @Controller method parameter annotated with @RequestBody or @ModelAttribute that is NOT also annotated with @Valid or @Validated. Java only.
Without @Valid / @Validated, Bean Validation constraints declared on the DTO (@NotNull, @Size, @Email, etc.) are silently ignored. Malformed or hostile input reaches the controller body. @PathVariable and @RequestParam are deliberately NOT covered because they typically bind to primitives or simple strings where bean validation is rarely declared.
| Option | Default | Description |
|---|---|---|
enabled |
false (vanilla) / true (spring-boot preset) |
Toggle the rule |
severity |
"error" |
"error" or "warning" |
Bad:
@RestController
public class UserController {
@PostMapping("/users")
public User create(@RequestBody UserDto dto) { ... } // SAFE903: no @Valid
}
Good:
@RestController
public class UserController {
@PostMapping("/users")
public User create(@Valid @RequestBody UserDto dto) { ... }
}
SAFE904: spring_async_checked_exception#
What it flags: A method annotated @Async that declares a throws clause. Java only.
The rule's name and historical framing emphasised checked exceptions, but the implementation flags any throws clause (checked or unchecked) because distinguishing the two requires class-resolution / type-inference we don't do. The conservative behaviour is justified: Spring's executor swallows whatever the method throws regardless of checked-vs-unchecked, so the throws clause is always misleading - it implies the caller can observe the exception when in fact they cannot. Fix by either catching inside the method body or returning a CompletableFuture whose failure state carries the exception (CompletableFuture.failedFuture(ex)).
If you have a deliberate throws RuntimeException on an @Async method (rare; the JLS doesn't require it), suppress with // nosafe: SAFE904 on the method declaration.
| Option | Default | Description |
|---|---|---|
enabled |
false (vanilla) / true (spring-boot preset) |
Toggle the rule |
severity |
"warning" |
"error" or "warning" |
Bad:
@Service
public class IngestService {
@Async
public void process(File f) throws IOException { ... } // SAFE904
}
Good:
@Service
public class IngestService {
@Async
public CompletableFuture<Void> process(File f) {
try {
// ... I/O work
return CompletableFuture.completedFuture(null);
} catch (IOException e) {
return CompletableFuture.failedFuture(e);
}
}
}
Framework preset rules (Python / PHP)#
The following five rules (SAFE905-909) generalise across the Python (Django / Flask / FastAPI) and PHP (Laravel) framework presets. Each serves multiple frameworks and is gated purely by its enabled flag - a framework preset flips it on. Detection is language-family aware (Python vs PHP node shapes), not tied to one specific framework. All ship disabled by default; the [tool.safelint.python] framework / [tool.safelint.php] framework presets enable the applicable ones (see the Python and PHP language pages). They are the non-Java analogue of the Spring SAFE9xx rules.
SAFE905: debug_mode_enabled#
What it flags: A framework debug / reload flag hard-enabled in code. Python + PHP.
Debug mode in production leaks stack traces, settings, and (Flask / Werkzeug) an interactive console; auto-reload is a development-only convenience. Detected patterns:
- Python:
DEBUG = True(Django settings),app.debug = True(Flask; the receiver must look like an app object), and adebug=True/reload=Truekeyword on a framework runner call -app.run(debug=True)(Flask),uvicorn.run(..., reload=True)(FastAPI / ASGI). Adebug=Truekeyword on an unrelated call (e.g.client.connect(debug=True)) is not flagged. - PHP: a config-array entry whose key ends in
debugmapped totrue('app.debug' => true,'debug' => true)..envfiles are not parsed, so this is code-only.
| Option | Default | Description |
|---|---|---|
enabled |
false (vanilla) / true (framework preset) |
Toggle the rule |
severity |
"warning" |
"error" or "warning" |
Bad:
DEBUG = True # Django settings.py - SAFE905
app.run(debug=True) # Flask - SAFE905
uvicorn.run("main:app", reload=True) # FastAPI - SAFE905
Good:
The framework presets enable this rule automatically; enable it directly with either TOML layout:
SAFE906: mass_assignment#
What it flags: Unbounded attribute binding from request data. Python + PHP.
"Bind everything the client sent" defeats the point of an allow-list and lets a caller set fields they should not. Detected patterns:
- Python (Django): a
ModelForm/ serializerMeta.fields = "__all__". - Python (Pydantic): an input model declaring
extra = "allow"- asclass Config: extra = "allow"(v1),model_config = ConfigDict(extra="allow"), ormodel_config = {"extra": "allow"}(v2). Enabled bypydantic = trueas well as the Django / FastAPI presets. - PHP (Laravel): an Eloquent
$guarded = [](guards nothing, so every attribute is mass-assignable).$fillableallow-lists are safe.
Flask does not enable this rule (it has no comparable mass-assignment idiom).
| Option | Default | Description |
|---|---|---|
enabled |
false (vanilla) / true (Django / FastAPI / pydantic / Laravel) |
Toggle the rule |
severity |
"error" |
"error" or "warning" |
Bad:
Good:
The django / fastapi / laravel presets and pydantic = true enable this rule automatically; enable it directly with either TOML layout:
SAFE907: unvalidated_request_input#
What it flags: Request data consumed whole with no validation layer. Python + PHP. The cross-framework generalisation of Spring's SAFE903.
Per function / method: a whole-object request-data read with no validation call in the same scope. Detected patterns:
- Python:
request.POST/request.data/request.json/request.form/request.body/request.query_paramsconsumed whole, with no concrete validation call (is_valid/full_clean/validate/model_validate/parse_obj) in the function (Django / Flask / FastAPI). A bareSerializer/Schemaname reference is not accepted as validation. Single-field access (request.POST.get('x'),request.GET['q']) is targeted and NOT flagged. - PHP (Laravel):
$request->all()/ bare$request->input()with no validation call in the method ($request->input('field')is a targeted read and is not flagged).
The rule is conservative and heuristic: a validation call anywhere in the scope clears the whole function.
What counts as validation in Laravel. $request->validate(...) is the shape the rule started with, but it is not the dominant one; on FreeScout Validator::make outnumbers it by 19 to 1. All four of these clear the read (since 2.15.0):
$request->validate(['name' => 'required']); // request as receiver
$this->validate($request, ['name' => 'required']); // ValidatesRequests trait
Validator::make($request->all(), $rules)->validate(); // the Validator facade
$this->validator($request->all())->validate(); // a validator built from the data
Only the unqualified Validator (the aliased import Laravel code writes) and the fully-qualified Illuminate\Support\Facades\Validator count as the facade; another namespace's Validator is a different class. Chaining a ->validate() onto any call built from the request data clears it regardless of the class, which is the $this->validator(...) case above.
The facade form also follows a one-step local alias, which is how Laravel code massages input before validating it:
$post = $request->all();
$post['body'] = strip_tags($post['body']);
$validator = Validator::make($post, $rules); // clears: $post holds the request data
if ($validator->fails()) {
return back()->withErrors($validator); // Validator::make BUILDS a validator;
} // something must then run or check it
Note what the rule does and does not see there. Validator::make(...) on its own only constructs a validator - the rules do not run until ->validate() is called or ->fails() is consulted - and safelint does not verify that you did either. It treats the make as the author's declaration of intent to validate, which is the same conservative stance the rule takes everywhere else (any validation call clears the whole function). A make whose result is dropped on the floor is a bug this rule will not catch.
A Form Request parameter clears the whole method, because the framework ran that class's rules() before the body was entered. Recognised by a parameter type whose final name segment ends in Request without being one of the base request types that carry no rules of their own - Request, FormRequest, ServerRequest, ServerRequestInterface, RequestInterface:
public function store(StoreUserRequest $request) {
return User::create($request->all()); // already validated
}
Each of these still requires the request: Validator::make($defaults, $rules) validates something else and does not clear a $request->all() elsewhere in the method, a variable rebound to other data stops standing in for the request, and $foo->request is an ordinary property rather than the framework request.
The Form Request test is a name heuristic, and cannot be more: confirming that StoreUserRequest really extends FormRequest needs the file that declares it. A parameter typed BillingRequest that is not a Form Request will clear the method too. Rename it, or ignore the rule for that file, if the suppression is unwanted.
Project validators. Real apps often validate through their own helper (validate_export_request(), an allowlist filter builder) rather than the framework's built-in call. Add those names to request_validators (Python, bare key) / request_validators_php (PHP) and they are unioned with the built-in set, so a read they guard no longer fires. Matched by exact call name (receiver stripped, like tainted_sink.sanitizers). This replaces the previous only-recourse of a file-level ignore, which also hid any genuinely-unvalidated read added to the same file later.
| Option | Default | Description |
|---|---|---|
enabled |
false (vanilla) / true (framework preset) |
Toggle the rule |
severity |
"warning" |
"error" or "warning" |
request_validators |
[] |
(Python.) Project validation-call names, unioned with the built-in set. Added in 2.12.0. |
request_validators_php |
[] |
(PHP.) Project validation-call names, unioned with the built-in validate. Added in 2.12.0. |
Bad:
Good:
def create(request):
serializer = ItemSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
return serializer.save()
The framework presets enable this rule automatically; enable it directly with either TOML layout:
# pyproject.toml
[tool.safelint.rules.unvalidated_request_input]
enabled = true
severity = "warning"
request_validators = ["validate_export_request", "clean_filters"] # Python; unioned with the built-ins
request_validators_php = ["allowlist"] # PHP; unioned with `validate`
# safelint.toml
[rules.unvalidated_request_input]
enabled = true
severity = "warning"
request_validators = ["validate_export_request", "clean_filters"]
SAFE908: csrf_protection_disabled#
What it flags: CSRF protection explicitly turned off in code. Python (Django) + PHP (Laravel). New in v2.11.0.
CSRF protection is on by default in these frameworks; disabling it opens a hole an attacker can drive state-changing requests through. Detected patterns:
- Python (Django): a
@csrf_exemptdecorator - bare (@csrf_exempt), called (@csrf_exempt()), or wrapped for a class-based view (@method_decorator(csrf_exempt)). - PHP (Laravel): a non-empty
$exceptproperty inside the CSRF middleware class - theVerifyCsrfTokenroute allow-list. An empty$except = []exempts nothing and is clean.
Class context is required on the PHP side (since 2.15.0). $except only means "CSRF-exempt routes" on VerifyCsrfToken; Laravel ships TrimStrings and EncryptCookies with an $except of their own that has nothing to do with CSRF, so matching the property name alone reported two findings on every unmodified Laravel app. The class now has to be named VerifyCsrfToken or extend it - directly, through a namespace-qualified name, or through the use ... as Middleware alias Laravel's own scaffolding writes:
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware {
protected $except = ['stripe/*']; // reported
}
class TrimStrings extends Middleware {
protected $except = ['password']; // clean: not the CSRF middleware
}
A trait is not followed into the class that mixes it in, so an $except declared in a trait is not reported.
More false-positive-prone than SAFE905-907 (a same-named decorator would match), so it is off under vanilla and switched on only by the presets that scope it: the Django and Laravel presets enable it; Flask (CSRF is extension-provided) and FastAPI do not.
| Option | Default | Description |
|---|---|---|
enabled |
false (vanilla) / true (Django + Laravel presets) |
Toggle the rule |
severity |
"error" |
"error" or "warning" |
Bad (Django):
Bad (Laravel):
class VerifyCsrfToken extends Middleware {
protected $except = ['stripe/*']; // SAFE908: routes exempted from CSRF
}
The Django / Laravel presets enable this rule automatically; enable it directly with either TOML layout:
SAFE909: hardcoded_secret#
What it flags: A secret key assigned a string literal in code. Python (Django / Flask) + PHP (Laravel). New in v2.11.0.
A committed secret is a credential leak the moment it lands in version control. Detected patterns:
- Python:
SECRET_KEY = "..."(Django) orx.secret_key = "..."(Flaskapp.secret_key) where the value is a string literal. Reading from the environment (SECRET_KEY = os.environ["X"]/= env("X")) is a call, not a literal, and is clean. An empty-string placeholder is not flagged. - PHP (Laravel): a
base64:-prefixed string literal - a hardcodedAPP_KEY.'key' => env('APP_KEY')has no literal and is clean..envfiles are not parsed, so this is code-only (a documented limit).
Off under vanilla and switched on only by the presets that scope it (a literal placeholder in an example or test-settings file can be a false positive): the Django, Flask, and Laravel presets enable it; FastAPI does not.
| Option | Default | Description |
|---|---|---|
enabled |
false (vanilla) / true (Django + Flask + Laravel presets) |
Toggle the rule |
severity |
"error" |
"error" or "warning" |
Bad:
Good:
The Django / Flask / Laravel presets enable this rule automatically; enable it directly with either TOML layout:
Rust-only rules#
The following 11 rules apply only to Rust source. They cover patterns the cross-language rules don't translate to cleanly (Rust has no try/catch, no global keyword, RAII handles resource cleanup), or that are uniquely valuable in Rust idiom (unsafe documentation, panic placement, lock poisoning, etc.). All ship disabled by default; opt in via [tool.safelint.rules.<name>] enabled = true. See Rust for the full language reference including idiomatic fix patterns.
SAFE110: needless_mut#
What it flags: let mut x = ... where x is never reassigned, never has &mut x taken, and is never used as a method receiver / field-access target / index target. Rust only.
Rust's default-immutable design encourages declaring mut only when truly needed. Needless mut widens the surface for accidental mutation and obscures which variables are actually meant to change. The rule is conservative - skips when usage is ambiguous (method call, field expression, index expression) to keep false-positive rate low. Mirrors clippy::needless_mut for projects without a clippy run. Holzmann rule 6 (smallest scope).
| Option | Default | Description |
|---|---|---|
enabled |
false |
Toggle the rule |
severity |
"warning" |
"error" or "warning" |
Bad:
Good:
SAFE112: unchecked_arithmetic_on_input#
What it flags: + / - / * (NOT / or %) where at least one operand is an identifier matching an integer-typed function parameter. Rust only.
Rust's bare + / - / * panic on overflow in debug builds and wrap silently in release builds - the worst of both worlds for production reliability. checked_* / wrapping_* / saturating_* make the choice explicit. / and % are excluded - division by zero is a separate panic-on-debug hazard not addressed by the checked_* family the same way. Static-only detection (parameter type annotations); locally-derived integers aren't tracked - cargo clippy covers the type-inference version. Holzmann rule 7 (check return values).
| Option | Default | Description |
|---|---|---|
enabled |
false |
Toggle the rule |
severity |
"warning" |
"error" or "warning" |
Bad:
pub fn total(price: u32, quantity: u32) -> u32 {
price * quantity // silent overflow in release - SAFE112
}
Good:
pub fn total(price: u32, quantity: u32) -> Result<u32, &'static str> {
price.checked_mul(quantity).ok_or("overflow")
}
SAFE204: panic_macros_outside_tests#
What it flags: panic! / todo! / unimplemented! macro invocations in non-test code. Rust only.
Production code should return Result<_, _> instead of crashing. Panics in test code (#[test] / #[cfg(test)] mod) are expected - they're the test framework's failure signal - so test context is exempt. unreachable!() is deliberately excluded from defaults - it's idiomatic for impossible-branch markers in match arms.
| Option | Default | Description |
|---|---|---|
enabled |
false |
Toggle the rule |
severity |
"warning" |
"error" or "warning" |
panic_macros_rust |
["panic", "todo", "unimplemented"] |
Macro names that count as "panicking". Add "unreachable" if you want it flagged. |
Bad:
pub fn parse_config(path: &str) -> Config {
let raw = std::fs::read_to_string(path).unwrap();
if raw.is_empty() {
panic!("config is empty"); // SAFE204
}
serde_yaml::from_str(&raw).unwrap()
}
Good:
pub fn parse_config(path: &str) -> Result<Config, ConfigError> {
let raw = std::fs::read_to_string(path)?;
if raw.is_empty() {
return Err(ConfigError::Empty);
}
serde_yaml::from_str(&raw).map_err(ConfigError::Parse)
}
SAFE205: lock_poisoning_ignored#
What it flags: mutex.lock().unwrap() / rwlock.read().unwrap() / .write().unwrap() / try_lock().unwrap() / try_read().unwrap() / try_write().unwrap() and the .expect("...") variants. Rust only.
When a thread panics while holding a Mutex / RwLock guard, the lock becomes poisoned: subsequent acquisitions return Err(PoisonError). .unwrap() cascades the panic to every other lock holder, often masking the original failure. Safer alternatives: match on PoisonResult, .into_inner() to recover explicitly, or parking_lot::Mutex which has no poison state.
| Option | Default | Description |
|---|---|---|
enabled |
false |
Toggle the rule |
severity |
"warning" |
"error" or "warning" |
Bad:
Good:
SAFE206: silent_result_discard#
What it flags: Empty Err arms in match (Err(_) => {}) and empty if let Err(_) = ... { } bodies. Rust only.
The Rust spiritual analogue of SAFE202 empty_except - "I caught the error and did literally nothing." Both wildcard (Err(_)) and binding (Err(e)) forms count; the silent thing is the no-op body. let _ = result; and result.ok(); do NOT fire - those are explicit auditable discards, not silent swallows. if let Ok(v) = result { ... } without else doesn't fire either (common idiom where the Err case is handled elsewhere).
| Option | Default | Description |
|---|---|---|
enabled |
false |
Toggle the rule |
severity |
"warning" |
"error" or "warning" |
Bad:
Good:
SAFE207: unlogged_error_branch#
What it flags: Err arms / if let Err(...) bodies with non-empty bodies that contain no log call and don't propagate / panic. Rust only.
The Rust spiritual analogue of SAFE203 logging_on_error - handling an error without logging it loses the failure context. Recognised log calls: error! / warn! / info! / debug! / trace! / log! / event! (log + tracing crates), eprintln! / eprint! / println! / print! / dbg!. Exempts bodies that contain a return_expression, a panic-like macro (panic! / todo! / unreachable! / unimplemented!), or a tail-position Err(...) re-raise.
Two further exemptions since 2.15.0:
- Logging through a same-file helper. A body that calls a function defined in the same file whose own body contains a recognised log call is not swallowing the error, it is routing it:
Err(e) => self.fail(&object.name, e.to_string()), // clean: fail() logs
fn fail(&mut self, object: &str, reason: String) {
warn!(object, %reason, "object failed; continuing");
self.outcome.failed.push((object.to_string(), reason));
}
The log call in the helper is the whole test. A helper that only records the failure to a list and never logs is not credited, and the branch still reports. One call hop only; a deeper chain still reports.
- An arm that enumerates one error variant and binds nothing. Err(store::Error::NotFound { .. }) => Ok(false) implements a documented "treat not-found as false" contract, and binds nothing, so there is no error value in scope to put in a message. Binding is the test rather than syntax, so the wildcard forms count as binding nothing too: Err(E::NotFound(_)) and Err(E::Io { source: _ }) are exempt. An arm that genuinely binds part of the error (Err(E::Io(e)), Err(E::Io { source }), Err(E::Io { source: inner })), a plain binding (Err(other)) or a wildcard (Err(_)) still reports, because there the author either has a value to log or has not discriminated anything.
| Option | Default | Description |
|---|---|---|
enabled |
false |
Toggle the rule |
severity |
"warning" |
"error" or "warning" |
Bad:
Good:
SAFE208: result_unwrap_outside_tests#
What it flags: Any .unwrap() / .expect() / .unwrap_unchecked() outside test code. Rust only.
What counts as test code (widened in 2.15.0): a #[test] / #[tokio::test] function or a #[cfg(test)] mod in the same file, plus two shapes Cargo makes idiomatic and an in-file attribute search can never see:
- A file under a
tests/directory. Cargo integration tests get no#[cfg(test)]- the directory is the gate - so every.unwrap()in atests/file was reported. Atestscomponent insidesrcdoes not count:src/tests/helpers.rsis ordinary crate source in a module namedtests, and when that module is gated the#[cfg(test)] mod tests;in its parent is what says so. Cargo's integration tests sit in atests/that is a sibling ofsrc, never within it. - A module gated from its parent.
#[cfg(test)] mod helpers;inlib.rsgateshelpers.rsentirely; the attribute lives in the parent file, not the module's own. Only amodnamed after the file counts, so#[cfg(test)] mod other;beside a plainmod helpers;does not gatehelpers.rs.
The broad Holzmann-rule-7 form: catches bare-variable unwraps (let r = foo(); r.unwrap();) and unwrap chains the narrower SAFE205 (lock-specific) / SAFE803 (nullable-method-specific) rules don't cover. With all three enabled, mutex.lock().unwrap() fires multiple codes - documented intentional overlap; users pick strictness level by enabling subsets. unwrap_or / unwrap_or_default / unwrap_or_else are NOT flagged - they're explicit-default-on-Err, not silent failures.
| Option | Default | Description |
|---|---|---|
enabled |
false |
Toggle the rule |
severity |
"warning" |
"error" or "warning" |
Bad:
pub fn read_config() -> Config {
let raw = std::fs::read_to_string("config.toml").unwrap(); // SAFE208
toml::from_str(&raw).unwrap() // SAFE208
}
Good:
pub fn read_config() -> Result<Config, ConfigError> {
let raw = std::fs::read_to_string("config.toml")?;
toml::from_str(&raw).map_err(ConfigError::Parse)
}
SAFE306: dangerous_mem_ops#
What it flags: Calls to std::mem::transmute / transmute_copy / forget / zeroed / uninitialized. Rust only.
All four are footguns: transmute reinterprets bits as a different type (use From / TryFrom / bytemuck instead); forget skips Drop (use ManuallyDrop); zeroed constructs an all-zero value of any type (use MaybeUninit::zeroed + explicit unsafe read so the hazard is visible at the use site); uninitialized was deprecated in 1.39+ in favour of MaybeUninit::uninit().
Path-qualified detection: the function must be a scoped_identifier whose path contains "mem" (so mem::transmute after use std::mem and std::mem::transmute both fire, but a user-defined my_helpers::transmute does NOT). Bare transmute(x) (no mem:: prefix) is NOT flagged.
| Option | Default | Description |
|---|---|---|
enabled |
false |
Toggle the rule |
severity |
"error" |
"error" or "warning" |
dangerous_mem_ops_rust |
["transmute", "transmute_copy", "forget", "zeroed", "uninitialized"] |
Names to flag (trailing bareword of the scoped path) |
Bad:
Good:
SAFE307: interior_mutable_static#
What it flags: static items whose type provides safe interior mutability, and lazy_static! declarations. Rust only. Disabled by default.
Holzmann rule 6 (declare data at the smallest possible scope) bans global mutable state. Rust's static mut route requires unsafe and is therefore already audit-gated by SAFE602 (undocumented_unsafe), but the idiomatic route, a plain static holding a Mutex / RwLock / OnceLock / Atomic* / a lazy_static! block, is entirely safe code and invisible to SAFE602. SAFE307 closes that gap.
Two shapes fire: a static whose declared type contains an interior-mutability wrapper name as a standalone token (qualified paths like std::sync::Mutex<T> match too); and a lazy_static! { ... } macro invocation, flagged wholesale because the macro's whole purpose is declaring lazily-initialised statics and its body is an opaque token tree (the same limitation SAFE801 has with sqlx::query!). const items (immutable by construction) and static mut (SAFE602's territory) are not flagged. Word-boundary matching keeps Lazy from matching a user type like LazyLoader.
| Option | Default | Description |
|---|---|---|
enabled |
false |
Toggle the rule |
severity |
"warning" |
"error" or "warning" |
interior_mutable_types_rust |
Mutex, RwLock, RefCell, Cell, OnceLock, OnceCell, Lazy, LazyLock, LazyCell, AtomicBool, AtomicI8..AtomicI64, AtomicIsize, AtomicU8..AtomicU64, AtomicUsize, AtomicPtr |
Wrapper type names that mark a static as interior-mutable |
# pyproject.toml
[tool.safelint.rules.interior_mutable_static]
enabled = true
severity = "warning"
# Narrow or extend the wrapper-type set (replaces the default list):
interior_mutable_types_rust = ["Mutex", "RwLock", "OnceLock", "AtomicUsize"]
# standalone safelint.toml (same keys, no [tool.safelint] prefix)
[rules.interior_mutable_static]
enabled = true
Bad:
static CACHE: Mutex<Vec<u8>> = Mutex::new(Vec::new()); // SAFE307
static COUNT: AtomicUsize = AtomicUsize::new(0); // SAFE307
Good:
const MAX_RETRIES: u32 = 5; // immutable constant, not flagged
// or pass the Mutex<Vec<u8>> explicitly to the consumers that need it
SAFE308: truncating_as_cast#
What it flags: as u8 / as i8 / as u16 / as i16 / as u32 / as i32 / as u64 / as i64 / as f32 casts. Rust only.
Rust's as operator silently truncates when the source value doesn't fit in the destination: 1_000_000u32 as u8 returns 64 (low byte), no panic, no error. TryFrom / try_into() returns Result<T, TryFromIntError>, making the failure mode explicit and checked. isize / usize / i128 / u128 / f64 are NOT flagged as targets (widest types; casts TO them from smaller types don't truncate). Holzmann rule 1 + 7.
| Option | Default | Description |
|---|---|---|
enabled |
false |
Toggle the rule |
severity |
"warning" |
"error" or "warning" |
truncating_cast_targets_rust |
["i8", "u8", "i16", "u16", "i32", "u32", "i64", "u64", "f32"] |
Target type names to flag |
Bad:
Good:
SAFE602: undocumented_unsafe#
What it flags: unsafe { ... } blocks lacking a // SAFETY: comment (case-insensitive) on a preceding line. Rust only.
The // SAFETY: comment convention (also enforced by clippy::undocumented_unsafe_blocks) documents why a particular use of unsafe is sound - which invariants the surrounding code upholds, why the safety contract of each unsafe operation is met. Without it, future readers (including the original author six months later) can't audit whether the unsafe is still justified.
Both // SAFETY: (line comment) and /* SAFETY: */ (block comment) forms count. Multiple intervening line comments are allowed (the SAFETY line doesn't need to be the immediately-previous sibling, but no non-comment statement may sit between them). unsafe fn declarations are NOT covered - they require /// # Safety doc comments, a separate convention.
| Option | Default | Description |
|---|---|---|
enabled |
false |
Toggle the rule |
severity |
"warning" |
"error" or "warning" |
Bad:
Good:
// SAFETY: dst was allocated and aligned by the caller (see `Buffer::reserve`);
// value is a Copy type so this can't leak Drop.
unsafe {
std::ptr::write(dst, value);
}
Go-only rules#
The following 2 rules apply only to Go source. They cover Go-idiom patterns the cross-language rules don't translate to cleanly (Go has no try/catch, so the swallowed-error and panic-placement hazards take Go-specific shapes). Both ship disabled by default; opt in via [tool.safelint.rules.<name>] enabled = true. See Go for the full language reference including idiomatic fix patterns.
SAFE209: empty_error_check#
What it flags: an if err != nil { } (or == nil) whose body is empty or comment-only. Go only.
Go's error handling is explicit: a function returns an error and the caller checks it. Writing the check and then leaving the body empty silently swallows the failure, which is worse than not checking at all (it looks handled). This is Go's analogue of Rust's SAFE206 (silent_result_discard) and the spirit of Python's SAFE202 (empty_except). A comment-only body fires too: the error was acknowledged and still ignored.
The error identifier is configurable; the default matches Go's conventional err. The comparison operand order is not assumed (err != nil and nil != err both match).
| Option | Default | Description |
|---|---|---|
enabled |
false |
Toggle the rule |
severity |
"warning" |
"error" or "warning" |
error_names_go |
["err"] |
Identifier names treated as the error variable |
# pyproject.toml
[tool.safelint.rules.empty_error_check]
enabled = true
error_names_go = ["err", "e", "rerr"]
Bad:
Good:
SAFE211: panic_calls_outside_tests#
What it flags: panic(...) calls in non-_test.go files. Go only.
Production Go code should return an error up the call stack, not unwind it with panic. A panic in a library forces every caller to recover or crash, defeating Go's explicit-error contract (Holzmann rule 1, simple control flow). Test files (_test.go) are exempt - a panic there is an acceptable test-failure signal, mirroring how Rust's SAFE204 exempts #[test] / #[cfg(test)] contexts.
The flagged call set is configurable; add the resolved barewords Fatal / Fatalf / Exit if your project treats log.Fatal* / os.Exit as panic-equivalent.
| Option | Default | Description |
|---|---|---|
enabled |
false |
Toggle the rule |
severity |
"warning" |
"error" or "warning" |
panic_calls_go |
["panic"] |
Call names that count as panicking |
# pyproject.toml
[tool.safelint.rules.panic_calls_outside_tests]
enabled = true
panic_calls_go = ["panic", "Fatal", "Exit"]
# safelint.toml
[rules.panic_calls_outside_tests]
enabled = true
panic_calls_go = ["panic", "Fatal", "Exit"]
Bad:
func mustParse(s string) Config {
c, err := parse(s)
if err != nil {
panic(err) // SAFE211
}
return c
}
Good: