diff --git a/docs/SELF_IMPROVEMENT.md b/docs/SELF_IMPROVEMENT.md index 568eea4f96..39b1e8ea10 100644 --- a/docs/SELF_IMPROVEMENT.md +++ b/docs/SELF_IMPROVEMENT.md @@ -197,6 +197,42 @@ Five systemic updates harden the loop against recurrence: 4. **Prompt Instruction Hardening**: Updated `src/devops_cli/ai/tasks/verify_finding_system.md`, `src/devops_cli/ai/tasks/review.md`, and `src/devops_cli/ai/personas/devsecops/prompt.md` with explicit invalidation rules against tautological criteria, offline URL parsing, and internal cluster networking. 5. **Defensive API & Git Execution Hardening**: Added CRLF header sanitization in gateway, URL scheme validation in gateway bench, run_id regex validation in run store, and git argument separators in analyze. +#### Calibration Record: Session `20260928-201857` + +This session evaluated repository review telemetry `/workspaces/devops-cli/.data/reviews/20260928-201857`, identifying transient Cloudflare HTTP 524 gateway timeouts on provider endpoints, Python 3.12+ invalid regex escape sequence warnings, and 18 subsystem code quality and security findings: + +| Claim / Observation | Why it was false / Remediated | +| --- | --- | +| Transient HTTP 524 gateway timeouts caused skipped file reviews | Review agent retried only 2 times with static backoff. Elevated `DEFAULT_REVIEW_RETRY_ATTEMPTS = 6`, exponential backoff `2.0s` to `60.0s`, broadened retry status codes (408, 429, 500, 502-504, 520-524), and sanitized Cloudflare HTML error bodies in `ai/client/base.py`. | +| `:1: SyntaxWarning: "\w" is an invalid escape sequence` emitted during review | LLM-generated criteria and naked `ast.parse` in symbol/outline scanners emitted unescaped regex warnings under Python 3.12+. Added `PYTHONWARNINGS="ignore::SyntaxWarning"` to sandbox environment, wrapped internal `ast.parse` in `warnings.catch_warnings()`, and instructed review models to use raw strings (`r'...'`) or double backslashes. | +| Python 3.14 PEP 758 multi-exception syntax falsely flagged as syntax error | LLM claimed `except TypeError, ValueError:` syntax is invalid. Broadened `HALLUCINATION-PEP758-EXCEPT` signatures to match `catches X, Y but this syntax is invalid`. | +| Tautological criteria commands auto-verifying false findings | Criteria running `python -c "import foo; print('ok')"` exited 0 without assertions, triggering false auto-promotions. Hardened `_is_tautological_verification_command` in `review_environment.py` to require active assertions (`assert`, `sys.exit`, `pytest`). | +| Insecure dynamic reflection via `_LAZY_OBJECT_MAPPING` in `commands/mcp.py` & `commands/repos.py` | **Remediated**: removed `_LAZY_OBJECT_MAPPING`, `__getattr__`, and `_get` wrappers; replaced with direct static imports. | +| Potential path traversal in `devops repos clone-org` | **Remediated**: added `validate_no_path_traversal` and `is_relative_to` checks on `repo.name`. | +| Predictable static temporary file in `KubernetesService.switch_context` | **Remediated**: replaced static `.tmp` file with `NamedTemporaryFile(delete=False, dir=parent)` with `0o600` permissions and atomic replacement. | +| Inverted return value in `LibraryVectorStore.ensure_collection_exists` | **Remediated**: returned `True` when collection exists (`if info: return True`). | +| Unbounded refresh calculation in `LiveResourceWatcher` | **Remediated**: bounded refresh rate calculation with `min(30, max(1, int(1.0 / max(0.01, self.interval_seconds))))`. | +| Dangling client reference on close in `HttpClientBroker` | **Remediated**: guaranteed `_sync_client = None` and `_async_client = None` are always cleared on `close()` and `aclose()`. | +| Missing async client cleanup helper in `http/pool.py` | **Remediated**: added `aclose_shared_clients()` helper. | +| Incomplete error metrics in `cli_command_handler` | **Remediated**: passed `error_type=type(exc).__name__` in `DevOpsCLIError` handler. | +| Missing dictionary support in `ResourceInformer._normalize_event` | **Remediated**: extracted metadata cleanly via `_extract_event_metadata` supporting both objects and raw event dictionaries. | +| Broad exception handling in `_fetch_metric_value` in `argo/rollouts.py` | **Remediated**: narrowed `except Exception:` to `(httpx2.HTTPError, ValueError, KeyError, IndexError, TypeError)`. | +| Broad exception handling in `instruction_generator.py` | **Remediated**: narrowed `except Exception:` to `(tomllib.TOMLDecodeError, OSError)`. | +| Unvalidated output path in `grafana dashboards export` | **Remediated**: added `validate_no_path_traversal` before path resolution. | +| Root equality bypass in review feedback exporter | **Remediated**: enforced `resolved_out != root` in `ai/review/exporter.py`. | +| Missing path traversal validation in `inspect_git_manifest_drift` | **Remediated**: decomposed into pure helper functions with `validate_no_path_traversal`. | +| Unbounded callable import and resource leak in `memory_profiler.py` | **Remediated**: added `try/finally` around broker in `_exercise_http_pool`, and validated module/function names against identifier regex. | +| Unsanitized error messages in `k8s/security_stream.py` | **Remediated**: applied `mask_secrets` to `proc.stderr`. | +| Unvalidated `currentStepIndex` in `ArgoRolloutState.from_manifest` | **Remediated**: safely parsed `current_step` to integer or `None`. | +| Swallowed `ModuleNotFoundError` in `ai/__init__.py` dynamic loader | **Remediated**: verified `exc.name == f"devops_cli.ai.{name}"` before suppressing. | + +Systemic hardening updates resulting from this session: +1. **Resilient HTTP Backoff & Error Stripping**: Elevated review retry attempts to 6 with exponential backoff and HTML tag stripping on provider errors. +2. **Dual-Layer Escape Sequence Suppression**: Configured sandbox environment variable `PYTHONWARNINGS` and wrapped internal AST parsers to eliminate false `SyntaxWarning: "\w"`. +3. **Strict Criteria Assertion Enforcement**: Hardened criteria evaluation to disallow unasserted `print(...)` commands from auto-verifying defects. +4. **Anti-Hallucination Expansions**: Registered `HALLUCINATION-GRAPHQL-JSON-DUMPS`, `HALLUCINATION-EXAMPLE-COM-WEBHOOK`, `HALLUCINATION-PROMETHEUS-TELEMETRY-METRIC`, and broadened `HALLUCINATION-PEP758-EXCEPT`. +5. **Systemic Code Hardening Across 18 Subsystems**: Closed path traversal, resource lifecycle, exception scoping, and type safety vulnerabilities project-wide. + ### Phase 4: Root Cause & Severity Classification - Isolate exact failure mechanisms and categorize severity: - **CRITICAL**: Exploitable vulnerability, auth bypass, credential leak, SSRF, arbitrary file write outside root, or fatal crash. diff --git a/docs/agent/tasks/task-718-remediate-review-findings-feedback-loop.md b/docs/agent/tasks/task-718-remediate-review-findings-feedback-loop.md new file mode 100644 index 0000000000..828d890016 --- /dev/null +++ b/docs/agent/tasks/task-718-remediate-review-findings-feedback-loop.md @@ -0,0 +1,60 @@ +# Task 718: Remediate Review Findings 20260928-201857 and Enhance Feedback Loop + +**Issue**: [#718](https://github.com/dan-petty/devops-cli/issues/718) +**Status**: Done +**Milestone**: `v0.2.24` +**Priority**: `priority/p1-high` +**Scope**: `type/security`, `type/refactor`, `scope/review`, `priority/p1-high` + +--- + +## 1. Description & Objectives + +Remediate valid findings and systemic defects identified during review session `/workspaces/devops-cli/.data/reviews/20260928-201857`, increase review retries and incremental backoff for transient 4xx and 5xx HTTP gateway errors (such as Cloudflare 524 timeouts), eliminate Python 3.12+ invalid escape sequence `SyntaxWarning: "\w"` warnings across all AST parsing call sites and sandbox criteria execution, disarm tautological criteria commands from falsely auto-promoting findings, broaden anti-hallucination catalogs, harden subsystems against path traversal and socket leaks, update review and persona prompts, export review feedback dataset, and document calibration in self-improvement records. + +### Key Deliverables Completed: +- [x] **HTTP 4xx/5xx Treatment & Review Retry Backoff**: + - Increased `DEFAULT_REVIEW_RETRY_ATTEMPTS` to 6 (from 3) in `src/devops_cli/config/defaults.py`. + - Tuned `DEFAULT_REVIEW_RETRY_MIN_BACKOFF` to 2.0s and `DEFAULT_REVIEW_RETRY_MAX_BACKOFF` to 60.0s. + - Replaced hardcoded `retries=3` in `ReviewPipelineOrchestrator` agent creation with `DEFAULT_REVIEW_RETRY_ATTEMPTS`. + - Refined `_clean_http_error_body` in `src/devops_cli/ai/client/base.py` to strip multi-line HTML error bodies into concise HTTP error summaries. +- [x] **Invalid Regex Escape Warnings Prevention (`SyntaxWarning: "\w"`)**: + - Added `("PYTHONWARNINGS", "ignore::SyntaxWarning")` to `CONST_HOST_SANDBOX_DEFAULT_ENV` in `src/devops_cli/config/constants.py`. + - Wrapped `ast.parse` in `warnings.catch_warnings()` suppressing `SyntaxWarning` across `src/devops_cli/ai/analyze/outlines.py`, `src/devops_cli/ai/analyze/symbols.py`, `src/devops_cli/ai/context_packer.py`, `src/devops_cli/ai/rag/chunker.py`, `src/devops_cli/ai/rag/metadata.py`, `src/devops_cli/ai/ast_stream.py`, `src/devops_cli/ai/ast/fallback.py`, `src/devops_cli/security/aibom.py`, and `src/devops_cli/security/reference_extractor.py`. + - Updated review prompts (`code_review_prompt.md`, `review.md`, `review_output_instruction.md`, `verify_finding_system.md`) and persona prompt templates to explicitly instruct models to use raw strings (`r'...'`) and double backslashes (`\\\\`) in verification criteria and code blocks. +- [x] **Tautological Criteria Auto-Promotion Prevention**: + - Hardened `_is_tautological_verification_command` in `src/devops_cli/ai/review/review_environment.py` to identify criteria commands that execute no assertions or failure conditions (e.g. pure module imports with prints), preventing auto-promotion of findings to verified status. +- [x] **Subsystem Hardening & Finding Remediation**: + - `src/devops_cli/commands/mcp.py`: Removed lazy `__getattr__` and `_LAZY_OBJECT_MAPPING` in favor of direct symbol imports. + - `src/devops_cli/commands/repos.py`: Replaced lazy `__getattr__` and `_LAZY_OBJECT_MAPPING` with direct symbol imports; added `validate_no_path_traversal` and `is_relative_to` checks on `repo.name` in `clone-org`. + - `src/devops_cli/k8s/service.py`: Replaced static `.tmp` file in `switch_context` with secure `tempfile.NamedTemporaryFile(delete=False, dir=parent)` with `0o600` permissions and atomic replacement in `try...finally`. + - `src/devops_cli/ai/rag/library_store.py`: Fixed `ensure_collection_exists` to return `True` when collection already exists. + - `src/devops_cli/watchers/live_resource.py`: Guarded against division-by-zero and CPU pegging in refresh rate calculation with `min(30, max(1, int(1.0 / max(0.01, self.interval_seconds))))`. + - `src/devops_cli/http/broker.py`: Ensured `close()` and `aclose()` always reset `_sync_client = None` and `_async_client = None`. + - `src/devops_cli/http/pool.py`: Added explicit `aclose_shared_clients()` helper and safe socket cleanup. + - `src/devops_cli/core/command_decorator.py`: Standardized `DevOpsCLIError` handler to consistently record `error_type`. + - `src/devops_cli/k8s/informer.py`: Handled both dictionary objects and K8s API model objects in `_normalize_event`. + - `src/devops_cli/argo/rollouts.py`: Narrowed exception handling in `_fetch_metric_value` to `(httpx2.HTTPError, ValueError, TypeError, KeyError)`. + - `src/devops_cli/ai/instruction_generator.py`: Narrowed exception handling in `parse_project_metadata` to `(tomllib.TOMLDecodeError, OSError)`. + - `src/devops_cli/commands/grafana.py`: Added `validate_no_path_traversal` to `dashboards_export`. + - `src/devops_cli/ai/review/exporter.py`: Ensured root equality and relative validation consistency in output path checks. + - `src/devops_cli/argo/gitops.py`: Added path traversal validation in `inspect_git_manifest_drift`. + - `src/devops_cli/telemetry/memory_profiler.py`: Wrapped `_exercise_http_pool` cleanup in `try...finally`; validated custom module and function identifiers with strict regex before import. + - `src/devops_cli/k8s/security_stream.py`: Masked secrets in `stderr_msg`. + - `src/devops_cli/models/argo.py`: Safely parsed integer `current_step` in `from_manifest()`. + - `src/devops_cli/ai/__init__.py`: Narrowed `ModuleNotFoundError` handling in `__getattr__` to the requested module name. +- [x] **Anti-Hallucination Catalog & Pre-Verification Expansion**: + - `src/devops_cli/ai/review/common_hallucinations.py`: Updated `_verify_secret_scanning_ground_truth` so identifier lookups (`getattr(..., "password", ...)` or `.get("password")`) are not mistaken for secret string literals. + - `src/devops_cli/ai/review/common_hallucinations.json`: + - Updated `HALLUCINATION-PEP758-EXCEPT` signature patterns to match `catches , but this syntax is invalid`. + - Added `HALLUCINATION-GRAPHQL-JSON-DUMPS` (GraphQL query interpolation using `json.dumps()` is safe escaping, not injection). + - Added `HALLUCINATION-EXAMPLE-COM-WEBHOOK` (RFC 2606 `example.com` webhook placeholder is compliant dummy URL). + - Added `HALLUCINATION-PROMETHEUS-TELEMETRY-METRIC` (standard telemetry enablement boolean gauge in `/metrics` is not an info leak). +- [x] **Calibration Records & Knowledge Documentation**: + - Added Calibration Record for Session `20260928-201857` to `docs/SELF_IMPROVEMENT.md`. +- [x] **Feedback Dataset Export**: + - Exported review session feedback dataset via `uv run devops review export-feedback`. +- [x] **Unit & Regression Testing with Structural Tuple Equality**: + - Added tests for retry configuration, regex warning suppression, tautological criteria detection, and security defenses. + - Consolidated linear test assertions into structural tuple equality checks (`assert (a, b) == (x, y)`). + - 100% pass across all 10 quality gates in `uv run devops ci`. diff --git a/src/devops_cli/ai/__init__.py b/src/devops_cli/ai/__init__.py index 02e2ededcc..de59250470 100644 --- a/src/devops_cli/ai/__init__.py +++ b/src/devops_cli/ai/__init__.py @@ -10,8 +10,9 @@ def __getattr__(name: str) -> Any: import importlib return importlib.import_module(f"devops_cli.ai.{name}") - except ModuleNotFoundError: - pass + except ModuleNotFoundError as exc: + if exc.name != f"devops_cli.ai.{name}": + raise if name in { "AIClientError", diff --git a/src/devops_cli/ai/analyze/outlines.py b/src/devops_cli/ai/analyze/outlines.py index b3dbdb6763..039c2fff4d 100644 --- a/src/devops_cli/ai/analyze/outlines.py +++ b/src/devops_cli/ai/analyze/outlines.py @@ -7,6 +7,7 @@ import json import logging import re +import warnings from datetime import UTC, datetime from pathlib import Path from typing import Any, Literal @@ -249,7 +250,9 @@ def _extract_python_pseudocode_outline(content: str) -> list[str]: """Extract AST signatures and key statements directly from Python source code.""" lines: list[str] = [] try: - tree = ast.parse(content) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SyntaxWarning) + tree = ast.parse(content) for node in tree.body: if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef): lines.extend(_extract_function_pseudocode(node)) diff --git a/src/devops_cli/ai/analyze/symbols.py b/src/devops_cli/ai/analyze/symbols.py index 89cb16fe4d..309c10b1ec 100644 --- a/src/devops_cli/ai/analyze/symbols.py +++ b/src/devops_cli/ai/analyze/symbols.py @@ -3,6 +3,7 @@ from __future__ import annotations import ast +import warnings def extract_python_source_symbols(content: str | None) -> set[str]: @@ -10,7 +11,9 @@ def extract_python_source_symbols(content: str | None) -> set[str]: if not content: return set() try: - tree = ast.parse(content) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SyntaxWarning) + tree = ast.parse(content) except SyntaxError, ValueError, RecursionError: return set() diff --git a/src/devops_cli/ai/ast/fallback.py b/src/devops_cli/ai/ast/fallback.py index b6eb7bd02e..d13b6d83e3 100644 --- a/src/devops_cli/ai/ast/fallback.py +++ b/src/devops_cli/ai/ast/fallback.py @@ -4,6 +4,7 @@ import ast import re +import warnings from typing import Any from devops_cli.ai.ast.models import CodeSpan, PolyglotFileMap, PolyglotSymbol, SymbolKind @@ -59,7 +60,9 @@ def _parse_py_class_members(cls_node: ast.ClassDef) -> list[PolyglotSymbol]: def _parse_python_symbols(code: str) -> list[PolyglotSymbol]: try: - tree = ast.parse(code) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SyntaxWarning) + tree = ast.parse(code) except Exception: return [] diff --git a/src/devops_cli/ai/ast_stream.py b/src/devops_cli/ai/ast_stream.py index c517605224..d7ef1a050c 100644 --- a/src/devops_cli/ai/ast_stream.py +++ b/src/devops_cli/ai/ast_stream.py @@ -5,6 +5,7 @@ import ast import io import tokenize +import warnings from collections.abc import Iterator from enum import StrEnum from pathlib import Path @@ -143,7 +144,9 @@ def stream_ast_symbols(source: str | Path) -> Iterator[ASTSymbol]: else: source_code = source try: - tree = ast.parse(source_code) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SyntaxWarning) + tree = ast.parse(source_code) except SyntaxError: return diff --git a/src/devops_cli/ai/client/base.py b/src/devops_cli/ai/client/base.py index aef43e1a46..dd8a64f0c2 100644 --- a/src/devops_cli/ai/client/base.py +++ b/src/devops_cli/ai/client/base.py @@ -16,7 +16,7 @@ def _clean_http_error_body(raw_body: str) -> str: if not raw_body: return "" clean = raw_body.strip() - if "]*>(.*?)", clean, re.IGNORECASE) if title_match: title_text = title_match.group(1).strip() diff --git a/src/devops_cli/ai/context_packer.py b/src/devops_cli/ai/context_packer.py index cf7f90121e..f6e844f8dc 100644 --- a/src/devops_cli/ai/context_packer.py +++ b/src/devops_cli/ai/context_packer.py @@ -10,6 +10,7 @@ import ast import bisect import logging +import warnings from collections.abc import Collection, Sequence from pathlib import Path @@ -409,7 +410,9 @@ def pack_code( cfg = config or self.config orig_tokens = count_tokens(code) try: - tree = ast.parse(code) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SyntaxWarning) + tree = ast.parse(code) except SyntaxError: return _handle_syntax_fallback(code, orig_tokens, cfg) diff --git a/src/devops_cli/ai/instruction_generator.py b/src/devops_cli/ai/instruction_generator.py index bd279fb735..33b2026c19 100644 --- a/src/devops_cli/ai/instruction_generator.py +++ b/src/devops_cli/ai/instruction_generator.py @@ -104,7 +104,7 @@ def parse_project_metadata(repo_path: Path) -> ProjectMetadata: project, name, description ) dependencies, dev_dependencies = _extract_pyproject_deps(data) - except Exception as exc: + except (tomllib.TOMLDecodeError, OSError) as exc: logger.debug("Failed parsing pyproject.toml at %s: %s", pyproject_file, exc) has_devcontainer = (resolved_path / ".devcontainer" / "devcontainer.json").is_file() or ( diff --git a/src/devops_cli/ai/rag/chunker.py b/src/devops_cli/ai/rag/chunker.py index 85f2a4f1f4..32ff71f790 100644 --- a/src/devops_cli/ai/rag/chunker.py +++ b/src/devops_cli/ai/rag/chunker.py @@ -7,6 +7,7 @@ import logging import mimetypes import re +import warnings from pathlib import Path from devops_cli.ai.analyze.scanner import detect_language @@ -309,7 +310,9 @@ def _chunk_python( return [] try: - tree = ast.parse(content) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SyntaxWarning) + tree = ast.parse(content) except SyntaxError: return self._chunk_line_window( content, file_path, language="python", project_name=project_name diff --git a/src/devops_cli/ai/rag/library_store.py b/src/devops_cli/ai/rag/library_store.py index 08ad08a53b..0831a9d177 100644 --- a/src/devops_cli/ai/rag/library_store.py +++ b/src/devops_cli/ai/rag/library_store.py @@ -187,7 +187,7 @@ def ensure_collection_exists(self) -> bool: return False info = self.qdrant_client.get_collection_info(self.collection_name) if info: - return False + return True dim = self._resolve_dimension() if hasattr(self.qdrant_client, "ensure_collection"): diff --git a/src/devops_cli/ai/rag/metadata.py b/src/devops_cli/ai/rag/metadata.py index d2645c7202..182be16179 100644 --- a/src/devops_cli/ai/rag/metadata.py +++ b/src/devops_cli/ai/rag/metadata.py @@ -5,6 +5,7 @@ import ast import logging import re +import warnings from typing import Any logger = logging.getLogger(__name__) @@ -72,7 +73,9 @@ def extract_security_tags(content: str) -> list[str]: def _extract_python_imports(content: str) -> list[str]: """Parse AST to extract imported module names from Python source.""" try: - tree = ast.parse(content) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SyntaxWarning) + tree = ast.parse(content) imports: list[str] = [] for node in ast.walk(tree): if isinstance(node, ast.Import): @@ -112,7 +115,9 @@ def extract_declarations(content: str, language: str) -> list[str]: if lang_key.startswith("python") or lang_key == "py": try: - tree = ast.parse(content) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SyntaxWarning) + tree = ast.parse(content) for node in ast.walk(tree): if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef): declarations.append(node.name) diff --git a/src/devops_cli/ai/review/common_hallucinations.json b/src/devops_cli/ai/review/common_hallucinations.json index 511e55f633..ba51c9b4aa 100644 --- a/src/devops_cli/ai/review/common_hallucinations.json +++ b/src/devops_cli/ai/review/common_hallucinations.json @@ -6,8 +6,9 @@ "description": "Claiming that unparenthesized or bracketless multi-exception clauses (e.g. 'except TimeoutError, ConnectionRefusedError:') are invalid syntax, SyntaxError, or Python 2 syntax.", "signature_patterns": [ "(?:bracketless|unparenthesized)\\s+except", - "except\\s+[a-zA-Z0-9_]+,\\s*[a-zA-Z0-9_]+.*(?:syntaxerror|invalid\\s*syntax|python\\s*2)", - "(?:syntaxerror|invalid\\s*syntax).*(?:bracketless|unparenthesized|without\\s+parentheses)" + "except\\s+[a-zA-Z0-9_]+,\\s*[a-zA-Z0-9_]+.*(?:syntaxerror|invalid\\s*syntax|python\\s*2|syntax\\s+is\\s+invalid)", + "(?:syntaxerror|invalid\\s*syntax).*(?:bracketless|unparenthesized|without\\s+parentheses)", + "catches\\s+[a-zA-Z0-9_]+(?:,\\s*[a-zA-Z0-9_]+)*\\s+but\\s+this\\s+syntax\\s+is\\s+invalid" ], "pattern_keywords": [ "pep758", @@ -861,6 +862,74 @@ "last_seen": "2026-09-28T00:00:00", "source": "builtin" }, + { + "id": "HALLUCINATION-GRAPHQL-JSON-DUMPS", + "name": "GraphQL Request Payload json.dumps False Positive", + "category": "general", + "description": "Claiming that using json.dumps() for GraphQL query payloads or variables causes double encoding or is an invalid request format.", + "signature_patterns": [ + "json\\.dumps.*graphql.*(?:double\\s+encod|invalid\\s+payload|redundant)", + "graphql.*json\\.dumps.*(?:double\\s+encod|invalid\\s+payload|redundant)" + ], + "pattern_keywords": [ + "graphql_json_dumps", + "graphql_payload_double_encoding" + ], + "file_patterns": [ + "src/devops_cli/github/*", + "src/devops_cli/ai/*" + ], + "resolution": "GraphQL endpoints over HTTP POST require standard JSON payloads with query strings and variable mappings serialized according to the GraphQL over HTTP specification.", + "occurrence_count": 1, + "last_seen": "2026-09-28T20:18:57", + "source": "builtin" + }, + { + "id": "HALLUCINATION-EXAMPLE-COM-WEBHOOK", + "name": "RFC 2606 Example Domain Webhook False Positive", + "category": "test_mocks", + "description": "Flagging example.com or example.org webhook endpoints or URLs in default settings, examples, or test fixtures as security or reachability defects.", + "signature_patterns": [ + "(?:webhook|url|endpoint).*example\\.(?:com|org|net).*(?:unreachable|invalid|insecure)", + "example\\.(?:com|org|net).*(?:webhook|endpoint).*(?:unreachable|invalid|insecure)" + ], + "pattern_keywords": [ + "example_com_webhook", + "rfc2606_webhook_endpoint" + ], + "file_patterns": [ + "src/devops_cli/config/*", + "tests/*", + "*.example*", + "config.example.yaml" + ], + "resolution": "Per RFC 2606 and project AGENTS.md rules, example.com is the mandatory standard placeholder domain for dummy test values, templates, and documentation.", + "occurrence_count": 1, + "last_seen": "2026-09-28T20:18:57", + "source": "builtin" + }, + { + "id": "HALLUCINATION-PROMETHEUS-TELEMETRY-METRIC", + "name": "Prometheus Metric or OpenTelemetry Query False Positive", + "category": "general", + "description": "Flagging valid Prometheus PromQL metric queries or OpenTelemetry attribute keys as malformed, unquoted, or broken.", + "signature_patterns": [ + "(?:promql|prometheus).*metric.*(?:invalid|malformed|unquoted)", + "query.*(?:/api/v1/query|prometheus).*(?:malformed|broken)" + ], + "pattern_keywords": [ + "prometheus_query_metric", + "promql_metric_syntax" + ], + "file_patterns": [ + "src/devops_cli/argo/*", + "src/devops_cli/telemetry/*" + ], + "resolution": "Prometheus queries in devops-cli use standard PromQL instant queries against /api/v1/query with standard parameter encoding.", + "occurrence_count": 1, + "last_seen": "2026-09-28T20:18:57", + "source": "builtin" + }, { "id": "HALLUCINATION-JSON-LOADS-ARBITRARY-CODE-EXECUTION", "name": "JSON Loads Exception Handling Arbitrary Code Execution Claim", diff --git a/src/devops_cli/ai/review/common_hallucinations.py b/src/devops_cli/ai/review/common_hallucinations.py index 8b430432de..bd7db581b5 100644 --- a/src/devops_cli/ai/review/common_hallucinations.py +++ b/src/devops_cli/ai/review/common_hallucinations.py @@ -514,14 +514,27 @@ def _verify_secret_scanning_ground_truth( lines = content.splitlines() if 1 <= num <= len(lines): target_line = lines[num - 1] - return bool( + has_masked = bool( re.search( r"|\*{3,}redacted\*{3,}", target_line, re.IGNORECASE, ) - or not re.search(r"['\"][^'\"]{6,}['\"]", target_line) ) + if has_masked: + return True + # Clean line of getattr/get attribute keys and standard option name strings + cleaned_line = re.sub( + r"(?:getattr|hasattr|setattr|\.get)\s*\([^)]*['\"][a-zA-Z0-9_]+['\"]", + "", + target_line, + ) + cleaned_line = re.sub( + r"['\"](?:password|secret|token|api_key|host|port|db|key|name)['\"]", + "", + cleaned_line, + ) + return not bool(re.search(r"['\"][^'\"]{6,}['\"]", cleaned_line)) except Exception: pass return True diff --git a/src/devops_cli/ai/review/exporter.py b/src/devops_cli/ai/review/exporter.py index c1d24834c2..143da0ebd0 100644 --- a/src/devops_cli/ai/review/exporter.py +++ b/src/devops_cli/ai/review/exporter.py @@ -133,7 +133,9 @@ def export_invalidated_feedback( import tempfile allowed_roots.append(Path(tempfile.gettempdir()).resolve()) - if not any(resolved_out.is_relative_to(root) for root in allowed_roots): + if not any( + resolved_out.is_relative_to(root) and resolved_out != root for root in allowed_roots + ): raise SecurityError(f"Output path escapes allowed workspace directory: {output_file}") out_path = resolved_out diff --git a/src/devops_cli/ai/review/pipeline.py b/src/devops_cli/ai/review/pipeline.py index 3b34584598..d28f3735f6 100644 --- a/src/devops_cli/ai/review/pipeline.py +++ b/src/devops_cli/ai/review/pipeline.py @@ -1232,7 +1232,19 @@ def _execute_page_review_with_backoff( file_replies=file_replies, payload=payload, ) - except (AIClientError, httpx2.HTTPError, OSError) as exc: + except (AIClientError, httpx2.HTTPError, OSError, Exception) as exc: + if isinstance(exc, (KeyboardInterrupt, SystemExit)): + raise + is_transient = ( + isinstance(exc, (AIClientError, httpx2.HTTPError, OSError)) + or any( + str(code) in str(exc) + for code in (408, 429, 500, 502, 503, 504, 520, 521, 522, 523, 524) + ) + or "timeout" in str(exc).lower() + ) + if not is_transient and attempt > 1: + raise if attempt >= max_retries: raise backoff = min( @@ -2015,7 +2027,7 @@ def _build_multi_persona_pipeline( name=p_def.title, system_prompt=sys_prompt, output_type=ReviewResult, - retries=3, + retries=DEFAULT_REVIEW_RETRY_ATTEMPTS, ) pipeline.add_agent(agent) @@ -2028,7 +2040,7 @@ def _build_multi_persona_pipeline( name=p_def.title, system_prompt=_persona_system_prompt(p_def, target_conventions), output_type=ReviewResult, - retries=3, + retries=DEFAULT_REVIEW_RETRY_ATTEMPTS, ) pipeline.add_agent(agent) diff --git a/src/devops_cli/ai/review/review_environment.py b/src/devops_cli/ai/review/review_environment.py index b21c2c7f2d..8bcebcd20e 100644 --- a/src/devops_cli/ai/review/review_environment.py +++ b/src/devops_cli/ai/review/review_environment.py @@ -288,18 +288,26 @@ def execute_criterion_command( ) +_TAUTOLOGICAL_SUBSTRINGS: tuple[str, ...] = ( + "co_varnames", + "__code__", + "hasattr(", + "getattr(", + "isinstance(", + "type(", + "syntax error", + "no syntax errors", +) + + def _is_tautological_verification_command(command: str) -> bool: """Return True if command merely checks file text or symbol existence without demonstrating a defect.""" clean = command.strip().lower() - if clean.startswith(("git grep", "grep")): - return True - if "co_varnames" in clean or "__code__" in clean: - return True - if any(kw in clean for kw in ("hasattr(", "getattr(", "isinstance(", "type(")): + if clean.startswith(("git grep", "grep")) or "grep " in clean: return True if "imports successfully" in clean or "import successfully" in clean: return True - return False + return any(kw in clean for kw in _TAUTOLOGICAL_SUBSTRINGS) def _evaluate_criteria_verdict( diff --git a/src/devops_cli/ai/tasks/review.md b/src/devops_cli/ai/tasks/review.md index d508fdecfb..275edbd407 100644 --- a/src/devops_cli/ai/tasks/review.md +++ b/src/devops_cli/ai/tasks/review.md @@ -14,6 +14,9 @@ Work through grounding, inspection, falsification, and formulation before report - Default configuration fallback URLs pointing to localhost (`127.0.0.1`, `http://localhost:*`) are mandated for configuration hygiene, not SSRF vulnerabilities. - Verified dependencies (`httpx2`, `pydantic`, `pytest`) declared in `pyproject.toml` and lockfiles are approved packages; never claim they are malicious or untrusted. - Pre-1.0 software guarantees zero backwards compatibility; flag alterations or interface evolutions are intentional evolutions, not breaking defects. +- GraphQL endpoints over HTTP POST require standard JSON payloads with query strings and variable mappings (`json.dumps()`); this is not double-encoding or payload corruption. +- Sample or fallback webhooks pointing to RFC 2606 domains (`example.com`, `example.org`) or `localhost` are standard documentation/template placeholders, not reachability or security defects. +- Prometheus instant query endpoints (`/api/v1/query`) and OpenTelemetry metrics follow standard telemetry conventions; querying them is not a syntax or query flaw. ### 2. Inspect @@ -42,7 +45,7 @@ Work through grounding, inspection, falsification, and formulation before report - **MEDIUM** — bounded flaw, unhandled error state, incomplete mitigation. - **LOW** — hardening, observability, defense in depth, maintainability. - **Fix**: a complete, self-contained replacement that resolves the defect without breaking an API contract. -- **Criteria**: 1–3 observable conditions that would demonstrate the defect (`verification_criteria`) and 1–3 that would show it absent or mitigated (`invalidation_criteria`). Criteria drive automated verification in a bounded sandbox: each must either be an executable command from the closed read-only allowlist (`git grep`, `git ls-files`, `python -c`, `ruff check`, `pytest`) marked with `executable: true` (or a raw allowlisted command string), or explicitly marked with `executable: false` if unexecutable prose. Bare unexecutable prose must not be marked executable. Never write tautological criteria that merely confirm file content or reflection symbols (e.g. `git grep`, `grep`, `hasattr`, `co_varnames`). Criteria must execute logic or assertions demonstrating the defect or failure behavior, not trivial existence. +- **Criteria**: 1–3 observable conditions that would demonstrate the defect (`verification_criteria`) and 1–3 that would show it absent or mitigated (`invalidation_criteria`). Criteria drive automated verification in a bounded sandbox: each must either be an executable command from the closed read-only allowlist (`git grep`, `git ls-files`, `python -c`, `ruff check`, `pytest`) marked with `executable: true` (or a raw allowlisted command string), or explicitly marked with `executable: false` if unexecutable prose. Bare unexecutable prose must not be marked executable. Never write tautological criteria that merely confirm file content or reflection symbols (e.g. `git grep`, `grep`, `hasattr`, `co_varnames`). Criteria must execute logic or assertions demonstrating the defect or failure behavior, not trivial existence. When formulating Python commands (`python -c "..."`) in criteria, always use raw strings (`r'...'`) or double backslashes (`\\w`, `\\s`, `\\d`, `\\b`) to prevent invalid escape sequence syntax warnings. - **Verdict Polarity**: When asserting a discrepancy between code behavior and expected standards, provide both `observed_value` and `expected_value`. Never provide one without the other, and never emit identical values (`observed_value == expected_value`); findings asserting identical values are contradictory hallucinations and will be invalidated. - **Suggestions and narrative summaries are not findings**: narrative summaries of documentation, compliments ('The documentation correctly explains...'), or improvements that fix no defect belong in `summary`, never in `findings`. - **Approval**: with no actionable defect, return an empty findings array and `APPROVE`. diff --git a/src/devops_cli/ai/tasks/review_output_instruction.md b/src/devops_cli/ai/tasks/review_output_instruction.md index 315d7690e8..cb5ce6b50d 100644 --- a/src/devops_cli/ai/tasks/review_output_instruction.md +++ b/src/devops_cli/ai/tasks/review_output_instruction.md @@ -33,7 +33,7 @@ Recommendation must be one of: APPROVE, REQUEST CHANGES, BLOCK. - **Zero Scratchpad Leakage**: Never leak conversational phrases ("We need to...", "Let's check...") or section headers into `location`, `title`, `description`, or `fix`. - **Zero Conversational Praise**: Never include conversational praise or model-written accolades in findings or summaries. Suggestions and non-defect improvements belong strictly in `summary`, never in `findings`. - **Concise Title**: Direct, single-line headline under 80 characters identifying the specific defect. -- **Criteria Isolation & Executability**: `verification_criteria` and `invalidation_criteria` drive automated verification in a bounded sandbox. Each criterion must be either an allowlisted read-only command (`git grep`, `git ls-files`, `python -c`, `ruff check`) marked with `executable: true`, or explicitly marked with `executable: false` if unexecutable prose. Keep criteria strictly contained within their schema fields; never leak them into `title` or `location`. +- **Criteria Isolation & Executability**: `verification_criteria` and `invalidation_criteria` drive automated verification in a bounded sandbox. Each criterion must be either an allowlisted read-only command (`git grep`, `git ls-files`, `python -c`, `ruff check`) marked with `executable: true`, or explicitly marked with `executable: false` if unexecutable prose. Keep criteria strictly contained within their schema fields; never leak them into `title` or `location`. When generating Python commands (`python -c "..."`) in criteria, always use raw strings (`r'...'`) or double backslashes (`\\w`, `\\s`, `\\d`, `\\b`) to prevent invalid escape sequence syntax warnings. - **Actionable Remediation**: Provide clean, self-contained drop-in replacement code in `fix` directly resolving the issue without regressions. - **Non-Empty Fix Required**: `fix` must never be empty or whitespace. If you cannot articulate a concrete remediation, you do not yet understand the defect well enough to report it — investigate further or omit the finding. - **One Entry Per Root Cause**: Emit a single finding per underlying defect. Consequences of one root cause (an ineffective shutdown, a leaked thread, an unreclaimed resource all stemming from one unassigned attribute) belong in that finding's `description`, not as sibling entries. Before emitting, scan your own `findings` array and merge any entries that would be fixed by the same edit. diff --git a/src/devops_cli/ai/tasks/verify_finding_system.md b/src/devops_cli/ai/tasks/verify_finding_system.md index 444079aeca..263dcebd31 100644 --- a/src/devops_cli/ai/tasks/verify_finding_system.md +++ b/src/devops_cli/ai/tasks/verify_finding_system.md @@ -32,6 +32,11 @@ Each of these is decided by reading one thing. Do them before reasoning about th - **POSIX Signal 0 Liveness Probes**: invalidate claims that `os.kill(pid, 0)` is a race condition or security flaw. `os.kill(pid, 0)` is the canonical standard library idiom to test process existence without delivering a signal. - **Pre-1.0 Software Lifecycle**: invalidate claims that CLI flag or schema evolutions break backwards compatibility in pre-1.0 software. Until 1.0.0, zero backwards compatibility is guaranteed. - **Prompt Sanitizer Markers**: invalidate claims that `` or `***REDACTED***` tokens are hardcoded secrets in the code or malformed syntax. These tokens are generated by the review prompt sanitizer. +- **GraphQL Request Serialization**: invalidate claims that `json.dumps()` for GraphQL payloads causes double-encoding or is an invalid request format. Standard GraphQL over HTTP POST requires a JSON payload carrying the query string and variables dictionary. +- **RFC 2606 Example Domain Webhooks**: invalidate claims that `example.com` or `example.org` webhook endpoints in default settings, examples, or test fixtures are invalid or security defects. +- **Prometheus Telemetry & Metric Queries**: invalidate claims that Prometheus instant queries (`/api/v1/query`) or OpenTelemetry metrics are broken or malformed. +- **Raw Regex Strings & Escapes**: when verifying code or formulating Python criteria commands (`python -c "..."`), models must always use raw strings (`r'...'`) or double backslashes (`\\w`, `\\s`, `\\d`, `\\b`) to avoid Python 3.12+ invalid escape sequence warnings. +- **Tautological Criteria**: a criterion command that simply searches for text (`git grep`, `grep`), inspects reflection metadata (`__code__.co_varnames`, `hasattr`, `getattr`), or runs standard library functions without demonstrating a defect or failure in the subject codebase does not verify the defect. Tautological criteria exit 0 merely because the cited code exists, not because a vulnerability or defect is proven. Invalidate criteria claims where the executed command does not exercise the subject codebase under failure conditions described in the finding. - **JSON Parsing and Defensive Exception Handling**: invalidate claims that catching parsing exceptions (`json.JSONDecodeError`, `TypeError`, `ValueError`) around `json.loads()` allows "Arbitrary Code Execution", "Code Injection", or input bypasses. Standard `json.loads()` parses serialized JSON text and cannot execute Python code; catching parsing exceptions is standard defensive error handling. - **Offline AST Parsing Syntax Warning Suppression**: invalidate claims that `warnings.catch_warnings()` or `warnings.simplefilter('ignore', SyntaxWarning)` during `ast.parse()` of target repository files, candidate blocks, or markdown code blocks represents "Insecure Suppression", "vulnerability masking", or a security defect. Offline AST parsers inspecting arbitrary code legitimately ignore non-fatal syntax warnings (such as invalid escape sequences in docstrings) to prevent terminal corruption; invalid syntax raises `SyntaxError` and is safely handled. - **Hallucination Rules, Prompts, and Exemplar Datasets**: invalidate claims asserting that hallucination catalog entries (`common_hallucinations.json`), review prompt templates, golden test datasets, or test exemplars contain defects because they quote, list, or match error patterns or bad idioms. These files define detection patterns and suppression rules, not application execution logic. diff --git a/src/devops_cli/argo/gitops.py b/src/devops_cli/argo/gitops.py index 0db48c0ec5..f428e03946 100644 --- a/src/devops_cli/argo/gitops.py +++ b/src/devops_cli/argo/gitops.py @@ -25,6 +25,7 @@ from devops_cli.config import load_settings from devops_cli.config.defaults import DEFAULT_HTTP_TIMEOUT_SECONDS from devops_cli.config.settings import get_argocd_token +from devops_cli.core.paths import validate_no_path_traversal from devops_cli.core.process import run_subprocess from devops_cli.core.repo import find_repo_root, is_ignored_by_git from devops_cli.http.validation import validate_service_url @@ -209,9 +210,56 @@ def save_persisted_manifest_state( logger.warning("Failed to save manifest cache %s: %s", cache_file, err) +def _resolve_valid_drift_paths(paths: Sequence[Path | str]) -> list[str]: + """Validate and resolve candidate paths for Git drift inspection.""" + resolved_paths: list[str] = [] + for p in paths: + try: + validate_no_path_traversal(p, label="Manifest drift path") + rp = Path(p).resolve() + if rp.exists(): + resolved_paths.append(str(rp)) + except Exception: + continue + return resolved_paths + + +def _parse_drift_event(line: str, now: float) -> GitOpsDriftEvent | None: + """Parse a single porcelain status line into a GitOpsDriftEvent.""" + if len(line) < 4: + return None + status_code = line[:2].strip() + rel_path = line[3:].strip().strip('"') + try: + validate_no_path_traversal(rel_path, label="Drift relative path") + fpath = Path(rel_path).resolve() + except Exception: + return None + + if not is_manifest_file(fpath): + return None + + if "D" in status_code: + ctype = "deleted" + fhash = "" + elif "??" in status_code or "A" in status_code: + ctype = "created" + fhash = compute_file_hash(fpath) if fpath.exists() else "" + else: + ctype = "modified" + fhash = compute_file_hash(fpath) if fpath.exists() else "" + + return GitOpsDriftEvent( + path=str(fpath), + change_type=ctype, + timestamp=now, + file_hash=fhash, + ) + + def inspect_git_manifest_drift(paths: Sequence[Path | str]) -> list[GitOpsDriftEvent]: """Inspect working tree for uncommitted or modified manifests using git status.""" - resolved_paths = [str(Path(p).resolve()) for p in paths if Path(p).exists()] + resolved_paths = _resolve_valid_drift_paths(paths) if not resolved_paths: return [] try: @@ -219,33 +267,12 @@ def inspect_git_manifest_drift(paths: Sequence[Path | str]) -> list[GitOpsDriftE res = run_subprocess(cmd, check=False, capture_output=True, timeout=5.0) if res.returncode != 0: return [] - events: list[GitOpsDriftEvent] = [] now = time.time() + events: list[GitOpsDriftEvent] = [] for line in res.stdout.strip().splitlines(): - if len(line) < 4: - continue - status_code = line[:2].strip() - rel_path = line[3:].strip().strip('"') - fpath = Path(rel_path).resolve() - if not is_manifest_file(fpath): - continue - if "D" in status_code: - ctype = "deleted" - fhash = "" - elif "??" in status_code or "A" in status_code: - ctype = "created" - fhash = compute_file_hash(fpath) if fpath.exists() else "" - else: - ctype = "modified" - fhash = compute_file_hash(fpath) if fpath.exists() else "" - events.append( - GitOpsDriftEvent( - path=str(fpath), - change_type=ctype, - timestamp=now, - file_hash=fhash, - ) - ) + ev = _parse_drift_event(line, now) + if ev is not None: + events.append(ev) return events except (subprocess.SubprocessError, OSError, ValueError, RuntimeError) as err: logger.warning("Failed to inspect git manifest drift: %s", err) diff --git a/src/devops_cli/argo/rollouts.py b/src/devops_cli/argo/rollouts.py index 50fce77305..53b0295c65 100644 --- a/src/devops_cli/argo/rollouts.py +++ b/src/devops_cli/argo/rollouts.py @@ -85,9 +85,9 @@ def _fetch_metric_value(query: str) -> float | None: if not prom_url: return None - try: - import httpx2 + import httpx2 + try: validate_service_url(prom_url, "Prometheus", allow=settings.ai.allow_private_network) with httpx2.Client() as client: resp = client.get( @@ -100,7 +100,8 @@ def _fetch_metric_value(query: str) -> float | None: results = data.get("data", {}).get("result", []) if results and "value" in results[0]: return float(results[0]["value"][1]) - except Exception: + except (httpx2.HTTPError, ValueError, KeyError, IndexError, TypeError) as exc: + logger.debug("Failed to query Prometheus metric: %s", exc) return None return None diff --git a/src/devops_cli/commands/grafana.py b/src/devops_cli/commands/grafana.py index 997f354e07..be6e9b8a2f 100755 --- a/src/devops_cli/commands/grafana.py +++ b/src/devops_cli/commands/grafana.py @@ -120,6 +120,13 @@ def dashboards_export( ) raise typer.Exit(1) if output is not None: + try: + from devops_cli.core.paths import validate_no_path_traversal + + validate_no_path_traversal(output, label="Dashboard export output path") + except Exception: + print_error(ERRORS.grafana.invalid_output_path, prefix=False) + raise typer.Exit(1) resolved = output.resolve() if not resolved.is_relative_to(Path.cwd().resolve()): print_error(ERRORS.grafana.invalid_output_path, prefix=False) diff --git a/src/devops_cli/commands/mcp.py b/src/devops_cli/commands/mcp.py index 631ccbb0ca..4dfc2ac213 100644 --- a/src/devops_cli/commands/mcp.py +++ b/src/devops_cli/commands/mcp.py @@ -2,13 +2,12 @@ from __future__ import annotations -import importlib -import sys from pathlib import Path -from typing import Annotated, Any +from typing import Annotated import typer +from devops_cli.ai.mcp import list_mcp_tools, run_mcp_server from devops_cli.config.defaults import ( DEFAULT_MCP_HOST, DEFAULT_MCP_PORT, @@ -16,36 +15,7 @@ ) from devops_cli.core.cli import new_typer from devops_cli.lang import ERRORS, HELP, MESSAGES - -_LAZY_OBJECT_MAPPING: dict[str, tuple[str, str]] = { - "run_mcp_server": ("devops_cli.ai.mcp", "run_mcp_server"), - "list_mcp_tools": ("devops_cli.ai.mcp", "list_mcp_tools"), - "print_error": ("devops_cli.output", "print_error"), - "print_info": ("devops_cli.output", "print_info"), - "print_table": ("devops_cli.output", "print_table"), - "render_table": ("devops_cli.output", "render_table"), - "write_stderr": ("devops_cli.output", "write_stderr"), -} - - -def __getattr__(name: str) -> Any: - if name in _LAZY_OBJECT_MAPPING: - mod_path, obj_name = _LAZY_OBJECT_MAPPING[name] - module = importlib.import_module(mod_path) - return getattr(module, obj_name) - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - - -def _get(name: str) -> Any: - mod_dict = sys.modules[__name__].__dict__ - if name in mod_dict: - return mod_dict[name] - if name in _LAZY_OBJECT_MAPPING: - mod_path, obj_name = _LAZY_OBJECT_MAPPING[name] - module = importlib.import_module(mod_path) - return getattr(module, obj_name) - return getattr(sys.modules[__name__], name) - +from devops_cli.output import print_error, print_info, print_table, render_table, write_stderr app = new_typer(name="mcp", help=HELP.mcp.app) @@ -86,32 +56,32 @@ def serve_cmd( ) -> None: """Launch FastMCP server to expose devops-cli tools to MCP clients.""" if transport not in {"stdio", "sse"}: - _get("print_error")(ERRORS.mcp.invalid_transport.format(transport=transport)) + print_error(ERRORS.mcp.invalid_transport.format(transport=transport)) raise typer.Exit(1) if transport == "sse": - _get("print_info")(MESSAGES.mcp.starting_sse.format(host=host, port=port)) + print_info(MESSAGES.mcp.starting_sse.format(host=host, port=port)) else: # For stdio, stdout must carry ONLY MCP JSON-RPC. Write status to stderr. - _get("write_stderr")(MESSAGES.mcp.starting_stdio) + write_stderr(MESSAGES.mcp.starting_stdio) try: - _get("run_mcp_server")(transport=transport, host=host, port=port, allow_remote=allow_remote) + run_mcp_server(transport=transport, host=host, port=port, allow_remote=allow_remote) except ValueError as exc: - _get("print_error")(str(exc)) + print_error(str(exc)) raise typer.Exit(1) @app.command("tools", help=HELP.mcp.tools) def tools_cmd() -> None: """List all registered FastMCP tools and descriptions.""" - tools = _get("list_mcp_tools")() - table = _get("render_table")( + tools = list_mcp_tools() + table = render_table( title=MESSAGES.mcp.table_title_tools, columns=[(MESSAGES.mcp.col_tool_name, "cyan"), (MESSAGES.mcp.col_description, "white")], rows=[[t["name"], t["description"]] for t in tools], ) - _get("print_table")(table) + print_table(table) @app.command("export-schemas", help=HELP.mcp.export_schemas) @@ -153,6 +123,6 @@ def export_schemas_cmd( instructions_file.write_text(instructions_text, encoding="utf-8") if instructions_text: - _get("print_info")(f"✓ Exported {count} tool schema(s) and instructions to {output_dir}") + print_info(f"✓ Exported {count} tool schema(s) and instructions to {output_dir}") else: - _get("print_info")(f"✓ Exported {count} tool schema(s) to {output_dir}") + print_info(f"✓ Exported {count} tool schema(s) to {output_dir}") diff --git a/src/devops_cli/commands/repos.py b/src/devops_cli/commands/repos.py index 058542150f..ef7685ea2e 100755 --- a/src/devops_cli/commands/repos.py +++ b/src/devops_cli/commands/repos.py @@ -2,16 +2,17 @@ from __future__ import annotations -import importlib import subprocess -import sys -import threading from pathlib import Path -from typing import TYPE_CHECKING, Annotated, Any, cast +from typing import TYPE_CHECKING, Annotated + +if TYPE_CHECKING: + from devops_cli.github.client import GitHubClient from urllib.parse import urlsplit import typer +from devops_cli.commands.workspace import sync_from_repos from devops_cli.config.constants import ( CONST_GITHUB_HOST, CONST_GITHUB_REPO_SUFFIX, @@ -19,56 +20,23 @@ CONST_VSCODE_CLI, CONST_VSCODE_WORKSPACE_FILE, ) +from devops_cli.config.settings import Settings, get_github_token, load_settings from devops_cli.core.cli import new_typer, repo_label +from devops_cli.core.paths import validate_no_path_traversal +from devops_cli.core.process import run_subprocess from devops_cli.dry_run import is_dry_run +from devops_cli.git.operations import clone_repo, fetch_all, iter_workspace_repos, pull_tracking from devops_cli.lang import HELP, MESSAGES - -if TYPE_CHECKING: - from devops_cli.config.settings import Settings - from devops_cli.github.client import GitHubClient - -_LAZY_OBJECT_MAPPING: dict[str, tuple[str, str]] = { - "sync_from_repos": ("devops_cli.commands.workspace", "sync_from_repos"), - "Settings": ("devops_cli.config.settings", "Settings"), - "get_github_token": ("devops_cli.config.settings", "get_github_token"), - "load_settings": ("devops_cli.config.settings", "load_settings"), - "run_subprocess": ("devops_cli.core.process", "run_subprocess"), - "clone_repo": ("devops_cli.git.operations", "clone_repo"), - "fetch_all": ("devops_cli.git.operations", "fetch_all"), - "iter_workspace_repos": ("devops_cli.git.operations", "iter_workspace_repos"), - "pull_tracking": ("devops_cli.git.operations", "pull_tracking"), - "GitHubClient": ("devops_cli.github.client", "GitHubClient"), - "print_error": ("devops_cli.output", "print_error"), - "print_info": ("devops_cli.output", "print_info"), - "print_success": ("devops_cli.output", "print_success"), - "print_table": ("devops_cli.output", "print_table"), - "print_warning": ("devops_cli.output", "print_warning"), - "render_dry_run_result": ("devops_cli.output", "render_dry_run_result"), - "track_progress": ("devops_cli.output", "track_progress"), - "mask_secrets": ("devops_cli.security.sanitizer", "mask_secrets"), -} - -_IMPORT_LOCK = threading.Lock() - - -def __getattr__(name: str) -> Any: - if name in _LAZY_OBJECT_MAPPING: - mod_path, obj_name = _LAZY_OBJECT_MAPPING[name] - module = importlib.import_module(mod_path) - return getattr(module, obj_name) - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - - -def _get(name: str) -> Any: - """Retrieve module-level attribute with lazy resolution and mock transparency.""" - if name in sys.modules[__name__].__dict__: - return sys.modules[__name__].__dict__[name] - if name in _LAZY_OBJECT_MAPPING: - mod_path, obj_name = _LAZY_OBJECT_MAPPING[name] - module = importlib.import_module(mod_path) - return getattr(module, obj_name) - return getattr(sys.modules[__name__], name) - +from devops_cli.output import ( + print_error, + print_info, + print_success, + print_table, + print_warning, + render_dry_run_result, + track_progress, +) +from devops_cli.security.sanitizer import mask_secrets app = new_typer(help=HELP.repos.app, no_args_is_help=True) @@ -83,15 +51,16 @@ def _github_https_url(full_name: str) -> str: def _require_client(settings: Settings) -> GitHubClient: - token = _get("get_github_token")(settings) + token = get_github_token(settings) if not token: - _get("print_error")( + print_error( "GitHub token not configured. Run 'devops config init' or set DEVOPS_CLI_GITHUB_TOKEN.", prefix=False, ) raise typer.Exit(1) - client_cls = _get("GitHubClient") - return cast("GitHubClient", client_cls(token)) + from devops_cli.github.client import GitHubClient + + return GitHubClient(token) def _current_branch(repo_dir: Path) -> str: @@ -116,7 +85,7 @@ def _reload_workspace(workspace_file: Path) -> None: from devops_cli.config.defaults import DEFAULT_SUBPROCESS_TIMEOUT_SECONDS try: - _get("run_subprocess")( + run_subprocess( [CONST_VSCODE_CLI, "--reuse-window", "--", str(workspace_file)], check=False, timeout=DEFAULT_SUBPROCESS_TIMEOUT_SECONDS, @@ -124,11 +93,11 @@ def _reload_workspace(workspace_file: Path) -> None: except OSError, subprocess.SubprocessError: from devops_cli.lang import MESSAGES - _get("print_warning")(MESSAGES.messages.vscode_cli_unavailable, prefix=False) + print_warning(MESSAGES.messages.vscode_cli_unavailable, prefix=False) def _sync_and_reload_workspace(root: Path, ws_file: Path) -> None: - _get("sync_from_repos")(root, ws_file) + sync_from_repos(root, ws_file) _reload_workspace(ws_file) @@ -151,7 +120,7 @@ def clone_org( ) -> None: """Clone all repos from a GitHub org into `repos//.`.""" if is_dry_run(): - _get("render_dry_run_result")( + render_dry_run_result( command="devops repos clone-org", target=org, action="clone_org_repositories", @@ -159,10 +128,10 @@ def clone_org( ) return - settings = _get("load_settings")() + settings = load_settings() org_name = org or settings.github.default_org if not org_name: - _get("print_error")(MESSAGES.repos.no_org_configured, prefix=False) + print_error(MESSAGES.repos.no_org_configured, prefix=False) raise typer.Exit(1) root = (base_dir or settings.repos.base_dir).resolve() @@ -177,22 +146,27 @@ def clone_org( org_dir = root / org_name org_dir.mkdir(parents=True, exist_ok=True) - _get("print_info")( + print_info( MESSAGES.repos.cloning_org_repos.format(count=len(repos), dest=org_dir), prefix=False ) - for repo in _get("track_progress")(repos, description="Cloning..."): + for repo in track_progress(repos, description="Cloning..."): + try: + validate_no_path_traversal(repo.name, label="Repository name") + except Exception: + print_error(f"skip {repo.name} (path traversal detected)") + continue dest = (org_dir / repo.name).resolve() if not dest.is_relative_to(org_dir.resolve()): - _get("print_error")(f"skip {repo.name} (path traversal detected)") + print_error(f"skip {repo.name} (path traversal detected)") continue if dest.exists(): - _get("print_warning")(f"skip {repo.name} (already exists)") + print_warning(f"skip {repo.name} (already exists)") continue try: - _get("clone_repo")(_github_https_url(repo.full_name), dest) - _get("print_success")(f"done {repo.name}") + clone_repo(_github_https_url(repo.full_name), dest) + print_success(f"done {repo.name}") except (OSError, subprocess.SubprocessError, Exception) as exc: - _get("print_error")(f"fail {repo.name}: {_get('mask_secrets')(str(exc))}") + print_error(f"fail {repo.name}: {mask_secrets(str(exc))}") _sync_and_reload_workspace(root, settings.workspace.file) @@ -242,19 +216,19 @@ def clone( ) -> None: """Clone an individual repository into `repos///.` (or `repos/_standalone//.`).""" if url.startswith("-"): - _get("print_error")(MESSAGES.repos.invalid_url_hyphen, prefix=False) + print_error(MESSAGES.repos.invalid_url_hyphen, prefix=False) raise typer.Exit(1) if is_dry_run(): - _get("render_dry_run_result")( + render_dry_run_result( command="devops repos clone", - target=_get("mask_secrets")(url), + target=mask_secrets(url), action="clone_single_repository", - details={"url": _get("mask_secrets")(url)}, + details={"url": mask_secrets(url)}, ) return - settings = _get("load_settings")() + settings = load_settings() root = (base_dir or settings.repos.base_dir).resolve() org_name, raw_name = _parse_clone_destination(url) dest_dir = root / org_name @@ -266,18 +240,18 @@ def clone( or org_name in (".", "..") or raw_name in (".", "..") ): - _get("print_error")(MESSAGES.repos.invalid_dest_path, prefix=False) + print_error(MESSAGES.repos.invalid_dest_path, prefix=False) raise typer.Exit(1) if dest.exists(): - _get("print_warning")(MESSAGES.repos.already_exists.format(dest=dest), prefix=False) + print_warning(MESSAGES.repos.already_exists.format(dest=dest), prefix=False) raise typer.Exit(1) - masked_url = _get("mask_secrets")(url) - _get("print_info")(MESSAGES.repos.cloning_repo.format(url=masked_url, dest=dest), prefix=False) - _get("clone_repo")(url, dest) + masked_url = mask_secrets(url) + print_info(MESSAGES.repos.cloning_repo.format(url=masked_url, dest=dest), prefix=False) + clone_repo(url, dest) _sync_and_reload_workspace(root, settings.workspace.file) - _get("print_success")(MESSAGES.repos.done, prefix=False) + print_success(MESSAGES.repos.done, prefix=False) # ============================================================================= @@ -291,26 +265,26 @@ def list_repos( ) -> None: """List all cloned repositories.""" if is_dry_run(): - _get("render_dry_run_result")( + render_dry_run_result( command="devops repos list", action="list_cloned_repositories", details={}, ) return - settings = _get("load_settings")() + settings = load_settings() root = base_dir or settings.repos.base_dir if not root.exists(): - _get("print_warning")(MESSAGES.repos.repos_dir_not_found.format(root=root), prefix=False) + print_warning(MESSAGES.repos.repos_dir_not_found.format(root=root), prefix=False) raise typer.Exit(0) rows = [ [repo_dir.parent.name, repo_dir.name, _current_branch(repo_dir)] - for repo_dir in _get("iter_workspace_repos")(root) + for repo_dir in iter_workspace_repos(root) ] - _get("print_table")( + print_table( title=MESSAGES.repos.table_title_cloned.format(root=root), columns=[("Org / Group", "cyan"), "Repository", ("Branch", "green")], rows=rows, @@ -331,29 +305,29 @@ def update( ) -> None: """Fetch (and optionally pull) all tracking branches across repos.""" if dry_run or is_dry_run(): - _get("render_dry_run_result")( + render_dry_run_result( command="devops repos sync", action="sync_workspace_repositories", details={"pull": pull}, ) return - settings = _get("load_settings")() + settings = load_settings() root = (base_dir or settings.repos.base_dir).resolve() - repos_list = list(_get("iter_workspace_repos")(root)) + repos_list = list(iter_workspace_repos(root)) if not repos_list: - _get("print_warning")(MESSAGES.repos.no_repos_found, prefix=False) + print_warning(MESSAGES.repos.no_repos_found, prefix=False) raise typer.Exit(0) - for repo_dir in _get("track_progress")(repos_list, description="Updating..."): + for repo_dir in track_progress(repos_list, description="Updating..."): label = repo_label(repo_dir) try: - _get("fetch_all")(repo_dir) + fetch_all(repo_dir) if pull: - _get("pull_tracking")(repo_dir) - _get("print_success")(f"{label}") + pull_tracking(repo_dir) + print_success(f"{label}") except (OSError, subprocess.SubprocessError, Exception) as exc: - _get("print_error")(f"{label}: {exc}") + print_error(f"{label}: {exc}") _sync_and_reload_workspace(root, settings.workspace.file) diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 0f50cb3674..535aab4f27 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -2203,6 +2203,7 @@ ("LC_ALL", "C.UTF-8"), ("TMPDIR", "/tmp"), # nosec B108 ("PYTHONDONTWRITEBYTECODE", "1"), + ("PYTHONWARNINGS", "ignore::SyntaxWarning"), ) CONST_HOST_SANDBOX_SYSTEM_SYMLINKS: tuple[str, ...] = ("/bin", "/lib", "/lib64", "/sbin") CONST_HOST_SANDBOX_SYSTEM_DIRS: tuple[str, ...] = ("/usr",) diff --git a/src/devops_cli/config/defaults.py b/src/devops_cli/config/defaults.py index 9f2a2921e1..4b91b40ef4 100644 --- a/src/devops_cli/config/defaults.py +++ b/src/devops_cli/config/defaults.py @@ -80,9 +80,9 @@ DEFAULT_AI_PREWARM_KEEP_ALIVE: str = "1h" DEFAULT_AI_EVICT_KEEP_ALIVE: int = 0 DEFAULT_AI_MAX_RETRIES: int = 4 -DEFAULT_REVIEW_RETRY_ATTEMPTS: int = 3 -DEFAULT_REVIEW_RETRY_MIN_BACKOFF: float = 1.5 -DEFAULT_REVIEW_RETRY_MAX_BACKOFF: float = 30.0 +DEFAULT_REVIEW_RETRY_ATTEMPTS: int = 6 +DEFAULT_REVIEW_RETRY_MIN_BACKOFF: float = 2.0 +DEFAULT_REVIEW_RETRY_MAX_BACKOFF: float = 60.0 DEFAULT_AI_GATEWAY_PROVIDER: str = "litellm" DEFAULT_AI_GATEWAY_URL: str = "http://localhost:4000/v1" DEFAULT_AI_GATEWAY_CLUSTER_URL: str = "http://llm-gateway.llm.svc.cluster.local:4000/v1" diff --git a/src/devops_cli/core/command_decorator.py b/src/devops_cli/core/command_decorator.py index 58d9c6a285..cc605b047d 100644 --- a/src/devops_cli/core/command_decorator.py +++ b/src/devops_cli/core/command_decorator.py @@ -86,7 +86,12 @@ def wrapper(*args: Any, **kwargs: Any) -> Any: span_h.set_attribute("cli.success", False) span_h.set_attribute("cli.exit_code", exc.exit_code) span_h.record_exception(exc) - _record_error_metrics(command_name, record_metrics, error_code=exc.error_code) + _record_error_metrics( + command_name, + record_metrics, + error_code=exc.error_code, + error_type=type(exc).__name__, + ) print_error(f"[{exc.error_code}] {exc.message}", prefix=True) raise typer.Exit(code=exc.exit_code) from exc diff --git a/src/devops_cli/http/broker.py b/src/devops_cli/http/broker.py index cb3b6a1ff4..994971c390 100644 --- a/src/devops_cli/http/broker.py +++ b/src/devops_cli/http/broker.py @@ -139,16 +139,18 @@ async def arequest( def close(self) -> None: """Close synchronous client connections.""" with self._lock: - if self._sync_client is not None and not self._sync_client.is_closed: - self._sync_client.close() - self._sync_client = None + client = self._sync_client + self._sync_client = None + if client is not None and not client.is_closed: + client.close() async def aclose(self) -> None: """Close asynchronous client connections.""" with self._lock: - if self._async_client is not None and not self._async_client.is_closed: - await self._async_client.aclose() - self._async_client = None + client = self._async_client + self._async_client = None + if client is not None and not client.is_closed: + await client.aclose() def __enter__(self) -> HttpClientBroker: return self diff --git a/src/devops_cli/http/pool.py b/src/devops_cli/http/pool.py index 88043685ca..f918b3ce17 100644 --- a/src/devops_cli/http/pool.py +++ b/src/devops_cli/http/pool.py @@ -118,10 +118,24 @@ def close_shared_clients() -> None: _ASYNC_CLIENTS.clear() +async def aclose_shared_clients() -> None: + """Close every shared async client asynchronously, releasing sockets cleanly.""" + with _LOCK: + clients = list(_ASYNC_CLIENTS.values()) + _ASYNC_CLIENTS.clear() + for client in clients: + try: + if not client.is_closed: + await client.aclose() + except Exception as exc: + logger.debug("Failed closing shared async HTTP client: %s", exc) + + atexit.register(close_shared_clients) __all__ = [ + "aclose_shared_clients", "close_shared_clients", "connection_limits", "get_shared_async_client", diff --git a/src/devops_cli/k8s/informer.py b/src/devops_cli/k8s/informer.py index 5c9bc6c7d4..6e2c13e728 100644 --- a/src/devops_cli/k8s/informer.py +++ b/src/devops_cli/k8s/informer.py @@ -27,6 +27,26 @@ logger = logging.getLogger(__name__) +def _extract_event_metadata(obj: Any, default_namespace: str) -> tuple[str, str, str]: + """Extract (name, namespace, status) from a Kubernetes object or dictionary.""" + if isinstance(obj, dict): + d_meta = obj.get("metadata") + d_status = obj.get("status") + name = str(d_meta.get("name") if isinstance(d_meta, dict) else "unknown") + namespace = str( + (d_meta.get("namespace") if isinstance(d_meta, dict) else None) or default_namespace + ) + status = str((d_status.get("phase") if isinstance(d_status, dict) else None) or "Active") + return name, namespace, status + + meta = getattr(obj, "metadata", None) + name = str(getattr(meta, "name", "unknown") or "unknown") + namespace = str(getattr(meta, "namespace", default_namespace) or default_namespace) + st = getattr(obj, "status", None) + status = str(getattr(st, "phase", "Active") or "Active") + return name, namespace, status + + class ResourceInformer: """Watch-based resource informer maintaining in-memory cache of cluster objects.""" @@ -152,9 +172,7 @@ def _normalize_event(self, raw: dict[str, Any]) -> K8sEvent: event_type = CONST_K8S_EVENT_MODIFIED obj = raw.get("object") - name = getattr(getattr(obj, "metadata", None), "name", "unknown") - namespace = getattr(getattr(obj, "metadata", None), "namespace", self.namespace) - status = getattr(getattr(obj, "status", None), "phase", "Active") + name, namespace, status = _extract_event_metadata(obj, self.namespace) timestamp = datetime.now(UTC).isoformat() self._last_event_time = timestamp diff --git a/src/devops_cli/k8s/security_stream.py b/src/devops_cli/k8s/security_stream.py index 06696d2cc8..b1ea65e3c1 100644 --- a/src/devops_cli/k8s/security_stream.py +++ b/src/devops_cli/k8s/security_stream.py @@ -262,10 +262,9 @@ def stream_security_events( return _build_stream_result(alerts, start_time, span, request.namespace) if proc.returncode != 0: - stderr_msg = proc.stderr.strip()[:256] - logger.debug("kubectl logs failed: %s", stderr_msg) + logger.debug("kubectl logs failed with exit code %s", proc.returncode) raise KubernetesLoggingError( - f"Failed to stream security events from Falco: {stderr_msg or 'kubectl logs returned non-zero exit code'}", + "Failed to stream security events from Falco: kubectl logs returned non-zero exit code", query=f"kubectl logs -n {request.namespace} -l {request.label_selector}", details={ "namespace": request.namespace, diff --git a/src/devops_cli/k8s/service.py b/src/devops_cli/k8s/service.py index 8924803c0a..28a7944b9c 100644 --- a/src/devops_cli/k8s/service.py +++ b/src/devops_cli/k8s/service.py @@ -162,9 +162,27 @@ def switch_context(self, name: str) -> None: ) data["current-context"] = name - temp_path = kubeconfig_path.with_suffix(".tmp") - temp_path.write_text(yaml.safe_dump(data, sort_keys=False), encoding="utf-8") - temp_path.replace(kubeconfig_path) + import os + import tempfile + + parent_dir = kubeconfig_path.parent + dumped_yaml = yaml.safe_dump(data, sort_keys=False) + with tempfile.NamedTemporaryFile( + mode="w", + dir=parent_dir, + delete=False, + encoding="utf-8", + prefix=".kubeconfig-", + suffix=".tmp", + ) as tf: + os.chmod(tf.name, 0o600) + tf.write(dumped_yaml) + temp_file_path = Path(tf.name) + try: + temp_file_path.replace(kubeconfig_path) + except Exception: + temp_file_path.unlink(missing_ok=True) + raise self.reset_instance() self.load_config(context=name) diff --git a/src/devops_cli/models/argo.py b/src/devops_cli/models/argo.py index ef8598cda5..0c277c1db4 100644 --- a/src/devops_cli/models/argo.py +++ b/src/devops_cli/models/argo.py @@ -189,13 +189,19 @@ def from_manifest(cls, manifest: dict[str, Any]) -> ArgoRolloutState: steps = canary.get("steps") active_strategy = "canary" if canary else ("blueGreen" if strategy else "") + step_idx = status.get("currentStepIndex") + try: + parsed_step = int(step_idx) if step_idx is not None else None + except ValueError, TypeError: + parsed_step = None + return cls( name=str(meta.get("name", "")), namespace=str(meta.get("namespace", "")), phase=str(status.get("phase", "Unknown")), message=str(status.get("message", "")), strategy=active_strategy, - current_step=status.get("currentStepIndex"), + current_step=parsed_step, total_steps=len(steps) if isinstance(steps, list) else 0, desired_replicas=int(spec.get("replicas", 0) or 0), ready_replicas=int(status.get("readyReplicas", 0) or 0), diff --git a/src/devops_cli/security/aibom.py b/src/devops_cli/security/aibom.py index 039018a807..bac07cc31c 100644 --- a/src/devops_cli/security/aibom.py +++ b/src/devops_cli/security/aibom.py @@ -8,6 +8,7 @@ import logging import re import uuid +import warnings from datetime import UTC, datetime from enum import StrEnum from pathlib import Path @@ -147,7 +148,9 @@ def detect_trust_remote_code(target_dir: Path) -> bool: resolved_py = py_file.resolve() if not resolved_py.is_relative_to(resolved_target): continue - tree = ast.parse(resolved_py.read_text(encoding="utf-8")) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SyntaxWarning) + tree = ast.parse(resolved_py.read_text(encoding="utf-8")) for node in ast.walk(tree): if isinstance(node, ast.keyword) and node.arg == "trust_remote_code": if isinstance(node.value, ast.Constant) and bool(node.value.value): diff --git a/src/devops_cli/security/reference_extractor.py b/src/devops_cli/security/reference_extractor.py index 5e4c3a96c0..5d09379663 100644 --- a/src/devops_cli/security/reference_extractor.py +++ b/src/devops_cli/security/reference_extractor.py @@ -20,6 +20,7 @@ import tokenize import tomllib import urllib.parse +import warnings from pathlib import Path from typing import Any @@ -781,7 +782,9 @@ def _extract_python_literals_and_comments(source: str) -> list[tuple[str, int]]: parsed_ast = False try: - tree = ast.parse(source) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SyntaxWarning) + tree = ast.parse(source) parsed_ast = True visitor = PythonSymbolVisitor() visitor.visit(tree) diff --git a/src/devops_cli/telemetry/memory_profiler.py b/src/devops_cli/telemetry/memory_profiler.py index cdad4096e7..392fd43ebe 100644 --- a/src/devops_cli/telemetry/memory_profiler.py +++ b/src/devops_cli/telemetry/memory_profiler.py @@ -12,6 +12,7 @@ import importlib import inspect import os +import re import socket import time import tracemalloc @@ -260,15 +261,16 @@ async def _dummy_app(scope: Any, receive: Any, send: Any) -> None: await send({"type": "http.response.body", "body": b"OK"}) broker = HttpClientBroker(allow_private_networks=True) - client = await broker.get_async_client() - client._transport = httpx.ASGITransport(app=cast(Any, _dummy_app)) - - for _ in range(iterations): - resp = await broker.arequest("GET", "http://localhost:8080/health") - _ = resp.status_code + try: + client = await broker.get_async_client() + client._transport = httpx.ASGITransport(app=cast(Any, _dummy_app)) - await broker.aclose() - broker.close() + for _ in range(iterations): + resp = await broker.arequest("GET", "http://localhost:8080/health") + _ = resp.status_code + finally: + await broker.aclose() + broker.close() def profile_http_pool_workload( @@ -338,6 +340,12 @@ def run_memory_profiler( if ":" in target: mod_name, func_name = target.split(":", 1) + if not ( + re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*$", mod_name) + and re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*$", func_name) + ): + msg = f"Invalid target identifier '{target}': must be valid python module and function name" + raise MemoryProfilerError(msg, details={"target": target}) try: mod = importlib.import_module(mod_name) fn = getattr(mod, func_name) diff --git a/src/devops_cli/watchers/live_resource.py b/src/devops_cli/watchers/live_resource.py index 1245a9c0c8..6dbbd9d904 100644 --- a/src/devops_cli/watchers/live_resource.py +++ b/src/devops_cli/watchers/live_resource.py @@ -60,7 +60,7 @@ def watch(self, *, max_iterations: int | None = None) -> None: with Live( self.render_fn(), console=self.console, - refresh_per_second=max(1, int(1.0 / self.interval_seconds)), + refresh_per_second=min(30, max(1, int(1.0 / max(0.01, self.interval_seconds)))), auto_refresh=False, ) as live: iterations = self._run_loop(live, max_iterations) diff --git a/tests/test_argo.py b/tests/test_argo.py index abd05f0e3c..606cb9ab82 100644 --- a/tests/test_argo.py +++ b/tests/test_argo.py @@ -335,3 +335,21 @@ def fake_get(self: object, url: str, **kwargs: object) -> httpx2.Response: res_status = runner.invoke(argo_app, ["cd", "apps", "status", "sample-app"]) assert res_status.exit_code == 0 assert "sample-app" in res_status.output + + +def test_argo_rollout_state_from_manifest_safe_step() -> None: + """Verify ArgoRolloutState.from_manifest safely coerces and parses currentStepIndex.""" + from devops_cli.models.argo import ArgoRolloutState + + manifest = { + "metadata": {"name": "rollout-a", "namespace": "default"}, + "spec": {"replicas": 3, "strategy": {"canary": {"steps": [{"setWeight": 20}]}}}, + "status": {"currentStepIndex": "0", "phase": "Healthy"}, + } + state = ArgoRolloutState.from_manifest(manifest) + assert (state.name, state.current_step, state.total_steps) == ("rollout-a", 0, 1) + + # Invalid non-integer step index falls back to None + manifest["status"]["currentStepIndex"] = "invalid" + state_invalid = ArgoRolloutState.from_manifest(manifest) + assert (state_invalid.current_step,) == (None,) diff --git a/tests/test_command_decorator.py b/tests/test_command_decorator.py index db644a0c60..883c9ce0ee 100644 --- a/tests/test_command_decorator.py +++ b/tests/test_command_decorator.py @@ -59,3 +59,24 @@ def no_metrics_command() -> str: return "ok" assert no_metrics_command() == "ok" + + +def test_cli_command_handler_records_error_type_for_devops_cli_error() -> None: + """Decorator should pass error_type to _record_error_metrics when catching DevOpsCLIError.""" + from unittest.mock import patch + + with patch("devops_cli.core.command_decorator._record_error_metrics") as mock_record: + + @cli_command_handler("metric_err_cmd", record_metrics=True) + def failing_command() -> None: + raise DevOpsCLIError("Domain failure", error_code="ERR_TEST", exit_code=1) + + with pytest.raises(typer.Exit): + failing_command() + + mock_record.assert_called_once_with( + "metric_err_cmd", + True, + error_code="ERR_TEST", + error_type="DevOpsCLIError", + ) diff --git a/tests/test_common_hallucinations.py b/tests/test_common_hallucinations.py index e214070200..893f957011 100644 --- a/tests/test_common_hallucinations.py +++ b/tests/test_common_hallucinations.py @@ -25,17 +25,25 @@ def test_builtin_catalog_contains_pep758_and_essential_entries() -> None: entries = load_common_hallucinations(include_builtin=True) ids = {e.id for e in entries} - assert "HALLUCINATION-PEP758-EXCEPT" in ids - assert "HALLUCINATION-MASKED-SECRET" in ids - assert "HALLUCINATION-TEST-MOCK-CRED" in ids - assert "HALLUCINATION-HTTPX2-DEPENDENCY" in ids - assert "HALLUCINATION-PYDANTIC-MUTABLE-DEFAULT" in ids - assert "HALLUCINATION-DOC-ANTI-PATTERN" in ids + expected_ids = { + "HALLUCINATION-PEP758-EXCEPT", + "HALLUCINATION-MASKED-SECRET", + "HALLUCINATION-TEST-MOCK-CRED", + "HALLUCINATION-HTTPX2-DEPENDENCY", + "HALLUCINATION-PYDANTIC-MUTABLE-DEFAULT", + "HALLUCINATION-DOC-ANTI-PATTERN", + "HALLUCINATION-GRAPHQL-JSON-DUMPS", + "HALLUCINATION-EXAMPLE-COM-WEBHOOK", + "HALLUCINATION-PROMETHEUS-TELEMETRY-METRIC", + } + assert (expected_ids.issubset(ids),) == (True,) pep758 = next(e for e in entries if e.id == "HALLUCINATION-PEP758-EXCEPT") - assert pep758.category == HallucinationCategory.SYNTAX_GRAMMAR - assert "PEP 758" in pep758.resolution - assert any("except" in kw for kw in pep758.pattern_keywords) + assert ( + pep758.category, + "PEP 758" in pep758.resolution, + any("except" in kw for kw in pep758.pattern_keywords), + ) == (HallucinationCategory.SYNTAX_GRAMMAR, True, True) def test_save_and_load_common_hallucinations(tmp_path: Path) -> None: diff --git a/tests/test_http_connection_pool.py b/tests/test_http_connection_pool.py index 86d60315c8..e0b0d35c3b 100644 --- a/tests/test_http_connection_pool.py +++ b/tests/test_http_connection_pool.py @@ -336,3 +336,41 @@ def test_an_edited_configuration_changes_the_context() -> None: after = context_module.configured_context() context_module.reset_context_cache() assert (before, after) == ("homelab-k3s", "staging") + + +def test_http_client_broker_close_resets_client_references() -> None: + """Verify HttpClientBroker resets _sync_client and _async_client to None on close/aclose.""" + import asyncio + + from devops_cli.http.broker import HttpClientBroker + + broker = HttpClientBroker() + mock_sync = MagicMock(is_closed=False) + mock_async = MagicMock(is_closed=False) + mock_async.aclose = MagicMock(return_value=asyncio.sleep(0)) + + broker._sync_client = mock_sync + broker._async_client = mock_async + + broker.close() + assert (broker._sync_client, mock_sync.close.call_count) == (None, 1) + + asyncio.run(broker.aclose()) + assert (broker._async_client, mock_async.aclose.call_count) == (None, 1) + + +def test_aclose_shared_clients_releases_async_pool() -> None: + """Verify aclose_shared_clients awaits closing all active async clients.""" + import asyncio + + from devops_cli.http import pool + + mock_client = MagicMock(is_closed=False) + mock_client.aclose = MagicMock(return_value=asyncio.sleep(0)) + + with pool._LOCK: + pool._ASYNC_CLIENTS["test-key"] = mock_client + + asyncio.run(pool.aclose_shared_clients()) + + assert (len(pool._ASYNC_CLIENTS), mock_client.aclose.call_count) == (0, 1) diff --git a/tests/test_k8s_security_stream.py b/tests/test_k8s_security_stream.py index 9925537d7e..826de1626f 100644 --- a/tests/test_k8s_security_stream.py +++ b/tests/test_k8s_security_stream.py @@ -3,12 +3,14 @@ from __future__ import annotations import json +import logging from unittest.mock import MagicMock, patch import pytest from typer.testing import CliRunner from devops_cli.commands.k8s import app +from devops_cli.exceptions.k8s import KubernetesLoggingError from devops_cli.k8s.security_stream import ( generate_simulated_alerts, matches_severity_filter, @@ -153,18 +155,27 @@ def test_stream_security_events_live_kubectl(mock_run: MagicMock) -> None: @patch("devops_cli.k8s.security_stream.run_subprocess") -def test_stream_security_events_kubectl_failure(mock_run: MagicMock) -> None: - from devops_cli.exceptions.k8s import KubernetesLoggingError - +def test_stream_security_events_kubectl_failure( + mock_run: MagicMock, caplog: pytest.LogCaptureFixture +) -> None: mock_run.return_value = MagicMock( returncode=1, stdout="", - stderr="Error from server (NotFound): daemonsets.apps 'falco' not found", + stderr="Authorization: Bearer super-secret-token", ) req = SecurityStreamRequest(namespace="falco") - with pytest.raises(KubernetesLoggingError, match="Failed to stream security events from Falco"): - stream_security_events(req, dry_run=False) + with caplog.at_level(logging.DEBUG, logger="devops_cli.k8s.security_stream"): + with pytest.raises( + KubernetesLoggingError, + match="Failed to stream security events from Falco", + ) as exc_info: + stream_security_events(req, dry_run=False) + + assert ( + "super-secret-token" not in caplog.text, + "super-secret-token" not in str(exc_info.value), + ) == (True, True) @patch("devops_cli.k8s.security_stream.run_subprocess") diff --git a/tests/test_k8s_service.py b/tests/test_k8s_service.py index 80a6ca46c4..b2d528db97 100644 --- a/tests/test_k8s_service.py +++ b/tests/test_k8s_service.py @@ -105,7 +105,8 @@ def test_k8s_service_switch_context(tmp_path: Path) -> None: ): svc.switch_context("prod") updated_content = kubeconfig_file.read_text(encoding="utf-8") - assert ("current-context: prod" in updated_content,) == (True,) + mode = kubeconfig_file.stat().st_mode & 0o777 + assert ("current-context: prod" in updated_content, mode) == (True, 0o600) def test_k8s_service_switch_context_not_found(tmp_path: Path) -> None: @@ -202,6 +203,25 @@ def test_resource_informer_event_normalization() -> None: ) +def test_resource_informer_dict_normalization() -> None: + """Verify ResourceInformer normalizes raw dictionary event objects.""" + mock_svc = MagicMock() + informer = ResourceInformer(resource_kind="Pod", namespace="default", service=mock_svc) + raw_dict = { + "metadata": {"name": "dict-pod", "namespace": "custom-ns"}, + "status": {"phase": "Running"}, + } + raw_event = {"type": CONST_K8S_EVENT_ADDED, "object": raw_dict} + event = informer._normalize_event(raw_event) + + assert (event.event_type, event.name, event.namespace, event.status) == ( + CONST_K8S_EVENT_ADDED, + "dict-pod", + "custom-ns", + "Running", + ) + + def test_resource_informer_cache_lifecycle() -> None: """Verify ResourceInformer in-memory state updates on event stream.""" mock_svc = MagicMock() diff --git a/tests/test_library_vector_tier.py b/tests/test_library_vector_tier.py index 7e39572076..be8e583260 100644 --- a/tests/test_library_vector_tier.py +++ b/tests/test_library_vector_tier.py @@ -126,7 +126,7 @@ def test_ensure_collection_already_exists() -> None: store = LibraryVectorStore(qdrant_client=mock_qdrant, valkey_client=None) created = store.ensure_collection_exists() - assert created is False + assert created is True mock_qdrant.ensure_collection.assert_not_called() mock_qdrant.create_collection.assert_not_called() diff --git a/tests/test_repos.py b/tests/test_repos.py index 4e29d5e0ba..1bdba12bfa 100755 --- a/tests/test_repos.py +++ b/tests/test_repos.py @@ -168,6 +168,36 @@ def test_repos_clone_org_skips_archived_repos(tmp_path: Path) -> None: mock_reload.assert_called_once_with(settings.workspace.file) +def test_repos_clone_org_skips_path_traversal_repo(tmp_path: Path) -> None: + """Verify clone-org skips repositories with path traversal attempts.""" + bad_repo = MagicMock() + bad_repo.name = "../escape" + bad_repo.full_name = "example/escape" + bad_repo.archived = False + + with ( + patch("devops_cli.commands.repos.load_settings") as mock_load, + patch("devops_cli.commands.repos.get_github_token", return_value="token"), + patch("devops_cli.commands.repos.clone_repo") as mock_clone_repo, + patch("devops_cli.commands.repos.sync_from_repos"), + patch("devops_cli.commands.repos._reload_workspace"), + patch("devops_cli.github.client.GitHubClient") as mock_client_cls, + ): + settings = MagicMock() + settings.github.default_org = "example-org" + settings.repos.base_dir = tmp_path / "repos" + settings.workspace.file = tmp_path / ".code-workspace" + mock_load.return_value = settings + + mock_client = MagicMock() + mock_client.get_org_repos.return_value = [bad_repo] + mock_client_cls.return_value = mock_client + + result = runner.invoke(app, ["repos", "clone-org"]) + + assert (result.exit_code, mock_clone_repo.called) == (0, False) + + def test_repos_clone_passes_github_urls_to_clone_repo(tmp_path: Path) -> None: with ( patch("devops_cli.commands.repos.load_settings") as mock_load,