From 7ea9a575d80ea13d40466ab3148f7b8ead5d53ca Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 24 Oct 2026 00:12:49 +0000 Subject: [PATCH] fix(telemetry): the command span holds no argument value, so a secret given to devops config set never reaches the trace backend The command span of `_delegate` put every argument in `cli.args`, with no mask. The tracer resource put `sys.argv` in `process.command_line`, through a secret pattern that keeps a credential for 5 of the 13 secret keys. Both went to the trace backend. The command span now keeps `cli.command` and `cli.args_count`, and has no `cli.args`. The resource has no `process.command_line`. The OpenTelemetry semantic conventions give `process.command_args` and `process.command_line` as Opt-In for this reason. The span of the command that runs holds Click's command path (`cli.command_path`, such as `devops config set`), which holds no argument. Task file: `docs/agent/tasks/task-1996-command-span-holds-no-argument-value.md` --- ARCHITECTURE.md | 2 +- docs/TELEMETRY.md | 1 + ...96-command-span-holds-no-argument-value.md | 24 +++++++ src/devops_cli/core/cli.py | 14 +++- src/devops_cli/docs/generator.py | 8 +++ src/devops_cli/main.py | 5 +- src/devops_cli/telemetry/tracer.py | 11 ++-- tests/test_otel_command_coverage.py | 66 +++++++++++++++++++ 8 files changed, 119 insertions(+), 12 deletions(-) create mode 100644 docs/agent/tasks/task-1996-command-span-holds-no-argument-value.md diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index ac80dff15d..857c94b8da 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -162,7 +162,7 @@ To ensure complete stylistic cohesion, maintainability, and zero boilerplate pro ### 1. Declarative CLI Command Dispatch & OpenTelemetry Instrumentation Every command is registered on a `new_typer()` app (`OTelTyper`, `devops_cli/core/cli.py`), which wraps it in a `cli.` OpenTelemetry span: - Each command handles `--dry-run` itself via `is_dry_run()` / `render_dry_run_result()`. -- Automatic OpenTelemetry span wrapping with standardized span attributes (`domain`, `operation`, `arguments`). +- Automatic OpenTelemetry span wrapping with standardized span attributes: the command, its command path and the number of arguments, never an argument value ([docs/TELEMETRY.md](docs/TELEMETRY.md)). - Centralized domain exception interception with formatted Rich diagnostics output. - Commands that offer machine-readable output declare their own `--format` (table/json/yaml via `devops_cli.output.serialization.emit_serialized`) or `--json` flag. There is no global `--format` option. diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index b55eb16d22..8570c6e23e 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -57,6 +57,7 @@ eviction window in `k8s/otel/values.yaml` are tracked separately under #1132. ## Distributed Tracing & W3C Context Propagation - **Root Trace Context**: CLI delegate sets up root spans (`cli.`) with execution metadata. +- **No Argument Values**: The command spans describe the command line with the command (`cli.command`), its command path (`cli.command_path`, such as `devops config set`), the number of arguments (`cli.args_count`) and the names of the parameters (`cli.kwargs_keys`). They do not record the argument values. An argument can be a credential (`devops config set `), and a secret pattern does not find all credentials. For this reason, the resource also has no `process.command_line` and no `process.command_args`. The OpenTelemetry semantic conventions make these two attributes Opt-In. - **W3C `traceparent` Injection**: Subprocesses, sandbox containers (`devops sandbox deploy`, `devops docker sandbox`, `devops test sandbox`) and commands run with `devops sandbox exec` receive the active span as `TRACEPARENT` in their environment (and `TRACESTATE` when one is set). A container's parent is its `sandbox.deploy` or `docker.workload_sandbox.run` span, and each exec's is its own `sandbox.exec` span. With telemetry disabled, nothing is added. - **OTLP Exporter**: Spans and metrics go to the OpenTelemetry Collector at `telemetry.endpoint` (`DEVOPS_CLI_TELEMETRY_ENDPOINT`). When devops-cli's configuration names none, OpenTelemetry's own `OTEL_EXPORTER_OTLP_ENDPOINT` names it, else `http://localhost:4318`. `telemetry.enabled` (`DEVOPS_CLI_TELEMETRY_ENABLED`) turns export off. When the configuration cannot load, those two variables alone decide, and export stays off unless `DEVOPS_CLI_TELEMETRY_ENABLED` turns it on. diff --git a/docs/agent/tasks/task-1996-command-span-holds-no-argument-value.md b/docs/agent/tasks/task-1996-command-span-holds-no-argument-value.md new file mode 100644 index 0000000000..90dc5ce00c --- /dev/null +++ b/docs/agent/tasks/task-1996-command-span-holds-no-argument-value.md @@ -0,0 +1,24 @@ +# Task: The Command Span Holds No Argument Value (#1996) + +**Issue**: [#1996](https://github.com/dan-petty/devops-cli/issues/1996) +**Scope**: `type/security`, `scope/telemetry` +**Feasibility**: Verified against the code, the live trace backend and the upstream conventions. `_delegate` in `src/devops_cli/main.py` put `" ".join(effective_args)` in the span attribute `cli.args`, with no mask. `OTelTelemetryClient` in `src/devops_cli/telemetry/tracer.py` put `mask_secrets(" ".join(sys.argv))` in the resource attribute `process.command_line` of every trace payload. The Tempo data source lists `cli.args` as a span attribute and `process.command_line` as a resource attribute, so both reach the backend. `mask_secrets` finds secrets by pattern: for `devops config set correct-horse-battery-staple`, it keeps the value for 5 of the 13 secret keys (`cloudflare.api_token`, `cloudflare.tunnel_token`, `runs.index_password`, `service.webhook_secrets`, `telemetry.logfire_token`). The OpenTelemetry semantic conventions give `process.command_args` and `process.command_line` as Opt-In, and say that a producer "SHOULD NOT" collect them by default "unless there is sanitization that excludes sensitive data". No dashboard, alert or query under `k8s/monitoring/` reads `cli.args` or `process.command_line`. + +## Description + +A command span recorded each argument, so a credential given to `devops config set` went to the trace backend. The command span of `_delegate` now holds the command and the number of arguments (`cli.args_count`), and no argument. The resource holds no `process.command_line`. The span of the command that runs (`_execute_traced_cli_command` in `src/devops_cli/core/cli.py`) now holds Click's command path (`cli.command_path`, such as `devops config set`), which holds the command names and no argument. Thus the trace still names the command that ran. + +## Acceptance Criteria + +- [x] A test runs `set ` through `_delegate` with telemetry export captured, and no exported span attribute, event or resource attribute holds the credential (`test_no_exported_attribute_holds_an_argument_value` in `tests/test_otel_command_coverage.py`). The test fails on `origin/main`, and it fails with only the `cli.args` change, because the resource also held the credential. +- [x] The spans keep the command, the number of arguments and the command path (`test_the_command_spans_keep_the_command_path_and_the_argument_count`). +- [x] No dashboard query under `k8s/monitoring/` reads `cli.args`. No change was necessary. + +## Deliverables + +- [x] `src/devops_cli/main.py`: the command span has no `cli.args`. +- [x] `src/devops_cli/telemetry/tracer.py`: the resource has no `process.command_line`. +- [x] `src/devops_cli/core/cli.py`: the span of the command that runs holds `cli.command_path`. +- [x] `docs/TELEMETRY.md` (from `src/devops_cli/docs/generator.py`) and `ARCHITECTURE.md` say which attributes describe the command line, and that no attribute holds an argument value. +- The message of a usage error can quote an argument (Click's "Got unexpected extra argument ()"), and the tracer records it in `error.message`. `except click.ClickException` in `_delegate` does not catch the errors Typer 0.27 raises, because Typer has its own copy of Click, so a usage error also counts no `devops_cli_command_total` with status `error`. Moved to #2024. +- A subprocess span holds the first eight arguments of the command it runs (`subprocess.cmd` and `process.command_line`, through a secret pattern). A command that passes the arguments of a person to a program, such as `devops uv run` or `devops gh api`, puts them there. Moved to #2025. diff --git a/src/devops_cli/core/cli.py b/src/devops_cli/core/cli.py index 8220f56e04..415f180ee4 100644 --- a/src/devops_cli/core/cli.py +++ b/src/devops_cli/core/cli.py @@ -79,7 +79,14 @@ def _execute_traced_cli_command( f_kwargs: dict[str, Any], cmd_name: str, ) -> Any: - """Execute CLI subcommand wrapped in OpenTelemetry span with telemetry recording.""" + """Execute CLI subcommand wrapped in OpenTelemetry span with telemetry recording. + + The span names the parameters and holds no parameter value, as the command span of + `main._delegate` does (#1996). Click's command path, such as `devops config set`, names the + command that runs: it holds the command names and no argument. + """ + from typer._click.globals import get_current_context + from devops_cli.telemetry import trace_span span_name = f"cli.{cmd_name}" @@ -87,13 +94,16 @@ def _execute_traced_cli_command( kwargs_summary = ", ".join(f_kwargs.keys()) if f_kwargs else "" func_name = getattr(f, "__qualname__", getattr(f, "__name__", str(f))) module_name = getattr(f, "__module__", "") - attrs = { + attrs: dict[str, Any] = { "cli.command": cmd_name, "code.function": func_name, "code.namespace": module_name, "cli.args_count": len(f_args), "cli.kwargs_keys": kwargs_summary, } + context = get_current_context(silent=True) + if context is not None: + attrs["cli.command_path"] = context.command_path with trace_span(span_name, attributes=attrs) as span_h: span_h.add_event("subcommand_started", {"command": cmd_name}) try: diff --git a/src/devops_cli/docs/generator.py b/src/devops_cli/docs/generator.py index 110ad32cc2..2ccb2e55ec 100644 --- a/src/devops_cli/docs/generator.py +++ b/src/devops_cli/docs/generator.py @@ -1094,6 +1094,14 @@ def generate_telemetry_docs(self) -> str: "## Distributed Tracing & W3C Context Propagation", "", "- **Root Trace Context**: CLI delegate sets up root spans (`cli.`) with execution metadata.", + "- **No Argument Values**: The command spans describe the command line with the " + "command (`cli.command`), its command path (`cli.command_path`, such as `devops config " + "set`), the number of arguments (`cli.args_count`) and the names of the parameters " + "(`cli.kwargs_keys`). They do not record the argument values. An argument can be a " + "credential (`devops config set `), and a secret pattern does not find " + "all credentials. For this reason, the resource also has no `process.command_line` " + "and no `process.command_args`. The OpenTelemetry semantic conventions make these two " + "attributes Opt-In.", "- **W3C `traceparent` Injection**: Subprocesses, sandbox containers (`devops sandbox " "deploy`, `devops docker sandbox`, `devops test sandbox`) and commands run with " "`devops sandbox exec` receive the active span as `TRACEPARENT` in their environment " diff --git a/src/devops_cli/main.py b/src/devops_cli/main.py index beecb9c6ce..a4dee2f4cd 100644 --- a/src/devops_cli/main.py +++ b/src/devops_cli/main.py @@ -133,8 +133,10 @@ def _delegate(module_path: str, command_name: str, args: list[str]) -> None: if _runs_a_review(command_name, args) else contextlib.nullcontext() ) - args_summary = " ".join(effective_args) if effective_args else "" start_time = time.perf_counter() + # The span holds the number of arguments and no argument value: an argument can be a + # credential (`devops config set `), and the span goes to the trace backend. + # OpenTelemetry gives `process.command_args` as Opt-In for this reason (#1996). with ( rule, trace_span( @@ -143,7 +145,6 @@ def _delegate(module_path: str, command_name: str, args: list[str]) -> None: "cli.command": command_name, "code.function": command_name, "code.namespace": module_path, - "cli.args": args_summary, "cli.args_count": len(effective_args), "cli.module": module_path, "cli.version": __version__, diff --git a/src/devops_cli/telemetry/tracer.py b/src/devops_cli/telemetry/tracer.py index d11e441365..ff60a9850a 100644 --- a/src/devops_cli/telemetry/tracer.py +++ b/src/devops_cli/telemetry/tracer.py @@ -882,13 +882,10 @@ def __init__( self._cached_resource_attributes.append( {"key": "k8s.cluster.name", "value": {"stringValue": k8s_ctx}} ) - if sys.argv: - from devops_cli.security.sanitizer import mask_secrets - - clean_cmd = mask_secrets(" ".join(sys.argv)) - self._cached_resource_attributes.append( - {"key": "process.command_line", "value": {"stringValue": clean_cmd}} - ) + # The resource holds no `process.command_line` and no `process.command_args`. They are + # Opt-In in the OpenTelemetry semantic conventions, which say not to collect them by + # default unless sanitization excludes sensitive data. A secret pattern does not: it + # misses a credential given to `devops config set` (#1996). self._meter_provider: Any = None self._metric_reader: Any = None self._meter: Any = None diff --git a/tests/test_otel_command_coverage.py b/tests/test_otel_command_coverage.py index e5be5274a5..48cf08e9c2 100644 --- a/tests/test_otel_command_coverage.py +++ b/tests/test_otel_command_coverage.py @@ -3,7 +3,10 @@ from __future__ import annotations +import json import subprocess +import sys +from types import SimpleNamespace from typing import Any from unittest.mock import MagicMock @@ -131,6 +134,69 @@ def dummy_list() -> None: assert "devops_cli_command_duration_seconds" in metric_names +# A credential that no secret pattern of `mask_secrets` finds, typed as the value of a secret key +# whose name the patterns also miss. +_TYPED_CREDENTIAL = "correct-horse-battery-staple" +_SET_A_CREDENTIAL = ["set", "cloudflare.tunnel_token", _TYPED_CREDENTIAL] + + +@pytest.fixture +def delegated_set(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]: + """Run `devops dummy set ` through `_delegate` and return each payload the + tracer exported. The tracer is made after `sys.argv` holds the command line, as it is when a + person runs the command.""" + monkeypatch.setattr(sys, "argv", ["devops", "dummy", *_SET_A_CREDENTIAL]) + reset_tracer() + exported: list[dict[str, Any]] = [] + monkeypatch.setattr(get_tracer(), "_send_payload", lambda _path, p: exported.append(p)) + + dummy_app = new_typer() + + @dummy_app.callback() + def dummy_cb() -> None: + pass + + @dummy_app.command(name="set") + def dummy_set(key: str, value: str) -> None: + pass + + module = SimpleNamespace(app=dummy_app) + monkeypatch.setattr("devops_cli.main.import_module", lambda _path: module) + + _delegate("devops_cli.commands.dummy", "dummy", list(_SET_A_CREDENTIAL)) + return exported + + +def test_no_exported_attribute_holds_an_argument_value( + delegated_set: list[dict[str, Any]], +) -> None: + """A credential given as an argument (`devops config set `) is in no span + attribute, event or resource attribute that goes to the trace backend (#1996).""" + assert (bool(delegated_set), _TYPED_CREDENTIAL in json.dumps(delegated_set, default=str)) == ( + True, + False, + ) + + +def test_the_command_spans_keep_the_command_path_and_the_argument_count( + delegated_set: list[dict[str, Any]], +) -> None: + """With no argument value, the trace still names the command that ran and how many arguments + it got.""" + spans = { + span["name"]: {a["key"]: next(iter(a["value"].values())) for a in span["attributes"]} + for payload in delegated_set + if "resourceSpans" in payload + for span in payload["resourceSpans"][0]["scopeSpans"][0]["spans"] + } + assert ( + spans["cli.dummy"]["cli.command"], + spans["cli.dummy"]["cli.args_count"], + "cli.args" in spans["cli.dummy"], + spans["cli.set"].get("cli.command_path"), + ) == ("dummy", "3", False, "devops dummy set") + + def test_subprocess_span_and_metrics( clean_tracer: list[tuple[str, dict[str, Any]]], monkeypatch: pytest.MonkeyPatch ) -> None: