Skip to content

fix(cli): argo ignores the namespace, and workspace, devcontainer, port-forward, tls, drift-report and label state handling #961

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 7 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.

Inconsistent namespace handling in workflow submission (src/devops_cli/commands/argo.py:427, MEDIUM, correctness)

  • Defect: The finding's stated mechanism is wrong: _await_workflow does receive target_ns (432). The same lines hold a real namespace-handling bug, though. --namespace is passed to _crd(namespace), and _crd(context) (91-93) builds ArgoCRDService(context=namespace). _api() then calls custom_objects_api(context=self.context), which does load_kube_config(context=resolve_context("argo")) (k8s/service.py:105-115; resolve_context returns an explicit value as-is). Outside a pod, devops argo workflows submit wf.yaml -n argo therefore looks up a kubeconfig context named after the namespace. It fails with KubernetesContextError, or targets the wrong cluster if a context with that name exists. The same misuse is in workflows list (406), workflows logs (450), rollouts list (481) and rollouts status (509). tests/test_argo.py patches ArgoCRDService._api, so the mix-up is never exercised.
  • Skeptic's ruling: The finding's stated mechanism is wrong: workflows_submit passes target_ns to _await_workflow. The triage is right that the same lines hold a real bug, and I confirmed it at runtime. In src/devops_cli/commands/argo.py, _crd(context) returns get_argo_crd_service(context=context), and every workflows and rollouts command calls _crd(namespace) with the --namespace value: workflows list, submit (twice), logs, rollouts list and rollouts status. ArgoCRDService._api then calls …
  • Fix: In commands/argo.py, stop passing the namespace to _crd. Either call _crd() with no argument in workflows_list, workflows_submit (both calls, and build the service once and reuse it for _await_workflow), workflows_logs, rollouts_list and rollouts_status, or add a --context/-c option (HELP.options.context, as gitops bootstrap already has) and pass that. Keep _namespace(namespace) only for the namespace= arguments. Then regenerate CLI_REFERENCE.md if you add an option.
  • Regression test: tests/test_argo.py: patch KubernetesService.custom_objects_api, not ArgoCRDService._api, with a fake that appends its context kwarg to a list and returns a MagicMock whose list_namespaced_custom_object returns {'items': []} and whose get and create return a Succeeded workflow. Invoke workflows list --namespace argocd, workflows submit wf.yaml --namespace argocd --wait, workflows logs my-wf --namespace argocd (with KubernetesService.read_pod_logs patched), `rollouts list --namespace …

Potential Denial of Service via Large Workspace Files (src/devops_cli/commands/workspace.py:107, LOW, correctness)

  • Defect: The DoS claim is wrong: an oversized file is never parsed (if ws_file.stat().st_size > DEFAULT_MAX_AST_FILE_SIZE_BYTES: print_warning(...); return {"folders": [], "settings": {}}). The warn-and-return-defaults behavior the finding cites, and the fix it proposes (raise instead), are a real defect for another reason. The oversized, malformed and JSONDecodeError branches all return empty defaults (errors.py:55-57 say "Using defaults."). add() (lines 154-185) then appends one folder and calls _save(ws_file, data), which atomically overwrites the user's workspace file. All existing folders and settings are lost. A realistic trigger is a VS Code .code-workspace with comments or trailing commas (JSONC, which VS Code accepts and json.loads rejects). The file is gitignored (.gitignore:52), so git cannot restore it. Non-UTF-8 content raises an uncaught UnicodeDecodeError.
  • Skeptic's ruling: The finding's DoS/CWE-400 framing is false. A file over 50 MiB is never read or parsed: _load checks stat().st_size first and returns early. The workspace file is also the trusted user's own config (default .code-workspace from settings or --workspace), not untrusted input. So there is no security issue. The warn-and-return-defaults pattern the finding points at does cause real data loss, though, and I reproduced it against the assess tree.

Reproduction: I wrote a .code-workspace …

  • Fix: In src/devops_cli/commands/workspace.py, split _load into two outcomes:
  • File absent: return the defaults, as today.
  • File present but unusable (over the size limit, JSONDecodeError, UnicodeDecodeError, or not a dict with a list folders): call print_error with the existing ERRORS.workspace message, then raise typer.Exit(1). add and remove then never call _save on content they could not read.

Reword ERRORS.workspace.{file_too_large,malformed,corrupted} in lang/en/errors.py. Drop "Using defaults." and say the file was left unchanged, pointing at devops workspace generate to rebuild it.

Optional: accept JSONC by stripping // and /* */ comments and trailing commas with a small tokenizer-aware pass, or a maintained reputable parser, before json.loads. Note that the rewrite would still drop the comments.

Update …

  • Regression test: In tests/test_workspace.py, add test_workspace_add_refuses_to_overwrite_unparseable_file:
  1. Write ws = tmp_path/'w.code-workspace' containing '{\n // c\n "folders": [{"path": "/x"},],\n "settings": {"a": 1}\n}'.
  2. Record before = ws.read_bytes().
  3. With _PROJECT_ROOT patched to tmp_path, invoke runner.invoke(workspace_app, ['add', str(tmp_path), '--workspace', str(ws)]).
  4. Assert exit_code != 0 and ws.read_bytes() == before.

Add a parametrized variant for malformed …

Insecure Exception Handling in Git Daemon PID Check (src/devops_cli/commands/devcontainer.py:1206, LOW, reliability)

  • Defect: The finding's mechanism is wrong. Catching OSError, ValueError only falls through to the port-9418 probe, which is correct. The false positive it predicts does happen, but through a different path. _is_git_daemon_running returns True as soon as os.kill(int(pid_file.read_text()), 0) succeeds, without the port probe. The pid file is /tmp/git-daemon.pid (_git_daemon_pid_file), and git daemon --detach --pid-file= never removes it. .devcontainer/devcontainer.json mounts source=devops-cli-tmp,target=/tmp,type=volume, so the file survives container rebuilds while PIDs restart from 1 in the new PID namespace. If any vscode-owned process happens to hold the old PID during post-start, _start_git_daemon reports "Git daemon is already running on port 9418" and never starts it, even with DEVOPS_GIT_DAEMON_AUTOSTART=true.
  • Skeptic's ruling: Upheld at LOW, but the mechanism is not the one the finding gives. Catching OSError, ValueError together is correct: a bad pid or a dead process falls through to the 127.0.0.1:9418 probe, and a PermissionError from another user's process does the same. The real defect is the success path. _is_git_daemon_running returns True as soon as os.kill(pid, 0) succeeds, without checking what that process is. The pid file is tempfile.gettempdir()/git-daemon.pid. git daemon --detach --pid-file …
  • Fix: Use the 127.0.0.1:9418 connect probe as the only liveness test, which is what the status message actually claims. If the pid file is kept, trust it only when /proc//cmdline contains 'git-daemon' or 'git\0daemon', and unlink a stale pid file before _start_git_daemon spawns a new daemon. Keep the combined except clause as it is.
  • Regression test: In tests/test_devcontainer.py, monkeypatch devops_cli.commands.devcontainer._git_daemon_pid_file to a tmp_path file containing str(os.getpid()). Monkeypatch socket.create_connection to raise ConnectionRefusedError. Assert _is_git_daemon_running() is False. Today it returns True because the live pytest process satisfies os.kill(pid, 0).

Potential Race Condition in Process State Management (src/devops_cli/k8s/port_forward_daemon.py:86, LOW, reliability)

  • Defect: The race the finding names, a liveness check followed by a save, is harmless: a process that dies after the check is pruned on the next list. The defect underneath it is real, though. Every state-file update is an unlocked read-modify-write with a non-atomic write. list_forwards reads (92) and may rewrite through save_forwards (101, write_text at 84). _launch_port_forwards (commands/k8s/networking.py:969-1003) does active_forwards = daemon_mgr.list_forwards(), spawns kubectl, appends and saves. stop_forwards (104-121) lists, kills and saves remaining. Concrete trigger: two devops k8s port-forward runs at once (say -s infra and -s llm), or a stop during a start. The later save overwrites the earlier one's records, leaving detached kubectl processes (start_new_session=True) that port-forward-status never lists and port-forward-stop never stops, while they keep …
  • Skeptic's ruling: The race the finding names is harmless, as the triage said. If a forward dies between is_alive and save_forwards, the next list_forwards prunes it. The triage's reframing does hold up against the code, though. Every change to the state file is an unlocked read-modify-write, and save_forwards writes in place with write_text: it truncates the file and then writes, with no temp file and no os.replace.

In _launch_port_forwards (commands/k8s/networking.py:959-1003), the CLI calls …

  • Fix: 1. In port_forward_daemon.py, add a locked() context manager on PortForwardDaemonManager. It takes fcntl.flock(LOCK_EX) on a sibling port_forwards.lock, following the pattern in sandbox/registry.py.
  1. Hold that lock around each list-modify-save sequence:
    • list_forwards together with its prune-save.
    • stop_forwards, which then needs internal unlocked _load and _save helpers so it does not take the lock twice.
    • All of _launch_port_forwards, from list through Popen and append to save. Expose this as with daemon_mgr.locked(): forwards = daemon_mgr.load(); ...; daemon_mgr.save(forwards).
  2. Make save_forwards atomic: write a NamedTemporaryFile in the same directory, then os.replace it over the state file, keeping the symlink guard. The existing output/file_writer.py atomic helper can serve if it fits.
  3. Record the process start time (field 22 of …
  • Regression test: Add to tests/test_k8s_port_forward_daemon.py. All of these use a tmp_path state file, spawn no kubectl and need no network.
  1. test_concurrent_launches_keep_both_records: two PortForwardDaemonManager instances share one state file. Each runs the locked load-append-save sequence with an os.getpid() record. Interleave them with threads and a barrier, so the second blocks on the lock until the first saves. Assert that both services are listed afterwards. Today the second save overwrites …

Insecure Deletion of Kubernetes TLS Secrets (src/devops_cli/commands/k8s/tls_management.py:95, LOW, reliability)

  • Defect: create_tls_secret runs kubectl delete secret <name> with check=False, then kubectl create secret tls .... When the create fails, it prints an error and exits 1, but the previously working secret is already gone, with no rollback. A mismatched cert/key pair is enough to trigger this: kubectl rejects it with 'tls: private key does not match public key'. A transient API error has the same effect. Ingresses then lose their TLS secret and fall back to the default certificate. enable_tls_stack --overwrite (lines 204-222) has the same delete-then-create sequence for each namespace. The 'concurrent process' race in the finding is speculative for a single-user CLI; the non-atomic replace is the real defect.
  • Skeptic's ruling: Upheld at LOW, re-scoped from the 'concurrent process race' to the non-atomic replace. create_tls_secret runs kubectl delete secret <name> with check=False and then kubectl create secret tls. When the create fails, it prints 'Failed to create TLS secret' and exits 1, but the working secret is already gone. There is no pre-validation; only file existence is checked. kubectl validates the cert and key client-side with tls.X509KeyPair, so a rotated cert passed with the old key (or a …
  • Fix: Replace the delete and create pair with an atomic upsert. Run kubectl create secret tls NAME --cert=... --key=... -n NS --dry-run=client -o yaml (capture=True) and, only if it succeeds, pass its stdout to kubectl apply -f - -n NS through runtime._run_cmd(..., input=yaml). _run_cmd already accepts input. Use the same helper in enable_tls_stack when --overwrite is set, and drop both kubectl delete secret calls.
  • Regression test: In tests/test_k8s_tls.py, patch devops_cli.commands.k8s.cluster_runtime._run_cmd with a side_effect that returns returncode=1 for any argv containing 'tls' together with 'create' and returncode=0 otherwise. Invoke create-tls-secret my-app-tls --cert c --key k using real tmp files. Assert exit_code == 1 and that no recorded call has both 'delete' and 'secret' in its argv. Today the delete is issued before the failing create.

Incomplete Error Handling in Report Saving (src/devops_cli/ai/library/drift_auditor.py:321, LOW, reliability)

  • Defect: if save_report_path is not None: try: report.save(save_report_path) except OSError: pass swallows every write failure without logging. The only caller, devops ai audit-library-usage (commands/ai.py:1531-1533), always passes .data/analysis/api_drift_report.json, and CHANGELOG.md:534 advertises it as the 'persistent JSON report'. If that directory is unwritable or the disk is full, nothing is reported and the previous run's report stays at that path, silently stale. AGENTS.md:106/324 forbid silently masking failures. Re-raising, as the finding suggests, is too strong, because the terminal or JSON output is the primary result.
  • Skeptic's ruling: I could not refute it. In drift_auditor.py, LibraryDriftAuditor.audit_workspace has if save_report_path is not None: try: report.save(save_report_path) except OSError: pass, which swallows the failure without a log line or a return signal. The only caller, commands/ai.py audit_library_usage_cmd, always passes analysis_directory(cwd)/'api_drift_report.json'. _render_drift_report never mentions the file, and CHANGELOG.md:534 advertises it as the 'persistent JSON report'. Concrete trigger: …
  • Fix: Change to except OSError as exc: logger.warning("Could not write drift report to %s: %s", save_report_path, exc) and record the failure on the result, e.g. report.save_error = str(exc), or return the saved path or None. Have audit_library_usage_cmd print_warning the failure in non-JSON mode, and print the report path on success. Optionally unlink(missing_ok=True) the old file before writing, so a stale report cannot pass as current. Do not re-raise, because the stdout/JSON result is still valid.
  • Regression test: tests/test_library_drift_auditor.py::test_save_failure_is_reported_not_silent. Create tmp_path/'blocker' as a regular file and pass save_report_path=tmp_path/'blocker'/'drift.json', so the mkdir raises an OSError, NotADirectoryError or FileExistsError, which is root-safe unlike chmod. Use caplog at WARNING on 'devops_cli.ai.library.drift_auditor' and assert a record mentioning the path. If save_error is added, also assert report.save_error is truthy. Both assertions fail today because the …

Potential Type Injection in GitHub Label Creation/Update (src/devops_cli/github/labels.py:129-139, LOW, quality)

  • Defect: The injection framing is wrong: client is always GitHubClient or GhCliClient, built in commands/gh.py:251 (_get_github_client() or GhCliClient(target_repo)), and no attacker controls it. The duck-typed dispatch the finding describes is still dead and wrong logic, though. func = getattr(client, method_name, None); if not callable(func): return makes a missing method a silent no-op, and sync still reports it as created or updated. except TypeError: func(name=..., color=..., description=...) (138-139) can never succeed, because both clients require repo positionally (client.py:217/225 and 360/376). Any TypeError raised inside the call is therefore replaced by a misleading 'missing repo' TypeError. sync_repository_labels repeats the pattern at 146-149. No test reaches either branch. The same pattern in milestones was removed by refactor(github): roadmap store that reads and writes items, releases and board fields behind one interface (#768) #919 when it moved to a typed RoadmapStore (see idx …
  • Skeptic's ruling: Upheld only as a narrowed LOW code-quality finding. The original HIGH injection claim is refuted. The only caller is sync_labels (commands/gh.py:251), which builds client as _get_github_client() or GhCliClient(target_repo), so there is no untrusted path that controls the object. Two of the triage's supporting points are also weaker than stated. (a) The if not callable(func): return branch never runs today, because both clients define create_label and edit_label (client.py:217/225, …
  • Fix: In github/labels.py, define class LabelClient(Protocol) with get_labels(repo) -> list[dict], create_label(repo, name, color, description='') and edit_label(repo, name, color, description=''). Type client: LabelClient in sync_repository_labels, call client.get_labels(repo), client.create_label(repo, ...) and client.edit_label(repo, ...) directly, and delete _apply_label_mutation's getattr/callable check and both except TypeError fallbacks. If the only remaining shape is the dicts both clients return, drop _extract_labels_from_raw's object branch too. In GhCliClient, run get_labels, create_label and edit_label with check=True, or raise GitHubOperationError on a non-zero returncode, so a failed list does not turn into 'everything to create'. Add --limit 1000 to gh label list in both GhCliClient.get_labels and commands/gh.py _get_repo_labels. In sync_labels, …
  • Regression test: tests/test_github_labels.py::test_sync_propagates_client_failure: build a stub client class whose get_labels(repo) returns [] and whose create_label(repo, name, color, description) raises GitHubOperationError, then call sync_repository_labels(stub, 'o/r', [LabelSpec(name='type/bug', color='D73A4A')]) and assert it raises. This passes today, so add tests/test_github_client.py::test_gh_cli_client_label_failures_raise: patch devops_cli.github.client.run_gh to return MagicMock(returncode=1, …

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/cli
    priority/p2-medium
    on Oct 2, 2026
  3. dan-petty commented on Oct 2, 2026

    @dan-petty
    OwnerAuthor

    Closed by #973, 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/clitype/bug

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions