diff --git a/cli/core/app.py b/cli/core/app.py index 82fcd88a73..04210f827a 100644 --- a/cli/core/app.py +++ b/cli/core/app.py @@ -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 diff --git a/cli/deploy/development/inventory.py b/cli/deploy/development/inventory.py index 20e9969d87..27caca3853 100644 --- a/cli/deploy/development/inventory.py +++ b/cli/deploy/development/inventory.py @@ -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 diff --git a/cli/deploy/development/proc.py b/cli/deploy/development/proc.py index 6e9e8c6e57..115da733d3 100644 --- a/cli/deploy/development/proc.py +++ b/cli/deploy/development/proc.py @@ -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, diff --git a/cli/meta/applications/in_group_deps/__main__.py b/cli/meta/applications/in_group_deps/__main__.py index d0d514e3f8..917ec6aea9 100755 --- a/cli/meta/applications/in_group_deps/__main__.py +++ b/cli/meta/applications/in_group_deps/__main__.py @@ -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: diff --git a/cli/mirror/cleanup/__main__.py b/cli/mirror/cleanup/__main__.py index ac025f31fc..1fb63bbb2a 100644 --- a/cli/mirror/cleanup/__main__.py +++ b/cli/mirror/cleanup/__main__.py @@ -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 diff --git a/plugins/filter/get_all_application_ids.py b/plugins/filter/get_all_application_ids.py index 4d418ea90d..f74d0085a8 100755 --- a/plugins/filter/get_all_application_ids.py +++ b/plugins/filter/get_all_application_ids.py @@ -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: diff --git a/plugins/filter/role_path_by_app_id.py b/plugins/filter/role_path_by_app_id.py index 446b6dae16..7e0d83bd22 100644 --- a/plugins/filter/role_path_by_app_id.py +++ b/plugins/filter/role_path_by_app_id.py @@ -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 diff --git a/plugins/lookup/nginx.py b/plugins/lookup/nginx.py index 50c4521914..681f206026 100644 --- a/plugins/lookup/nginx.py +++ b/plugins/lookup/nginx.py @@ -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"), diff --git a/pyproject.toml b/pyproject.toml index f33a60541d..6ac1e8d3e8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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"] diff --git a/roles/svc-bkp-rmt-2-loc/files/pull-specific-host.py b/roles/svc-bkp-rmt-2-loc/files/pull-specific-host.py index 8479b38412..55fa80450b 100755 --- a/roles/svc-bkp-rmt-2-loc/files/pull-specific-host.py +++ b/roles/svc-bkp-rmt-2-loc/files/pull-specific-host.py @@ -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 diff --git a/roles/svc-opt-ssd-hdd/files/script.py b/roles/svc-opt-ssd-hdd/files/script.py index 3e381c251a..8a7edb57e1 100644 --- a/roles/svc-opt-ssd-hdd/files/script.py +++ b/roles/svc-opt-ssd-hdd/files/script.py @@ -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 diff --git a/roles/sys-ctl-cln-bkps/files/script.py b/roles/sys-ctl-cln-bkps/files/script.py index 0645f1aaff..50767a8673 100644 --- a/roles/sys-ctl-cln-bkps/files/script.py +++ b/roles/sys-ctl-cln-bkps/files/script.py @@ -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() diff --git a/roles/sys-ctl-rpr-container-soft/files/script.py b/roles/sys-ctl-rpr-container-soft/files/script.py index 80c94f0c07..846a2c9ea5 100755 --- a/roles/sys-ctl-rpr-container-soft/files/script.py +++ b/roles/sys-ctl-rpr-container-soft/files/script.py @@ -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 diff --git a/roles/sys-svc-compose-ca/files/compose_ca.py b/roles/sys-svc-compose-ca/files/compose_ca.py index e09b4c281c..9b596f5c76 100755 --- a/roles/sys-svc-compose-ca/files/compose_ca.py +++ b/roles/sys-svc-compose-ca/files/compose_ca.py @@ -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] = {} diff --git a/roles/sys-svc-compose/files/compose.py b/roles/sys-svc-compose/files/compose.py index 8b74036caa..34995272c5 100755 --- a/roles/sys-svc-compose/files/compose.py +++ b/roles/sys-svc-compose/files/compose.py @@ -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 diff --git a/roles/sys-svc-container/files/container.py b/roles/sys-svc-container/files/container.py index 53d7e81866..f90f7f0b27 100755 --- a/roles/sys-svc-container/files/container.py +++ b/roles/sys-svc-container/files/container.py @@ -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 diff --git a/roles/web-app-bigbluebutton/filter_plugins/compose_mods.py b/roles/web-app-bigbluebutton/filter_plugins/compose_mods.py index 1e0643bc67..e0bd0569a2 100644 --- a/roles/web-app-bigbluebutton/filter_plugins/compose_mods.py +++ b/roles/web-app-bigbluebutton/filter_plugins/compose_mods.py @@ -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 diff --git a/roles/web-app-keycloak/library/keycloak_kcadm_update.py b/roles/web-app-keycloak/library/keycloak_kcadm_update.py index 777632f57e..591f1c0473 100755 --- a/roles/web-app-keycloak/library/keycloak_kcadm_update.py +++ b/roles/web-app-keycloak/library/keycloak_kcadm_update.py @@ -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, diff --git a/roles/web-app-odoo/files/addons/auth_oauth_https/models/res_users.py b/roles/web-app-odoo/files/addons/auth_oauth_https/models/res_users.py index e2d2bb04ea..1c38eda98e 100644 --- a/roles/web-app-odoo/files/addons/auth_oauth_https/models/res_users.py +++ b/roles/web-app-odoo/files/addons/auth_oauth_https/models/res_users.py @@ -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"): diff --git a/utils/cache/base.py b/utils/cache/base.py index 9bb629807a..0d820c92b7 100644 --- a/utils/cache/base.py +++ b/utils/cache/base.py @@ -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 diff --git a/utils/cache/users.py b/utils/cache/users.py index bd49a6cfa0..4b79a44243 100644 --- a/utils/cache/users.py +++ b/utils/cache/users.py @@ -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 diff --git a/utils/docker/version_updater.py b/utils/docker/version_updater.py index 2ae87a712b..9774be3f87 100644 --- a/utils/docker/version_updater.py +++ b/utils/docker/version_updater.py @@ -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 [] diff --git a/utils/manager/value_generator.py b/utils/manager/value_generator.py index 0e8192b9f6..9db524d838 100644 --- a/utils/manager/value_generator.py +++ b/utils/manager/value_generator.py @@ -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":