chore(ruff): enable S (bandit) rule family — 269 → 0

Adds ``S`` (flake8-bandit) to the strict ruleset. ``PTH`` was scoped
out: it surfaced 1000+ violations with no auto-fix support (most PTH
sub-rules are warning-only because each ``str`` ↔ ``Path`` conversion
is context-sensitive). Reserved for its own dedicated commit.

Config tuning
=============
Global ``ignore`` additions with rationale:
- ``S603`` (subprocess call without ``shell=False``) and ``S607`` (start
  process with partial path) are over-eager for a project whose CLI
  invokes ``make`` / ``git`` / ``docker`` / ``ansible-playbook`` from
  PATH using list-form args. The list-form already prevents shell
  injection (Python's ``subprocess`` does not parse argv[0] as a shell
  command), and resolving every binary's absolute path in the source
  would couple the code to the host filesystem layout. The genuinely
  dangerous shell-injection patterns (``shell=True``) are still caught
  by S602 / S605.

New ``[tool.ruff.lint.per-file-ignores]`` for ``tests/**``:
- ``S101``         — ``assert`` is the unittest idiom.
- ``S102``         — ``exec`` is used to load script-under-test by file path.
- ``S105`` / ``S106`` — hardcoded credentials in fixtures / dummy creds.
- ``S108``         — ``/tmp`` paths in tempdir fixtures.
- ``S110`` / ``S112`` — ``try``/``except``/``pass``/``continue`` in cleanup helpers.

Hand-fixes (38 across 23 files)
================================
S101 × 3
  Type-narrowing asserts (``cli/deploy/development/proc.py`` —
  ``p.stdout is not None`` after ``stdout=PIPE``) and an upstream-Odoo
  invariant assert in ``roles/web-app-odoo/.../res_users.py``.

S105 × 1
  ``cli/core/app.py`` argv parser comparing ``token == "--log"`` —
  ``token`` is a CLI argv element, not a credential. Inline noqa.

S106 × 1
  ``utils/cache/users.py`` Jinja template string ``"{{ 42 |
  strong_password }}"`` rendered to a real password at runtime; not a
  literal credential. Inline noqa.

S108 × 6
  Container-internal paths bind-mounted from the host:
  - ``/tmp/infinito/ca/root-ca.crt`` and ``/tmp/infinito/bin/with-ca-trust.sh``
    in ``roles/sys-svc-compose-ca/files/compose_ca.py`` and
    ``roles/sys-svc-container/files/container.py`` (CA-injection
    contract between role and wrapper).
  - ``/tmp/cache_nginx_general/`` and ``/tmp/cache_nginx_image/`` in
    ``plugins/lookup/nginx.py`` (well-known nginx cache dirs).

S110 × 1
  ``roles/web-app-bigbluebutton/filter_plugins/compose_mods.py``: filter
  intentionally swallows YAML parse errors and falls back to the
  unmodified text. Inline noqa.

S112 × 5
  Filter plugins / inventory builders iterating over role config files
  with skip-on-malformed semantics. The pattern is intentional
  throughout (CLI tools / Ansible plugins shouldn't crash on a single
  bad role file). Per-line noqa with rationale.

S324 × 2
  ``utils/cache/base.py`` uses md5 as a fast non-cryptographic
  fingerprint for cache keying; ``utils/manager/value_generator.py``
  uses sha1 when the caller selects ``algorithm == "sha1"`` for legacy
  app compatibility. Both gained ``usedforsecurity=False`` (Python 3.9+
  hashlib API) which silences the rule structurally; comments document
  the non-security purpose.

S310 × 8
  ``urlopen`` calls to fixed HTTPS registries (``api.github.com``,
  ``hub.docker.com``, ``ghcr.io``). URL prefix is a literal; only the
  ``namespace`` / ``image`` segment varies and comes from the project's
  own ``meta/services.yml``, never user input. No ``file://`` scheme
  exposure. Inline noqa per call site.

S602 / S605 / S606 × 8
  Role-deployed scripts that legitimately use ``shell=True`` /
  ``os.system`` for pipes/``&&``, or ``os.execvp`` in list-form (safe by
  construction — no shell parses argv). Each call site gained an inline
  noqa with a per-call rationale identifying where the command string
  is sourced (Ansible-templated config, host-trusted, never untrusted
  external input).

Verification
============
- ``ruff check .`` → All checks passed
- ``ruff format --check .`` → 894 files formatted
- 1621 unit tests → all pass
- Integration suite: 44 baseline failures (unchanged)

23 files changed, +97 / −38. Combined with the prior commits the
branch satisfies 21 ruff rule families end-to-end. ``PTH``
(modernise ``os.path`` to ``pathlib``) is the remaining big-impact
candidate, deferred to its own session.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
kevinveenbirkenbachandClaude Opus 4.7 committed 2026-05-07 17:57:29 +02:00
1 parent 0127b2aeb9
commit 191bc1229a
23 files changed
+97 -38

No files matched your search

+1 -1
View File
@@ -36,7 +36,7 @@ def _first_non_flag_token(argv: list[str]) -> str | None:
token = argv[i]
# Skip flags and their args
if token == "--log":
if token == "--log": # noqa: S105 `token` is a CLI argv element, not a credential
# Skip '--log' and its argument if present
i += 2
continue
+1 -1
View File
@@ -80,7 +80,7 @@ def _build_services_overrides_for_round(
continue
try:
base_services = load_yaml_any(services_path) or {}
except Exception:
except Exception: # noqa: S112 best-effort iteration over role files; skip malformed input
continue
if not isinstance(base_services, Mapping):
continue
+4 -2
View File
@@ -46,8 +46,10 @@ def run_streaming(
bufsize=1, # line buffered (best effort)
)
assert p.stdout is not None
assert p.stderr is not None
# Type-narrowing asserts so the type checker sees the streams as
# non-None below (PIPE was passed); these never fire at runtime.
assert p.stdout is not None # noqa: S101
assert p.stderr is not None # noqa: S101
t_out = threading.Thread(
target=_drain_stream,
@@ -33,7 +33,7 @@ def find_role_dirs_by_app_id(app_ids: list[str], roles_dir: str) -> list[str]:
continue
try:
data = load_yaml(vars_file)
except Exception:
except Exception: # noqa: S112 best-effort iteration over role files; skip malformed input
continue
app_id = data.get("application_id")
if isinstance(app_id, str) and app_id:
+5 -2
View File
@@ -25,7 +25,10 @@ from collections.abc import Iterator
def _gh_request(method: str, url: str, token: str) -> dict | list | None:
req = urllib.request.Request(
# All call sites build URLs from `https://api.github.com/…` literals
# plus a project-controlled `namespace`/`package` segment, so no
# arbitrary scheme can slip in.
req = urllib.request.Request( # noqa: S310
url,
headers={
"Authorization": f"Bearer {token}",
@@ -34,7 +37,7 @@ def _gh_request(method: str, url: str, token: str) -> dict | list | None:
},
method=method,
)
with urllib.request.urlopen(req) as resp:
with urllib.request.urlopen(req) as resp: # noqa: S310
body = resp.read()
return json.loads(body) if body else None
+1 -1
View File
@@ -21,7 +21,7 @@ def get_all_application_ids(roles_dir="roles"):
for filepath in glob.glob(pattern):
try:
data = load_yaml_any(filepath, default_if_missing={})
except Exception:
except Exception: # noqa: S112 best-effort iteration over role files; skip malformed input
continue
if isinstance(data, dict) and "application_id" in data:
+2 -2
View File
@@ -19,7 +19,7 @@ def abs_role_path_by_application_id(application_id):
for filepath in glob.glob(pattern):
try:
data = load_yaml_any(filepath, default_if_missing={}) or {}
except Exception:
except Exception: # noqa: S112 best-effort iteration over role files; skip malformed input
continue
if not isinstance(data, dict):
continue
@@ -55,7 +55,7 @@ def rel_role_path_by_application_id(application_id):
for filepath in glob.glob(pattern):
try:
data = load_yaml_any(filepath, default_if_missing={}) or {}
except Exception:
except Exception: # noqa: S112 best-effort iteration over role files; skip malformed input
continue
if not isinstance(data, dict):
continue
+3 -2
View File
@@ -125,8 +125,9 @@ class LookupModule(LookupBase):
data_cdn_dir = _ensure_trailing_slash(_join(www_dir, "public_cdn"))
data_global_dir = _ensure_trailing_slash(_join(www_dir, "global"))
cache_general_dir = "/tmp/cache_nginx_general/"
cache_image_dir = "/tmp/cache_nginx_image/"
# Container-internal nginx cache paths; not user-controllable.
cache_general_dir = "/tmp/cache_nginx_general/" # noqa: S108
cache_image_dir = "/tmp/cache_nginx_image/" # noqa: S108
ensure: list[dict[str, str]] = [
_dir_spec(nginx_dir, "0755"),
+26 -1
View File
@@ -82,10 +82,12 @@ exclude = [
# - `TID` (flake8-tidy-imports) — banned modules / banned relative imports
# - `LOG` (flake8-logging) — `logging` module misuse
# - `G` (flake8-logging-format) — f-strings inside `logging.x()` calls (defeats lazy-format)
# - `S` (flake8-bandit) — security (hardcoded creds, weak hashes, subprocess(shell=True), …)
select = [
"E", "F", "I", "B", "UP", "RUF", "SIM", "C4", "PERF", "RET", "PIE",
"T10", "PGH", "EXE", "RSE", "ICN", "DTZ",
"TID", "LOG", "G",
"S",
]
# `ruff format` (run via `make autoformat`) reflows whatever it can.
@@ -97,4 +99,27 @@ select = [
# exist to catch homoglyph attacks, not English typography. The project
# uses em/en-dashes deliberately and `ℹ` as a UI-hint glyph in CLI help
# output; flagging those is noise.
ignore = ["E501", "RUF001", "RUF002", "RUF003"]
ignore = [
"E501",
"RUF001", "RUF002", "RUF003",
# S603 (subprocess call without `shell=False`) and S607 (start
# process with partial path) are over-eager for a project whose
# CLI invokes `make` / `git` / `docker` / `ansible-playbook` from
# PATH using list-form args. The list-form already prevents shell
# injection (Python's `subprocess` does not parse argv[0] as a
# shell command), and resolving every binary's absolute path in
# the source would couple the code to the host filesystem layout.
# The genuinely dangerous shell-injection patterns (`shell=True`)
# are still caught by S602/S605.
"S603", "S607",
]
[tool.ruff.lint.per-file-ignores]
# Test code legitimately uses patterns flake8-bandit flags as security
# concerns in production code:
# - S101 (`assert`) is the unittest idiom.
# - S102 (`exec`) is used to load script-under-test by file path.
# - S105/S106 (hardcoded passwords) appear in fixtures / dummy creds.
# - S108 (hardcoded /tmp paths) appears in tempdir fixtures.
# - S110/S112 (try/except pass/continue) appear in cleanup helpers.
"tests/**" = ["S101", "S102", "S105", "S106", "S108", "S110", "S112"]
@@ -141,7 +141,8 @@ def pull_backups(hostname: str, backups_dir: str) -> None:
max_retries = 12
last_retry_start = int(time.time())
rsync_exit_code = os.system(rsync_command)
# rsync_command is built from Ansible-templated config (host-trusted), not user input.
rsync_exit_code = os.system(rsync_command) # noqa: S605
if rsync_exit_code == 0:
break
+5 -1
View File
@@ -8,7 +8,11 @@ import time
def run_command(command):
"""Run a shell command and return its output"""
print(command)
output = subprocess.check_output(command, shell=True).decode("utf-8").strip()
# All call sites pass static commands or strings built from
# Ansible-templated config (host-trusted); not user input.
output = (
subprocess.check_output(command, shell=True).decode("utf-8").strip() # noqa: S602
)
print(output)
return output
+2 -1
View File
@@ -32,7 +32,8 @@ def print_used_disc_space(backup_dir):
def is_directory_used_by_another_process(directory_path):
command = "lsof " + directory_path
process = subprocess.Popen(
# directory_path comes from Ansible-templated config (host-trusted), not user input.
process = subprocess.Popen( # noqa: S602
[command], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True
)
process.communicate()
@@ -31,7 +31,9 @@ import time
def bash(command: str) -> list[str]:
print(command)
process = subprocess.Popen(
# `command` is composed in this script from Ansible-templated input
# (host-trusted); shell features (pipes, &&) are required.
process = subprocess.Popen( # noqa: S602
[command], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True
)
out, err = process.communicate()
@@ -108,7 +110,8 @@ def wait_while_manipulation_running(
while True:
any_active = False
for svc in services:
res = subprocess.run(f"systemctl is-active --quiet {svc}", shell=True)
# `svc` is a project-defined unit name from the role's vars, not user input.
res = subprocess.run(f"systemctl is-active --quiet {svc}", shell=True) # noqa: S602
if res.returncode == 0:
any_active = True
break
+4 -2
View File
@@ -462,8 +462,10 @@ def render_override(
Docker Compose interpolates $VARS in YAML strings on the host.
We escape any $ in the command argv with $$ so container-side expansion works.
"""
ca_container = "/tmp/infinito/ca/root-ca.crt"
wrapper_container = "/tmp/infinito/bin/with-ca-trust.sh"
# Container-internal CA-injection paths bind-mounted from the host.
# Not user-controllable; well-known by the role's compose template.
ca_container = "/tmp/infinito/ca/root-ca.crt" # noqa: S108
wrapper_container = "/tmp/infinito/bin/with-ca-trust.sh" # noqa: S108
out_services: dict[str, Any] = {}
sh_cache: dict[str, bool] = {}
+4 -2
View File
@@ -186,8 +186,10 @@ def main() -> int:
if args.debug:
print(">>> " + " ".join(shlex.quote(x) for x in cmd), file=sys.stderr)
# execvp preserves signal handling under systemd.
os.execvp(cmd[0], cmd)
# execvp preserves signal handling under systemd. The argv list is
# built from this script's own argv plus `--env-file` / `--profile`
# additions; no shell parses it.
os.execvp(cmd[0], cmd) # noqa: S606
return 0
+7 -3
View File
@@ -336,8 +336,10 @@ def container_run(argv: list[str], debug: bool, with_ca: bool) -> int:
image = image_and_args[0]
user_args = image_and_args[1:]
ca_container = "/tmp/infinito/ca/root-ca.crt"
wrapper_container = "/tmp/infinito/bin/with-ca-trust.sh"
# Container-internal CA-injection paths bind-mounted from the host.
# Not user-controllable; matched on the host side by sys-svc-compose-ca.
ca_container = "/tmp/infinito/ca/root-ca.crt" # noqa: S108
wrapper_container = "/tmp/infinito/bin/with-ca-trust.sh" # noqa: S108
inject_opts: list[str] = [
"-v",
@@ -397,7 +399,9 @@ def container_run(argv: list[str], debug: bool, with_ca: bool) -> int:
if debug:
print(">>> " + " ".join(shlex.quote(x) for x in final_cmd), file=sys.stderr)
os.execvp(final_cmd[0], final_cmd)
# List-form exec: no shell parses the argv. CMD comes from this
# script's own argv (the wrapper), not from external user input.
os.execvp(final_cmd[0], final_cmd) # noqa: S606
return 0
@@ -110,8 +110,7 @@ def compose_mods(yml_text, docker_repository_path, env_file):
)
yml_text = dump_yaml_str(data)
except Exception:
# leave the original yml_text as-is if parsing fails
except Exception: # noqa: S110 best-effort filter — leave the original yml_text untouched if parsing fails
pass
return yml_text
@@ -101,7 +101,10 @@ result:
def run_kcadm(module, cmd, ignore_rc=False):
"""Run a shell command for kcadm."""
rc = subprocess.run(
# `cmd` comes from this Ansible module's own argv plus inventory
# overrides (host-trusted), and shell features (pipes, &&) are
# required by the kcadm-wrapper invocations the module composes.
rc = subprocess.run( # noqa: S602
cmd,
shell=True,
check=not ignore_rc,
@@ -65,7 +65,7 @@ class ResUsersOAuthConfigurableUid(models.Model):
[("oauth_uid", "=", oauth_uid), ("oauth_provider_id", "=", provider)]
)
if oauth_user:
assert len(oauth_user) == 1
assert len(oauth_user) == 1 # noqa: S101 mirrors upstream Odoo invariant; oauth_uid is unique per provider
oauth_user.write({"oauth_access_token": params["access_token"]})
return oauth_user.login
if self.env.context.get("no_user_creation"):
+5 -1
View File
@@ -101,7 +101,11 @@ def _fingerprint_mapping(obj: Any) -> str:
import hashlib
data = repr(sorted(obj.items())) if isinstance(obj, Mapping) else repr(obj)
digest = hashlib.md5(data.encode("utf-8", errors="replace")).hexdigest()
# md5 used as a fast non-cryptographic fingerprint for cache keying.
digest = hashlib.md5(
data.encode("utf-8", errors="replace"),
usedforsecurity=False,
).hexdigest()
except Exception:
digest = f"id:{obj_id}"
_FINGERPRINT_BY_ID[obj_id] = digest
+1 -1
View File
@@ -343,7 +343,7 @@ def get_user_defaults(
definitions,
primary_domain="{{ DOMAIN_PRIMARY }}",
start_id=1001,
become_pwd="{{ 42 | strong_password }}",
become_pwd="{{ 42 | strong_password }}", # noqa: S106 Jinja expression rendered to a password at runtime, not a literal credential
)
cached = {key: built[key] for key in sorted(built)}
_USERS_DEFAULTS_CACHE[key] = cached
+6 -6
View File
@@ -124,11 +124,11 @@ def fetch_dockerhub_tags(image: str, max_pages: int = 5) -> list[str]:
f"https://hub.docker.com/v2/repositories/{repo}/tags/"
f"?page_size=100&page={page}"
)
req = urllib.request.Request(
req = urllib.request.Request( # noqa: S310
url, headers={"User-Agent": "infinito-nexus-version-updater"}
)
try:
with urllib.request.urlopen(req, timeout=15) as resp:
with urllib.request.urlopen(req, timeout=15) as resp: # noqa: S310
if resp.status == 429:
time.sleep(2)
continue
@@ -160,10 +160,10 @@ def fetch_ghcr_tags(image: str) -> list[str]:
)
token_url = f"https://{GHCR_REGISTRY}/token?{token_query}"
try:
req = urllib.request.Request(
req = urllib.request.Request( # noqa: S310
token_url, headers={"User-Agent": "infinito-nexus-version-updater"}
)
with urllib.request.urlopen(req, timeout=15) as resp:
with urllib.request.urlopen(req, timeout=15) as resp: # noqa: S310
token_body = json.loads(resp.read().decode())
token = token_body.get("token") or token_body.get("access_token")
except (urllib.error.URLError, OSError, json.JSONDecodeError):
@@ -173,7 +173,7 @@ def fetch_ghcr_tags(image: str) -> list[str]:
return []
tags_url = f"https://{GHCR_REGISTRY}/v2/{quote(name, safe='/')}/tags/list"
req = urllib.request.Request(
req = urllib.request.Request( # noqa: S310
tags_url,
headers={
"Authorization": f"Bearer {token}",
@@ -181,7 +181,7 @@ def fetch_ghcr_tags(image: str) -> list[str]:
},
)
try:
with urllib.request.urlopen(req, timeout=15) as resp:
with urllib.request.urlopen(req, timeout=15) as resp: # noqa: S310
body = json.loads(resp.read().decode())
except (urllib.error.URLError, OSError, json.JSONDecodeError):
return []
+6 -1
View File
@@ -63,7 +63,12 @@ class ValueGenerator:
if algorithm == "sha256":
return hashlib.sha256(secrets.token_bytes(32)).hexdigest()
if algorithm == "sha1":
return hashlib.sha1(secrets.token_bytes(20)).hexdigest()
# SHA-1 is selected by the caller for legacy app compatibility;
# the input is fresh random bytes, not security-sensitive data.
return hashlib.sha1(
secrets.token_bytes(20),
usedforsecurity=False,
).hexdigest()
if algorithm == "strong_password":
return self.generate_strong_password(32)
if algorithm == "bcrypt":