Skip to content

fix(security): dive invents layers, the rbac audit checks nothing, and checkov's fallback and the complexity scan miss cases #957

Closed

Description

@dan-petty

Problem

The devsecops review session 20261001-224227 (2026-10-02, a path review of the whole repository with local models) raised 563 findings. A triage of every finding against release/v0.2.25 (c279c18) judged 489 false. Each of the 6 defects below was confirmed with code evidence and then upheld by a second agent that tried to refute it. The severities are re-rated; the review's own ratings were inflated.

Incomplete Exception Handling in Dive Analysis (src/devops_cli/security/dive.py:52-75, MEDIUM, correctness)

  • Defect: When dive is not on PATH or is a symlink (lines 51-52), run_dive_analysis returns made-up results for any image: efficiency_score=0.98, total_bytes=150 * 1024 * 1024, and two layers, FROM python:3.14-slim and COPY --from=ghcr.io/astral-sh/uv /uv /bin/uv. Package-manager installs such as Homebrew or mise shims are symlinks. Any exception (lines 107-109) returns DiveAnalysisResult(image_name=image_name): 100% efficiency, 0 bytes, no layers. Callers present this as a real analysis. devops docker analyze-layers (commands/docker.py:378-404) prints the layer table and efficiency summary with no fallback marker; the only hint is a logger.debug. The LLM tool docker_analyze_layers (ai/tools/builtin_tools.py:519-534) hands the model 'Efficiency Score: 98.0% ... Total Image Size: 150.0 MB'. dive is not installed in the devcontainer or CI, so this is the default output. …
  • Skeptic's ruling: Confirmed in src/devops_cli/security/dive.py run_dive_analysis. When shutil.which('dive') is None or a symlink (Homebrew and mise shims are symlinks), it returns invented data for any image: efficiency 0.98, 150 MB, and two layers, FROM python:3.14-slim and COPY --from=ghcr.io/astral-sh/uv /uv /bin/uv. Only a logger.debug notes this. Reproduced with dive absent, the devcontainer default: run_dive_analysis('does-not-exist/nope:1') returned those values, and the LLM tool …
  • Fix: Delete the synthetic layers. Add status: Literal['ran','unavailable','failed'] and reason: str to DiveAnalysisResult, or raise a typed DiveUnavailableError, on a missing binary and on any subprocess or parse failure. analyze-layers prints a warning and exits non-zero unless the status is 'ran'. docker_analyze_layers returns 'Dive not available: '. Separately, check dive's real JSON export keys and output target, and fix the parser.
  • Regression test: tests/test_security_dive.py: with shutil.which patched to return None, assert run_dive_analysis('img:1').status == 'unavailable' and layers == [], and that docker_analyze_layers('img:1') does not contain 'Efficiency Score'. With subprocess.run raising, assert the status is 'failed'. A CliRunner test asserts devops docker analyze-layers img:1 exits non-zero when dive is missing. Today the fake 98% result is returned and the command exits 0.

Incomplete RBAC Audit Implementation (src/devops_cli/commands/k8s/security_audit.py:48, MEDIUM, security)

  • Defect: rbac_audit makes no cluster call. Outside dry-run it always prints one fixed row: [namespace or "default", "cluster-admin-binding", "ClusterRole/cluster-admin", "[green]PASS[/green]"]. README.md:207 and docs/commands/k8s.md:318 describe devops k8s rbac-audit as 'Audit RBAC RoleBindings and ServiceAccounts for overprivileged access', and docs/ROADMAP.md:34 marks 'Kubernetes RBAC policy scanner' as done. tests/test_k8s.py:739-741 asserts the hardcoded string with no cluster. A user running it against a cluster with overprivileged bindings gets a PASS, which is false security assurance. No open issue covers it.
  • Skeptic's ruling: Upheld; I could not refute it. rbac_audit in commands/k8s/security_audit.py makes no cluster call and no kubectl call. Outside dry-run it always prints one fixed row, [namespace or "default", "cluster-admin-binding", "ClusterRole/cluster-admin", "[green]PASS[/green]"], and exits 0. It is registered as devops k8s rbac-audit in k8s/init.py. README.md:207, docs/commands/k8s.md and docs/CLI_REFERENCE.md describe it as 'Audit RBAC RoleBindings and ServiceAccounts for overprivileged …
  • Fix: Implement the audit with runtime._run_cmd(['kubectl','get','clusterrolebindings,rolebindings','-o','json'] (+ ['-n', ns] when --namespace is set), capture=True) and kubectl get clusterroles,roles -o json. Flag bindings to cluster-admin, admin or edit, roles with '' in verbs, resources or apiGroups, and ServiceAccount, group or user subjects outside kube-system and system:. Escape names when rendering, and exit nonzero when there are violations. The pre-1.0 alternative is to delete the command and correct README, docs/commands/k8s.md, CLI_REFERENCE.md, ROADMAP.md:34 and RELEASE_NOTES.md, with no shim.
  • Regression test: Replace the assertion in tests/test_k8s.py:739-741. Patch devops_cli.commands.k8s.cluster_runtime._run_cmd to return a CompletedProcess whose stdout is a ClusterRoleBinding JSON list binding ServiceAccount default/ci-bot to ClusterRole cluster-admin. Invoke rbac-audit, then assert exit_code != 0, that 'ci-bot' and 'FAIL' (or the violation marker) appear in the output, and that 'PASS' does not appear for that binding. Today the mock is never called, the output is the hardcoded PASS row, …

Insecure Regex Pattern for Dockerfile Base Image Detection (src/devops_cli/security/checkov.py:53, LOW, correctness)

  • Defect: The 'regex injection' claim and the whitespace/comment bypass are wrong: the pattern is a constant, and FROM img :latest is not a valid Dockerfile. The proposed regex is the same pattern with a named group added. The native fallback does miss real :latest bases, though. In re.match(r"^FROM\s+\S+:latest", ...) the \S+ consumes --platform=$BUILDPLATFORM and cannot cross the next space, so FROM --platform=$BUILDPLATFORM python:latest AS build produces no finding. Reproduced: _run_native_fallback_iac_checks returned zero findings, while plain FROM python:latest was flagged. An untagged FROM alpine (implicitly latest) is never flagged, and stripped.startswith("USER ") (line 55) is case-sensitive although Dockerfile instructions are not. checkov is not installed in the devcontainer or in CI, so this fallback is what devops scan actually runs.
  • Skeptic's ruling: The original mechanism is refuted. The pattern is a constant, so there is no regex injection, and FROM img :latest is not valid Dockerfile syntax. The triage's re-framed defect reproduces against src/devops_cli/security/checkov.py _check_dockerfile_fallback, run through _run_native_fallback_iac_checks:
    (1) FROM --platform=$BUILDPLATFORM python:latest AS build gives no ':latest' finding, because \S+ consumes the --platform= flag and cannot cross the next space.
    (2) An untagged `FROM …
  • Fix: Parse FROM with a case-insensitive regex that allows flags: ^FROM\s+(?:--\S+\s+)*(?P<image>\S+)(?:\s+AS\s+(?P<alias>\S+))?. Record stage aliases. Skip scratch, earlier aliases and $ARG images. Flag when the image has no tag and no digest, or its tag is latest and there is no @sha256: digest. Detect USER with re.match(r'^USER\s+', stripped, re.I).
  • Regression test: tests/test_security_checkov.py: Dockerfile fixtures with (a) FROM --platform=$BUILDPLATFORM python:latest AS build + USER 1000, (b) FROM alpine + USER 1000, (c) FROM python:3.12-slim + user nobody, (d) FROM base AS b / FROM b + USER 1 with base pinned. Assert one ':latest' finding for (a) and for (b), no 'runs as root' finding for (c), and no latest finding for the alias in (d). (a), (b) and (c) fail today.

Incomplete Kubernetes Manifest Parsing for Privileged Containers (src/devops_cli/security/checkov.py:77-81, LOW, correctness)

  • Defect: The claimed mechanism is wrong: the check is line-based, so how deeply the field is nested does not matter. But if "kind: Deployment" not in content and "kind: Pod" not in content: return findings skips DaemonSet, StatefulSet, ReplicaSet, Job and CronJob manifests entirely. Reproduced: a DaemonSet with securityContext: privileged: true gave zero findings, while the same manifest as a Deployment gave dep.yaml:11 Privileged container execution allowed. The repo's own k8s/gpu-feature-discovery/daemonset.yaml is a privileged DaemonSet that this fallback passes. The substring test "privileged: true" in line also misses privileged: True and extra spaces. checkov is not provisioned in the devcontainer or CI, so this fallback is the default path. feat(ai): pinned image tags and bounded shared valkey in the llm stack #711 explicitly leaves fallback fixes out of scope. The finding's fix uses yaml.safe_load, which fails on multi-document files.
  • Skeptic's ruling: The original mechanism (nesting, anchors) is wrong, because the check is line-based. The triage's defect is real. In src/devops_cli/security/checkov.py _check_k8s_fallback, if "kind: Deployment" not in content and "kind: Pod" not in content: return findings skips every other workload kind. Reproduced: a DaemonSet with securityContext: privileged: true gave zero findings, and the identical manifest as a Deployment gave dep.yaml:12 Privileged container execution allowed. The repo's own …
  • Fix: Remove the kind substring gate. Load documents with yaml.safe_load_all. For each mapping document, collect pod specs from spec, spec.template.spec and spec.jobTemplate.spec.template.spec. Walk containers, initContainers and ephemeralContainers, and flag securityContext.privileged is True, getting the line from a line-tracking loader or a regex search for that container. If YAML fails to parse, fall back to a case-insensitive line regex ^\s*privileged:\s*(true|yes|on)\b.
  • Regression test: tests/test_security_checkov.py: write a DaemonSet and a CronJob (privileged under jobTemplate.spec.template.spec.containers[].securityContext) and a Pod with privileged: True, then call _run_native_fallback_iac_checks(tmp_path). Assert one 'Privileged container execution allowed' finding per file. All three files get zero today.

Incorrect Handling of Nested Function Definitions in Complexity Calculation (src/devops_cli/security/complexity.py:80-81, LOW, correctness)

  • Defect: The nested-function guard at lines 133-136 (if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)): self.visit(child)) only inspects the children of the node being visited. _handle_function passes each body statement straight to self._visit_with_depth(item, depth=1) (lines 80-81), so a def that is a direct statement of a function body never reaches self.visit. Its branches and depth are charged to the parent, and it is never reported on its own. Reproduced: def outer(x): def inner(y): if y: ... if y > 2: ... produced only outer (cc=3, depth=2) and no inner. With the same closure inside if x:, the scanner reports it separately and leaves it out of the parent (outer2=2, inner2=3). ruff C901 reports inner separately. tests/test_scan_complexity.py:120-138 covers only the inside-an-if case, which confirms the intent. Affects devops scan complexity, …
  • Skeptic's ruling: Confirmed in src/devops_cli/security/complexity.py. _handle_function passes each body statement straight to self._visit_with_depth(item, depth=1). The nested-function guard in _visit_with_depth checks only the children of the node being visited, never the node itself. So a def that is a direct statement of a function body is walked as part of the parent and never reported separately. Reproduced: def outer(x): def inner(y): if y: ...; if y > 2: ... produced only `('outer', cc=3, …
  • Fix: At the top of _visit_with_depth, add if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): self.visit(node); return, and drop the now-redundant child check, or keep it for clarity. If refactor(ci): one nesting metric module shared by the pre-commit hook and the scanner #773 lands first, fold the fixture into that change.
  • Regression test: tests/test_scan_complexity.py: analyze_file_complexity on def outer(x):\n def inner(y):\n if y:\n return 1\n if y > 2:\n return 2\n return inner\n should give two functions: outer with cc 1 and inner with cc 3. Add a second case with class C: and def m defined directly in a function: expect m.is_method is True. Both fail today, where only outer is reported, with cc 3, and m.is_method is False.

Incomplete Exception Handling in Semgrep Execution (src/devops_cli/security/semgrep.py:142-154, LOW, quality)

  • Defect: _execute_and_parse_semgrep does turn a non-zero exit with no JSON output into [], but it has no caller anywhere in src or tests (grep), so the claimed misreport cannot happen. The live path is BaseSecurityScanner._run_scanner_command → _handle_non_json_output / _handle_json_output (base.py:131-184), which returns ScanOutcome("failed", [], f"Scanner exited with code {returncode}: {err_msg}") when there are no findings and the exit code is non-zero. The real defect is a dead, divergent copy of the execution path; it led this review astray. Its twin _execute_bandit_subprocess (bandit.py:124-136) is dead too, and semgrep's import subprocess is used only by the dead helper.
  • Skeptic's ruling: The finding's claim is refuted. _execute_and_parse_semgrep (src/devops_cli/security/semgrep.py) has no caller in src, tests or docs (grep), so it cannot misreport anything. The live path is BaseSecurityScanner._run_scanner_command. In it, _handle_non_json_output and _handle_json_output return ScanOutcome('failed', ...) on a non-zero exit with no findings. The triage's re-framed defect is real and violates the project policy that the codebase stays clean of obsolete code. …
  • Fix: Delete _execute_and_parse_semgrep and _execute_bandit_subprocess, along with the imports only they use (json, subprocess and DEFAULT_SUBPROCESS_TIMEOUT_SECONDS in semgrep.py; json and DEFAULT_SUBPROCESS_TIMEOUT_SECONDS in bandit.py). Keep from devops_cli.core.process import run_subprocess # noqa: F401 in both, as gitleaks.py does.
  • Regression test: Add a hygiene test (e.g. tests/test_codebase_hygiene_and_shims.py) that uses AST to collect the module-level _private functions in src/devops_cli/security/*.py and asserts each name is referenced somewhere else in src/ or tests/. Today it fails, naming _execute_and_parse_semgrep and _execute_bandit_subprocess, and it passes once they are deleted.

Acceptance criteria

  • Each defect above is fixed as its Fix line describes, or the PR says why another fix is better.
  • Each has its Regression test: offline, failing on the base revision and passing after the fix.
  • Removed code goes without shims (pre-1.0), and docs that described it are corrected.
  • uv run devops ci passes.

Key questions

  • One PR for all of these? Yes (proposed). They share a module area and none needs a design decision; each fix is small.

Activity

  1. added this to the v0.2.25 milestone on Oct 2, 2026
  2. added
    type/bug
    scope/security
    priority/p2-medium
    on Oct 2, 2026
  3. dan-petty commented on Oct 2, 2026

    @dan-petty
    OwnerAuthor

    Closed by #979, merged into release/v0.2.25.

    GitHub only acts on closing keywords when a pull request merges into the default branch, so this was closed by devops gh issues close-merged.

  4. added a commit that references this issue on Oct 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p2-mediumscope/securitytype/bug

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions