Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<command>` 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.

Expand Down
1 change: 1 addition & 0 deletions docs/TELEMETRY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<subcommand>`) 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 <key> <value>`), 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.

Expand Down
Original file line number Diff line number Diff line change
@@ -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 <key> 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 <key> <credential>` 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 (<value>)"), 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.
14 changes: 12 additions & 2 deletions src/devops_cli/core/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,21 +79,31 @@ 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}"
start_time = time.perf_counter()
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:
Expand Down
8 changes: 8 additions & 0 deletions src/devops_cli/docs/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.<subcommand>`) 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 <key> <value>`), 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 "
Expand Down
5 changes: 3 additions & 2 deletions src/devops_cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <key> <value>`), and the span goes to the trace backend.
# OpenTelemetry gives `process.command_args` as Opt-In for this reason (#1996).
with (
rule,
trace_span(
Expand All @@ -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__,
Expand Down
11 changes: 4 additions & 7 deletions src/devops_cli/telemetry/tracer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
66 changes: 66 additions & 0 deletions tests/test_otel_command_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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 <key> <credential>` 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 <key> <value>`) 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:
Expand Down
Loading