From 48410dede015a16f5b51a27ca2380546855f1553 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 9 Oct 2026 09:43:10 -0600 Subject: [PATCH 01/15] fix(k8s): k8s-monitoring collectors run in the chart's preset shapes, and node-exporter keeps the series the node dashboards read (#1129) (#1500) --- changelog.d/1129.md | 5 + ...k-1080-host-journals-and-health-metrics.md | 4 +- ...toring-presets-and-node-exporter-series.md | 45 +++++++++ ...a-spend-projections-and-dashboard-fixes.md | 6 +- ...tel-collector-and-prometheus-dashboards.md | 2 +- k8s/README.md | 2 +- k8s/monitoring/k8s-monitoring-values.yaml | 39 +++----- tests/fixtures/metrics/dcgm-exporter.yaml | 2 +- tests/fixtures/metrics/litellm.yaml | 2 +- tests/test_k8s_monitoring_alerting.py | 4 +- tests/test_k8s_monitoring_integration.py | 99 ++++++++++++------- 11 files changed, 139 insertions(+), 71 deletions(-) create mode 100644 changelog.d/1129.md create mode 100644 docs/agent/tasks/task-1129-k8s-monitoring-presets-and-node-exporter-series.md diff --git a/changelog.d/1129.md b/changelog.d/1129.md new file mode 100644 index 0000000000..ab1434a99a --- /dev/null +++ b/changelog.d/1129.md @@ -0,0 +1,5 @@ +### Fixed +- Prometheus keeps every series node-exporter serves (no allow list; its collector flags decide what is collected), so Node Exporter Full and the Kubernetes node dashboard show data again (#1129). +- The `alloy-singleton` collector runs as one Deployment pod through the chart's `singleton` preset instead of a DaemonSet per node, so Kubernetes events are watched and shipped once (#1129). +- Alloy writes the cluster name to Prometheus once, as `cluster`, without the duplicate `k8s_cluster_name` label (#1129). +- `kube_hpa_labels` is removed from the kube-state-metrics allow list, since kube-state-metrics v2 never serves it (#1129). diff --git a/docs/agent/tasks/task-1080-host-journals-and-health-metrics.md b/docs/agent/tasks/task-1080-host-journals-and-health-metrics.md index 3f1e2146e1..6a57129a01 100644 --- a/docs/agent/tasks/task-1080-host-journals-and-health-metrics.md +++ b/docs/agent/tasks/task-1080-host-journals-and-health-metrics.md @@ -17,7 +17,7 @@ The owner's decision (2026-10-03) is 30 days of history for homelab logs and met - **`k8s/monitoring/k8s-monitoring-values.yaml`**: - `nodeLogs` runs on `alloy-logs`, which mounts `/var/log` through its `filesystem-log-reader` preset and runs as root, so it reads the journal files (mode 0640). The relabel rules (`extraDiscoveryRules`) keep kernel lines at every priority, the `k3s`, `k3s-agent`, `nvidia-power-limit`, `containerd` and `systemd-journald` units at info and above, systemd's own lines about those units (journal field `UNIT`) at info and above, and every other line at warning and above. `journalLabels` adds `transport`, `structuredMetadata` adds `boot_id`, and the chart sets `job="integrations/kubernetes/journal"`, `instance` (the node name), `unit` and `level`. - `extraLogProcessingStages` adds a `stage.limit` per `unit` label: 1 line/s after a burst of 10,000, dropping the excess. Kernel lines carry no `unit` label, so they are never limited. - - `hostMetrics.linuxHosts.metricsTuning.includeMetrics` adds `node_boot_time_seconds`, `node_hwmon_temp_celsius`, `node_hwmon_chip_names`, `node_systemd_unit_state`, `node_pressure_.*`, `node_edac_correctable_errors_total`, `node_edac_uncorrectable_errors_total`, `node_nvme_info`, `node_filesystem_avail_bytes` and `node_filesystem_size_bytes`. The last two were already kept by the chart's `node_filesystem.*`; they are named so the list holds without it. + - `hostMetrics.linuxHosts.metricsTuning.includeMetrics` adds `node_boot_time_seconds`, `node_hwmon_temp_celsius`, `node_hwmon_chip_names`, `node_systemd_unit_state`, `node_pressure_.*`, `node_edac_correctable_errors_total`, `node_edac_uncorrectable_errors_total`, `node_nvme_info`, `node_filesystem_avail_bytes` and `node_filesystem_size_bytes`. The last two were already kept by the chart's `node_filesystem.*`; they are named so the list holds without it. Since #1129 host metrics have no allow list; node-exporter serves these series and Prometheus keeps them all. - `telemetryServices.node-exporter` turns on the systemd collector with `--collector.systemd.unit-include` set to the same five units, and sets `DBUS_SYSTEM_BUS_ADDRESS` to the host's socket under the `/host/root` mount the chart already has. Helm replaces a list, so the chart's own `--collector.filesystem.fs-types-exclude` argument is repeated unchanged (the rendered DaemonSet diff shows only the two systemd arguments and the variable added). - **`tests/test_k8s_monitoring_integration.py`**: `test_node_journals_reach_loki_through_the_alloy_logs_daemonset` pins the feature, its collector, the labels, the four keep rules built from one unit tuple, and the rate limit. `test_host_metrics_keep_the_series_that_explain_a_host_failure` pins the allowlist, the node-exporter arguments built from the same tuple, and the D-Bus address. Both failed on the previous values (`KeyError: 'nodeLogs'`, `KeyError: 'extraArgs'`) and pass now. - **`k8s/README.md`**: a "Host Journals and Health Metrics" section, after the dashboards section, with what is kept, the labels, where Alloy counts the journal lines it drops, and four queries. @@ -33,7 +33,7 @@ The owner's decision (2026-10-03) is 30 days of history for homelab logs and met ## Acceptance Criteria - [x] `k8s/monitoring/k8s-monitoring-values.yaml` turns on the chart's node journal collection through the existing `alloy-logs` collector, for the kernel and the units `k3s`, `k3s-agent`, `nvidia-power-limit`, `containerd` and `systemd-journald`, labelled by node (`instance`) and unit, with a priority filter and a per-unit rate limit sized against the measured volume. `test_node_journals_reach_loki_through_the_alloy_logs_daemonset` pins the feature and the unit list. -- [x] The host metrics allowlist adds every requested series, each from a collector the chart's node-exporter runs, the systemd collector turned on through chart values. `test_host_metrics_keep_the_series_that_explain_a_host_failure` pins the list. +- [x] The host metrics allowlist adds every requested series, each from a collector the chart's node-exporter runs, the systemd collector turned on through chart values. `test_host_metrics_keep_the_series_that_explain_a_host_failure` pinned the list; since #1129 it asserts that no keep rule is rendered. - [x] Series added per node are counted (41 to 66) and stay under the stated budget of 100. - [x] `helm template k8s-monitoring grafana/k8s-monitoring --version 4.5.2 --namespace monitoring --values k8s/monitoring/k8s-monitoring-values.yaml` renders; the rendered `alloy-logs` configuration passes `alloy validate` in the running Alloy v1.19.2 image, which rejects an unknown attribute or a broken regex in the same file. - [x] `helm upgrade k8s-monitoring grafana/k8s-monitoring --version 4.5.2 --namespace monitoring --values k8s/monitoring/k8s-monitoring-values.yaml --force-conflicts --dry-run=server` ends `DESCRIPTION: Dry run complete` (re-run on 2026-10-03 for revision 38); `helm list` shows the release still `deployed` at revision 37. diff --git a/docs/agent/tasks/task-1129-k8s-monitoring-presets-and-node-exporter-series.md b/docs/agent/tasks/task-1129-k8s-monitoring-presets-and-node-exporter-series.md new file mode 100644 index 0000000000..eeffb9d525 --- /dev/null +++ b/docs/agent/tasks/task-1129-k8s-monitoring-presets-and-node-exporter-series.md @@ -0,0 +1,45 @@ +# Task: k8s-monitoring Collectors Run in the Chart's Preset Shapes, and node-exporter Keeps the Series the Node Dashboards Read (#1129) + +**Issue**: [#1129](https://github.com/dan-petty/devops-cli/issues/1129) +**Status**: Done +**Milestone**: v0.2.32 +**Priority**: priority/p1-high +**Scope**: scope/k8s, scope/telemetry + +## Description +Four settings in `k8s/monitoring/k8s-monitoring-values.yaml` (k8s-monitoring 4.5.2) did not do what the file said. Each fix uses a chart feature that already exists: + +1. **node-exporter has no allow list.** The chart's `_linux_hosts.alloy.tpl` concatenates the default list (on unless `useDefaultAllowList` is `false`), the integration list (only when `useIntegrationAllowList` is `true`) and `includeMetrics`, and renders the `keep` rule only when that list is non-empty. The flag flipped in three releases (v0.2.24, v0.2.25, v0.2.26), and each time a different set of Node Exporter Full and Kubernetes node dashboard panels went empty; the integration list still dropped 38 names the dashboard reads that node-exporter serves. `metricsTuning` now sets `useDefaultAllowList: false` and `useIntegrationAllowList: false` with no `includeMetrics`, so no keep rule is rendered and Prometheus keeps every series node-exporter serves. node-exporter's collector flags (`telemetryServices.node-exporter.extraArgs`) remain the one place that decides what is collected, and the chart's ramfs/tmpfs filesystem drop stays. The #1080 host-failure series come through because node-exporter serves them, with the systemd collector #1080 turned on. +2. **`alloy-singleton` is a singleton.** The collector had no `presets`, so the Alloy chart's default made it a DaemonSet with one pod per node, each running `loki.source.kubernetes_events` and shipping the whole event stream. `clusterEvents` runs unclustered, and the chart says it then "should run on a singleton collector". `collectors.alloy-singleton.presets: [singleton]` makes it a one-replica Deployment. +3. **The cluster name is written once.** The chart's prometheus destination defaults to `clusterLabels: [cluster, k8s.cluster.name]`, so every Alloy-written series carried both `cluster` and `k8s_cluster_name`. Dashboards and rules key on `cluster` only; `destinations.localPrometheus.clusterLabels: [cluster]` drops the duplicate. +4. **`kube_hpa_labels` leaves the kube-state-metrics allow list.** It is a kube-state-metrics v1 name that v2 never serves; the chart's default KSM list already carries `kube_horizontalpodautoscaler_*`. The dashboards that still query it are fixed in #1136. + +`destinations.localLoki` keeps the chart's default `clusterLabels`, so Loki streams still carry `k8s_cluster_name`; the item is scoped to the Prometheus destination. + +## Acceptance Criteria +- [x] `hostMetrics.linuxHosts.metricsTuning` sets `useDefaultAllowList: false` and `useIntegrationAllowList: false` and has no `includeMetrics`, with a comment saying that node-exporter's collector flags (`telemetryServices.node-exporter.extraArgs`) decide what is collected and why there is no allow list. `test_host_metrics_keep_the_series_that_explain_a_host_failure` rebuilds the keep sources the way `_linux_hosts.alloy.tpl` concatenates them (default list unless `useDefaultAllowList` is false, integration list when `useIntegrationAllowList` is true, then `includeMetrics`), without the lists' contents, and asserts they are empty alongside the unchanged node-exporter arguments and D-Bus address. No list fixture is checked in. +- [x] Review mutation: removing `useDefaultAllowList: false` (the chart default is `true`) fails `test_host_metrics_keep_the_series_that_explain_a_host_failure` with keep sources `['default']`. +- [x] `collectors.alloy-singleton.presets: [singleton]`. `test_each_alloy_collector_runs_in_one_controller_preset` asserts, as one tuple, that each collector names exactly one of the controller presets `singleton`, `daemonset`, `statefulset` and `deployment`, and that the `clusterEvents` collector uses `singleton` while `clusterEvents.clustering` is unset or false. +- [x] Review mutation: removing `presets` from `alloy-singleton` fails `test_each_alloy_collector_runs_in_one_controller_preset`. +- [x] `destinations.localPrometheus.clusterLabels: [cluster]`, pinned by `test_alloy_writes_the_cluster_name_once`; deleting the line fails it. +- [x] `kube_hpa_labels` is removed from the KSM `includeMetrics`. The refinement of 2026-10-08 replaced the criterion that expected `True` at both places pinning the allow-list flag: `test_k8s_monitoring_cadvisor_and_ksm_metrics_tuning` no longer reads `useIntegrationAllowList` or requires `kube_hpa_labels`, and the host-metrics test asserts both flags off with no `includeMetrics`. +- [x] The LiteLLM and DCGM exporter capture fixtures (`tests/fixtures/metrics/litellm.yaml`, `dcgm-exporter.yaml`) drop `k8s_cluster_name` from their Alloy target labels; `tests/test_stack_dashboards.py` passes against them. +- [x] No test reaches the network or runs `helm`. Each new or changed test's call phase is 0.01 s (`uv run pytest tests/test_k8s_monitoring_integration.py --durations=10`). +- [x] `changelog.d/1129.md` exists; `CHANGELOG.md` and `docs/ROADMAP.md` are untouched. +- [x] Review render, outside the gate: `helm template` of the k8s-monitoring 4.5.2 chart with the previous and the new values differs in exactly four hunks: `kube_hpa_labels` leaves the KSM keep regex; the `node_exporter` keep rule is gone (the ramfs/tmpfs drop rule stays); `k8s_cluster_name` leaves the `prometheus.remote_write "localprometheus"` external labels; the `alloy-singleton` Alloy resource gains `type: deployment` and `replicas: 1`. +- Pending a person, after the v0.2.32 release PR merges into main and Argo CD syncs the `k8s-monitoring` Application (it tracks main with selfHeal, so do not apply early with `devops k8s deploy-stack` from the release branch: Argo CD would revert it): + 1. `kubectl get application -n argocd k8s-monitoring -o jsonpath='{.status.sync.status} {.status.sync.revisions}'` prints `Synced ["4.5.2",""]`. + 2. `kubectl get alloys.collectors.grafana.com -n monitoring k8s-monitoring-alloy-singleton -o jsonpath='{.spec.controller.type} {.spec.controller.replicas}'` prints `deployment 1`. + 3. `kubectl get deploy,ds -n monitoring | grep alloy-singleton` shows only `deployment.apps/k8s-monitoring-alloy-singleton 1/1`, and no DaemonSet of that name. + 4. `kubectl get endpointslices -n monitoring -l kubernetes.io/service-name=k8s-monitoring-alloy-singleton -o jsonpath='{range .items[*].endpoints[*]}{.addresses[0]}{"\n"}{end}' | wc -l` prints `1`, so the events Ingress reaches one Alloy UI. + 5. Ten minutes later, in Grafana Explore against Prometheus: `count(node_uname_info)` equals the node count; `count by (__name__) ({__name__=~"node_load1|node_context_switches_total|node_netstat_Tcp_CurrEstab|node_disk_io_now"})` returns all four names; `count by (__name__) ({__name__=~"node_procs_blocked|node_forks_total|node_scrape_collector_success|node_systemd_units", job="integrations/node_exporter"})` returns all four names; `count({k8s_cluster_name!=""})` is empty (the issue's `count_over_time` form errors on duplicate labelsets). + 6. Node Exporter Full shows data on every node, except the processes, interrupts and TCP connection-state panels (collectors off by default) and panels for hardware a node lacks. + +## Deliverables +- [x] `k8s/monitoring/k8s-monitoring-values.yaml`: no node-exporter allow list, `alloy-singleton` on the `singleton` preset, `clusterLabels: [cluster]` on the Prometheus destination, `kube_hpa_labels` removed. +- [x] `tests/test_k8s_monitoring_integration.py`: the host-metrics and cAdvisor/KSM tests rewritten; `test_each_alloy_collector_runs_in_one_controller_preset` and `test_alloy_writes_the_cluster_name_once` added. +- [x] `tests/fixtures/metrics/litellm.yaml`, `tests/fixtures/metrics/dcgm-exporter.yaml`: `k8s_cluster_name` removed from the target labels. +- [x] `tests/test_k8s_monitoring_alerting.py`: the node-exporter comment says where the series come from now. +- [x] `k8s/README.md` "Host Journals and Health Metrics": host metrics have no allow list. +- [x] Task files #1080, #1175 and #693 note what changed since #1129. +- [x] `changelog.d/1129.md`. diff --git a/docs/agent/tasks/task-1175-grafana-spend-projections-and-dashboard-fixes.md b/docs/agent/tasks/task-1175-grafana-spend-projections-and-dashboard-fixes.md index 8f3ed2a235..a2009feca3 100644 --- a/docs/agent/tasks/task-1175-grafana-spend-projections-and-dashboard-fixes.md +++ b/docs/agent/tasks/task-1175-grafana-spend-projections-and-dashboard-fixes.md @@ -12,7 +12,7 @@ Remediates multi-series rolling average sprawl, time-range spend and savings pro 1. **Dashboard Rolling Averages Aggregation**: In `ai-spend.json`, converted multi-series rolling average queries that generated one rolling average line per item into single aggregate totals (`Total Rolling Avg`) across all items. 2. **AI Spend & Local Savings Projections**: In `ai-spend.json`, updated 30-day, 90-day, and 1-year run rate projection stat panels to extrapolate from the observed dashboard time range (`rate(...[$__range])`) multiplied out for each projection window, replacing the fixed 1-hour rate window. 3. **LLM Gateway Time to First Token**: In `llm-stack.json`, resolved empty panel by querying `histogram_quantile(0.95, sum by (le, model) (rate(litellm_llm_api_time_to_first_token_metric_bucket[5m])))`, removing the broken `model_id` join on ephemeral LiteLLM hash identifiers. -4. **Node Exporter Full Dropdown Selectors**: In `k8s-monitoring-values.yaml`, enabled `useIntegrationAllowList: true` and added `node_uname_info`, `node_load.*`, `node_disk_io_now`, and `node_netstat_Tcp_CurrEstab` to `includeMetrics`, restoring host metric series required for dashboard 1860 dropdown selectors and system metrics. +4. **Node Exporter Full Dropdown Selectors**: In `k8s-monitoring-values.yaml`, enabled `useIntegrationAllowList: true` and added `node_uname_info`, `node_load.*`, `node_disk_io_now`, and `node_netstat_Tcp_CurrEstab` to `includeMetrics`, restoring host metric series required for dashboard 1860 dropdown selectors and system metrics. Since #1129 node-exporter has no allow list. 5. **NVIDIA DCGM Exporter Grid Layout**: Provisioned local dashboard `nvidia-dcgm.json` with a 2x2 grid layout for bottom panels (GPU SM Clocks, GPU Utilization, Tensor Core Utilization, GPU Framebuffer Memory Used) at width 12 and height 8, replacing upstream dashboard 12239's single-column 50% row layout. 6. **Project & Engineering Velocity Metrics**: In `project-metrics.json`, changed snapshot counters (`devops_cli_project_*`) to query series values directly rather than applying `increase()`, and exempted static snapshot counters from rate-or-increase rules in tests. 7. **Ingress & Cloudflare Tunnel Traffic**: In `ingress-tunnel.json`, ensured "Traffic by Ingress Host / Router" gracefully handles router traffic with service traffic fallback. @@ -21,7 +21,7 @@ Remediates multi-series rolling average sprawl, time-range spend and savings pro - [x] In `ai-spend.json`, rolling averages on panels 8, 10, 11, and 15 compute an aggregate sum across all items labeled `Total Rolling Avg (...)`. - [x] In `ai-spend.json`, 30-day, 90-day, and 1-year projection panels calculate rates over `[$__range]` extrapolated to 30d, 90d, and 365d. - [x] In `llm-stack.json`, Time to First Token p95 queries `litellm_llm_api_time_to_first_token_metric_bucket` grouped by `(le, model)`. -- [x] In `k8s-monitoring-values.yaml`, `useIntegrationAllowList` is set to `true` and `includeMetrics` includes `node_uname_info`, `node_load.*`, `node_disk_io_now`, and `node_netstat_Tcp_CurrEstab`. +- [x] In `k8s-monitoring-values.yaml`, `useIntegrationAllowList` is set to `true` and `includeMetrics` includes `node_uname_info`, `node_load.*`, `node_disk_io_now`, and `node_netstat_Tcp_CurrEstab` (since #1129, no allow list). - [x] `nvidia-dcgm.json` positions bottom panels in a 2x2 grid `((0, 16), (12, 16), (0, 24), (12, 24))` and is registered in `kustomization.yaml`. - [x] `project-metrics.json` displays current snapshot values without `increase()` on cumulative release counters. - [x] `ingress-tunnel.json` Traffic by Ingress Host / Router provides clean router/service metric evaluation. @@ -32,7 +32,7 @@ Remediates multi-series rolling average sprawl, time-range spend and savings pro ## Deliverables - [x] `k8s/monitoring/dashboards/ai-spend.json`: Consolidated rolling averages and dynamic time-range projection rates. - [x] `k8s/monitoring/dashboards/llm-stack.json`: LiteLLM TTFT p95 per model metric query without volatile hash joins. -- [x] `k8s/monitoring/k8s-monitoring-values.yaml`: Enabled integration allowlist and added required node-exporter series. +- [x] `k8s/monitoring/k8s-monitoring-values.yaml`: Enabled integration allowlist and added required node-exporter series (since #1129, no allow list). - [x] `k8s/monitoring/dashboards/nvidia-dcgm.json`: 2x2 panel layout for DCGM metrics. - [x] `k8s/monitoring/grafana-values.yaml` & `k8s/monitoring/dashboards/kustomization.yaml`: Configured local dashboard delivery for DCGM. - [x] `k8s/monitoring/dashboards/project-metrics.json`: Corrected snapshot counter query semantics. diff --git a/docs/agent/tasks/task-693-llm-gateway-otel-collector-and-prometheus-dashboards.md b/docs/agent/tasks/task-693-llm-gateway-otel-collector-and-prometheus-dashboards.md index d4a87990a4..03f095b53d 100644 --- a/docs/agent/tasks/task-693-llm-gateway-otel-collector-and-prometheus-dashboards.md +++ b/docs/agent/tasks/task-693-llm-gateway-otel-collector-and-prometheus-dashboards.md @@ -41,7 +41,7 @@ The collector's pods carry `prometheus.io/scrape` and `prometheus.io/port` annot ## Captures Taken on 2026-10-01 from the deployed exporters through the Kubernetes API service proxy, in the plain text format (version 0.0.4). Each records the image or chart version, every family as its `# TYPE` line prints it with its type and label names, and the target labels its scrape path adds. No label values are kept. -- **LiteLLM** `ghcr.io/berriai/litellm:v1.103.0`, the gateway's `/metrics/`: 107 families. Target labels from the `llm-gateway` ServiceMonitor through Alloy: `cluster`, `container`, `endpoint`, `instance`, `job`, `k8s_cluster_name`, `namespace`, `pod`, `service`. +- **LiteLLM** `ghcr.io/berriai/litellm:v1.103.0`, the gateway's `/metrics/`: 107 families. Target labels from the `llm-gateway` ServiceMonitor through Alloy: `cluster`, `container`, `endpoint`, `instance`, `job`, `k8s_cluster_name`, `namespace`, `pod`, `service`. Since #1129, Alloy no longer adds `k8s_cluster_name`. - **DCGM exporter** `4.6.1-4.8.4-distroless` (chart 4.8.4), one pod on a GPU that reports the profiling fields: 20 families, labelled `hostname`, not `Hostname`. Same target labels as the gateway. - **OTel Collector** `0.159.0` (chart 0.174.0), port 8888: 34 families. Counters print without `_total`, and the endpoint answers in the text format even when OpenMetrics is asked for, as the server's scrape does. Target labels are the `kubernetes-pods` job's (`job`, `instance`, `namespace`, `pod`, `node`, `cluster`) plus the pod labels its labelmap copies. - **Prometheus server** `v3.15.0` (chart 29.35.0), `/metrics`: 264 families. The `prometheus` job adds `job` and `instance` only, so panels do not filter on `cluster`. diff --git a/k8s/README.md b/k8s/README.md index b095b09689..ca34bae122 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -210,7 +210,7 @@ Each node sends its journal to Loki and its health series to Prometheus through - **Journal (`nodeLogs`)**: the `alloy-logs` DaemonSet, which already reads pod logs, reads `/var/log/journal`. It keeps kernel lines at every priority, the `k3s`, `k3s-agent`, `nvidia-power-limit`, `containerd` and `systemd-journald` units and systemd's own lines about them at info and above, and every other line at warning and above. Each unit may send 1 line/s after a burst of 10,000; kernel lines have no limit. Lines carry `job="integrations/kubernetes/journal"`, `instance` (the node), `unit`, `transport` and `level`, with the boot ID as structured metadata (`boot_id`). - **What the journal reader drops**: counted only on each `alloy-logs` pod's own `/metrics` (port 12345), which Prometheus does not scrape. Every entry the keep rules drop counts as `loki_source_journal_target_parsing_errors_total{error="empty_labels"}`, so that series counts the filter at work, not errors; lines the rate limit cuts count per unit in `loki_process_dropped_lines_by_label_total{label_name="unit"}`. -- **Metrics (`hostMetrics`)**: beyond the chart's default list, `node_boot_time_seconds`, `node_hwmon_temp_celsius` with `node_hwmon_chip_names`, `node_pressure_*`, the EDAC correctable and uncorrectable error counters, `node_nvme_info`, filesystem size and free space, and `node_systemd_unit_state` for the units above. node-exporter's systemd collector reads unit state over the host's D-Bus socket, reached through the node root the chart mounts at `/host/root`. +- **Metrics (`hostMetrics`)**: Prometheus keeps every series node-exporter serves, with no allow list (#1129), because node-exporter's collector flags decide what is collected. Among them are `node_boot_time_seconds`, `node_hwmon_temp_celsius` with `node_hwmon_chip_names`, `node_pressure_*`, the EDAC correctable and uncorrectable error counters, `node_nvme_info`, filesystem size and free space, and `node_systemd_unit_state` for the units above, from the systemd collector the values turn on. node-exporter's systemd collector reads unit state over the host's D-Bus socket, reached through the node root the chart mounts at `/host/root`. ```text {job="integrations/kubernetes/journal", transport="kernel"} # LogQL: kernel lines diff --git a/k8s/monitoring/k8s-monitoring-values.yaml b/k8s/monitoring/k8s-monitoring-values.yaml index 05c42d0684..31402fe51b 100644 --- a/k8s/monitoring/k8s-monitoring-values.yaml +++ b/k8s/monitoring/k8s-monitoring-values.yaml @@ -10,6 +10,9 @@ destinations: localPrometheus: type: prometheus url: http://prometheus.monitoring.svc.cluster.local:9090/api/v1/write + # Dashboards and rules key on `cluster`; the chart default would also write `k8s_cluster_name`. + clusterLabels: + - cluster localLoki: type: loki url: http://loki.logging.svc.cluster.local:3100/loki/api/v1/push @@ -52,7 +55,6 @@ clusterMetrics: - kube_pod_container_status_running - kube_pod_status_qos_class - kube_pod_status_reason - - kube_hpa_labels - kube_pod_container_status_ready - kube_pod_container_status_last_terminated_exitcode - kube_pod_container_status_terminated @@ -64,30 +66,16 @@ hostMetrics: collector: alloy-metrics linuxHosts: enabled: true + # No allow list: node-exporter's collector flags (telemetryServices.node-exporter.extraArgs) + # decide what is collected, and Prometheus keeps every series it serves. With the default list, + # the integration list and includeMetrics all empty, the chart renders no keep rule; its + # ramfs/tmpfs filesystem drop stays. An allow list cannot follow a third-party dashboard (Node + # Exporter Full), and each release that widened or narrowed it left different panels empty + # (#1129). The series that explain a host failure (#1080) come through because node-exporter + # serves them, with the systemd collector turned on under telemetryServices. metricsTuning: - useIntegrationAllowList: true - # Beyond the chart's default list, the series that explain a host failure (#1080): boot time - # (an unclean restart), temperatures with their chip names, pressure stalls, memory errors - # (EDAC), the NVMe disk, free filesystem space, and the host units' state. node-exporter runs - # every collector these need by default except systemd, turned on under telemetryServices. - # Setting useIntegrationAllowList to true includes the chart's integration list, and includeMetrics - # guarantees node_uname_info (for Node Exporter Full dropdowns), load, disk I/O, and TCP metrics. - includeMetrics: - - node_time_seconds - - node_boot_time_seconds - - node_hwmon_temp_celsius - - node_hwmon_chip_names - - node_systemd_unit_state - - node_pressure_.* - - node_edac_correctable_errors_total - - node_edac_uncorrectable_errors_total - - node_nvme_info - - node_filesystem_avail_bytes - - node_filesystem_size_bytes - - node_uname_info - - node_load.* - - node_disk_io_now - - node_netstat_Tcp_CurrEstab + useDefaultAllowList: false + useIntegrationAllowList: false clusterEvents: enabled: true @@ -212,6 +200,9 @@ collectors: cpu: 1000m memory: 1024Mi alloy-singleton: + # clusterEvents runs unclustered, so exactly one pod watches and ships the events. + presets: + - singleton alloy: enableReporting: false resources: diff --git a/tests/fixtures/metrics/dcgm-exporter.yaml b/tests/fixtures/metrics/dcgm-exporter.yaml index a1c17d7122..dcaa58d5cb 100644 --- a/tests/fixtures/metrics/dcgm-exporter.yaml +++ b/tests/fixtures/metrics/dcgm-exporter.yaml @@ -17,7 +17,7 @@ scraped_by: >- The chart's own ServiceMonitor (serviceMonitor.enabled in k8s/monitoring/dcgm-exporter-values.yaml), read by Alloy (k8s-monitoring 4.5.2), which remote-writes to the Prometheus server. -target_labels: [cluster, container, endpoint, instance, job, k8s_cluster_name, namespace, node, pod, service] +target_labels: [cluster, container, endpoint, instance, job, namespace, node, pod, service] families: DCGM_FI_DEV_DEC_UTIL: {type: gauge, labels: [DCGM_FI_DRIVER_VERSION, UUID, device, gpu, hostname, modelName, pci_bus_id]} DCGM_FI_DEV_ENC_UTIL: {type: gauge, labels: [DCGM_FI_DRIVER_VERSION, UUID, device, gpu, hostname, modelName, pci_bus_id]} diff --git a/tests/fixtures/metrics/litellm.yaml b/tests/fixtures/metrics/litellm.yaml index 4434327cf0..071a464487 100644 --- a/tests/fixtures/metrics/litellm.yaml +++ b/tests/fixtures/metrics/litellm.yaml @@ -15,7 +15,7 @@ taken_from: >- scraped_by: >- The llm-gateway ServiceMonitor (k8s/monitoring/k8s-monitoring-values.yaml), read by Alloy (k8s-monitoring 4.5.2), which remote-writes to the Prometheus server. -target_labels: [cluster, container, endpoint, instance, job, k8s_cluster_name, namespace, pod, service] +target_labels: [cluster, container, endpoint, instance, job, namespace, pod, service] families: litellm_active_users: {type: gauge, labels: []} litellm_api_key_budget_remaining_hours_metric: {type: gauge} diff --git a/tests/test_k8s_monitoring_alerting.py b/tests/test_k8s_monitoring_alerting.py index 7fec067ff9..74520117e3 100644 --- a/tests/test_k8s_monitoring_alerting.py +++ b/tests/test_k8s_monitoring_alerting.py @@ -43,8 +43,8 @@ # are host directories), so the rule over them stays silent until one does. "kubelet_volume_stats_available_bytes", "kubelet_volume_stats_capacity_bytes", - # node-exporter, scraped by k8s-monitoring's host metrics; boot time and systemd unit - # state come from its allow list in #1080. + # node-exporter, scraped by k8s-monitoring's host metrics with no allow list (#1129); + # systemd unit state comes from the collector #1080 turned on. "node_boot_time_seconds", "node_filesystem_avail_bytes", "node_filesystem_size_bytes", diff --git a/tests/test_k8s_monitoring_integration.py b/tests/test_k8s_monitoring_integration.py index 0d832a0fd8..2c8e25727c 100644 --- a/tests/test_k8s_monitoring_integration.py +++ b/tests/test_k8s_monitoring_integration.py @@ -20,6 +20,9 @@ HOST_UNITS = ("k3s", "k3s-agent", "nvidia-power-limit", "containerd", "systemd-journald") HOST_UNIT_PATTERN = f"({'|'.join(HOST_UNITS)})\\.service" +# The k8s-monitoring chart's presets that set an Alloy collector's controller (`collectors/presets/`). +CONTROLLER_PRESETS = {"singleton", "daemonset", "statefulset", "deployment"} + def _k8s_monitoring_values() -> Any: with open(K8S_DIR / "monitoring" / "k8s-monitoring-values.yaml", encoding="utf-8") as f: @@ -39,8 +42,6 @@ def test_k8s_monitoring_cadvisor_and_ksm_metrics_tuning() -> None: ksm_inc = set( cm.get("kube-state-metrics", {}).get("metricsTuning", {}).get("includeMetrics", []) ) - hm_tuning = data.get("hostMetrics", {}).get("linuxHosts", {}).get("metricsTuning", {}) - use_integration_allow_list = hm_tuning.get("useIntegrationAllowList") required_cadvisor = { "machine_cpu_cores", @@ -69,7 +70,6 @@ def test_k8s_monitoring_cadvisor_and_ksm_metrics_tuning() -> None: "kube_pod_container_status_running", "kube_pod_status_qos_class", "kube_pod_status_reason", - "kube_hpa_labels", "kube_pod_container_status_ready", "kube_pod_container_status_last_terminated_exitcode", "kube_pod_container_status_terminated", @@ -77,11 +77,10 @@ def test_k8s_monitoring_cadvisor_and_ksm_metrics_tuning() -> None: "kube_deployment_status_replicas_unavailable", } - assert ( - required_cadvisor.issubset(cadvisor_inc), - required_ksm.issubset(ksm_inc), - use_integration_allow_list, - ) == (True, True, True) + assert (required_cadvisor.issubset(cadvisor_inc), required_ksm.issubset(ksm_inc)) == ( + True, + True, + ) def test_node_journals_reach_loki_through_the_alloy_logs_daemonset() -> None: @@ -127,38 +126,31 @@ def test_node_journals_reach_loki_through_the_alloy_logs_daemonset() -> None: def test_host_metrics_keep_the_series_that_explain_a_host_failure() -> None: - """Prometheus keeps each node's boot time, temperatures, pressure, memory and NVMe health, - filesystem space and the host units' state (#1080). The systemd collector is the one the - chart's node-exporter leaves off: it reads unit state over the host's D-Bus socket, which the - node's root mount already exposes, and only for the host units.""" + """Host metrics have no keep rule: node-exporter's collector flags decide what is collected, + and Prometheus keeps every series it serves (#1129). The series that explain a host failure + (#1080: boot time, temperatures with their chip names, pressure, EDAC memory errors, NVMe, + filesystem space and the host units' state) come through because node-exporter serves them. + The systemd collector is turned on here for the host units only: it reads unit state over + the host's D-Bus socket, which the node's root mount already exposes. + + The keep sources are rebuilt the way the chart's `_linux_hosts.alloy.tpl` concatenates them + (the default list unless `useDefaultAllowList` is false, the integration list when + `useIntegrationAllowList` is true, then `includeMetrics`), without the lists' contents.""" values = _k8s_monitoring_values() tuning = values["hostMetrics"]["linuxHosts"]["metricsTuning"] exporter = values["telemetryServices"]["node-exporter"] + keep_sources = [ + source + for source, on in ( + ("default", tuning.get("useDefaultAllowList", True)), + ("integration", tuning.get("useIntegrationAllowList", False)), + ("includeMetrics", bool(tuning.get("includeMetrics"))), + ) + if on + ] - assert ( - tuning["useIntegrationAllowList"], - tuning["includeMetrics"], - exporter["extraArgs"], - exporter["env"], - ) == ( - True, - [ - "node_time_seconds", - "node_boot_time_seconds", - "node_hwmon_temp_celsius", - "node_hwmon_chip_names", - "node_systemd_unit_state", - "node_pressure_.*", - "node_edac_correctable_errors_total", - "node_edac_uncorrectable_errors_total", - "node_nvme_info", - "node_filesystem_avail_bytes", - "node_filesystem_size_bytes", - "node_uname_info", - "node_load.*", - "node_disk_io_now", - "node_netstat_Tcp_CurrEstab", - ], + assert (keep_sources, exporter["extraArgs"], exporter["env"]) == ( + [], [ "--collector.filesystem.fs-types-exclude=^(autofs|binfmt_misc|bpf|cgroup2?|configfs" "|debugfs|devpts|devtmpfs|fusectl|hugetlbfs|iso9660|mqueue|nsfs|overlay|proc|procfs" @@ -170,6 +162,41 @@ def test_host_metrics_keep_the_series_that_explain_a_host_failure() -> None: ) +def test_each_alloy_collector_runs_in_one_controller_preset() -> None: + """Each Alloy collector names exactly one of the chart's controller presets (#1129). + `clusterEvents` runs unclustered, so its collector must be one pod: the chart's `singleton` + preset makes it a one-replica Deployment, and without a preset the Alloy chart defaults to a + DaemonSet, where every node's pod watches and ships the whole event stream.""" + values = _k8s_monitoring_values() + controllers = { + name: sorted(CONTROLLER_PRESETS.intersection(collector.get("presets", []))) + for name, collector in values["collectors"].items() + } + events = values["clusterEvents"] + + assert ( + controllers, + controllers[events["collector"]], + events.get("clustering", False), + ) == ( + { + "alloy-metrics": ["statefulset"], + "alloy-singleton": ["singleton"], + "alloy-logs": ["daemonset"], + }, + ["singleton"], + False, + ) + + +def test_alloy_writes_the_cluster_name_once() -> None: + """Alloy labels what it writes to Prometheus with the cluster name as `cluster` only (#1129). + Dashboards and rules key on `cluster`; the chart default also writes `k8s_cluster_name`.""" + values = _k8s_monitoring_values() + + assert values["destinations"]["localPrometheus"]["clusterLabels"] == ["cluster"] + + def test_k8s_monitoring_ksm_telemetry_service_config() -> None: """Verify kube-state-metrics telemetry service enables endpoints collector and resource labels.""" values_path = K8S_DIR / "monitoring" / "k8s-monitoring-values.yaml" From 630fb2d1c4fd62e33086b40fc1aaeb1eaf40e062 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 9 Oct 2026 09:43:24 -0600 Subject: [PATCH 02/15] fix(security): the host sandbox declares a noexec /tmp it never applies (#798) (#1502) Bubblewrap has no noexec option for a tmpfs, so the host sandbox's `/tmp` was mounted executable while its policy declared `noexec`. The host sandbox now defaults to DEFAULT_HOST_SANDBOX_POLICY, which declares only the 64 MiB size. A policy with a tmpfs option bubblewrap cannot apply (`noexec`, or a size such as `size=50%` that is not in bytes) fails when the HostSandbox is constructed, with a SandboxValidationError naming the option, instead of being dropped. The size is parsed by docker.utils.parse_bytes in place of the hand-written regex. The container policy keeps noexec (#698). SECURITY.md says the host sandbox's `/tmp` allows execution. The output-cap test now runs a shell loop that ignores SIGPIPE, so closing the pipes does not end it, and asserts that the run ends within 1 s, under the reap's 1 s grace. The test fails if the kill at the cap is removed. --- SECURITY.md | 2 +- changelog.d/798.md | 3 + ...-declares-a-noexec-tmp-it-never-applies.md | 65 +++++++++++++++++++ src/devops_cli/sandbox/host.py | 59 +++++++++++------ tests/test_host_sandbox.py | 52 +++++++++++---- 5 files changed, 147 insertions(+), 34 deletions(-) create mode 100644 changelog.d/798.md create mode 100644 docs/agent/tasks/task-798-host-sandbox-declares-a-noexec-tmp-it-never-applies.md diff --git a/SECURITY.md b/SECURITY.md index 24ee6c9b65..f2eb79af61 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -25,7 +25,7 @@ All code authored in or evaluated by DevOps CLI must strictly adhere to the foll 3. **Subprocess Bounded Execution**: All external commands (`git`, `helm`, `kubectl`, `tofu`, `docker`) are executed via bounded argument lists (preventing shell injection) with mandatory non-infinite timeouts. 4. **Data Isolation**: Agent-generated review logs, benchmarks, and temporary telemetry artifacts are isolated under dedicated agent subfolders (`/agent`, e.g. `./.data/agent`), completely segregated from the primary user workspace data tier (`DEVOPS_CLI_DATA_DIR` / `data.dir`). 5. **Least Privilege Runtime**: Kubernetes pods, Docker containers, and CI jobs run under unprivileged, non-root user contexts (`USER 1000:1000`). -6. **Host Sandbox Confinement**: Executable verification criteria and model-generated shell commands are confined within Linux unprivileged namespaces via `bubblewrap` (`bwrap`), enforcing unshared namespaces, cleared environment, read-only repository and system mounts, zero network egress, and isolated POSIX process groups. +6. **Host Sandbox Confinement**: Executable verification criteria and model-generated shell commands are confined within Linux unprivileged namespaces via `bubblewrap` (`bwrap`), enforcing unshared namespaces, cleared environment, read-only repository and system mounts, zero network egress, and isolated POSIX process groups. The host sandbox's `/tmp` is a private 64 MiB tmpfs mounted nosuid and nodev, which the confined command can write to and execute from, because bubblewrap has no noexec option for a tmpfs. --- diff --git a/changelog.d/798.md b/changelog.d/798.md new file mode 100644 index 0000000000..955263f79f --- /dev/null +++ b/changelog.d/798.md @@ -0,0 +1,3 @@ +### Security +- The host sandbox no longer declares a noexec `/tmp` that bubblewrap never applied (#798). Bubblewrap has no noexec option for a tmpfs, so the host policy now declares only the 64 MiB size, and the container sandboxes keep their `size=64m,noexec` policy. A host sandbox whose policy declares a tmpfs option bubblewrap cannot apply, such as `noexec` or `size=50%`, now fails at construction with an error naming the option, instead of dropping it. SECURITY.md now says that the host sandbox's `/tmp` allows execution. +- The output-cap test now runs a writer that ignores SIGPIPE and checks that the sandbox kills it at the cap within 1 s, well before its timeout (#798). diff --git a/docs/agent/tasks/task-798-host-sandbox-declares-a-noexec-tmp-it-never-applies.md b/docs/agent/tasks/task-798-host-sandbox-declares-a-noexec-tmp-it-never-applies.md new file mode 100644 index 0000000000..7bb853c3d9 --- /dev/null +++ b/docs/agent/tasks/task-798-host-sandbox-declares-a-noexec-tmp-it-never-applies.md @@ -0,0 +1,65 @@ +# Task: The Host Sandbox Declares a Noexec /tmp It Never Applies (#798) + +**Issue**: [#798](https://github.com/dan-petty/devops-cli/issues/798) +**Status**: Done +**Milestone**: v0.2.32 +**Priority**: priority/p3-low +**Scope**: type/security, scope/security + +## Description + +The host sandbox (`src/devops_cli/sandbox/host.py`) read the same `SandboxPolicy` as the container +runners, whose `/tmp` is `size=64m,noexec`. Only the size reached bubblewrap. The `noexec` flag was +dropped without a word. With bubblewrap 0.13.0, `bwrap --help` lists only `--size` (and `--perms`) +as modifiers for `--tmpfs`, with no noexec option. Inside the sandbox, `/proc/self/mounts` showed +`/tmp` as `rw,nosuid,nodev,size=65536k`, and a script written to `/tmp` ran. + +The host sandbox cannot enforce noexec. The confined child has no capabilities to remount `/tmp`. +Landlock would need a dependency outside the standard library. And noexec would not stop +`sh /tmp/x` anyway. So the host policy now declares only what bubblewrap applies, and +SECURITY.md says that the host sandbox's `/tmp` allows execution. The container policy +(`DEFAULT_SANDBOX_POLICY`) keeps `size=64m,noexec`. Whether the container engines enforce it is a +question for the audit in #698. + +The output-cap test used a writer that exited by itself after 50 KB, so it never showed that the +sandbox kills a process at the cap. An endless writer such as `yes` is not enough either: it dies +of SIGPIPE once the sandbox closes its pipes. The test now runs a shell loop that ignores SIGPIPE, +so only the kill at the cap ends it within the reap's 1 s grace. + +The host policy still declares a `pids_limit` that the host sandbox ignores, as +`_run_sandbox_process` documents: bubblewrap has no process limit, and RLIMIT_NPROC is per user, +not per process tree. `SandboxPolicy.pids_limit` is an `int` with no "no limit" value, and the +container runners apply it, so dropping it from the host policy changes the shared model and is +outside this item. No issue tracks it: #698 audits the container runners only, and #772, which +adds the host sandbox's resource limits, sets no process-count limit but does not cover the +declared value. + +## Key Changes + +- `src/devops_cli/sandbox/host.py`: + - `DEFAULT_HOST_SANDBOX_POLICY` declares `/tmp` as `size=64m`, and `HostSandbox` defaults to it. + - `_tmpfs_mount_args(path, options)` replaces the regex in `_parse_tmpfs_size_bytes`. It turns a + `size` option into `--size ` with `docker.utils.parse_bytes` (the existing `docker` + dependency) and raises `SandboxValidationError` naming any other option, or a size that + `parse_bytes` refuses (such as `size=50%`), instead of dropping it. + - `HostSandbox.__init__` builds the tmpfs arguments once, so a policy that bubblewrap cannot + apply fails when the sandbox is constructed, not when it runs a command. +- `SECURITY.md`, item 6 ("Host Sandbox Confinement"): the host sandbox's `/tmp` is a private + 64 MiB tmpfs mounted nosuid and nodev, which the confined command can write to and execute from. +- `tests/test_host_sandbox.py`: + - `test_host_sandbox_default_policy_mounts_tmp_as_declared` and + `test_host_sandbox_refuses_a_tmpfs_option_bubblewrap_cannot_apply` are new. + - `test_host_sandbox_kills_an_endless_writer_at_the_output_cap` replaces + `test_host_sandbox_kills_process_exceeding_output_cap`. + - `test_sandbox_binds_the_virtualenv_interpreter_installation_read_only` builds its writable + policy from `DEFAULT_HOST_SANDBOX_POLICY`. + +## Acceptance Criteria + +- [x] **The host stops declaring noexec.** `test_host_sandbox_default_policy_mounts_tmp_as_declared` shows that the default host policy declares `/tmp` as `size=64m` and that the arguments mount it with `--size 67108864 --tmpfs /tmp`. +- [x] **An option bubblewrap cannot apply is refused.** `test_host_sandbox_refuses_a_tmpfs_option_bubblewrap_cannot_apply` constructs host sandboxes whose policies declare `size=64m,noexec` and `size=50%`, and expects a `SandboxValidationError` naming `noexec` and `size=50%`. +- [x] **Containers keep noexec.** `DEFAULT_SANDBOX_POLICY` in `src/devops_cli/sandbox/models.py` is unchanged, and `tests/test_sandbox_lifecycle.py` still pins its `size=64m,noexec` tmpfs. +- [x] **The docs say which.** SECURITY.md item 6 says that the host sandbox's `/tmp` allows execution, and why. +- [x] **The cap kills an endless writer.** `test_host_sandbox_kills_an_endless_writer_at_the_output_cap` (bubblewrap-marked) runs a shell loop that ignores SIGPIPE, with a 30 s timeout and a 1024-byte cap. It asserts that the run fails without timing out, keeps at most 1024 bytes, reports the cap, and ends within 1 s. That is under the reap's 1 s grace, so the test fails if the kill at the cap is removed (the run then takes about 1.06 s, or about 2.09 s with no kill at all). +- [x] **No RLIMIT_NPROC and no fork bombs.** No test sets a process limit or spawns processes without bound. +- [x] **Release.** `changelog.d/798.md` records the change under `### Security`. diff --git a/src/devops_cli/sandbox/host.py b/src/devops_cli/sandbox/host.py index 2a616b5287..ad6abcec0b 100644 --- a/src/devops_cli/sandbox/host.py +++ b/src/devops_cli/sandbox/host.py @@ -4,7 +4,6 @@ import contextlib import os -import re import selectors import shutil import signal @@ -29,7 +28,14 @@ _linked_worktree_common_dir, _repo_root_candidates, ) -from devops_cli.sandbox.models import DEFAULT_SANDBOX_POLICY, SandboxPolicy +from devops_cli.exceptions.sandbox import SandboxValidationError +from devops_cli.sandbox.models import SandboxPolicy + +# bubblewrap mounts a tmpfs nosuid,nodev but has no noexec option, so the host policy declares +# only the size, and the container policy (DEFAULT_SANDBOX_POLICY) keeps noexec. +DEFAULT_HOST_SANDBOX_POLICY: Final[SandboxPolicy] = SandboxPolicy( + tmpfs={"/tmp": "size=64m"} # nosec B108 +) @dataclass(frozen=True) @@ -74,15 +80,28 @@ def _terminate_process_group(pid: int, sig: signal.Signals = signal.SIGTERM) -> pass -def _parse_tmpfs_size_bytes(opts: str) -> int | None: - """Parse size limit in bytes from tmpfs mount options string.""" - m = re.search(r"\bsize=(\d+)([kmgKMG]?)\b", opts) - if not m: - return None - num = int(m.group(1)) - unit = m.group(2).lower() - multipliers = {"": 1, "k": 1024, "m": 1024 * 1024, "g": 1024 * 1024 * 1024} - return num * multipliers.get(unit, 1) +def _tmpfs_mount_args(path: str, options: str) -> list[str]: + """The bubblewrap options that mount a tmpfs at `path` with its declared mount options. + + bubblewrap can set only a tmpfs's size, in bytes, so any other option, or a size it cannot + express in bytes (such as `size=50%`), is refused rather than dropped. + """ + from docker.errors import DockerException # type: ignore[import-untyped] + from docker.utils import parse_bytes # type: ignore[import-untyped] + + args: list[str] = [] + for option in filter(None, options.split(",")): + name, _, value = option.partition("=") + refused = SandboxValidationError( + f"bubblewrap cannot apply the tmpfs option '{option}' on {path}", path=path + ) + if name != "size": + raise refused + try: + args.extend(["--size", str(parse_bytes(value))]) + except DockerException as exc: + raise refused from exc + return [*args, "--tmpfs", path] def _is_mock_subprocess(proc: Any) -> bool: @@ -402,7 +421,15 @@ def __init__( ) -> None: resolved = bwrap_binary or shutil.which("bwrap") or DEFAULT_HOST_SANDBOX_BINARY self.bwrap_binary: Final[Path] = Path(resolved) - self.policy: Final[SandboxPolicy] = policy if policy is not None else DEFAULT_SANDBOX_POLICY + self.policy: Final[SandboxPolicy] = ( + policy if policy is not None else DEFAULT_HOST_SANDBOX_POLICY + ) + # Built here so a policy whose tmpfs bubblewrap cannot apply fails at construction. + self._tmpfs_args: Final[list[str]] = [ + arg + for path, options in self.policy.tmpfs.items() + for arg in _tmpfs_mount_args(path, options) + ] def is_available(self) -> bool: """Verify whether the bubblewrap binary exists and is executable.""" @@ -435,13 +462,7 @@ def _resolve_repo_mounts( resolved_cwd = cwd.resolve() effective_root = _effective_repo_root(resolved_cwd, repo_root) - mount_args: list[str] = [] - for tmp_dir, opts in self.policy.tmpfs.items(): - size_bytes = _parse_tmpfs_size_bytes(opts) - if size_bytes is not None: - mount_args.extend(["--size", str(size_bytes)]) - mount_args.extend(["--tmpfs", tmp_dir]) # nosec B108 - + mount_args = [*self._tmpfs_args] bind_flag = "--ro-bind" if self.policy.read_only else "--bind" mount_args.extend([bind_flag, str(effective_root), str(effective_root)]) if not resolved_cwd.is_relative_to(effective_root): diff --git a/tests/test_host_sandbox.py b/tests/test_host_sandbox.py index e3251b4013..d420b75b99 100644 --- a/tests/test_host_sandbox.py +++ b/tests/test_host_sandbox.py @@ -13,7 +13,8 @@ from devops_cli.ai.review.review_environment import execute_criterion_command from devops_cli.config.constants import CONST_ALLOWED_CRITERIA_BINARIES -from devops_cli.sandbox.host import HostSandbox +from devops_cli.exceptions.sandbox import SandboxValidationError +from devops_cli.sandbox.host import DEFAULT_HOST_SANDBOX_POLICY, HostSandbox from devops_cli.sandbox.models import SandboxPolicy _PROJECT_ROOT = Path(__file__).resolve().parents[1] @@ -235,24 +236,45 @@ def test_host_sandbox_consumes_custom_policy(tmp_path: Path) -> None: ) == (True, True, True, True, True, True, True, True) -@pytest.mark.bwrap -def test_host_sandbox_kills_process_exceeding_output_cap(tmp_path: Path) -> None: - """Verify that process generating unbounded output is terminated and output is capped (#663).""" +def test_host_sandbox_default_policy_mounts_tmp_as_declared(tmp_path: Path) -> None: + """The host policy declares only what bubblewrap applies to `/tmp`: its size (#798).""" sandbox = HostSandbox() - res = sandbox.execute( - [ - "python3", - "-c", - "import sys; sys.stdout.write('A' * 50000); sys.stdout.flush()", - ], - cwd=tmp_path, - max_output_bytes=1024, + options = _sandbox_options(sandbox.build_bwrap_args(["true"], cwd=tmp_path)) + at = options.index("--tmpfs") + assert (sandbox.policy.tmpfs, options[at - 2 : at + 2]) == ( + {"/tmp": "size=64m"}, # nosec B108 + ["--size", "67108864", "--tmpfs", "/tmp"], # nosec B108 ) + + +@pytest.mark.parametrize( + ("options", "refused"), + [("size=64m,noexec", "'noexec'"), ("size=50%", "'size=50%'")], +) +def test_host_sandbox_refuses_a_tmpfs_option_bubblewrap_cannot_apply( + options: str, refused: str +) -> None: + """A tmpfs option bubblewrap cannot apply fails the sandbox's construction, naming it (#798).""" + with pytest.raises(SandboxValidationError, match=refused): + HostSandbox(policy=SandboxPolicy(tmpfs={"/tmp": options})) # nosec B108 + + +@pytest.mark.bwrap +def test_host_sandbox_kills_an_endless_writer_at_the_output_cap(tmp_path: Path) -> None: + """A writer that survives its pipes closing ends only by the kill at the output cap (#798). + + The writer ignores SIGPIPE, so closing the pipes does not end it. Without the kill at the cap, + the run lasts until the reap's kill after its 1 s grace. + """ + writer = ["sh", "-c", "trap '' PIPE; while :; do echo y; done 2>/dev/null"] + res = HostSandbox().execute(writer, cwd=tmp_path, timeout=30.0, max_output_bytes=1024) assert ( res.passed, + res.timed_out, len(res.stdout) <= 1024, "Output exceeded maximum limit" in str(res.error), - ) == (False, True, True) + res.duration_seconds < 1.0, + ) == (False, False, True, True, True) @pytest.mark.bwrap @@ -420,7 +442,9 @@ def test_sandbox_binds_the_virtualenv_interpreter_installation_read_only( monkeypatch.setenv("HOME", str(tmp_path / "home")) installation = tmp_path / "home" / ".local" / "share" / "uv" / "python" / "cpython-3.14" repo = _repo_with_virtualenv(tmp_path / "repo", _python_installation(installation)) - sandbox = HostSandbox(policy=SandboxPolicy(read_only=False)) + sandbox = HostSandbox( + policy=DEFAULT_HOST_SANDBOX_POLICY.model_copy(update={"read_only": False}) + ) args = sandbox.build_bwrap_args(["true"], cwd=repo) assert (_sandbox_path(args), _repo_binds(args)) == ( f"{repo / '.venv' / 'bin'}:{_SYSTEM_PATH}", From 4716d7fdbd9db39a23789b90f35c04e6d7693baf Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 9 Oct 2026 09:44:37 -0600 Subject: [PATCH 03/15] refactor(release): the release no longer pins, bumps or pre-publishes the service image tag; image updater rolls service:latest (#1486) (#1504) Argo CD Image Updater (#1485) keeps Application devops on the digest service:latest points at, so the custom tag process is gone: - The cut no longer bumps newTag in k8s/devops/kustomization.yaml or rewrites Argo CD targetRevisions, and stages nothing under k8s/. devops release check drops the pin and targetRevision checks; tests/test_k8s_argocd_apps.py already holds every git source on main. - k8s/devops/kustomization.yaml loses its images: pin. - release.yml has no release/v* trigger, plan or promote step. On main it builds, smoke-tests, scans, pushes by digest and attests the image, then tags it vX.Y.Z and latest. - ci.yml's Service Image job builds release pull requests too. - RELEASE_CYCLE.md, docs/ROUTINE_TASKS.md and k8s/README.md describe the new flow; the task files of #1451, #741, #1261 and #755 note what this removed. --- .github/workflows/ci.yml | 9 +- .github/workflows/release.yml | 170 +------ RELEASE_CYCLE.md | 11 +- changelog.d/1486.md | 8 + docs/ROUTINE_TASKS.md | 9 +- .../task-1261-argocd-target-revision-main.md | 2 + .../task-1451-image-before-main-pins-it.md | 2 + ...sk-1486-release-drops-service-image-tag.md | 54 +++ .../tasks/task-741-devops-cli-in-cluster.md | 2 + .../task-755-argocd-reconciles-cluster.md | 2 + k8s/README.md | 10 +- k8s/devops/kustomization.yaml | 3 - src/devops_cli/commands/release.py | 196 +------- src/devops_cli/config/constants.py | 3 - src/devops_cli/lang/en/messages.py | 3 - tests/test_architectural_invariants.py | 24 - tests/test_ci.py | 101 ++-- tests/test_k8s_devops_runtime.py | 28 +- tests/test_release.py | 166 ++----- tests/test_release_service_image_plan.py | 451 ------------------ 20 files changed, 184 insertions(+), 1070 deletions(-) create mode 100644 changelog.d/1486.md create mode 100644 docs/agent/tasks/task-1486-release-drops-service-image-tag.md delete mode 100644 tests/test_release_service_image_plan.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f04c97aedf..907d8295a9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -157,16 +157,13 @@ jobs: imageTag: pr-${{ github.event.pull_request.number }} push: "always" - # A release pull request's head is this repository's release/vX.Y.Z, whose every push runs - # release.yml's Build & Publish Service Image on the same tree (#1451), so this job builds - # every other pull request into main. + # Builds, smoke-tests and scans the Service image of every pull request into main, release + # pull requests included, without pushing it; release.yml publishes it after the merge (#1486). service-image: name: Service Image if: >- github.event_name == 'workflow_dispatch' || - (github.event_name == 'pull_request' && github.base_ref == 'main' && - !(startsWith(github.head_ref, 'release/v') && - github.event.pull_request.head.repo.full_name == github.repository)) + (github.event_name == 'pull_request' && github.base_ref == 'main') runs-on: ubuntu-latest timeout-minutes: 30 permissions: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c4d46e6516..08677cd5d8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,9 +4,6 @@ on: push: branches: - main - # A release branch publishes the Service image its version pins, so the image exists - # before main pins it (#1451). - - "release/v*" tags: - "v*" workflow_dispatch: @@ -157,13 +154,10 @@ jobs: service-image: name: Build & Publish Service Image needs: release - # A push to release/vX.Y.Z publishes service:vX.Y.Z once the branch holds X.Y.Z; the release - # job does not run there. On main, after the release job, the image the release branch - # published gets `latest` once its provenance verifies, and is never replaced (#1451). - if: >- - !cancelled() && ( - needs.release.result == 'success' || - (github.event_name == 'push' && startsWith(github.ref, 'refs/heads/release/v'))) + # On main (a push, or a dispatch from main), after the release job, it builds, smoke-tests, + # scans, pushes by digest and attests service:vX.Y.Z, then tags it vX.Y.Z and latest; Image + # Updater rolls the cluster onto the new digest (#1486). + if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest timeout-minutes: 30 permissions: @@ -173,18 +167,10 @@ jobs: attestations: write env: SERVICE_IMAGE: ghcr.io/${{ github.repository }}/service - # What the image is built from: every path the Dockerfile copies out of the build context, - # the Dockerfile and .dockerignore, and this workflow, which builds it. The image's - # io.github.dan-petty.devops-cli.image-inputs label holds the hash of their git entries, so - # a run can tell whether a published image was built from its own tree. - # tests/test_architectural_invariants.py keeps this list in step with the Dockerfile. - SERVICE_IMAGE_INPUTS: Dockerfile .dockerignore pyproject.toml uv.lock src .github/workflows/release.yml steps: - name: Check out repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - fetch-depth: 0 - name: Log in to GitHub Container Registry (GHCR) uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4 @@ -193,134 +179,21 @@ jobs: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - # Decides `action`: publish (build, push, attest, then tag), promote (point `latest` at the - # published image) or none. A tag main pins is never overwritten: main's run builds only a - # tag no image has, and a release branch stops publishing once main holds its version. An - # image counts as published only when release.yml attested it on main or on the release - # branch: a label is just its pusher's claim. `shell: bash` runs it with pipefail, as - # tests/test_release_service_image_plan.py does, and every command whose failure decides - # something sits in an assignment of its own, so errexit stops the step instead. - - name: Plan Service Image Publication - id: plan - shell: bash - env: - REF_NAME: ${{ github.ref_name }} - RELEASE_VERSION: ${{ needs.release.outputs.version }} - LABEL: io.github.dan-petty.devops-cli.image-inputs - GH_TOKEN: ${{ github.token }} - run: | - read -ra INPUT_PATHS <<< "$SERVICE_IMAGE_INPUTS" - INPUTS=$(git ls-tree HEAD -- "${INPUT_PATHS[@]}" | sha256sum | cut -d' ' -f1) - HEAD_VERSION=$(python3 -c "import tomllib; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])") - FORMAT="{{ .Manifest.Digest }} {{ index .Image.Config.Labels \"${LABEL}\" }}" - { - echo "inputs=${INPUTS}" - echo "label=${LABEL}" - echo "version=${HEAD_VERSION}" - } >> "$GITHUB_OUTPUT" - # Whether release.yml signed the provenance of digest $1 on main or on release/vX.Y.Z. - attested() { - gh attestation verify "oci://${SERVICE_IMAGE}@$1" -R "$GITHUB_REPOSITORY" \ - --cert-identity-regex "^https://github\.com/${GITHUB_REPOSITORY}/\.github/workflows/release\.yml@refs/heads/(main|release/v${HEAD_VERSION//./\\.})\$" >/dev/null - } - - if [[ "$GITHUB_REF" == refs/heads/release/v* ]]; then - if [ "$REF_NAME" != "release/v${HEAD_VERSION}" ]; then - echo "::notice::${REF_NAME} holds ${HEAD_VERSION}; it publishes its image once the cut sets ${REF_NAME#release/v}." - echo "action=none" >> "$GITHUB_OUTPUT" - exit 0 - fi - TIP=$(git ls-remote origin "refs/heads/${REF_NAME}" | cut -f1) - if [ "$TIP" != "$GITHUB_SHA" ]; then - echo "::notice::${GITHUB_SHA} is no longer the tip of ${REF_NAME}; the tip's run publishes." - echo "action=none" >> "$GITHUB_OUTPUT" - exit 0 - fi - git fetch --no-tags --quiet origin +refs/heads/main:refs/remotes/origin/main - MAIN_VERSION=$(git show origin/main:pyproject.toml | python3 -c "import sys, tomllib; print(tomllib.loads(sys.stdin.read())['project']['version'])") - if [ "$MAIN_VERSION" = "$HEAD_VERSION" ]; then - echo "::notice::main holds ${HEAD_VERSION}, so service:v${HEAD_VERSION} is the image main pins and is not replaced." - echo "action=none" >> "$GITHUB_OUTPUT" - exit 0 - fi - # The release pull request commits the merge of main and this branch, so the image - # built here is the one main pins only when that merge keeps these inputs. - if ! MERGED=$(git merge-tree --write-tree --no-messages origin/main HEAD); then - echo "::error::main does not merge cleanly into ${REF_NAME}. Merge main into ${REF_NAME} (RELEASE_CYCLE.md, Step 3)." - exit 1 - fi - MERGED_INPUTS=$(git ls-tree "$MERGED" -- "${INPUT_PATHS[@]}" | sha256sum | cut -d' ' -f1) - if [ "$MERGED_INPUTS" != "$INPUTS" ]; then - echo "::error::main has image changes ${REF_NAME} lacks, so the merged tree would differ from the image built here. Merge main into ${REF_NAME} (RELEASE_CYCLE.md, Step 3)." - exit 1 - fi - PUBLISHED=$(docker buildx imagetools inspect "${SERVICE_IMAGE}:v${HEAD_VERSION}" --format "$FORMAT" 2>/dev/null || true) - if [ "${PUBLISHED#* }" = "$INPUTS" ]; then - if attested "${PUBLISHED%% *}"; then - echo "::notice::service:v${HEAD_VERSION} (${PUBLISHED%% *}) was built and attested from these inputs already." - echo "action=none" >> "$GITHUB_OUTPUT" - exit 0 - fi - echo "::warning::service:v${HEAD_VERSION} (${PUBLISHED%% *}) claims these inputs, but release.yml did not attest it on main or ${REF_NAME}; publishing it again." - fi - { - echo "action=publish" - echo "latest=false" - } >> "$GITHUB_OUTPUT" - exit 0 - fi - - if [ "$HEAD_VERSION" != "$RELEASE_VERSION" ]; then - echo "::error::This tree holds ${HEAD_VERSION}, not ${RELEASE_VERSION}; service:v${RELEASE_VERSION} is published only from the tree that holds its version." - exit 1 - fi - if PUBLISHED=$(docker buildx imagetools inspect "${SERVICE_IMAGE}:v${HEAD_VERSION}" --format "$FORMAT" 2>"$RUNNER_TEMP/inspect.err"); then - if ! attested "${PUBLISHED%% *}"; then - echo "::error::service:v${HEAD_VERSION} (${PUBLISHED%% *}) has no provenance from release.yml on main or release/v${HEAD_VERSION} that could be verified, so latest is not pointed at it. Re-run this job; if it fails again, find who pushed that image." - exit 1 - fi - # A tag main pins is never replaced. The merged tree differs from the image when main - # moved after the branch's last push, or a push after the merge (a later fix, or the - # one that recovers a failed release run) changed the inputs: those changes ship in - # the next release. - if [ "${PUBLISHED#* }" != "$INPUTS" ]; then - echo "::warning::service:v${HEAD_VERSION} was built from inputs ${PUBLISHED#* }, not this tree's ${INPUTS}, and a tag main pins is never replaced; this tree's image changes ship in the next release (k8s/README.md, 'When a release merges into main')." - fi - { - echo "action=promote" - echo "digest=${PUBLISHED%% *}" - } >> "$GITHUB_OUTPUT" - elif grep -q ': not found$' "$RUNNER_TEMP/inspect.err"; then - echo "::warning::No release branch published service:v${HEAD_VERSION}; building it from this tree, and roadmap-service waits for it." - { - echo "action=publish" - echo "latest=true" - } >> "$GITHUB_OUTPUT" - else - echo "::error::Could not read service:v${HEAD_VERSION} from GHCR, so nothing was published; re-run this job." - cat "$RUNNER_TEMP/inspect.err" >&2 - exit 1 - fi - - name: Set up Docker Buildx - if: steps.plan.outputs.action == 'publish' uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v3 - name: Extract Metadata for Service Image - if: steps.plan.outputs.action == 'publish' id: meta uses: docker/metadata-action@8e671d84a3bd81afdfc4fdbb96a42b07c2a80934 # v5 with: images: ${{ env.SERVICE_IMAGE }} tags: | - type=raw,value=v${{ steps.plan.outputs.version }} - type=raw,value=latest,enable=${{ steps.plan.outputs.latest == 'true' }} + type=raw,value=v${{ needs.release.outputs.version }} + type=raw,value=latest labels: | org.opencontainers.image.licenses=MIT - ${{ steps.plan.outputs.label }}=${{ steps.plan.outputs.inputs }} - name: Build and Load Service Image - if: steps.plan.outputs.action == 'publish' uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v6 with: context: . @@ -332,7 +205,6 @@ jobs: cache-to: type=gha,mode=max - name: Run Service Image Smoke Test - if: steps.plan.outputs.action == 'publish' env: IMAGE: devops-cli-service:local run: | @@ -348,7 +220,6 @@ jobs: if docker run --rm --entrypoint python "$IMAGE" -c 'import pytest'; then exit 1; fi - name: Scan Service Image for Vulnerabilities - if: steps.plan.outputs.action == 'publish' uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 with: image-ref: devops-cli-service:local @@ -361,7 +232,6 @@ jobs: # Pushed by digest only: the tags move to the digest once its provenance is attested, so # a tag never names an unattested image and a failed attestation is retried by a re-run. - name: Build and Push Service Image - if: steps.plan.outputs.action == 'publish' id: push uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v6 with: @@ -373,49 +243,21 @@ jobs: cache-from: type=gha - name: Attest Build Provenance - if: steps.plan.outputs.action == 'publish' uses: actions/attest-build-provenance@9d57eef8c06cd9d6b433effeeb7a6a77b3ff94ad # v2 with: subject-name: ghcr.io/${{ github.repository }}/service subject-digest: ${{ steps.push.outputs.digest }} push-to-registry: true - # The plan ran minutes ago. On a release branch the release pull request may have merged - # since, or a newer push superseded this commit, so both are checked again right before - # the tag moves: once main holds the version, service:vX.Y.Z is never replaced. - name: Tag the Attested Service Image id: tag - if: steps.plan.outputs.action == 'publish' shell: bash env: DIGEST: ${{ steps.push.outputs.digest }} TAGS: ${{ steps.meta.outputs.tags }} - REF_NAME: ${{ github.ref_name }} - VERSION: ${{ steps.plan.outputs.version }} run: | - if [[ "$GITHUB_REF" == refs/heads/release/v* ]]; then - TIP=$(git ls-remote origin "refs/heads/${REF_NAME}" | cut -f1) - if [ "$TIP" != "$GITHUB_SHA" ]; then - echo "::notice::${GITHUB_SHA} is no longer the tip of ${REF_NAME}, so ${DIGEST} stays untagged; the tip's run tags its own image." - exit 0 - fi - git fetch --no-tags --quiet origin +refs/heads/main:refs/remotes/origin/main - MAIN_VERSION=$(git show origin/main:pyproject.toml | python3 -c "import sys, tomllib; print(tomllib.loads(sys.stdin.read())['project']['version'])") - if [ "$MAIN_VERSION" = "$VERSION" ]; then - echo "::error::main merged ${VERSION} while this run built ${DIGEST}, so it stays untagged: service:v${VERSION} is the image main pins and is never replaced. This commit's image changes ship in the next release." - exit 1 - fi - fi TAG_ARGS=() while read -r TAG; do if [ -n "$TAG" ]; then TAG_ARGS+=(--tag "$TAG"); fi done <<< "$TAGS" docker buildx imagetools create "${TAG_ARGS[@]}" "${SERVICE_IMAGE}@${DIGEST}" - - # The plan verified this digest's provenance from release.yml; `latest` is one more name - # for the same digest, so that provenance still verifies. - - name: Point latest at the Published Service Image - if: steps.plan.outputs.action == 'promote' - env: - DIGEST: ${{ steps.plan.outputs.digest }} - run: docker buildx imagetools create --tag "${SERVICE_IMAGE}:latest" "${SERVICE_IMAGE}@${DIGEST}" diff --git a/RELEASE_CYCLE.md b/RELEASE_CYCLE.md index 3dd149bb64..c51d5d85f2 100644 --- a/RELEASE_CYCLE.md +++ b/RELEASE_CYCLE.md @@ -162,7 +162,6 @@ sequenceDiagram Dev->>CLI: devops release prepare X.Y.Z --create-pr CLI->>Git: Push branch release/vX.Y.Z & Open Release PR - Git->>Rel: Push to release/vX.Y.Z publishes service:vX.Y.Z Git->>CI: Trigger CI Validation CI-->>Git: All validation checks passed (Green) Dev->>Git: Peer Review & PR Approval @@ -172,7 +171,7 @@ sequenceDiagram Rel->>Rel: Extract release notes (devops release notes) Rel->>Git: Auto-cut annotated tag vX.Y.Z Rel->>Git: Publish GitHub Release & Assets - Rel->>Rel: Point service:latest at service:vX.Y.Z + Rel->>Rel: Build, attest and tag service:vX.Y.Z and latest ``` ### Automated Release Cutting & Ruleset Bypass (`roadmap-service`) @@ -205,16 +204,14 @@ uv run devops release prepare X.Y.Z --create-pr - Documentation freshness (`devops docs check`) - Pytest unit tests and test coverage thresholds - Bandit static security scanning -2. Each push to `release/vX.Y.Z` that holds version X.Y.Z runs `release.yml`'s **Build & Publish Service Image**, so the image `main` will pin exists before the merge ([#1451](https://github.com/dan-petty/devops-cli/issues/1451)). When the image's inputs changed, or the tag's image has no provenance from `release.yml`, it builds, smoke-tests and scans `service:vX.Y.Z`, pushes it by digest, attests it and then tags it. `ci.yml`'s **Service Image** job skips the release PR for that reason. - - The check fails when `main` has image changes the branch lacks; commits on `main` that leave the image's inputs alone don't count. Merge `main` into the branch with a release-process pull request, which `devops pr check-readiness` exempts from grounding, and merge it with **Create a merge commit**, which the release ruleset allows: `git fetch origin`, `git switch -c chore/open-vX.Y.Z-main origin/main`, `git push -u origin chore/open-vX.Y.Z-main`, then `uv run devops pr create --base release/vX.Y.Z --title "chore(release): merge main into release/vX.Y.Z"`. - - Merge the release PR only with this check green. The run checks `main` again right before it tags, so a release PR merged while it runs leaves `service:vX.Y.Z` without that push's change, and the run fails. +2. `ci.yml`'s **Service Image** job builds, smoke-tests and scans the release PR's image without pushing; `release.yml` publishes it after the merge (Step 5). 3. Maintainers review the release diff, changelog, and documentation updates. ### A Critical Fix While the Release PR Is Open Opening the release PR cuts the release, and a critical fix (P0 with `type/bug` or `type/security`) still joins it, so the release branch holds every change before the release PR merges: 1. `devops roadmap intake` places the fix in the cut release, and `devops roadmap reprioritize` keeps it there with an "is cut, and a critical fix still joins it" comment. Intake places any other candidate with no milestone in the backlog, as after the start, and the start of a release a person cut before it pulls nothing in. 2. The fix's pull request targets `release/vX.Y.Z`. `devops pr check-readiness` accepts it because the issue it closes is in release vX.Y.Z. -3. The release PR's head is `release/vX.Y.Z`, so it picks up the fix's commit and its checks run again, and the push publishes `service:vX.Y.Z` again when the fix changed the image's inputs. Its description is not regenerated yet ([#1346](https://github.com/dan-petty/devops-cli/issues/1346)), so a person edits its list of deliverables and its notes. +3. The release PR's head is `release/vX.Y.Z`, so it picks up the fix's commit and its checks run again. Its description is not regenerated yet ([#1346](https://github.com/dan-petty/devops-cli/issues/1346)), so a person edits its list of deliverables and its notes. 4. The fix adds `changelog.d/.md` like any item. Once the release's fragments were collected into its `CHANGELOG.md` section, a person collects the late one before the release PR merges: a `chore/open-vX.Y.Z-collate-` pull request into `release/vX.Y.Z` moves its entries into the version's section and deletes it, as #1293 did for #1290 in v0.2.28. A fragment left behind is collected into the next release's section. [#1103](https://github.com/dan-petty/devops-cli/issues/1103) moves the collection to the release merge, which ends this step. 5. Merge the release PR only once its milestone holds no open item. [#1425](https://github.com/dan-petty/devops-cli/issues/1425) adds the check that enforces this, and makes `devops pr check-readiness` refuse a pull request into a release branch whose release PR has merged. If the release PR merged while an admitted fix was still open, move the fix to the next release: set its issue's milestone to vNEXT, and retarget its pull request with `uv run devops pr edit --base release/vNEXT`. Otherwise the fix stays in the shipped release, whose milestone `release.yml` closes, because no job moves an item out of a shipped release. @@ -230,7 +227,7 @@ Upon PR merge into `main`, [`.github/workflows/release.yml`](.github/workflows/r 2. Runs release verification without the CI suite (`devops release check --allow-dirty --skip-ci`). 3. Cuts and pushes the annotated git tag `vX.Y.Z`. 4. Extracts release notes using `devops release notes` and creates the official GitHub Release. -5. Points the Service image's `latest` at `service:vX.Y.Z`, which the release branch published, once its provenance from `release.yml` verifies. It never replaces `service:vX.Y.Z`: when the merged tree's image inputs differ from the image's (`main` moved after the branch's last push, or a later push to `main`, such as one that recovers a failed release run, changed them), it warns and those changes ship in the next release. It builds the image only when no image has that tag, and fails when the tag's image has no verifiable provenance. +5. Builds, smoke-tests and scans the Service image from the merged tree, pushes it by digest, attests its build provenance, then tags it `vX.Y.Z` and `latest`. Within one poll, Argo CD Image Updater moves Application `devops` to the new digest, and nothing is committed ([#1486](https://github.com/dan-petty/devops-cli/issues/1486)). Every run on `main`, such as a push that recovers a failed release run, rebuilds the image and moves both tags. ### Step 6: Post-Release DevContainer Validation Verify DevContainer lifecycle operations: diff --git a/changelog.d/1486.md b/changelog.d/1486.md new file mode 100644 index 0000000000..479b3903fc --- /dev/null +++ b/changelog.d/1486.md @@ -0,0 +1,8 @@ +### Changed +- The release no longer pins, bumps or pre-publishes the Service image's tag; Argo CD Image Updater rolls the Service onto `service:latest` (#1486). A release pull request's CI now builds, smoke-tests and scans the Service image without pushing it. On the merge to `main`, `release.yml` builds the image, scans it, pushes it by digest and attests its provenance, then tags it `vX.Y.Z` and `latest`, and Image Updater moves Application `devops` onto the new digest within one poll, with no git commit. + +### Removed +- The release cut's bump of the Service image's `newTag` and its rewrite of the Argo CD git sources' `targetRevision` (#1486). +- `devops release check`'s checks of the Service image pin and of the Argo CD `targetRevision`s (#1486). +- The `images:` pin in `k8s/devops/kustomization.yaml` (#1486). +- Service image publishing from `release/vX.Y.Z` in `release.yml`, with its publication plan and the step that pointed `latest` at an image the release branch published (#1486). diff --git a/docs/ROUTINE_TASKS.md b/docs/ROUTINE_TASKS.md index 7a64862c26..118dad812d 100644 --- a/docs/ROUTINE_TASKS.md +++ b/docs/ROUTINE_TASKS.md @@ -253,10 +253,9 @@ sequenceDiagram participant Hub as GitHub (Main & Releases) Maintainer->>Branch: devops roadmap close --confirm (closes items, cuts the release on release/vX.Y.Z) - Branch->>CI: release.yml publishes service:vX.Y.Z Branch->>CI: Quality Gates Validate Release PR Maintainer->>Hub: Squash-Merge Release PR into main once its checks are green - CI->>Hub: release.yml cuts tag, creates release, closes milestone, points service:latest at service:vX.Y.Z + CI->>Hub: release.yml cuts tag, creates release, closes milestone, builds, attests and tags service:vX.Y.Z and latest ``` #### Step-by-Step Procedure: @@ -265,10 +264,10 @@ sequenceDiagram - Bumps version in `pyproject.toml` (`__init__.py` derives `__version__` from it). - Collects the `changelog.d/` fragments into the target version's block in `CHANGELOG.md` and deletes them, leaving `[Unreleased]` an empty heading. - Regenerates docs and updates README Command Matrix. - - Commits the bumps on `release/v`, pushes it, and opens a GitHub Release PR from it into `main` titled `feat(release): v`. The push publishes `service:v` (step 5). + - Commits the bumps on `release/v`, pushes it, and opens a GitHub Release PR from it into `main` titled `feat(release): v`. 3. **Run Authoritative Release Check**: Run `uv run devops release check` to verify tree cleanliness, version matching, and CI validation. -4. **Human Maintainer Merge**: The maintainer reviews the Release PR and squash-merges it into `main` once its checks are green, **Build & Publish Service Image** included (`uv run devops pr check-readiness ` passes). Merged while that check is still running, the release can pin an image without the branch's last change (`k8s/README.md`, "When a release merges into main"). -5. **Automated Publishing & Milestone Closure**: GitHub Actions (`release.yml`) cuts the git tag, extracts release notes with `devops release notes` (over GitHub's 125,000-character Release body limit, each entry's title alone and a link to the version's section of `CHANGELOG.md` at its tag), creates the GitHub Release, closes the release milestone via `devops gh milestones close `, publishes the pre-built DevContainer image, and points the production service image's `latest` at `service:v`, which `release.yml` published and attested from `release/v` before the merge, once that provenance verifies (verified via `gh attestation verify oci://ghcr.io/dan-petty/devops-cli/service:v -R dan-petty/devops-cli --signer-workflow dan-petty/devops-cli/.github/workflows/release.yml --source-ref refs/heads/release/v`; `--source-ref refs/heads/main` when the release merged over a failed check and `main`'s run built the image). +4. **Human Maintainer Merge**: The maintainer reviews the Release PR and squash-merges it into `main` once its checks are green (`uv run devops pr check-readiness ` passes). +5. **Automated Publishing & Milestone Closure**: GitHub Actions (`release.yml`) cuts the git tag, extracts release notes with `devops release notes` (over GitHub's 125,000-character Release body limit, each entry's title alone and a link to the version's section of `CHANGELOG.md` at its tag), creates the GitHub Release, closes the release milestone via `devops gh milestones close `, publishes the pre-built DevContainer image, and builds, scans, pushes and attests the production service image `service:v` from `main` before tagging it `v` and `latest`; Argo CD Image Updater then rolls the Service onto the new digest (verified via `gh attestation verify oci://ghcr.io/dan-petty/devops-cli/service:v -R dan-petty/devops-cli --signer-workflow dan-petty/devops-cli/.github/workflows/release.yml --source-ref refs/heads/main`). 6. **Post-Release DevContainer Validation**: Run `uv run devops devcontainer run-lifecycle --all` to verify container lifecycle tasks. 7. **Next Active Milestone Initialization & Issue/Views Population**: - Cut and push the next release branch (`release/vX.Y.Z`) from `main`. diff --git a/docs/agent/tasks/task-1261-argocd-target-revision-main.md b/docs/agent/tasks/task-1261-argocd-target-revision-main.md index 86a83d0000..2aa7a05b34 100644 --- a/docs/agent/tasks/task-1261-argocd-target-revision-main.md +++ b/docs/agent/tasks/task-1261-argocd-target-revision-main.md @@ -6,6 +6,8 @@ **Priority**: priority/p1-high **Scope**: type/bug, scope/k8s +> **Superseded in part by #1486.** It removed the cut's `targetRevision` rewrite and `devops release check`'s check, and the service-image pin; `tests/test_k8s_argocd_apps.py` holds the git sources on `main`. + --- ## 1. Description & Objectives diff --git a/docs/agent/tasks/task-1451-image-before-main-pins-it.md b/docs/agent/tasks/task-1451-image-before-main-pins-it.md index d7e9e3fdc8..7b0ebc5a1a 100644 --- a/docs/agent/tasks/task-1451-image-before-main-pins-it.md +++ b/docs/agent/tasks/task-1451-image-before-main-pins-it.md @@ -6,6 +6,8 @@ **Priority**: P2-Medium (set by intake on 2026-10-08) **Scope**: type/bug, scope/k8s, scope/ci, scope/release +> **Superseded by #1486.** Release-branch publishing, the plan step and the promote step are gone: `release.yml` builds, attests and tags the Service image only on `main`, and Image Updater rolls it out. + ## Description The release cut sets `newTag: vX.Y.Z` for `ghcr.io/dan-petty/devops-cli/service` in `k8s/devops/kustomization.yaml`. Argo CD's `devops` Application tracks `main` and syncs about two minutes after the release merges, but `release.yml` published the image only at the end of its run on `main` (23:43:28 to 23:50:20 for v0.2.28). roadmap-service uses the Recreate strategy, so its pod was stopped and its replacement backed off on the missing image for several minutes, and for as long as the release run stayed red (v0.2.27). diff --git a/docs/agent/tasks/task-1486-release-drops-service-image-tag.md b/docs/agent/tasks/task-1486-release-drops-service-image-tag.md new file mode 100644 index 0000000000..bded49542d --- /dev/null +++ b/docs/agent/tasks/task-1486-release-drops-service-image-tag.md @@ -0,0 +1,54 @@ +# Task: The release no longer pins, bumps or pre-publishes the service image tag; Image Updater rolls service:latest (#1486) + +**Issue**: [#1486](https://github.com/dan-petty/devops-cli/issues/1486) +**Status**: Done +**Milestone**: v0.2.32 +**Priority**: priority/p2-medium +**Scope**: type/refactor, scope/release + +## Description + +The owner asked on 2026-10-09 to remove the custom process that updated the Service image tag. Since #1485 (v0.2.31), Argo CD Image Updater keeps Application `devops` on the digest `ghcr.io/dan-petty/devops-cli/service:latest` points at, so the pin, its bump, its check and release-branch publishing had become redundant. This item removes them and keeps building the image. + +- **The cut and `release check`.** The cut no longer sets `newTag` in `k8s/devops/kustomization.yaml` or rewrites the Argo CD git sources' `targetRevision`, and `_release_paths` stages nothing under `k8s/`. `devops release check` no longer checks the pin or the `targetRevision`s: `test_git_sources_and_revisions` (`tests/test_k8s_argocd_apps.py`) already holds every git source, `bootstrap` and `cluster` included, on `main`. `CONST_SERVICE_IMAGE`, `CONST_SERVICE_IMAGE_KUSTOMIZATION` and the `updated_service_image_tag` message are gone. +- **The manifests.** `k8s/devops/kustomization.yaml` has no `images:` block. Git names the image untagged, and Image Updater's `spec.source.kustomize.images` entry on Application `devops` sets `service:latest@sha256:`. +- **`release.yml`.** It has no `release/v*` push trigger. The service-image job runs only when `github.ref == 'refs/heads/main'` (a push to `main`, or a dispatch from `main`), after the release job succeeds. It builds, smoke-tests and scans the image, pushes it by digest, attests its provenance, then tags it `vX.Y.Z` and `latest`. The plan step, `SERVICE_IMAGE_INPUTS` and the inputs label, the release-branch checks in the tag step, the promote step and the checkout's `fetch-depth: 0` (only the plan used the history) are gone. +- **`ci.yml`.** The **Service Image** job no longer skips release pull requests: it builds, smoke-tests and scans the image of every pull request into `main` without pushing it. +- **Docs.** RELEASE_CYCLE.md (the sequence diagram, Step 3 item 2, the critical-fix item 3 and Step 5 item 5), docs/ROUTINE_TASKS.md (the diagram and steps 2, 4 and 5) and k8s/README.md ("When a release merges into `main`" steps 1 and 3, "Service Image Updates" and the directory tree) describe the new flow. The task files of #1451, #741, #1261 and #755 each carry a one-line note naming what this item removed. + +## Acceptance Criteria + +- [x] No file in the repository and no step of the release writes or checks a Service image tag: no `images:` pin, no `newTag` bump, no pin check in `devops release check`, no `targetRevision` rewrite. `test_release_prepare_leaves_k8s_untouched` (`tests/test_release.py`) runs `devops release prepare 0.1.8` over a kustomization pinning `v0.1.7` and an Application on `release/v0.1.7`: both files stay byte-identical, and `_release_paths` names nothing under `k8s/`. `test_kustomization_lists_every_manifest_and_pins_no_image_and_stays_out_of_the_root` (`tests/test_k8s_devops_runtime.py`) holds the kustomization free of `images`, and `test_both_workloads_run_the_digest_image_updater_sets_and_pull_it_only_when_missing` still renders both workloads on Image Updater's digest without the pin. +- [x] `release.yml` runs the Service image job only on `main`, pushes it by digest, attests it and only then tags `vX.Y.Z` and `latest`, and has no release-branch trigger, plan or promote step. `test_service_image_release_job_invariants` (`tests/test_ci.py`) pins the trigger, the job's condition, needs and permissions, the absence of the plan, its gates and the promote step, the step order, the metadata tags, the push by digest with no tags and an SBOM, the tag step, the Trivy inputs, and no `${{` in a `run:` block. +- [x] `ci.yml` builds the release PR's Service image without pushing. `test_service_image_ci_job_invariants` (`tests/test_ci.py`) pins a condition with no release-branch or head-repository clause, read-only permissions, and a build that loads and does not push. +- [x] The removed tests are gone: `tests/test_release_service_image_plan.py`, the pin, bump and `targetRevision` tests in `tests/test_release.py`, `test_the_kustomization_survives_the_release_bump_rewrite` (`tests/test_k8s_devops_runtime.py`) and `test_release_service_image_inputs_are_what_the_image_is_built_from` (`tests/test_architectural_invariants.py`). +- [x] RELEASE_CYCLE.md, docs/ROUTINE_TASKS.md and k8s/README.md describe the new flow, and the #1451 task file notes it is superseded by this item. +- [x] `changelog.d/1486.md`. +- Pending a person: once this is on `release/v0.2.32`, `gh run list -R dan-petty/devops-cli --workflow release.yml --branch release/v0.2.32 --limit 3` lists no run that a push started after it. +- Pending a person: the v0.2.32 release pull request shows `ci.yml`'s **Service Image** check (build, smoke test, Trivy) green, and no **Build & Publish Service Image** check. +- Pending a person: right after the release merges, `devops argo cd apps status devops` is Synced and Healthy, and the roadmap-service pod has not restarted: `kubectl -n devops get pods -l app.kubernetes.io/name=roadmap-service -o jsonpath='{.items[*].spec.containers[*].image}'` still names the previous `service:latest@sha256:` digest. +- Pending a person: in the `release.yml` run on `main` (`gh run list -R dan-petty/devops-cli --workflow release.yml --branch main --limit 1`), the job **Build & Publish Service Image** builds, scans, pushes, attests and tags. +- Pending a person: `docker buildx imagetools inspect ghcr.io/dan-petty/devops-cli/service:latest --format '{{ .Manifest.Digest }}'` and the same for `service:v0.2.32` print the same digest, and `gh attestation verify oci://ghcr.io/dan-petty/devops-cli/service:v0.2.32 -R dan-petty/devops-cli --signer-workflow dan-petty/devops-cli/.github/workflows/release.yml --source-ref refs/heads/main` passes. +- Pending a person: within about two minutes, `kubectl -n argocd get imageupdater devops -o jsonpath='{.status.recentUpdates}'` records that digest, `kubectl -n argocd get application devops -o jsonpath='{.spec.source.kustomize.images}'` holds it, and the roadmap-service pod's `imageID` (`kubectl -n devops get pods -l app.kubernetes.io/name=roadmap-service -o jsonpath='{.items[*].status.containerStatuses[*].imageID}'`) and CronJob `devops-cli`'s image (`kubectl -n devops get cronjob devops-cli -o jsonpath='{.spec.jobTemplate.spec.template.spec.containers[*].image}'`) carry it. +- Pending a person: `git log origin/main -- k8s/devops/kustomization.yaml` shows no commit after the release merge. + +## Decisions and Deviations + +- **The job runs only when `github.ref` is `refs/heads/main`.** One clause covers a push to `main` and a dispatch from `main`, and `success()` of `needs: release` is implied. A dispatch from another branch, or a tag push, runs the release job but publishes no Service image, so nothing but `main` moves `latest`, which Image Updater deploys within one poll. +- **Every run on `main` rebuilds the image and moves both tags.** `release.yml` runs on every push to `main`, and its release job already re-publishes the GitHub Release and the devcontainer's `vX.Y.Z,latest` each time. A later push, such as one that recovers a failed release run, builds the image from `main`'s tree, moves `vX.Y.Z` and `latest`, and Image Updater rolls the workloads onto it. No guard was added. +- **A dispatch's `version` input names the image.** The image takes the version the GitHub Release takes, `needs.release.outputs.version`; the plan's check that the tree holds that version is gone, and no guard replaces it. +- **A re-created Application renders the untagged image.** Until Image Updater's next poll writes the digest again, a re-created `devops` Application renders `ghcr.io/dan-petty/devops-cli/service` with no tag (`latest`); with `imagePullPolicy: IfNotPresent` a node pulls it only when it holds no copy. +- **The merge's own sync restarts nothing.** Image Updater's `kustomize.images` entry already outranked the pin, so removing the pin leaves the rendered image, `service:latest@sha256:`, unchanged until `latest` moves. +- **Release pull requests no longer need `main` merged in for the image.** The plan step compared the release branch's image inputs with the merge of `main`; `ci.yml` builds the pull request's merge commit, and `release.yml` builds `main`'s tree, so neither needs it. +- **#755's task file got a note too.** It still described the cut rewriting `targetRevision`, which this item removes, so it carries a one-line note like those of #1451, #741 and #1261. #1485's task file already scopes the pin "until #1486" and stays as it is. + +## Deliverables + +- [x] `src/devops_cli/commands/release.py`: the pin, bump, `targetRevision` rewrite and their checks removed; `_release_paths` stages nothing under `k8s/`. +- [x] `src/devops_cli/config/constants.py`, `src/devops_cli/lang/en/messages.py`: the service-image constants and message removed. +- [x] `k8s/devops/kustomization.yaml`: the `images:` block removed. +- [x] `.github/workflows/release.yml`, `.github/workflows/ci.yml`. +- [x] `tests/test_release.py`, `tests/test_ci.py`, `tests/test_k8s_devops_runtime.py`, `tests/test_architectural_invariants.py`; `tests/test_release_service_image_plan.py` deleted. +- [x] RELEASE_CYCLE.md, docs/ROUTINE_TASKS.md, k8s/README.md. +- [x] Notes in the task files of #1451, #741, #1261 and #755. +- [x] `changelog.d/1486.md`. diff --git a/docs/agent/tasks/task-741-devops-cli-in-cluster.md b/docs/agent/tasks/task-741-devops-cli-in-cluster.md index e650da5e2c..5ca19eda3c 100644 --- a/docs/agent/tasks/task-741-devops-cli-in-cluster.md +++ b/docs/agent/tasks/task-741-devops-cli-in-cluster.md @@ -6,6 +6,8 @@ **Priority**: priority/p1-high **Scope**: type/feature, scope/k8s, priority/p1-high +> **Superseded in part by #1486.** The service-image pin in `k8s/devops/kustomization.yaml`, its bump in the cut and its check in `devops release check` were removed; Image Updater sets the image's digest. + ## Description devops-cli runs in the homelab cluster as Jobs made from a suspended CronJob in namespace `devops`, so agents drive it with kubectl and never handle keys, and model calls reach the gateway without the tunnel's edge timeout. Every Secret the stacks read comes from the workstation keyring through one table (`src/devops_cli/k8s/cluster_secrets.py`) and one command, `devops k8s push-secrets`, which `devops k8s deploy-stack` runs before applying anything. It replaces the hand-run `--from-literal` steps and deploy-stack's client-side Qdrant Secret apply, which leaked the key into the last-applied annotation. diff --git a/docs/agent/tasks/task-755-argocd-reconciles-cluster.md b/docs/agent/tasks/task-755-argocd-reconciles-cluster.md index 40b88ccc06..71ddfc359c 100644 --- a/docs/agent/tasks/task-755-argocd-reconciles-cluster.md +++ b/docs/agent/tasks/task-755-argocd-reconciles-cluster.md @@ -6,6 +6,8 @@ **Priority**: priority/p1-high **Scope**: type/feature, scope/k8s +> **Superseded in part by #1261 and #1486.** The git sources track `main` (#1261), and the cut's `targetRevision` rewrite and `devops release check`'s check are gone (#1486); `tests/test_k8s_argocd_apps.py` holds them on `main`. + --- ## 1. Description & Objectives diff --git a/k8s/README.md b/k8s/README.md index ca34bae122..1fdcaabb5c 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -398,9 +398,9 @@ These values exist only in the cluster and in `config.yaml`. Once `cluster` has #### When a release merges into `main` -1. The Applications track `main` (`devops release check` holds them there), so a merge moves `main` forward and the host patches stay in place. Run `devops k8s deploy-stack --stack devops --argocd-revision release/vX.Y.Z` from a checkout of the release, right before merging, when the release changes `k8s/devops/configmap.example.yaml` (the ConfigMap follows only deploy-stack) or adds, removes, renames or reorders an Ingress or IngressRoute, or a host in one. If the release moved a host that `main` also renders, the Application shows the ComparisonError `testing value failed` until the merge, and its live Ingresses stay as they were. +1. The Applications track `main` (`tests/test_k8s_argocd_apps.py` holds them there), so a merge moves `main` forward and the host patches stay in place. Run `devops k8s deploy-stack --stack devops --argocd-revision release/vX.Y.Z` from a checkout of the release, right before merging, when the release changes `k8s/devops/configmap.example.yaml` (the ConfigMap follows only deploy-stack) or adds, removes, renames or reorders an Ingress or IngressRoute, or a host in one. If the release moved a host that `main` also renders, the Application shows the ComparisonError `testing value failed` until the merge, and its live Ingresses stay as they were. 2. Merge. Argo CD builds the release with the staged hosts. -3. The Release Orchestration workflow publishes `service:vX.Y.Z` from `release/vX.Y.Z` before the merge. Each push to that branch, once it holds version X.Y.Z, builds, smoke-tests, scans, attests and tags the image when its inputs (`SERVICE_IMAGE_INPUTS` in `release.yml`) changed, and the release pull request shows the result as the **Build & Publish Service Image** check; merge only with it green. Until the merge each such push replaces `service:vX.Y.Z`, so don't run that tag on the cluster before then: with `imagePullPolicy: IfNotPresent` a node keeps the image it pulled first. Once `main` holds the version, a branch run no longer moves the tag: it checks `main` again right before it tags and fails instead (only a merge in the seconds between that check and the tag slips past it), so a merge while the check runs ships the image without that push's change. The workflow's run on `main` points `latest` at the same image once its provenance from `release.yml` verifies. When the image was built from other inputs than `main`'s tree (`main` moved after the branch's last push, or a later push to `main` changed them), it warns and leaves the image alone; ship the difference in the next release. If no image has the tag, because the release merged over a failed check, that run builds it and tags it `latest` too. Within one poll of `latest` moving, Image Updater puts the `devops` Application on its new digest ([Service Image Updates](#service-image-updates)), and roadmap-service, which uses the Recreate strategy, is down only while its pod restarts. Until then both workloads keep the previous release's digest, although `main` pins `service:vX.Y.Z`, so the sync after the merge never waits for an image that is not published yet. +3. On the merge, the Release Orchestration workflow's run on `main` builds, smoke-tests, scans, pushes and attests `service:vX.Y.Z`, then tags it `vX.Y.Z` and `latest`. Within one poll of `latest` moving, Image Updater puts the `devops` Application on the new digest ([Service Image Updates](#service-image-updates)), and roadmap-service, which uses the Recreate strategy, is down only while its pod restarts. Until then both workloads keep the previous release's digest: the merge's own sync changes no image, and nothing is committed. A later run on `main`, such as one that recovers a failed release run, rebuilds the image and moves both tags, and Image Updater rolls the workloads onto it. 4. Check: `devops argo cd apps status devops` and `devops argo cd apps status ingress` are Synced and Healthy, ImageUpdater `devops` is Ready and the `devops` Application's `spec.source.kustomize.images` names the digest `service:latest` points at ([Service Image Updates](#service-image-updates)), `kubectl get ingress,ingressroute -A -o yaml | grep example.com` prints nothing, and `kubectl -n devops get configmap devops-cli-config -o yaml` holds the configured repositories and the release's template values (gateway URL, models, context windows). > [!NOTE] @@ -410,8 +410,8 @@ These values exist only in the cluster and in `config.yaml`. Once `cluster` has Application `argocd-image-updater` runs [Argo CD Image Updater](https://argocd-image-updater.readthedocs.io/en/stable/) in namespace `argocd`, from the argo-helm chart pinned to a version like the other chart Applications. Its one ImageUpdater, `devops` in `k8s/argocd/image-updater-values.yaml`, keeps the `devops` Application on the digest `ghcr.io/dan-petty/devops-cli/service:latest` points at: -- Every two minutes it reads that digest. When the Application runs another one, it writes `ghcr.io/dan-petty/devops-cli/service:latest@sha256:` into the Application's `spec.source.kustomize.images`, and Argo CD rolls roadmap-service and CronJob `devops-cli` onto it. That entry outranks the `newTag` pin in `k8s/devops/kustomization.yaml`. -- It commits nothing to git. The `cluster` Application leaves `spec.source.kustomize` on `devops` alone, as it does for the host patches, and deploy-stack's merge patch replaces only `kustomize.patches`. If the `devops` Application is re-created, it renders the git pin until the next poll writes the digest again. +- Every two minutes it reads that digest. When the Application runs another one, it writes `ghcr.io/dan-petty/devops-cli/service:latest@sha256:` into the Application's `spec.source.kustomize.images`, and Argo CD rolls roadmap-service and CronJob `devops-cli` onto it. Git names the image untagged, and that entry sets its tag and digest. +- It commits nothing to git. The `cluster` Application leaves `spec.source.kustomize` on `devops` alone, as it does for the host patches, and deploy-stack's merge patch replaces only `kustomize.patches`. If the `devops` Application is re-created, it renders the untagged image (`latest`; with `IfNotPresent` a node pulls it only when missing) until the next poll writes the digest again. - Both containers set `imagePullPolicy: IfNotPresent`, so a node pulls a digest once, and a registry outage does not block a restart onto an image the node holds. - It acts only on Argo CD Applications, so a native `devops k8s deploy-stack` installs no release of it: a cluster without Argo CD has no Application to update, and its devops stack runs the untagged image, `latest`. @@ -563,7 +563,7 @@ k8s/ │ ├── deployment.yaml # Multi-replica non-root cloudflared deployment │ └── networkpolicy.yaml # Network isolation for tunnel ingress and egress ├── devops/ # In-cluster devops-cli runtime; not in the root kustomization -│ ├── kustomization.yaml # Its resources, and the service image's tag (`devops release prepare` sets it; Image Updater's digest on Application devops outranks it) +│ ├── kustomization.yaml # Its resources; Image Updater sets the service image's digest on Application devops │ ├── serviceaccount.yaml # devops-cli service account without an API token │ ├── configmap.example.yaml # devops-cli config template: deploy-stack renders ConfigMap devops-cli-config from it and config.yaml │ ├── cronjob.yaml # Suspended CronJob devops-cli, the template of every cluster job diff --git a/k8s/devops/kustomization.yaml b/k8s/devops/kustomization.yaml index bab140b827..ca8f478e7c 100644 --- a/k8s/devops/kustomization.yaml +++ b/k8s/devops/kustomization.yaml @@ -5,6 +5,3 @@ resources: - cronjob.yaml - networkpolicy.yaml - roadmap-service -images: -- name: ghcr.io/dan-petty/devops-cli/service - newTag: v0.2.31 diff --git a/src/devops_cli/commands/release.py b/src/devops_cli/commands/release.py index 2bc579ced4..efe8cef0da 100644 --- a/src/devops_cli/commands/release.py +++ b/src/devops_cli/commands/release.py @@ -32,8 +32,6 @@ CONST_INIT_PY_PATH, CONST_PYPROJECT_FILENAME, CONST_README_FILENAME, - CONST_SERVICE_IMAGE, - CONST_SERVICE_IMAGE_KUSTOMIZATION, CONST_UV_LOCK_FILENAME, ) from devops_cli.config.defaults import ( @@ -155,166 +153,6 @@ def _get_init_version(root: Path) -> str | None: return None -def _service_image_entries(document: Any) -> list[dict[str, Any]]: - """The kustomization's `images:` entries for the service image.""" - images = document.get("images") if isinstance(document, dict) else None - return [ - image - for image in images or [] - if isinstance(image, dict) and image.get("name") == CONST_SERVICE_IMAGE - ] - - -def _load_service_image_kustomization(root: Path) -> tuple[Path, Any] | None: - """The runtime kustomization's path and parsed document, or None where there is none.""" - import yaml - - path = _resolve_safe_project_path(root, CONST_SERVICE_IMAGE_KUSTOMIZATION) - if not path.exists(): - return None - return path, yaml.safe_load(path.read_text(encoding="utf-8")) - - -def _get_service_image_tag(root: Path) -> str | None: - """The tag the runtime kustomization pins the service image to, or None where it has none.""" - loaded = _load_service_image_kustomization(root) - entries = _service_image_entries(loaded[1]) if loaded else [] - return str(entries[0].get("newTag")) if entries else None - - -def _update_service_image_tag(root: Path, new_version: str) -> bool: - """Pin the runtime kustomization's service image to `v`; False where it has none.""" - import yaml - - from devops_cli.output import write_text_file - - loaded = _load_service_image_kustomization(root) - entries = _service_image_entries(loaded[1]) if loaded else [] - if not loaded or not entries: - return False - for entry in entries: - entry["newTag"] = f"v{new_version}" - write_text_file(loaded[0], yaml.safe_dump(loaded[1], sort_keys=False)) - return True - - -def _extract_git_revisions_from_doc(doc: Any) -> list[str]: - """Extract git targetRevision values from an Argo CD Application doc.""" - if not isinstance(doc, dict) or doc.get("kind") != "Application": - return [] - spec = doc.get("spec", {}) - revisions: list[str] = [] - source = spec.get("source") - if isinstance(source, dict) and "chart" not in source and "targetRevision" in source: - revisions.append(str(source["targetRevision"])) - for s in spec.get("sources", []): - if isinstance(s, dict) and "chart" not in s and "targetRevision" in s: - revisions.append(str(s["targetRevision"])) - return revisions - - -def _get_argocd_git_target_revisions(root: Path) -> list[tuple[Path, str]]: - """Return (file_path, target_revision) for every git source in Applications under k8s/argocd/.""" - import yaml - - argocd_dir = root / "k8s" / "argocd" - if not argocd_dir.is_dir(): - return [] - - results: list[tuple[Path, str]] = [] - for path in sorted(argocd_dir.rglob("*.yaml")): - try: - content = path.read_text(encoding="utf-8") - for doc in yaml.safe_load_all(content): - for rev in _extract_git_revisions_from_doc(doc): - results.append((path, rev)) - except Exception: - continue - return results - - -def _resolve_argocd_next_revision(root: Path, current_version: str) -> str | None: - """Resolve targetRevision for Argo CD manifests to 'main'.""" - git_revisions = _get_argocd_git_target_revisions(root) - if not git_revisions: - return None - return "main" - - -def _apply_git_revision_to_doc(doc: Any, next_revision: str) -> bool: - """Update git-source targetRevisions in an Application doc to next_revision.""" - if not isinstance(doc, dict) or doc.get("kind") != "Application": - return False - spec = doc.get("spec", {}) - changed = False - source = spec.get("source") - if isinstance(source, dict) and "chart" not in source and "targetRevision" in source: - if source["targetRevision"] != next_revision: - source["targetRevision"] = next_revision - changed = True - for s in spec.get("sources", []): - if isinstance(s, dict) and "chart" not in s and "targetRevision" in s: - if s["targetRevision"] != next_revision: - s["targetRevision"] = next_revision - changed = True - return changed - - -def _apply_argocd_target_revisions(root: Path, next_revision: str) -> bool: - """Rewrite git-source targetRevisions under k8s/argocd/ to next_revision.""" - import yaml - - from devops_cli.output import write_text_file - - argocd_dir = root / "k8s" / "argocd" - if not argocd_dir.is_dir(): - return False - - updated = False - for path in sorted(argocd_dir.rglob("*.yaml")): - try: - docs = list(yaml.safe_load_all(path.read_text(encoding="utf-8"))) - except Exception: - continue - - file_changed = any(_apply_git_revision_to_doc(d, next_revision) for d in docs) - if file_changed: - content = ( - yaml.safe_dump_all(docs, sort_keys=False) - if len(docs) > 1 - else yaml.safe_dump(docs[0], sort_keys=False) - ) - write_text_file(path, content) - updated = True - return updated - - -def _verify_argocd_target_revisions(repo_root: Path, pyproject_ver: str) -> None: - """Verify git targetRevisions under k8s/argocd/ are uniform and match 'main'.""" - revisions = _get_argocd_git_target_revisions(repo_root) - if not revisions: - return - - rev_set = {rev for _, rev in revisions} - if len(rev_set) > 1: - _get("print_error")( - f"Argo CD git-source targetRevisions mismatch under k8s/argocd/: found multiple revisions {sorted(rev_set)}. " - "They must be uniform.", - prefix=False, - ) - raise typer.Exit(1) - - rev = next(iter(rev_set)) - expected = "main" - if rev != expected: - _get("print_error")( - f"Version mismatch: Argo CD git-source targetRevision '{rev}' does not match expected '{expected}'. " - f"Run `devops release prepare {pyproject_ver}`.", - prefix=False, - ) - raise typer.Exit(1) - - def _get_latest_git_tag(root: Path) -> str | None: """Retrieve latest git tag if git is available.""" from devops_cli.git.operations import get_latest_git_tag @@ -786,8 +624,7 @@ def _release_paths(root: Path) -> list[str]: """The paths a release commit stages. `changelog.d/` is among them where it exists, so the commit records the fragments the cut - deleted, and so is the runtime kustomization whose image tag the bump sets; naming a path - that does not exist would fail the whole `git add`. + deleted; naming a path that does not exist would fail the whole `git add`. """ paths = [ CONST_PYPROJECT_FILENAME, @@ -800,10 +637,6 @@ def _release_paths(root: Path) -> list[str]: paths.append(CONST_UV_LOCK_FILENAME) if (root / CONST_CHANGELOG_FRAGMENTS_DIR).is_dir(): paths.append(f"{CONST_CHANGELOG_FRAGMENTS_DIR}/") - if (root / CONST_SERVICE_IMAGE_KUSTOMIZATION).is_file(): - paths.append(str(CONST_SERVICE_IMAGE_KUSTOMIZATION)) - if (root / "k8s" / "argocd").is_dir(): - paths.append("k8s/argocd/") return paths @@ -1196,22 +1029,11 @@ def _checkout_cut_branch(root: Path, cut_branch: str, remote_ref: str) -> None: def _apply_cut_modifications(root: Path, version: str, sync_docs: bool) -> None: - """Apply version bumps to pyproject, init, image tag, uv.lock, argocd revisions, and optionally sync docs.""" - next_revision = _resolve_argocd_next_revision(root, version) + """Apply version bumps to pyproject, init, uv.lock, and optionally docs.""" if _update_pyproject_version(root, version): _get("print_info")(MESSAGES.release.updated_pyproject.format(version=version), prefix=False) if _update_init_version(root, version): _get("print_info")(MESSAGES.release.updated_init.format(version=version), prefix=False) - if _update_service_image_tag(root, version): - _get("print_info")( - MESSAGES.release.updated_service_image_tag.format(version=version), - prefix=False, - ) - if next_revision and _apply_argocd_target_revisions(root, next_revision): - _get("print_info")( - f"Updated Argo CD git-source targetRevisions under k8s/argocd/ to {next_revision}.", - prefix=False, - ) if _update_uv_lock_version(root, version): _get("print_info")(f"Updated {CONST_UV_LOCK_FILENAME} to version {version}.", prefix=False) if sync_docs: @@ -1640,8 +1462,7 @@ def release_pr( def _verify_release_versions(repo_root: Path) -> str: - """Verify version consistency across pyproject.toml, __init__.py, the service image tag and - CHANGELOG.md.""" + """Verify version consistency across pyproject.toml, __init__.py and CHANGELOG.md.""" pyproject_ver = _get_pyproject_version(repo_root) init_ver = _get_init_version(repo_root) changelog_ver = _get_latest_changelog_version(repo_root) @@ -1654,15 +1475,6 @@ def _verify_release_versions(repo_root: Path) -> str: ) raise typer.Exit(1) - image_tag = _get_service_image_tag(repo_root) - if image_tag is not None and image_tag != f"v{pyproject_ver}": - _get("print_error")( - f"Version mismatch: {CONST_SERVICE_IMAGE_KUSTOMIZATION} pins {CONST_SERVICE_IMAGE} " - f"to {image_tag}, not v{pyproject_ver}. Run `devops release prepare {pyproject_ver}`.", - prefix=False, - ) - raise typer.Exit(1) - if not changelog_ver or changelog_ver != pyproject_ver: _get("print_error")( f"Version mismatch: CHANGELOG.md ({changelog_ver or 'missing'}) does not match " @@ -1680,8 +1492,6 @@ def _verify_release_versions(repo_root: Path) -> str: ) raise typer.Exit(1) - _verify_argocd_target_revisions(repo_root, pyproject_ver) - return pyproject_ver diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 8cb1f4047c..742c8e67b1 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -39,9 +39,6 @@ CONST_CHANGELOG_FILENAME = "CHANGELOG.md" CONST_README_FILENAME = "README.md" CONST_INIT_PY_PATH = Path("src/devops_cli/__init__.py") -# The in-cluster runtime's kustomization pins the service image to the release's tag (#741). -CONST_SERVICE_IMAGE = "ghcr.io/dan-petty/devops-cli/service" -CONST_SERVICE_IMAGE_KUSTOMIZATION = Path("k8s/devops/kustomization.yaml") CONST_CONVENTIONAL_COMMIT_CATEGORIES: Final[dict[str, str]] = { "feat": "Added", "fix": "Fixed & Hardened", diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py index 1a755334c3..98f4bf15ed 100644 --- a/src/devops_cli/lang/en/messages.py +++ b/src/devops_cli/lang/en/messages.py @@ -438,9 +438,6 @@ class ReleaseMessages: preparing_release: str = "Preparing release version [cyan]{version}[/cyan]..." updated_pyproject: str = "✓ Updated pyproject.toml to version [bold]{version}[/bold]" updated_init: str = "✓ Updated src/devops_cli/__init__.py to version [bold]{version}[/bold]" - updated_service_image_tag: str = ( - "✓ Pinned the service image in k8s/devops/kustomization.yaml to [bold]v{version}[/bold]" - ) updated_changelog: str = ( "✓ Updated CHANGELOG.md with release header [bold][{version}] - {date}[/bold]" ) diff --git a/tests/test_architectural_invariants.py b/tests/test_architectural_invariants.py index 72b9b49123..3ff911b98d 100644 --- a/tests/test_architectural_invariants.py +++ b/tests/test_architectural_invariants.py @@ -567,30 +567,6 @@ def _covered(path: str) -> bool: ) -def test_release_service_image_inputs_are_what_the_image_is_built_from() -> None: - """release.yml's SERVICE_IMAGE_INPUTS names every COPY source, the build definition and itself. - - The release branch labels the Service image with the hash of these paths, and main's run - points `latest` at that image only when its own tree hashes the same (#1451). A COPY source - left out would let main promote an image built from other code; a path the image is not - built from (CHANGELOG.md, docs) would republish on every push and fail a merge whose image - is right. - """ - import yaml - - repo_root = Path(__file__).resolve().parents[1] - workflow = yaml.safe_load( - (repo_root / ".github" / "workflows" / "release.yml").read_text(encoding="utf-8") - ) - declared = set(workflow["jobs"]["service-image"]["env"]["SERVICE_IMAGE_INPUTS"].split()) - expected = _dockerfile_build_context_sources(repo_root / "Dockerfile") | { - "Dockerfile", - ".dockerignore", - ".github/workflows/release.yml", - } - assert declared == expected - - def _find_workflow_runner_mutations(workflow_path: Path, pattern: re.Pattern[str]) -> list[str]: """Find commands in workflow run steps that mutate the runner environment (#832).""" import yaml diff --git a/tests/test_ci.py b/tests/test_ci.py index 20dbb0eebe..0fd1e7e8ba 100644 --- a/tests/test_ci.py +++ b/tests/test_ci.py @@ -697,12 +697,9 @@ def test_service_image_ci_job_invariants() -> None: "github.event_name == 'workflow_dispatch'" in condition, job.get("permissions"), ) == (True, True, True, {"contents": "read"}) - # A release pull request from this repository is built, scanned and published by - # release.yml on each push to its head (#1451); a fork's release/v* head still builds here. - assert ( - "!(startsWith(github.head_ref, 'release/v') &&" in condition, - "github.event.pull_request.head.repo.full_name == github.repository" in condition, - ) == (True, True) + # Every pull request into main builds here, the release pull request included: release.yml + # publishes the image only after the merge (#1486). + assert ("release/v" in condition, "head.repo.full_name" in condition) == (False, False) build_step = next(s for s in job["steps"] if s.get("name") == "Build and Load Service Image") assert ( @@ -717,18 +714,30 @@ def test_service_image_ci_job_invariants() -> None: def test_service_image_release_job_invariants() -> None: - """The release service-image job verifies needs, permissions, step order, and Trivy inputs.""" + """release.yml publishes the Service image only from main, after the release job (#1486). + + It builds, smoke-tests and scans the image, pushes it by digest and attests it, and only then + tags it `vX.Y.Z` and `latest`, so a tag never names an unattested image. No release branch + publishes it, and no plan decides whether to build: Image Updater rolls the cluster onto the + digest `latest` moves to. + """ import yaml release_wf = ( yaml.safe_load(Path(".github/workflows/release.yml").read_text(encoding="utf-8")) or {} ) job = release_wf["jobs"]["service-image"] + steps = job["steps"] assert ( + "release/v*" in release_wf[True]["push"]["branches"], + job["if"], job.get("needs"), job.get("permissions"), + "SERVICE_IMAGE_INPUTS" in job.get("env", {}), ) == ( + False, + "github.ref == 'refs/heads/main'", "release", { "contents": "read", @@ -736,44 +745,16 @@ def test_service_image_release_job_invariants() -> None: "id-token": "write", "attestations": "write", }, + False, ) - - # A release branch publishes the image main pins before main pins it (#1451): the job runs on - # a push to release/v* (where the release job does not), and on main only after the release - # job succeeds. Only the plan step decides whether anything is built or pushed. - assert "release/v*" in release_wf[True]["push"]["branches"] assert ( - "!cancelled()" in job["if"], - "needs.release.result == 'success'" in job["if"], - "startsWith(github.ref, 'refs/heads/release/v')" in job["if"], - "refs/heads/release/" not in release_wf["jobs"]["release"]["if"], - ) == (True, True, True, True) - plan_index = next(i for i, s in enumerate(job["steps"]) if s.get("id") == "plan") - # The plan and tag steps run under pipefail (`shell: bash`), as their tests run them, so a - # failed `git ls-remote` stops them. The plan verifies provenance with the job's token. - tag_index = next(i for i, s in enumerate(job["steps"]) if s.get("id") == "tag") - assert ( - job["steps"][plan_index].get("shell"), - job["steps"][tag_index].get("shell"), - job["steps"][plan_index]["env"].get("GH_TOKEN"), - ) == ("bash", "bash", "${{ github.token }}") - gated = { - s["name"]: s.get("if") - for s in job["steps"][plan_index + 1 :] - if s.get("name") != "Point latest at the Published Service Image" - } - assert set(gated.values()) == {"steps.plan.outputs.action == 'publish'"}, gated - promote = next( - s for s in job["steps"] if s.get("name") == "Point latest at the Published Service Image" - ) - assert (promote["if"], "imagetools create" in promote["run"]) == ( - "steps.plan.outputs.action == 'promote'", - True, - ) + [s.get("name") for s in steps if s.get("id") == "plan"], + [s.get("name") for s in steps if "steps.plan" in str(s.get("if", ""))], + "Point latest at the Published Service Image" in [s.get("name") for s in steps], + ) == ([], [], False) - step_names = [s.get("name", "") for s in job["steps"]] + step_names = [s.get("name", "") for s in steps] indices = ( - step_names.index("Plan Service Image Publication"), step_names.index("Build and Load Service Image"), step_names.index("Run Service Image Smoke Test"), step_names.index("Scan Service Image for Vulnerabilities"), @@ -783,23 +764,32 @@ def test_service_image_release_job_invariants() -> None: ) assert indices == tuple(sorted(indices)), f"Steps out of order: {indices}" - # The image is pushed by digest and tagged only after its provenance is attested, so a tag - # never names an unattested image (#1451). - push_with = next( - s for s in job["steps"] if s.get("name") == "Build and Push Service Image" - ).get("with", {}) - tag_step = next(s for s in job["steps"] if s.get("name") == "Tag the Attested Service Image") + meta_tags = next(s for s in steps if s.get("id") == "meta")["with"]["tags"] + push_with = next(s for s in steps if s.get("name") == "Build and Push Service Image")["with"] + tag_step = next(s for s in steps if s.get("name") == "Tag the Attested Service Image") assert ( + [line.strip() for line in meta_tags.splitlines() if line.strip()], "push-by-digest=true" in str(push_with.get("outputs", "")), "tags" in push_with, - "imagetools create" in tag_step["run"], + push_with.get("sbom") in (True, "true"), + tag_step.get("shell"), tag_step["env"]["DIGEST"], - ) == (True, False, True, "${{ steps.push.outputs.digest }}") - - trivy_step = next( - s for s in job["steps"] if s.get("name") == "Scan Service Image for Vulnerabilities" + "imagetools create" in tag_step["run"], + "refs/heads/release" in tag_step["run"], + ) == ( + ["type=raw,value=v${{ needs.release.outputs.version }}", "type=raw,value=latest"], + True, + False, + True, + "bash", + "${{ steps.push.outputs.digest }}", + True, + False, ) - trivy_with = trivy_step.get("with", {}) + + trivy_with = next( + s for s in steps if s.get("name") == "Scan Service Image for Vulnerabilities" + ).get("with", {}) assert ( trivy_with.get("scanners"), trivy_with.get("severity"), @@ -807,10 +797,7 @@ def test_service_image_release_job_invariants() -> None: str(trivy_with.get("exit-code")), ) == ("vuln", "HIGH,CRITICAL", True, "1") - push_step = next(s for s in job["steps"] if s.get("name") == "Build and Push Service Image") - assert push_step.get("with", {}).get("sbom") in (True, "true") - - interpolated_runs = [s.get("name", "") for s in job["steps"] if "${{" in s.get("run", "")] + interpolated_runs = [s.get("name", "") for s in steps if "${{" in s.get("run", "")] assert not interpolated_runs, ( f"run: blocks in service-image release job must not contain ${{}}: {interpolated_runs}" ) diff --git a/tests/test_k8s_devops_runtime.py b/tests/test_k8s_devops_runtime.py index bc6c277e1e..7e82a76443 100644 --- a/tests/test_k8s_devops_runtime.py +++ b/tests/test_k8s_devops_runtime.py @@ -9,9 +9,7 @@ from typing import Any import yaml -from packaging.version import Version -from devops_cli import __version__ from devops_cli.config import options as opt from devops_cli.config.env import OPTION_TO_ENV_VAR from devops_cli.config.settings import Settings @@ -225,11 +223,10 @@ def test_perimeter_admits_no_ingress_and_exactly_four_egress_rules() -> None: ) -def test_kustomization_lists_every_manifest_and_pins_the_image_and_stays_out_of_the_root() -> None: - """The tag is a release tag no newer than the version in development. +def test_kustomization_lists_every_manifest_and_pins_no_image_and_stays_out_of_the_root() -> None: + """Git names the service image untagged; Image Updater sets its digest on Application devops. - `devops release check` holds it equal to the version at the cut; between cuts it keeps - naming the last published image, so opening a cycle needs no tag that does not exist yet. + A release writes nothing here (#1486), so the kustomization carries no `images:` entry. """ kustomization = _doc("kustomization.yaml") on_disk = [ @@ -247,22 +244,11 @@ def test_kustomization_lists_every_manifest_and_pins_the_image_and_stays_out_of_ ).stdout.split() manifests = sorted([*tracked, "roadmap-service"]) root = yaml.safe_load((K8S_DIR / "kustomization.yaml").read_text(encoding="utf-8")) - (image,) = kustomization["images"] - tag = str(image["newTag"]) assert ( sorted(kustomization["resources"]), - sorted(image), - image["name"], - tag.startswith("v") and str(Version(tag[1:])) == tag[1:], - Version(tag[1:]) <= Version(__version__), + "images" in kustomization, [r for r in root["resources"] if r.startswith("devops")], - ) == (manifests, ["name", "newTag"], "ghcr.io/dan-petty/devops-cli/service", True, True, []) - - -def test_the_kustomization_survives_the_release_bump_rewrite() -> None: - """`devops release prepare` rewrites it with `yaml.safe_dump`, which keeps no comment.""" - text = (DEVOPS_DIR / "kustomization.yaml").read_text(encoding="utf-8") - assert yaml.safe_dump(yaml.safe_load(text), sort_keys=False) == text + ) == (manifests, False, []) def test_both_workloads_run_the_digest_image_updater_sets_and_pull_it_only_when_missing( @@ -270,8 +256,8 @@ def test_both_workloads_run_the_digest_image_updater_sets_and_pull_it_only_when_ ) -> None: """Application devops renders the CronJob and roadmap-service on Image Updater's digest (#1485). - Argo CD adds the Application's `spec.source.kustomize.images` to the kustomization it builds, - as this overlay does, and that entry outranks the `newTag` pin in k8s/devops. A tag of + Git names the image untagged, and Argo CD adds the Application's `spec.source.kustomize.images` + entry, which sets the digest, to the kustomization it builds, as this overlay does. A tag of `latest` would default the pull policy to Always, so both containers set IfNotPresent. """ service = "ghcr.io/dan-petty/devops-cli/service" diff --git a/tests/test_release.py b/tests/test_release.py index 749f7bffdd..f2f9dc549b 100644 --- a/tests/test_release.py +++ b/tests/test_release.py @@ -266,142 +266,52 @@ def test_release_check_version_mismatch(sample_project_dir: Path) -> None: assert "Version mismatch" in result.output -def _write_runtime_kustomization(root: Path, tag: str) -> Path: - path = root / "k8s" / "devops" / "kustomization.yaml" - path.parent.mkdir(parents=True) - document = { - "resources": ["cronjob.yaml"], - "images": [{"name": "ghcr.io/dan-petty/devops-cli/service", "newTag": tag}], - } - path.write_text(yaml.safe_dump(document, sort_keys=False), encoding="utf-8") - return path - - -def test_release_prepare_pins_the_service_image_to_the_new_version( - sample_project_dir: Path, -) -> None: - path = _write_runtime_kustomization(sample_project_dir, "v0.1.7") - with patch("devops_cli.commands.release.DocGenerator.write_all_docs"): - result = runner.invoke(app, ["prepare", "0.1.8", "--root", str(sample_project_dir)]) - images = yaml.safe_load(path.read_text(encoding="utf-8"))["images"] - assert (result.exit_code, images[0]["newTag"]) == (0, "v0.1.8") - - -def test_release_paths_stage_the_runtime_kustomization(tmp_path: Path) -> None: - _write_runtime_kustomization(tmp_path, "v0.1.7") - assert "k8s/devops/kustomization.yaml" in _release_paths(tmp_path) +def test_release_prepare_leaves_k8s_untouched(sample_project_dir: Path) -> None: + """The cut neither bumps a service image tag nor rewrites an Argo CD targetRevision (#1486). - -def test_release_check_fails_when_the_service_image_tag_is_out_of_step( - sample_project_dir: Path, -) -> None: - _write_runtime_kustomization(sample_project_dir, "v0.1.6") - result = runner.invoke(app, ["check", "--root", str(sample_project_dir), "--allow-dirty"]) - output = " ".join(result.output.split()) - assert (result.exit_code, "k8s/devops/kustomization.yaml pins" in output) == ( - 1, - True, + Image Updater rolls the Service onto the digest `service:latest` moves to, so a release + writes nothing under k8s/ and stages nothing there. + """ + kustomization = sample_project_dir / "k8s" / "devops" / "kustomization.yaml" + application = sample_project_dir / "k8s" / "argocd" / "apps" / "test-app.yaml" + kustomization.parent.mkdir(parents=True) + application.parent.mkdir(parents=True) + kustomization.write_text( + yaml.safe_dump( + { + "resources": ["cronjob.yaml"], + "images": [{"name": "ghcr.io/dan-petty/devops-cli/service", "newTag": "v0.1.7"}], + }, + sort_keys=False, + ), + encoding="utf-8", ) - - -def _write_argocd_application( - root: Path, - name: str = "test-app", - git_revision: str = "main", - chart_revision: str = "1.2.3", -) -> Path: - path = root / "k8s" / "argocd" / "apps" / f"{name}.yaml" - path.parent.mkdir(parents=True, exist_ok=True) - doc = { - "apiVersion": "argoproj.io/v1alpha1", - "kind": "Application", - "metadata": {"name": name, "namespace": "argocd"}, - "spec": { - "project": "default", - "sources": [ - { - "repoURL": "https://charts.example.com", - "chart": "test-chart", - "targetRevision": chart_revision, + application.write_text( + yaml.safe_dump( + { + "apiVersion": "argoproj.io/v1alpha1", + "kind": "Application", + "metadata": {"name": "test-app", "namespace": "argocd"}, + "spec": { + "source": { + "repoURL": "https://example.com/devops-cli.git", + "targetRevision": "release/v0.1.7", + "path": "k8s/test", + }, }, - { - "repoURL": "https://github.com/dan-petty/devops-cli", - "targetRevision": git_revision, - "path": "k8s/test", - }, - ], - "destination": { - "server": "https://kubernetes.default.svc", - "namespace": "test", }, - }, - } - path.write_text(yaml.safe_dump(doc, sort_keys=False), encoding="utf-8") - return path - - -def test_release_paths_stage_argocd(tmp_path: Path) -> None: - _write_argocd_application(tmp_path) - assert "k8s/argocd/" in _release_paths(tmp_path) - - -def test_release_prepare_rewrites_argocd_target_revisions( - sample_project_dir: Path, -) -> None: - app_path = _write_argocd_application(sample_project_dir, git_revision="release/v0.1.7") + sort_keys=False, + ), + encoding="utf-8", + ) + before = (kustomization.read_bytes(), application.read_bytes()) with patch("devops_cli.commands.release.DocGenerator.write_all_docs"): result = runner.invoke(app, ["prepare", "0.1.8", "--root", str(sample_project_dir)]) - assert result.exit_code == 0 - doc = yaml.safe_load(app_path.read_text(encoding="utf-8")) - sources = doc["spec"]["sources"] - assert (sources[0]["targetRevision"], sources[1]["targetRevision"]) == ( - "1.2.3", - "main", - ) - - -def test_release_check_fails_on_mismatched_argocd_target_revisions( - sample_project_dir: Path, -) -> None: - _write_argocd_application(sample_project_dir, name="app1", git_revision="main") - _write_argocd_application(sample_project_dir, name="app2", git_revision="release/v0.1.8") - result = runner.invoke(app, ["check", "--root", str(sample_project_dir), "--allow-dirty"]) - assert (result.exit_code, "Argo CD git-source targetRevisions mismatch" in result.output) == ( - 1, - True, - ) - - -def test_release_check_fails_on_argocd_target_revision_not_matching_main( - sample_project_dir: Path, -) -> None: - _write_argocd_application(sample_project_dir, git_revision="release/v0.1.6") - result = runner.invoke(app, ["check", "--root", str(sample_project_dir), "--allow-dirty"]) assert ( result.exit_code, - "does not match expected 'main'" in result.output, - ) == (1, True) - - -def test_release_check_succeeds_with_matching_argocd_target_revisions( - sample_project_dir: Path, -) -> None: - _write_argocd_application(sample_project_dir, git_revision="main") - with ( - patch( - "devops_cli.commands.release.DocGenerator.check_docs", - return_value=(True, []), - ), - patch("devops_cli.commands.release.run_subprocess") as mock_sub, - ): - mock_sub.return_value = subprocess.CompletedProcess( - args=["uv", "run", "devops", "ci", "run"], - returncode=0, - stdout="All checks passed!", - stderr="", - ) - result = runner.invoke(app, ["check", "--root", str(sample_project_dir), "--allow-dirty"]) - assert result.exit_code == 0 + (kustomization.read_bytes(), application.read_bytes()) == before, + [p for p in _release_paths(sample_project_dir) if p.startswith("k8s")], + ) == (0, True, []) def test_release_check_dirty_repo(sample_project_dir: Path) -> None: diff --git a/tests/test_release_service_image_plan.py b/tests/test_release_service_image_plan.py deleted file mode 100644 index f3fabcf050..0000000000 --- a/tests/test_release_service_image_plan.py +++ /dev/null @@ -1,451 +0,0 @@ -"""release.yml's Service image plan and tag steps: a release branch publishes the image main will -pin, and nothing replaces it once main pins it (#1451). - -Each step runs verbatim under bash in a real git repository with an `origin` remote. Only the -process edge is faked, by scripts on PATH: `docker` answers `docker buildx imagetools inspect` -from a directory standing in for GHCR and records `imagetools create`, `gh` answers -`gh attestation verify` from the certificate identity recorded for a digest, and, where a test -asks for it, `git` fails `ls-remote` as a network error would. Nothing reaches the network. -""" - -from __future__ import annotations - -import hashlib -import os -import shutil -import subprocess -from collections.abc import Callable -from pathlib import Path -from typing import Any - -import pytest -import yaml - -WORKFLOW = Path(__file__).resolve().parents[1] / ".github" / "workflows" / "release.yml" -REPOSITORY = "dan-petty/devops-cli" -IMAGE = f"ghcr.io/{REPOSITORY}/service" -FAKE_DOCKER = """#!/usr/bin/env bash -# docker buildx imagetools inspect REF --format F: prints " " from $FAKE_GHCR/. -# docker buildx imagetools create ARGS: appends ARGS to $FAKE_GHCR/created. -if [ "$3" = "create" ]; then echo "${*:4}" >> "$FAKE_GHCR/created"; exit 0; fi -tag="${4##*:}" -if [ -f "$FAKE_GHCR/$tag.err" ]; then cat "$FAKE_GHCR/$tag.err" >&2; exit 1; fi -if [ -f "$FAKE_GHCR/$tag" ]; then printf '%s' "$(cat "$FAKE_GHCR/$tag")"; exit 0; fi -echo "ERROR: $4: not found" >&2 -exit 1 -""" -FAKE_GH = """#!/usr/bin/env bash -# gh attestation verify oci://IMAGE@DIGEST ... --cert-identity-regex RE: passes when the signing -# identity recorded in $FAKE_GHCR/attested/DIGEST matches RE, as the certificate check does. -[ "$1 $2" = "attestation verify" ] || exit 2 -digest="${3##*@}" -regex="" -while [ $# -gt 0 ]; do - if [ "$1" = "--cert-identity-regex" ]; then regex="$2"; fi - shift -done -if [ ! -f "$FAKE_GHCR/attested/$digest" ]; then echo "no attestations for $digest" >&2; exit 1; fi -san="$(cat "$FAKE_GHCR/attested/$digest")" -if [[ -n "$regex" && "$san" =~ $regex ]]; then exit 0; fi -echo "$san does not match $regex" >&2 -exit 1 -""" -FAKE_GIT = """#!/usr/bin/env bash -# git ls-remote fails as an unreachable remote does; every other git command is the real one. -if [ "$1" = "ls-remote" ]; then - echo "fatal: unable to access 'https://example.com/': Could not resolve host: example.com" >&2 - exit 128 -fi -exec {real_git} "$@" -""" - - -def _signer(ref: str, workflow: str = "release.yml") -> str: - """The SubjectAlternativeName GitHub's OIDC token gives a workflow run on `ref`.""" - return f"https://github.com/{REPOSITORY}/.github/workflows/{workflow}@{ref}" - - -def _workflow() -> dict[str, Any]: - workflow: dict[str, Any] = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8")) - return workflow - - -def _git(cwd: Path, *args: str) -> str: - return subprocess.run( - ["git", *args], cwd=cwd, check=True, capture_output=True, text=True - ).stdout.strip() - - -def _commit(work: Path, message: str, files: dict[str, str]) -> str: - for name, text in files.items(): - (work / name).parent.mkdir(parents=True, exist_ok=True) - (work / name).write_text(text, encoding="utf-8") - _git(work, "add", "-A") - _git(work, "commit", "-q", "-m", message) - return _git(work, "rev-parse", "HEAD") - - -def _pyproject(version: str) -> str: - return f'[project]\nname = "devops-cli"\nversion = "{version}"\n' - - -@pytest.fixture -def repo(tmp_path: Path) -> dict[str, Any]: - """main at 0.2.28, and release/v0.2.29 cut to 0.2.29 with one more item before the cut.""" - origin = tmp_path / "origin.git" - _git(tmp_path, "init", "-q", "--bare", "-b", "main", str(origin)) - work = tmp_path / "work" - _git(tmp_path, "init", "-q", "-b", "main", str(work)) - _git(work, "config", "user.email", "ci@example.com") - _git(work, "config", "user.name", "CI") - _git(work, "config", "commit.gpgsign", "false") - _git(work, "config", "tag.gpgsign", "false") - _git(work, "remote", "add", "origin", str(origin)) - _commit( - work, - "base", - { - "pyproject.toml": _pyproject("0.2.28"), - "uv.lock": "lock\n", - "Dockerfile": "FROM scratch\n", - ".dockerignore": "*\n", - "src/devops_cli/a.py": "A = 1\n", - "CHANGELOG.md": "## [0.2.28]\n", - }, - ) - _git(work, "push", "-q", "origin", "main") - _git(work, "checkout", "-q", "-b", "release/v0.2.29") - pre_cut = _commit(work, "item", {"src/devops_cli/b.py": "B = 1\n"}) - cut = _commit(work, "feat(release): v0.2.29", {"pyproject.toml": _pyproject("0.2.29")}) - _git(work, "push", "-q", "origin", "release/v0.2.29") - return {"tmp": tmp_path, "origin": origin, "work": work, "pre_cut": pre_cut, "cut": cut} - - -def _inputs(work: Path, sha: str) -> str: - paths = _workflow()["jobs"]["service-image"]["env"]["SERVICE_IMAGE_INPUTS"].split() - listing = _git(work, "ls-tree", sha, "--", *paths) + "\n" - return hashlib.sha256(listing.encode()).hexdigest() - - -def _bin(tmp: Path, git_fails: bool) -> Path: - """The fakes on PATH: docker and gh always, git only when `git_fails`.""" - bin_dir = tmp / ("bin-offline" if git_fails else "bin") - bin_dir.mkdir(exist_ok=True) - fakes = {"docker": FAKE_DOCKER, "gh": FAKE_GH} - if git_fails: - fakes["git"] = FAKE_GIT.format(real_git=shutil.which("git")) - for name, script in fakes.items(): - (bin_dir / name).write_text(script, encoding="utf-8") - (bin_dir / name).chmod(0o755) - return bin_dir - - -def _run( - repo: dict[str, Any], - step_id: str, - sha: str, - ref: str, - env: dict[str, str] | None = None, - ghcr: dict[str, str] | None = None, - attested: dict[str, str] | None = None, - git_fails: bool = False, -) -> tuple[int, dict[str, str], str]: - """Run the service-image step `step_id` at `sha` on `ref`. - - `ghcr` maps a tag to " " or "!error"; `attested` maps a digest to the - identity that signed its provenance. Returns the exit code, the step's outputs, and its log. - """ - tmp: Path = repo["tmp"] - run_dir = tmp / f"run-{step_id}-{sha[:8]}-{ref.rsplit('/', 1)[-1]}" - _git(tmp, "clone", "-q", str(repo["origin"]), str(run_dir)) - _git(run_dir, "checkout", "-q", "--detach", sha) - fake_ghcr = tmp / "ghcr" - (fake_ghcr / "attested").mkdir(parents=True, exist_ok=True) - for tag, answer in (ghcr or {}).items(): - target = fake_ghcr / (f"{tag}.err" if answer.startswith("!") else tag) - target.write_text(answer.lstrip("!"), encoding="utf-8") - for digest, signer in (attested or {}).items(): - (fake_ghcr / "attested" / digest).write_text(signer, encoding="utf-8") - output = tmp / "github_output" - output.write_text("", encoding="utf-8") - job = _workflow()["jobs"]["service-image"] - step = next(s for s in job["steps"] if s.get("id") == step_id) - step_env = { - **os.environ, - "PATH": f"{_bin(tmp, git_fails)}{os.pathsep}{os.environ['PATH']}", - "GITHUB_REF": ref, - "GITHUB_SHA": sha, - "GITHUB_REPOSITORY": REPOSITORY, - "GITHUB_OUTPUT": str(output), - "RUNNER_TEMP": str(tmp), - "REF_NAME": ref.removeprefix("refs/heads/"), - "SERVICE_IMAGE": IMAGE, - "SERVICE_IMAGE_INPUTS": job["env"]["SERVICE_IMAGE_INPUTS"], - "FAKE_GHCR": str(fake_ghcr), - **{k: v for k, v in step["env"].items() if "${{" not in str(v)}, - **(env or {}), - } - done = subprocess.run( - ["bash", "-euo", "pipefail", "-c", step["run"]], - cwd=run_dir, - env=step_env, - capture_output=True, - text=True, - check=False, - ) - outputs = dict( - line.split("=", 1) for line in output.read_text(encoding="utf-8").splitlines() if line - ) - return done.returncode, outputs, done.stdout + done.stderr - - -def _plan( - repo: dict[str, Any], - sha: str, - ref: str, - release_version: str = "", - ghcr: dict[str, str] | None = None, - attested: dict[str, str] | None = None, -) -> tuple[int, dict[str, str], str]: - env = {"RELEASE_VERSION": release_version} - return _run(repo, "plan", sha, ref, env, ghcr, attested) - - -def _tag(repo: dict[str, Any], sha: str, ref: str, tags: str) -> tuple[int, list[str], str]: - """Run the tag step for digest sha256:bbb; returns the exit code, the tags created, the log.""" - env = {"DIGEST": "sha256:bbb", "TAGS": tags, "VERSION": "0.2.29"} - code, _, log = _run(repo, "tag", sha, ref, env) - created = repo["tmp"] / "ghcr" / "created" - return code, created.read_text(encoding="utf-8").splitlines() if created.exists() else [], log - - -BRANCH = "refs/heads/release/v0.2.29" -MAIN = "refs/heads/main" - - -def test_a_branch_before_its_cut_publishes_nothing(repo: dict[str, Any]) -> None: - _git(repo["work"], "push", "-q", "-f", "origin", f"{repo['pre_cut']}:release/v0.2.29") - code, out, _ = _plan(repo, repo["pre_cut"], BRANCH) - assert (code, out["action"]) == (0, "none") - - -def test_the_cut_publishes_its_version_without_latest(repo: dict[str, Any]) -> None: - code, out, _ = _plan(repo, repo["cut"], BRANCH) - assert (code, out["action"], out["latest"], out["version"], out["inputs"]) == ( - 0, - "publish", - "false", - "0.2.29", - _inputs(repo["work"], repo["cut"]), - ) - - -def test_a_push_that_leaves_the_inputs_alone_publishes_nothing(repo: dict[str, Any]) -> None: - collate = _commit(repo["work"], "collate", {"CHANGELOG.md": "## [0.2.29]\n"}) - _git(repo["work"], "push", "-q", "origin", "release/v0.2.29") - published = f"sha256:aaa {_inputs(repo['work'], repo['cut'])}" - code, out, _ = _plan( - repo, collate, BRANCH, ghcr={"v0.2.29": published}, attested={"sha256:aaa": _signer(BRANCH)} - ) - assert (code, out["action"]) == (0, "none") - - -@pytest.mark.parametrize( - "signer", - [None, _signer("refs/heads/feature"), _signer(BRANCH, workflow="ci.yml")], - ids=["unattested", "release.yml-on-another-branch", "another-workflow"], -) -def test_an_image_release_yml_did_not_attest_is_published_again( - repo: dict[str, Any], signer: str | None -) -> None: - """The label is only the pusher's claim; provenance from release.yml is what counts.""" - published = f"sha256:aaa {_inputs(repo['work'], repo['cut'])}" - attested = {"sha256:aaa": signer} if signer else {} - code, out, _ = _plan(repo, repo["cut"], BRANCH, ghcr={"v0.2.29": published}, attested=attested) - assert (code, out["action"], out["latest"]) == (0, "publish", "false") - - -def test_a_fix_after_the_cut_republishes(repo: dict[str, Any]) -> None: - fix = _commit(repo["work"], "fix", {"src/devops_cli/a.py": "A = 2\n"}) - _git(repo["work"], "push", "-q", "origin", "release/v0.2.29") - published = f"sha256:aaa {_inputs(repo['work'], repo['cut'])}" - code, out, _ = _plan( - repo, fix, BRANCH, ghcr={"v0.2.29": published}, attested={"sha256:aaa": _signer(BRANCH)} - ) - assert (code, out["action"], out["latest"]) == (0, "publish", "false") - - -def test_a_superseded_run_publishes_nothing(repo: dict[str, Any]) -> None: - _commit(repo["work"], "fix", {"src/devops_cli/a.py": "A = 2\n"}) - _git(repo["work"], "push", "-q", "origin", "release/v0.2.29") - code, out, _ = _plan(repo, repo["cut"], BRANCH) - assert (code, out["action"]) == (0, "none") - - -@pytest.mark.parametrize("step_id", ["plan", "tag"]) -def test_an_unreadable_branch_tip_fails_closed(repo: dict[str, Any], step_id: str) -> None: - """A failed `git ls-remote` stops the step instead of reading as a superseded commit.""" - env = {"DIGEST": "sha256:bbb", "TAGS": f"{IMAGE}:v0.2.29", "VERSION": "0.2.29"} - code, out, log = _run(repo, step_id, repo["cut"], BRANCH, env, git_fails=True) - created = repo["tmp"] / "ghcr" / "created" - assert (code, out.get("action"), "no longer the tip" in log, created.exists()) == ( - 128, - None, - False, - False, - ) - - -def _push_to_main(repo: dict[str, Any], files: dict[str, str]) -> None: - work = repo["work"] - _git(work, "checkout", "-q", "main") - _commit(work, "fix on main", files) - _git(work, "push", "-q", "origin", "main") - - -def test_a_branch_missing_main_image_changes_fails_before_publishing( - repo: dict[str, Any], -) -> None: - _push_to_main(repo, {"uv.lock": "lock 2\n"}) - code, out, log = _plan(repo, repo["cut"], BRANCH) - assert (code, out.get("action"), "Merge main into release/v0.2.29" in log) == ( - 1, - None, - True, - ) - - -def test_a_branch_missing_main_commits_that_leave_the_image_alone_still_publishes( - repo: dict[str, Any], -) -> None: - """Merging the release keeps the branch's image inputs, so the image built here is the one.""" - _push_to_main(repo, {"NOTES.md": "x\n"}) - code, out, _ = _plan(repo, repo["cut"], BRANCH) - assert (code, out["action"]) == (0, "publish") - - -def _merge(repo: dict[str, Any], extra: dict[str, str] | None = None) -> str: - """Squash release/v0.2.29 into main and tag the merge, as the PR and the release job do.""" - work = repo["work"] - _git(work, "checkout", "-q", "main") - _git(work, "merge", "-q", "--squash", "release/v0.2.29") - merged = _commit(work, "feat(release): v0.2.29 (#1)", extra or {}) - _git(work, "tag", "-a", "v0.2.29", "-m", "v0.2.29") - _git(work, "push", "-q", "--follow-tags", "origin", "main") - return merged - - -def test_a_merged_release_is_never_republished_from_its_branch(repo: dict[str, Any]) -> None: - _merge(repo) - code, out, _ = _plan(repo, repo["cut"], BRANCH) - assert (code, out["action"]) == (0, "none") - - -def test_main_points_latest_at_the_image_built_from_its_inputs(repo: dict[str, Any]) -> None: - merged = _merge(repo, {"CHANGELOG.md": "## [0.2.29]\n"}) - published = f"sha256:aaa {_inputs(repo['work'], repo['cut'])}" - attested = {"sha256:aaa": _signer(BRANCH)} - code, out, _ = _plan(repo, merged, MAIN, "0.2.29", {"v0.2.29": published}, attested) - assert (code, out["action"], out["digest"]) == (0, "promote", "sha256:aaa") - - -def _later_push(repo: dict[str, Any]) -> str: - """A push to main after the release merged that changes the image's inputs.""" - _merge(repo) - later = _commit(repo["work"], "chore(deps): bump", {"uv.lock": "lock 2\n"}) - _git(repo["work"], "push", "-q", "origin", "main") - return later - - -def _recovery(repo: dict[str, Any]) -> str: - """The release merged but its release job failed before tagging; the fix is the tagged commit.""" - work = repo["work"] - _git(work, "checkout", "-q", "main") - _git(work, "merge", "-q", "--squash", "release/v0.2.29") - _commit(work, "feat(release): v0.2.29 (#1)", {}) - fix = _commit(work, "fix(release): the check", {"src/devops_cli/a.py": "A = 3\n"}) - _git(work, "tag", "-a", "v0.2.29", "-m", "v0.2.29") - _git(work, "push", "-q", "--follow-tags", "origin", "main") - return fix - - -@pytest.mark.parametrize( - "make_head", - [lambda repo: _merge(repo, {"src/devops_cli/a.py": "A = 3\n"}), _later_push, _recovery], - ids=["the-release-merge", "a-later-push", "the-push-that-recovers-a-failed-release"], -) -def test_main_never_replaces_the_image_it_pins_and_still_points_latest_at_it( - repo: dict[str, Any], make_head: Callable[[dict[str, Any]], str] -) -> None: - """A tree with other inputs than the published image ships them in the next release.""" - head = make_head(repo) - published = f"sha256:aaa {_inputs(repo['work'], repo['cut'])}" - attested = {"sha256:aaa": _signer(BRANCH)} - code, out, log = _plan(repo, head, MAIN, "0.2.29", {"v0.2.29": published}, attested) - assert (code, out["action"], out["digest"], "ship in the next release" in log) == ( - 0, - "promote", - "sha256:aaa", - True, - ) - - -def test_main_points_latest_at_an_image_its_own_run_built(repo: dict[str, Any]) -> None: - """A release merged over a failed check was built by main's run, signed on main.""" - later = _later_push(repo) - published = f"sha256:aaa {_inputs(repo['work'], later)}" - attested = {"sha256:aaa": _signer(MAIN)} - code, out, _ = _plan(repo, later, MAIN, "0.2.29", {"v0.2.29": published}, attested) - assert (code, out["action"]) == (0, "promote") - - -def test_main_refuses_an_image_release_yml_did_not_attest(repo: dict[str, Any]) -> None: - merged = _merge(repo) - published = f"sha256:aaa {_inputs(repo['work'], repo['cut'])}" - attested = {"sha256:aaa": _signer("refs/heads/feature")} - code, out, log = _plan(repo, merged, MAIN, "0.2.29", {"v0.2.29": published}, attested) - assert (code, out.get("action"), "no provenance" in log) == (1, None, True) - - -def test_main_builds_a_missing_image_with_latest(repo: dict[str, Any]) -> None: - merged = _merge(repo) - code, out, _ = _plan(repo, merged, MAIN, "0.2.29") - assert (code, out["action"], out["latest"]) == (0, "publish", "true") - - -def test_main_fails_closed_when_ghcr_cannot_be_read(repo: dict[str, Any]) -> None: - merged = _merge(repo) - code, out, _ = _plan(repo, merged, MAIN, "0.2.29", {"v0.2.29": "!ERROR: i/o timeout"}) - assert (code, out.get("action")) == (1, None) - - -def test_the_branch_tip_tags_its_attested_digest(repo: dict[str, Any]) -> None: - code, created, _ = _tag(repo, repo["cut"], BRANCH, f"{IMAGE}:v0.2.29") - assert (code, created) == (0, [f"--tag {IMAGE}:v0.2.29 {IMAGE}@sha256:bbb"]) - - -def test_main_tags_the_image_it_built_with_latest(repo: dict[str, Any]) -> None: - merged = _merge(repo) - code, created, _ = _tag(repo, merged, MAIN, f"{IMAGE}:v0.2.29\n{IMAGE}:latest") - assert (code, created) == ( - 0, - [f"--tag {IMAGE}:v0.2.29 --tag {IMAGE}:latest {IMAGE}@sha256:bbb"], - ) - - -def test_a_release_merged_during_the_build_keeps_the_image_main_pins( - repo: dict[str, Any], -) -> None: - """The plan ran before the merge; the tag step sees main holding the version and stops.""" - _merge(repo) - code, created, log = _tag(repo, repo["cut"], BRANCH, f"{IMAGE}:v0.2.29") - assert (code, created, "never replaced" in log) == (1, [], True) - - -def test_a_run_superseded_during_the_build_leaves_the_tag_to_the_tip( - repo: dict[str, Any], -) -> None: - _commit(repo["work"], "fix", {"src/devops_cli/a.py": "A = 2\n"}) - _git(repo["work"], "push", "-q", "origin", "release/v0.2.29") - code, created, log = _tag(repo, repo["cut"], BRANCH, f"{IMAGE}:v0.2.29") - assert (code, created, "no longer the tip" in log) == (0, [], True) From 3be8c3a1d70a647699c10347ab46b6de0b6cbe4d Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 9 Oct 2026 09:46:01 -0600 Subject: [PATCH 04/15] fix(ci): ci's trivy scans run the trivy version tools.lock pins, so ci and local scans agree (#1499) (#1503) --- .github/workflows/ci.yml | 2 +- .github/workflows/release.yml | 2 +- changelog.d/1499.md | 2 ++ ...-trivy-scans-run-the-tools-lock-version.md | 29 +++++++++++++++++++ src/devops_cli/tools_lock/tools.lock | 9 +++--- tests/test_workflow_contracts.py | 15 ++++++++++ 6 files changed, 53 insertions(+), 6 deletions(-) create mode 100644 changelog.d/1499.md create mode 100644 docs/agent/tasks/task-1499-ci-trivy-scans-run-the-tools-lock-version.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 907d8295a9..1335a899c3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -248,7 +248,7 @@ jobs: severity: HIGH,CRITICAL ignore-unfixed: true exit-code: "1" - version: v0.70.0 + version: v0.75.0 # Advisory only: reports newer upstream releases without gating any merge. Scheduled so diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 08677cd5d8..6d7ba5e8b2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -227,7 +227,7 @@ jobs: severity: HIGH,CRITICAL ignore-unfixed: true exit-code: "1" - version: v0.70.0 + version: v0.75.0 # Pushed by digest only: the tags move to the digest once its provenance is attested, so # a tag never names an unattested image and a failed attestation is retried by a re-run. diff --git a/changelog.d/1499.md b/changelog.d/1499.md new file mode 100644 index 0000000000..a90f18faea --- /dev/null +++ b/changelog.d/1499.md @@ -0,0 +1,2 @@ +### Fixed +- CI's and the release's Service image scans run Trivy 0.75.0, the version `tools.lock` pins for `devops install-tools`, instead of 0.70.0, and a workflow contract test fails whenever an `aquasecurity/trivy-action` step's `version` differs from the lock (#1499). diff --git a/docs/agent/tasks/task-1499-ci-trivy-scans-run-the-tools-lock-version.md b/docs/agent/tasks/task-1499-ci-trivy-scans-run-the-tools-lock-version.md new file mode 100644 index 0000000000..65ce802786 --- /dev/null +++ b/docs/agent/tasks/task-1499-ci-trivy-scans-run-the-tools-lock-version.md @@ -0,0 +1,29 @@ +# Task: CI's Trivy scans run the Trivy version tools.lock pins (#1499) + +**Issue**: [#1499](https://github.com/dan-petty/devops-cli/issues/1499) +**Status**: Done +**Milestone**: v0.2.32 +**Scope**: type/bug, scope/ci + +## Description + +- Both `aquasecurity/trivy-action` steps, the Service Image scan in `.github/workflows/ci.yml` and in `.github/workflows/release.yml`, now pass `version: v0.75.0` instead of `v0.70.0`, so CI scans with the Trivy `devops install-tools` installs. +- `tools.lock`'s `[binary.trivy].version` is the single source for Trivy's version: a workflow contract test fails whenever a `trivy-action` step's `version` differs from it, so a lock bump fails CI until the workflows match. The lock's header names the workflows in its bump procedure. + +## Acceptance Criteria + +- [x] Both `trivy-action` steps pass `version: v0.75.0` (`ci.yml`, `release.yml`). +- [x] `test_every_trivy_scan_runs_the_trivy_tools_lock_pins` in `tests/test_workflow_contracts.py` failed on the unfixed tree with v0.70.0 against 0.75.0, and passes now. +- Pending a person: the Service image scan with Trivy v0.75.0. An item PR into release/v0.2.32 does not run ci.yml's Service Image job (it needs `base_ref == main` or `workflow_dispatch`). Run: + 1. `gh workflow run ci.yml --ref fix/1499-ci-trivy-version-from-tools-lock` + 2. `gh run list --workflow ci.yml --branch fix/1499-ci-trivy-version-from-tools-lock --event workflow_dispatch --limit 1` + 3. `gh run watch ` + + In the Service Image job, the "Scan Service Image for Vulnerabilities" step must install Trivy v0.75.0 and pass. Once #1486 has removed the release-PR skip, the v0.2.32 release PR into main runs the same scan by itself. + +## Deliverables + +- [x] `.github/workflows/ci.yml` and `.github/workflows/release.yml`: the Service Image scan's `trivy-action` step passes `version: v0.75.0`. +- [x] `tests/test_workflow_contracts.py`: `test_every_trivy_scan_runs_the_trivy_tools_lock_pins`. +- [x] `src/devops_cli/tools_lock/tools.lock` header: Trivy's version is also the `version` of every `aquasecurity/trivy-action` step in `.github/workflows/`, and the bump procedure runs `tests/test_workflow_contracts.py`. +- [x] `changelog.d/1499.md` under `### Fixed`. diff --git a/src/devops_cli/tools_lock/tools.lock b/src/devops_cli/tools_lock/tools.lock index 3f5802900f..b88419e630 100644 --- a/src/devops_cli/tools_lock/tools.lock +++ b/src/devops_cli/tools_lock/tools.lock @@ -9,15 +9,16 @@ # the release asset's `digest` (`gh api repos///releases/tags/`), checked # against the publisher's checksum file. Where the release has no digest, the publisher's file # alone gives it: popeye's `checksums.sha256`, get.helm.sh's `.sha256sum` and -# dl.k8s.io's `kubectl.sha256`. +# dl.k8s.io's `kubectl.sha256`. Trivy's version is also the `version` of every +# `aquasecurity/trivy-action` step in `.github/workflows/`. # # To bump a Python tool, set its `version` here and in `.in`, then, in this directory, run # uv pip compile --universal --generate-hashes --python-version 3.14 .in -o .txt # Bandit's version is the project's dev dependency in pyproject.toml. # -# Then run `uv run pytest tests/test_tools_lock.py tests/test_install_tools.py`, and -# `devops install-tools --target-dir ` followed by `devops install-tools --check --target-dir -# ` to install and confirm every pin. +# Then run `uv run pytest tests/test_tools_lock.py tests/test_install_tools.py +# tests/test_workflow_contracts.py`, and `devops install-tools --target-dir ` followed by +# `devops install-tools --check --target-dir ` to install and confirm every pin. python_version = "3.14" diff --git a/tests/test_workflow_contracts.py b/tests/test_workflow_contracts.py index 07c60592fd..f2ab34e226 100644 --- a/tests/test_workflow_contracts.py +++ b/tests/test_workflow_contracts.py @@ -13,6 +13,8 @@ import pytest import yaml +from devops_cli.tools_lock import load_tools_lock + WORKFLOWS_DIR = Path(".github/workflows") RELEASE_PATH = WORKFLOWS_DIR / "release.yml" @@ -81,3 +83,16 @@ def test_release_workflow_attest_build_provenance_mutation() -> None: with pytest.raises(AssertionError, match="has subject-digest without subject-name"): _assert_attest_build_provenance_contract(mutated) + + +def test_every_trivy_scan_runs_the_trivy_tools_lock_pins() -> None: + """CI's Trivy scans run the Trivy `devops install-tools` installs, so CI and local scans agree (#1499).""" + pinned = f"v{load_tools_lock().binary['trivy'].version}" + + assert [ + (path.name, job_id, step.get("with", {}).get("version")) + for path in sorted(WORKFLOWS_DIR.glob("*.yml")) + for job_id, step in _extract_steps_with_action( + _load_workflow(path), "aquasecurity/trivy-action" + ) + ] == [("ci.yml", "service-image", pinned), ("release.yml", "service-image", pinned)] From 1f1a5f8297e8f68c8c3d32a1d33d7a5648281831 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 9 Oct 2026 09:49:49 -0600 Subject: [PATCH 05/15] fix(ci): review workflow tests start the logfire SDK's credential check, which the network guard blocks (#965) (#1505) --- changelog.d/965.md | 2 ++ .../task-767-github-session-per-identity.md | 2 +- ...view-tests-start-no-logfire-token-check.md | 31 +++++++++++++++++++ pyproject.toml | 6 ++++ tests/test_review.py | 20 ++---------- tests/test_review_stage_flags.py | 1 - 6 files changed, 43 insertions(+), 19 deletions(-) create mode 100644 changelog.d/965.md create mode 100644 docs/agent/tasks/task-965-review-tests-start-no-logfire-token-check.md diff --git a/changelog.d/965.md b/changelog.d/965.md new file mode 100644 index 0000000000..f3915ca463 --- /dev/null +++ b/changelog.d/965.md @@ -0,0 +1,2 @@ +### Fixed +- The `devops review` command tests no longer start the Logfire SDK's token-check thread, which printed the "Logfire API is unreachable" warning on every run and made the dry-run socket-recorder test flaky. The tests read the per-test config instead of a `MagicMock` settings object, and a background thread that dies with an exception now fails the test run (#965). diff --git a/docs/agent/tasks/task-767-github-session-per-identity.md b/docs/agent/tasks/task-767-github-session-per-identity.md index f574128441..5cea14d6aa 100644 --- a/docs/agent/tasks/task-767-github-session-per-identity.md +++ b/docs/agent/tasks/task-767-github-session-per-identity.md @@ -65,4 +65,4 @@ Part B (the session's `rest`, `graphql` and `paginate` transport, the ledger fed - Since #1398, `security/sanitizer.py` masks every GitHub token prefix (`ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_`, `github_pat_`), including the long `ghs_APPID_JWT` installation tokens. - `tests/test_analyze.py::test_analyze_path_errors` and `tests/test_repos.py` (`:742`) share `tmp_path.parent / "outside_dir"`. When both run in one worker, the repos test leaves `secret.txt` there and the analyze test's `rmdir` fails. This predates this change. - `CONST_GH_WEBHOOK_SIGNATURE_HEADER` (`config/constants.py`) has no reader; #752 moves the webhook helpers and can take it or drop it. -- `tests/test_review.py::test_review_path_workflow` and four other review tests warn "Logfire API is unreachable": Logfire's credential check tries `logfire-us.pydantic.dev` and is stopped by the network guard. It happens on the base branch too, so a test reaches Logfire's credential lookup that should be stubbed. +- `tests/test_review.py::test_review_path_workflow` and four other review tests warned "Logfire API is unreachable": Logfire's credential check tried `logfire-us.pydantic.dev` and was stopped by the network guard. It happened on the base branch too. Since #965, those tests read the per-test config instead of a `MagicMock` settings object, so they no longer configure Logfire, and the warning fails the test run. diff --git a/docs/agent/tasks/task-965-review-tests-start-no-logfire-token-check.md b/docs/agent/tasks/task-965-review-tests-start-no-logfire-token-check.md new file mode 100644 index 0000000000..82e81d2d88 --- /dev/null +++ b/docs/agent/tasks/task-965-review-tests-start-no-logfire-token-check.md @@ -0,0 +1,31 @@ +# Task: Review Workflow Tests Start No Logfire Token Check (#965) + +**Issue**: [#965](https://github.com/dan-petty/devops-cli/issues/965) +**Status**: Done +**Milestone**: v0.2.32 +**Priority**: priority/p2-medium +**Scope**: type/bug, priority/p2-medium, scope/ci + +## Description +Five `devops review` command tests started the Logfire SDK's `check_logfire_token` thread. The conftest DNS guard blocked the thread's lookup of the Logfire API, so every run printed "Logfire API is unreachable", and the leaked thread could resolve its host inside a later test that records socket calls, which made the dry-run socket-recorder test flaky. + +The cause was in the tests. Each one patched `devops_cli.commands.review.load_settings` with a bare `MagicMock`, so `settings.telemetry.logfire` was truthy. `_init_logfire_if_enabled` (`commands/review.py`) then called `LogfireBridge.configure` (`telemetry/logfire.py`), which resolved a non-empty token from the mock through `get_logfire_token` and called `logfire.configure(send_to_logfire=True, token=...)`. That call starts the SDK's token-check thread. + +The five tests now read the per-test config that the autouse `isolate_devops_cli_config` fixture writes, where `telemetry.logfire` keeps its default, off. Two `filterwarnings` entries in `pyproject.toml` make the warning an error. The warning is raised inside the background thread, so it reaches a test only as pytest's unhandled-thread warning; that warning is an error too, which fails the run whenever any background thread dies with an exception. Nothing under `src/` changes. + +## Key Changes +- `tests/test_review.py`: `test_review_path_workflow`, `test_review_branch_workflow`, `test_review_pr_workflow` and `test_review_path_watch_mode` no longer patch `load_settings`. The three workflow tests also drop an inert `monkeypatch` of `devops_cli.core.validation.validate_service_url`, a name no review path reads, and the parameters left unused. +- `tests/test_review_stage_flags.py`: `test_review_cli_stage_flags_propagation` no longer patches `load_settings`. +- `pyproject.toml` (`[tool.pytest.ini_options]`): `filterwarnings` turns `Logfire API is unreachable` and `pytest.PytestUnhandledThreadExceptionWarning` into errors. + +## Acceptance Criteria +- [x] The cause is named: the `MagicMock` settings made `_init_logfire_if_enabled` call `LogfireBridge.configure`, which read the token from the mock through `get_logfire_token` and called `logfire.configure`, starting the `check_logfire_token` thread. +- [x] A test run never configures the Logfire SDK unless a test asks for it: the `filterwarnings` entries in `pyproject.toml` fail any test that starts the token check, and `tests/test_review.py` and `tests/test_review_stage_flags.py` pass with them. +- [x] The corrected reproduction passes: `uv run pytest -p no:cacheprovider -q -n 0 tests/test_review.py tests/test_review_stage_flags.py -W "error:Logfire API is unreachable:UserWarning" -W "error::pytest.PytestUnhandledThreadExceptionWarning"`. +- [x] `uv run devops ci` passes: the pre-push gate and the PR's checks run it. + +## Deliverables +- [x] The five tests read the per-test config instead of a `MagicMock` settings object. +- [x] `pyproject.toml` warning filters that keep the token check out of every test run. +- [x] `changelog.d/965.md`. +- The four other tests that patch `_init_logfire_if_enabled` alongside a `MagicMock` `load_settings` (the `--full` test in `tests/test_review.py`, two in `tests/test_review_pr_post.py`, one in `tests/test_review_path_routing.py`): moved to #1326, which migrates them to the `config` fixture. diff --git a/pyproject.toml b/pyproject.toml index 3cc22b420e..57d26341d6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -150,6 +150,12 @@ addopts = "-n logical -p no:logfire -p no:pytest_logfire" markers = [ "bwrap: live sandbox tests requiring bubblewrap; skipped where bwrap is not installed", ] +# Logfire's token check warns from a background thread, so the warning fails a test only +# through pytest's unhandled-thread warning; both are errors so no test starts it (#965). +filterwarnings = [ + "error:Logfire API is unreachable:UserWarning", + "error::pytest.PytestUnhandledThreadExceptionWarning", +] [tool.coverage.run] diff --git a/tests/test_review.py b/tests/test_review.py index da6912212d..22cb462ace 100644 --- a/tests/test_review.py +++ b/tests/test_review.py @@ -29,11 +29,8 @@ def test_review_explain() -> None: assert res_br.exit_code == 0 -def test_review_path_workflow(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: +def test_review_path_workflow(tmp_path: Path) -> None: """Verify devops review path workflow execution.""" - monkeypatch.setattr( - "devops_cli.core.validation.validate_service_url", lambda *args, **kwargs: None - ) py_file = tmp_path / "app.py" py_file.write_text("def run():\n pass\n", encoding="utf-8") @@ -44,19 +41,14 @@ def test_review_path_workflow(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) - return_value=(["code page"], "Path Review", "AGENTS.md", []), ), patch("devops_cli.commands.review._execute_review_workflow", return_value=mock_wf), - patch("devops_cli.commands.review.load_settings"), ): res = runner.invoke(review_app, ["path", str(py_file), "--persona", "architect"]) assert res.exit_code == 0 -def test_review_branch_workflow(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: +def test_review_branch_workflow() -> None: """Verify devops review branch workflow execution, handed the base revision its diff starts from (#593).""" - monkeypatch.setattr( - "devops_cli.core.validation.validate_service_url", lambda *args, **kwargs: None - ) - mock_wf = [(MagicMock(title="DevSecOps", name="devsecops"), "Security comments")] prepared = ( ["diff content"], @@ -70,7 +62,6 @@ def test_review_branch_workflow(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) patch( "devops_cli.commands.review._execute_review_workflow", return_value=mock_wf ) as workflow, - patch("devops_cli.commands.review.load_settings"), ): res = runner.invoke(review_app, ["branch", "feat/my-feature", "--persona", "devsecops"]) @@ -80,12 +71,9 @@ def test_review_branch_workflow(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) ) -def test_review_pr_workflow(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: +def test_review_pr_workflow() -> None: """Verify devops review pr workflow execution, handed the base revision its diff starts from (#593).""" - monkeypatch.setattr( - "devops_cli.core.validation.validate_service_url", lambda *args, **kwargs: None - ) mock_pull = MagicMock() mock_wf = [(MagicMock(title="QA", name="qa"), "QA feedback")] prepared = (["pr diff"], "PR 10", "AGENTS.md", mock_pull, "org/repo", sentinel.base_revision) @@ -95,7 +83,6 @@ def test_review_pr_workflow(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> patch( "devops_cli.commands.review._execute_review_workflow", return_value=mock_wf ) as workflow, - patch("devops_cli.commands.review.load_settings"), ): res = runner.invoke(review_app, ["pr", "10", "--persona", "qa"]) @@ -428,7 +415,6 @@ def test_review_path_watch_mode(tmp_path: Path) -> None: with ( patch("devops_cli.commands.review._make_review_clients"), - patch("devops_cli.commands.review.load_settings"), patch("devops_cli.watchers.file_watcher.DebouncedFileWatcher.watch") as mock_watcher_watch, ): res = runner.invoke(review_app, ["path", str(py_file), "--watch", "--debounce-ms", "300"]) diff --git a/tests/test_review_stage_flags.py b/tests/test_review_stage_flags.py index 1900f7d7e7..c10bbed858 100644 --- a/tests/test_review_stage_flags.py +++ b/tests/test_review_stage_flags.py @@ -90,7 +90,6 @@ def test_resolve_stage_flags_conflicting_no_and_only() -> None: def test_review_cli_stage_flags_propagation() -> None: """Verify CLI review commands pass resolved stage flags to workflow.""" with ( - patch("devops_cli.commands.review.load_settings"), patch("devops_cli.commands.review._make_review_clients"), patch( "devops_cli.commands.review._prepare_path_content", From 77dadbb10e0a97b71215d74392e1afcf06b45f04 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 9 Oct 2026 10:00:01 -0600 Subject: [PATCH 06/15] fix(security): URL and host:port reads use the sending client's parser (#1112) (#1506) --- changelog.d/1112.md | 12 ++ ...k-1112-url-and-host-port-client-parsers.md | 75 +++++++++++++ .../ai/benchmark/embedding_runner.py | 42 ++++--- src/devops_cli/ai/benchmark/model_spec.py | 29 +++++ src/devops_cli/ai/benchmark/runner.py | 25 ++--- src/devops_cli/ai/library/docs_ingester.py | 39 ++++--- src/devops_cli/ai/mcp/server.py | 18 ++- src/devops_cli/ai/models/ollama.py | 17 +-- src/devops_cli/ai/spend/pricing.py | 27 ++--- src/devops_cli/commands/benchmark.py | 10 +- src/devops_cli/commands/k8s/networking.py | 12 +- src/devops_cli/config/constants.py | 5 +- src/devops_cli/config/settings.py | 17 ++- src/devops_cli/http/urls.py | 106 ++++++++++++++++++ src/devops_cli/k8s/credentials.py | 35 ++++-- src/devops_cli/sandbox/metrics.py | 23 +++- src/devops_cli/sandbox/models.py | 25 +++-- src/devops_cli/sandbox/probe.py | 49 +++++--- src/devops_cli/security/vault_broker.py | 16 +-- .../security/vulnerability_lookup.py | 7 +- src/devops_cli/telemetry/instruments.py | 5 +- src/devops_cli/telemetry/tracer.py | 65 ++++++----- tests/test_ai_benchmark.py | 52 +++++++++ tests/test_ai_client_security.py | 15 +++ tests/test_docs_ingester.py | 76 ++++++++++++- tests/test_embedding_benchmark.py | 80 ++++++++++--- tests/test_k8s_credentials.py | 77 ++++++++++++- tests/test_mcp.py | 15 +++ tests/test_sandbox_metrics.py | 22 ++++ tests/test_sandbox_policy_properties.py | 58 +++++++++- tests/test_sandbox_probe.py | 31 +++-- tests/test_telemetry.py | 76 +++++++++---- tests/test_vault_broker.py | 2 + tests/test_vulnerability_lookup.py | 11 ++ 34 files changed, 940 insertions(+), 234 deletions(-) create mode 100644 changelog.d/1112.md create mode 100644 docs/agent/tasks/task-1112-url-and-host-port-client-parsers.md create mode 100644 src/devops_cli/ai/benchmark/model_spec.py create mode 100644 src/devops_cli/http/urls.py diff --git a/changelog.d/1112.md b/changelog.d/1112.md new file mode 100644 index 0000000000..78117ad3d0 --- /dev/null +++ b/changelog.d/1112.md @@ -0,0 +1,12 @@ +### Changed +- The settings parser refuses scheme-less URLs for `argocd.url`, `grafana.url`, `ai.ollama_urls`, and `OLLAMA_BASE_URL` with a prescriptive `ConfigurationError` instead of prefixing `http://`. +- The network probe refuses targets lacking a host name or carrying invalid ports with a `ValidationError`. +- The embedding benchmark refuses unrecognised endpoints under a gateway provider, requiring `--provider` to benchmark external endpoints. +- Sandbox whitelist parsing refuses entries containing empty port suffixes (`example.com:`, `example.com:/path`). + +### Fixed +- URL, endpoint, and authority reads across benchmark runners, docs ingester, telemetry exporters, vulnerability lookups, and pricing now use sending client parsers (`httpx2.URL` and `read_url_or_authority`), preventing scheme sniffing and port mismatch bugs. +- Benchmark key trust boundaries compare canonical URL origins through `httpx2.Origin`, preventing trust boundary leaks and ensuring consistent host evaluation. +- The documentation crawler normalizes link resolution and origin checks using `httpx2.URL.origin`, preventing scheme downgrades and SSRF boundary escapes. +- OTLP telemetry client preserves explicit collector schemes and endpoints, preventing invalid gRPC port conversions and TLS configuration errors. +- Vault broker URI parsing respects scheme case-insensitivity and preserves fragment separation. diff --git a/docs/agent/tasks/task-1112-url-and-host-port-client-parsers.md b/docs/agent/tasks/task-1112-url-and-host-port-client-parsers.md new file mode 100644 index 0000000000..d45a4dc557 --- /dev/null +++ b/docs/agent/tasks/task-1112-url-and-host-port-client-parsers.md @@ -0,0 +1,75 @@ +# Task: URL and host:port reads use the sending client's parser (#1112) + +**Issue**: [#1112](https://github.com/dan-petty/devops-cli/issues/1112) +**Status**: Done +**Milestone**: v0.2.32 +**Priority**: priority/p2-medium +**Scope**: scope/security + +## Description +Several modules read URLs or bare `host:port` pairs using ad-hoc substring tests, scheme sniffing (`"://"`), manual port tables (`443 if https else 80`), hand-rolled `split(":")` splits, and `str.replace` chains before handing the values to underlying clients (`httpx2`, `OTLPSpanExporter`, `socket`). When the custom parsing logic disagreed with the sending client, security boundaries broke: checks evaluated against one host while requests dialled another (e.g. `https://example.com\@192.0.2.1/v1`), valid IPv6 or IDN endpoints were rejected, and scheme-less credentials were sent over plaintext HTTP. + +This fix unifies URL, authority, and model spec parsing around sending client parsers: +1. Created `devops_cli.http.urls` providing: + - `get_url_origin(value)`: Resolves canonical `httpx2.Origin` or `None` without raising. + - `read_url_or_authority(s)`: Parses standard URLs or bare authorities (`host[:port]`) into a `SplitResult` with a valid host, supporting bare and bracketed IPv6. + - `extract_domain_target(s)`: Extracts the canonical domain or hostname. + - `append_path(base, reference)`: Appends relative paths without dropping trailing slashes or path prefixes. +2. Centralized `model@endpoint` parsing into `devops_cli.ai.benchmark.model_spec`: + - `parse_model_spec(entry)` cleanly splits `(model, endpoint)` preserving userinfo. + - `parse_model_list(model_str)` splits comma-separated model strings. + - Removed `CONST_MODEL_ENDPOINT_MARKERS` and ad-hoc splits. +3. Hardened key trust, crawler, probe, and credentials paths: + - Benchmark runner key trust (`_key_for_endpoint`) checks canonical origin equality against configured endpoints via `get_url_origin`. + - Docs ingester normalizes link resolution and origin checks via `httpx2.URL.origin`, sanitizes directory slugs, and prevents path traversal escapes. + - Network probe (`_parse_target_endpoint`) returns `httpx2.Origin` and raises `ValidationError` for missing hosts or invalid ports. + - OTLP telemetry exporter preserves user endpoints and derives `insecure` flag from scheme. + - ArgoCD, Grafana, and Ollama settings refuse scheme-less URLs with `ConfigurationError`. + - Vault broker URI parsing handles case-insensitive `vault://` schemes and preserves fragment separation. + +## Key Changes +- **URL & Origin Utilities** (`src/devops_cli/http/urls.py`): + - Implemented `get_url_origin`, `read_url_or_authority`, `extract_domain_target`, and `append_path`. +- **Model Spec Centralization** (`src/devops_cli/ai/benchmark/model_spec.py`): + - Implemented `parse_model_spec` and `parse_model_list`. + - Replaced manual splits in `runner.py`, `embedding_runner.py`, `benchmark.py`, and `server.py`. +- **Key Trust & Benchmark Runner** (`src/devops_cli/ai/benchmark/runner.py` & `embedding_runner.py`): + - Used `get_url_origin` to match origins across configured base URLs and endpoints. + - Required `--provider` when benchmark endpoint does not match configured `gateway_url` under gateway provider. +- **Docs Ingester Hardening** (`src/devops_cli/ai/library/docs_ingester.py`): + - Replaced `netloc`, `urljoin`, and `urlparse` with `httpx2.URL` and `httpx2.Origin` comparisons. + - Sanitized directory slugs to prevent traversal via `%2e%2e` and stripped userinfo. +- **Probe & Telemetry** (`src/devops_cli/sandbox/probe.py`, `src/devops_cli/telemetry/tracer.py`, `src/devops_cli/sandbox/metrics.py`): + - `_parse_target_endpoint` returns `httpx2.Origin` and validates host and port. + - `_build_scrape_url` parses target via `read_url_or_authority` and constructs valid `httpx2.URL`. + - OTLP trace exporter passes unmodified endpoint and sets `insecure` from scheme. +- **Settings & Credentials** (`src/devops_cli/k8s/credentials.py`, `src/devops_cli/config/settings.py`, `src/devops_cli/ai/models/ollama.py`): + - `_clean_service_base_url` and `get_ollama_urls` refuse scheme-less entries with `ConfigurationError`. +- **Tests**: + - Added key trust test cases for backslash host mismatch, default https ports, IDN punycode, and unparseable URLs in `tests/test_ai_benchmark.py`. + - Added crawler origin filtering and slug traversal tests in `tests/test_docs_ingester.py`. + - Added probe origin return and validation tests in `tests/test_sandbox_probe.py`. + - Added telemetry OTLPSpanExporter and connection probe tests in `tests/test_telemetry.py`. + - Added service credential scheme-less validation tests in `tests/test_k8s_credentials.py`. + - Added Ollama URL normalization tests in `tests/test_ai_client_security.py`. + - Added scrape URL construction tests in `tests/test_sandbox_metrics.py`. + - Added whitelist host extraction and rejection tests in `tests/test_sandbox_policy_properties.py`. + - Added Vault URI scheme-casing tests in `tests/test_vault_broker.py`. + - Added MCP model string acceptance and rejection tests in `tests/test_mcp.py`. + - Added embedding provider resolution tests in `tests/test_embedding_benchmark.py`. + +## Acceptance Criteria +- [x] Key trust tests verify backslash mismatches fail closed, IDN origins match, and unparseable URLs return empty keys without raising. +- [x] Direct calls to `_key_for_endpoint` fail closed on malformed URLs. +- [x] Docs ingester follows links on same origin, skips scheme downgrades and invalid URLs, and confines directory slugs to children of the ingest root. +- [x] Network probe `_parse_target_endpoint` returns `httpx2.Origin` with scheme, host, and port, and raises `ValidationError` on malformed targets. +- [x] OTLP telemetry client preserves endpoints, dials correct host/port, and infers protocol from port 4317. +- [x] Credentials minting refuses scheme-less `argocd.url` and `grafana.url` with `ConfigurationError`. +- [x] `get_ollama_urls` normalizes uppercase schemes and refuses scheme-less URLs. +- [x] `_build_scrape_url` preserves target paths and handles hosts starting with "http". +- [x] Sandbox whitelist host extraction normalizes case and rejects empty port entries. +- [x] Vault broker parses uppercase `VAULT://` URIs. +- [x] MCP tools reject endpoint overrides (`x@...`) and accept valid multi-model specs. +- [x] Embedding runner selects provider based on origin matching or refuses unknown endpoints under gateway provider. +- [x] No forbidden parsing constructs remain across modified files. +- [x] All automated tests pass offline without external network dependencies. diff --git a/src/devops_cli/ai/benchmark/embedding_runner.py b/src/devops_cli/ai/benchmark/embedding_runner.py index 679609c02e..a0e81341f7 100644 --- a/src/devops_cli/ai/benchmark/embedding_runner.py +++ b/src/devops_cli/ai/benchmark/embedding_runner.py @@ -18,6 +18,7 @@ from devops_cli.ai.benchmark.embedding_tasks import ( EmbeddingEvalPair, ) +from devops_cli.ai.benchmark.model_spec import parse_model_spec from devops_cli.ai.benchmark.runner import _get_benchmarks_base_dir, _key_for_endpoint from devops_cli.ai.rag.embeddings import EmbeddingsEngine from devops_cli.ai.vector_similarity import cosine_similarity @@ -252,21 +253,35 @@ def is_dry_run_active(self) -> bool: def _engine_for_model(self, model_name: str, server_url: str | None = None) -> EmbeddingsEngine: """Instantiate an EmbeddingsEngine configured for the specified model and server.""" + from devops_cli.ai.benchmark.model_spec import parse_model_spec from devops_cli.core.validation import validate_url + from devops_cli.exceptions import ValidationError + from devops_cli.http.urls import get_url_origin endpoint = server_url - clean_model = model_name - if "@" in model_name: - clean_model, _, explicit_endpoint = model_name.partition("@") - if explicit_endpoint: - endpoint = explicit_endpoint + clean_model, explicit_endpoint = parse_model_spec(model_name) + if explicit_endpoint: + endpoint = explicit_endpoint if not endpoint and self.servers: endpoint = self.servers[0] resolved_provider = self.provider - if endpoint and (":11434" in endpoint or "ollama" in endpoint): - resolved_provider = "ollama" + if endpoint: + endpoint_origin = get_url_origin(endpoint) + ollama_origins = { + origin for u in self.settings.ai.ollama_urls if (origin := get_url_origin(u)) + } + gateway_origin = get_url_origin(self.settings.ai.gateway_url or "") + if endpoint_origin and endpoint_origin in ollama_origins: + resolved_provider = "ollama" + elif endpoint_origin and gateway_origin and endpoint_origin == gateway_origin: + resolved_provider = "gateway" + elif self.provider == "gateway": + raise ValidationError( + f"Embedding benchmark endpoint '{endpoint}' does not match configured gateway_url " + f"'{self.settings.ai.gateway_url}'. Specify --provider to benchmark an explicit endpoint under another provider." + ) allow_priv = self.settings.ai.allow_private_network ai_kwargs: dict[str, Any] = { @@ -292,10 +307,9 @@ def evaluate_model( ) -> EmbeddingBenchmarkResult: """Execute full benchmark evaluation for a single model.""" endpoint = server_url - if "@" in model_name: - _clean_model, _, explicit_endpoint = model_name.partition("@") - if explicit_endpoint: - endpoint = explicit_endpoint + _clean_model, explicit_endpoint = parse_model_spec(model_name) + if explicit_endpoint: + endpoint = explicit_endpoint if not endpoint: endpoint = self.servers[0] if self.servers else "default" return self.evaluate_model_on_server(model_name, endpoint, pairs, corpus) @@ -308,7 +322,7 @@ def evaluate_model_on_server( # noqa: C901 corpus: list[str], ) -> EmbeddingBenchmarkResult: """Execute full benchmark evaluation for a single model on a specific server.""" - clean_model = model_name.split("@")[0] + clean_model, _ = parse_model_spec(model_name) with self._print_lock: print_info( @@ -534,8 +548,8 @@ def run(self) -> EmbeddingBenchmarkReport: # Build Cartesian product of (model, server) if multiple servers provided target_runs: list[tuple[str, str]] = [] for m in self.models: - if "@" in m: - clean_m, _, srv = m.partition("@") + clean_m, srv = parse_model_spec(m) + if srv: target_runs.append((clean_m, srv)) elif len(self.servers) > 1: for srv in self.servers: diff --git a/src/devops_cli/ai/benchmark/model_spec.py b/src/devops_cli/ai/benchmark/model_spec.py new file mode 100644 index 0000000000..87daded192 --- /dev/null +++ b/src/devops_cli/ai/benchmark/model_spec.py @@ -0,0 +1,29 @@ +"""Model spec parsing for benchmark commands and runners.""" + +from __future__ import annotations + + +def parse_model_spec(entry: str) -> tuple[str, str | None]: + """Parse a 'model[@endpoint]' specification. + + Returns (model, endpoint) where endpoint is None if '@' is not present in entry. + """ + if "@" not in entry: + return entry, None + model, _, endpoint = entry.partition("@") + return model, endpoint + + +def parse_model_list(models: str | None, default_model: str | None = None) -> list[str]: + """Parse comma-separated model string into list of models.""" + if models: + return [m.strip() for m in models.split(",") if m.strip()] + if default_model is not None: + return [default_model] + return [] + + +__all__ = [ + "parse_model_list", + "parse_model_spec", +] diff --git a/src/devops_cli/ai/benchmark/runner.py b/src/devops_cli/ai/benchmark/runner.py index ae6f44a1d6..fc55daf5f5 100644 --- a/src/devops_cli/ai/benchmark/runner.py +++ b/src/devops_cli/ai/benchmark/runner.py @@ -11,7 +11,6 @@ from datetime import UTC, datetime from pathlib import Path from typing import Any -from urllib.parse import urlsplit from devops_cli.ai.client import LLMClient from devops_cli.ai.review_schema import extract_json_block @@ -19,6 +18,7 @@ from devops_cli.config.constants import CONST_AI_GATEWAY_PROVIDER, CONST_AI_PROVIDER_API_BASES from devops_cli.config.settings import AIConfig, Settings, get_ai_api_key, load_settings from devops_cli.dry_run.state import is_dry_run +from devops_cli.http.urls import get_url_origin from devops_cli.models.benchmark import ( BenchmarkReport, BenchmarkTask, @@ -53,16 +53,6 @@ def _get_benchmarks_base_dir() -> Path: return d -def _url_origin(url: str) -> tuple[str, str, int] | None: - """The scheme, host and port a URL reaches, or None for one that names no host.""" - parts = urlsplit(url.strip()) - try: - port = parts.port or (443 if parts.scheme == "https" else 80) - except ValueError: - return None - return (parts.scheme, parts.hostname, port) if parts.hostname is not None else None - - def _key_for_endpoint(settings: Settings, client_config: AIConfig) -> str: """The configured AI key when `client_config` sends it to an endpoint the configuration names. @@ -80,7 +70,7 @@ def _key_for_endpoint(settings: Settings, client_config: AIConfig) -> str: configured.gateway_url, CONST_AI_PROVIDER_API_BASES.get(configured.provider.lower()), ) - if url and (origin := _url_origin(url)) + if url and (origin := get_url_origin(url)) } provider = client_config.provider.lower() endpoint = ( @@ -88,7 +78,7 @@ def _key_for_endpoint(settings: Settings, client_config: AIConfig) -> str: if provider == CONST_AI_GATEWAY_PROVIDER else client_config.api_base_url or CONST_AI_PROVIDER_API_BASES.get(provider) ) - if endpoint and _url_origin(endpoint) in trusted: + if endpoint and get_url_origin(endpoint) in trusted: return get_ai_api_key(settings) or "" return "" @@ -209,14 +199,13 @@ def _client_for_model( server_url: str | None = None, ) -> LLMClient: """Instantiate an LLMClient for a given model override and server endpoint.""" + from devops_cli.ai.benchmark.model_spec import parse_model_spec from devops_cli.core.validation import validate_url endpoint = server_url - clean_model = model_name - if "@" in model_name: - clean_model, _, explicit_endpoint = model_name.partition("@") - if explicit_endpoint: - endpoint = explicit_endpoint + clean_model, explicit_endpoint = parse_model_spec(model_name) + if explicit_endpoint: + endpoint = explicit_endpoint if not endpoint and self.servers: m_idx = self.models.index(model_name) if model_name in self.models else 0 diff --git a/src/devops_cli/ai/library/docs_ingester.py b/src/devops_cli/ai/library/docs_ingester.py index 9da3a9572b..9289adb0fa 100644 --- a/src/devops_cli/ai/library/docs_ingester.py +++ b/src/devops_cli/ai/library/docs_ingester.py @@ -10,7 +10,7 @@ from html.parser import HTMLParser from pathlib import Path from typing import ClassVar -from urllib.parse import urldefrag, urljoin, urlparse +from urllib.parse import urldefrag import httpx2 @@ -237,11 +237,10 @@ def ingest_remote_docs( """Ingest remote documentation page over HTTP/HTTPS with strict SSRF validation.""" validate_service_url(url, "Docs Ingestion", allow=False) - parsed_origin = urlparse(url) - origin_netloc = parsed_origin.netloc - base_slug = ( - parsed_origin.path.strip("/").replace("/", "_") or parsed_origin.netloc - ) or "remote_doc" + parsed_url = httpx2.URL(url) + start_origin = parsed_url.origin + ingest_root = resolve_store_path(Path("docs_ingest")) + base_slug = _compute_base_slug(parsed_url, ingest_root) target_dir = resolve_store_path( Path("docs_ingest") / base_slug, explicit=output_dir, @@ -282,7 +281,7 @@ def ingest_remote_docs( markdown_text = raw_text page_slug = ( - urlparse(clean_url).path.strip("/").replace("/", "_") or base_slug + httpx2.URL(clean_url).path.strip("/").replace("/", "_") or base_slug ) or "page" chunks = _chunk_markdown_content( markdown_text, source=mask_uri_credentials(clean_url), slug=page_slug @@ -290,7 +289,7 @@ def ingest_remote_docs( all_chunks.extend(chunks) if max_pages > 1 and len(visited) < max_pages: - _collect_child_links(links, clean_url, origin_netloc, visited, queue) + _collect_child_links(links, clean_url, start_origin, visited, queue) chunk_files = _save_chunks(all_chunks, target_dir) @@ -304,24 +303,34 @@ def ingest_remote_docs( ) +def _compute_base_slug(parsed_url: httpx2.URL, ingest_root: Path) -> str: + """Compute safe base directory slug from URL path, falling back to host.""" + path_slug = parsed_url.path.strip("/").replace("/", "_") + if path_slug and (ingest_root / path_slug).resolve().parent == ingest_root.resolve(): + return path_slug + return parsed_url.host or "remote_doc" + + def _collect_child_links( links: list[str], current_url: str, - origin_netloc: str, + start_origin: httpx2.Origin, visited: set[str], queue: list[str], ) -> None: """Filter and enqueue candidate links on the same origin domain.""" + base_url = httpx2.URL(current_url) for link in links: - resolved = urljoin(current_url, link) - p_res = urlparse(resolved) - is_same_origin = p_res.netloc == origin_netloc and p_res.scheme in ("http", "https") - if not is_same_origin: + try: + resolved = base_url.join(link) + if resolved.origin != start_origin: + continue + except httpx2.InvalidURL, ValueError: continue - if p_res.path.lower().endswith( + if resolved.path.lower().endswith( (".png", ".jpg", ".jpeg", ".gif", ".svg", ".zip", ".tar", ".gz", ".pdf") ): continue - clean_res = urldefrag(resolved).url + clean_res = urldefrag(str(resolved)).url if clean_res not in visited and clean_res not in queue: queue.append(clean_res) diff --git a/src/devops_cli/ai/mcp/server.py b/src/devops_cli/ai/mcp/server.py index 9a0e6812f7..0a30620597 100644 --- a/src/devops_cli/ai/mcp/server.py +++ b/src/devops_cli/ai/mcp/server.py @@ -35,7 +35,6 @@ CONST_MCP_LAZY_DOMAINS, CONST_MCP_MAX_COMMAND_OUTPUT_CHARS, CONST_MIN_SECURITY_STREAM_TAIL_LINES, - CONST_MODEL_ENDPOINT_MARKERS, CONST_VERIFIED_BY_AGENT, ) from devops_cli.config.defaults import ( @@ -2295,8 +2294,21 @@ def _validate_mcp_benchmark_target(provider: str, model: str) -> None: ERRORS.mcp.unknown_provider.format(choices=", ".join(CONST_AI_PROVIDER_IDS)), field="provider", ) - if any(marker in model for marker in CONST_MODEL_ENDPOINT_MARKERS): - raise ValidationError(ERRORS.mcp.model_names_endpoint, field="model") + import httpx2 + + from devops_cli.ai.benchmark.model_spec import parse_model_list, parse_model_spec + + entries = parse_model_list(model) + for entry in entries: + _clean_model, endpoint = parse_model_spec(entry) + if endpoint is not None: + raise ValidationError(ERRORS.mcp.model_names_endpoint, field="model") + try: + is_abs = httpx2.URL(entry).is_absolute_url + except ValueError, httpx2.InvalidURL: + is_abs = True + if is_abs: + raise ValidationError(ERRORS.mcp.model_names_endpoint, field="model") @mcp.tool() diff --git a/src/devops_cli/ai/models/ollama.py b/src/devops_cli/ai/models/ollama.py index de4ea20917..3d23288197 100644 --- a/src/devops_cli/ai/models/ollama.py +++ b/src/devops_cli/ai/models/ollama.py @@ -51,22 +51,17 @@ def normalize_ollama_base_url(url: str, *, allow_private: bool = True) -> str: if not clean_url: clean_url = DEFAULT_OLLAMA_BASE_URL - if "://" in clean_url: - scheme = clean_url.split("://", 1)[0].lower() - if scheme not in ("http", "https"): - raise InvalidURLError( - clean_url, - reason=f"Invalid Ollama URL scheme '{scheme}': must be http or https", - ) - elif not clean_url.startswith(("http://", "https://")): - clean_url = f"http://{clean_url}" - parsed = urlsplit(clean_url) - if parsed.scheme not in ("http", "https"): + if parsed.scheme.lower() not in ("http", "https"): raise InvalidURLError( clean_url, reason=f"Invalid Ollama URL scheme '{parsed.scheme}': must be http or https", ) + if not parsed.netloc: + raise InvalidURLError( + clean_url, + reason=f"Invalid Ollama URL '{clean_url}': missing host or authority", + ) host = (parsed.hostname or "").lower() if _is_cloud_metadata_host(host): diff --git a/src/devops_cli/ai/spend/pricing.py b/src/devops_cli/ai/spend/pricing.py index 894e8e0f12..e5946b1be7 100644 --- a/src/devops_cli/ai/spend/pricing.py +++ b/src/devops_cli/ai/spend/pricing.py @@ -73,17 +73,14 @@ def _is_configured_ai_server_host(host: str) -> bool: settings.ai.portkey_url, *settings.ai.ollama_urls, ) + from devops_cli.http.urls import extract_domain_target + for cand in candidates: if not cand: continue - clean_cand = cand.strip().lower() - cand_target = clean_cand if "://" in clean_cand else f"http://{clean_cand}" - try: - cand_parsed = urlsplit(cand_target) - if cand_parsed.hostname and cand_parsed.hostname == host: - return True - except Exception: - continue + cand_host = extract_domain_target(cand.strip().lower()) + if cand_host and cand_host == host: + return True return False @@ -105,15 +102,13 @@ def _is_single_server_local(server: str) -> bool: clean = server.strip().lower() if not clean: return False - if clean in CONST_LOCAL_TRANSPORT_LABELS or clean.startswith("http+unix://"): + if clean in CONST_LOCAL_TRANSPORT_LABELS or urlsplit(clean).scheme == "http+unix": + return True + from devops_cli.http.urls import extract_domain_target + + host = extract_domain_target(clean) + if host and _is_local_host(host): return True - target = clean if "://" in clean else f"http://{clean}" - try: - parsed = urlsplit(target) - if parsed.hostname and _is_local_host(parsed.hostname): - return True - except Exception: - pass return False diff --git a/src/devops_cli/commands/benchmark.py b/src/devops_cli/commands/benchmark.py index d0df5e8bd8..9122f136fc 100644 --- a/src/devops_cli/commands/benchmark.py +++ b/src/devops_cli/commands/benchmark.py @@ -8,6 +8,7 @@ import typer from pydantic import BaseModel +from devops_cli.ai.benchmark.model_spec import parse_model_list from devops_cli.config.constants import CONST_BENCHMARK_TYPES from devops_cli.config.defaults import ( DEFAULT_BENCHMARK_CONCURRENCY, @@ -55,13 +56,6 @@ def _validate_benchmark_type(benchmark_type: str) -> None: ) -def _parse_model_list(models: str | None, default_model: str) -> list[str]: - """Parse comma-separated model string into list of models.""" - if models: - return [m.strip() for m in models.split(",") if m.strip()] - return [default_model] - - def _parse_server_list(servers: str | None) -> list[str] | None: """Parse and validate comma-separated Ollama server endpoints.""" if not servers: @@ -313,7 +307,7 @@ def run_benchmark( from devops_cli.config.settings import load_settings settings = load_settings() - model_list = _parse_model_list(models, settings.ai.model) + model_list = parse_model_list(models, settings.ai.model) safe_concurrency = max(1, min(concurrency, 32)) server_list = _parse_server_list(servers) diff --git a/src/devops_cli/commands/k8s/networking.py b/src/devops_cli/commands/k8s/networking.py index 728a8fe9a7..45969fe70d 100644 --- a/src/devops_cli/commands/k8s/networking.py +++ b/src/devops_cli/commands/k8s/networking.py @@ -215,15 +215,15 @@ def _detect_service_url(service: str, namespace: str, context: str | None = None def _verify_url_reachability(url: str, timeout: float = DEFAULT_HTTP_PROBE_TIMEOUT_SECONDS) -> bool: """Check if target HTTP URL host and port can accept socket connections.""" import socket - from urllib.parse import urlparse + + from devops_cli.http.urls import get_url_origin try: - parsed = urlparse(url) - host = parsed.hostname - port = parsed.port or (443 if parsed.scheme == "https" else 80) - if not host: + origin = get_url_origin(url) + if not origin or not origin.host: return False - with socket.create_connection((host, port), timeout=timeout): + port = origin.port or 80 + with socket.create_connection((origin.host, port), timeout=timeout): return True except Exception as exc: logger.debug("URL %s reachability check failed: %s", url, exc) diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 742c8e67b1..513c6334a4 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -307,10 +307,7 @@ # The kinds of run `devops ai benchmark --type` takes: `auto` picks embedding when a model's name # says it embeds and chat otherwise. Any other value is refused rather than run as chat (#950). CONST_BENCHMARK_TYPES: Final[tuple[str, ...]] = ("auto", "chat", "embedding") -# What makes a `--models` entry name the server it runs on: `model@endpoint`, or a URL. Only a -# person at the command line names one; an MCP client is refused, so a model never takes the AI -# key to a host the client chose (#954). -CONST_MODEL_ENDPOINT_MARKERS: Final[tuple[str, ...]] = ("@", "://") + CONST_AUDIT_LOG_NAME = "audit.jsonl" CONST_FEEDBACK_DATASET_NAME = "feedback_dataset.jsonl" CONST_EMBEDDING_REPORT_FILENAME = "embedding_report.json" diff --git a/src/devops_cli/config/settings.py b/src/devops_cli/config/settings.py index 4fdf2e333f..6e470fa406 100644 --- a/src/devops_cli/config/settings.py +++ b/src/devops_cli/config/settings.py @@ -523,12 +523,27 @@ def get_ollama_urls(self) -> list[str]: if not self.ollama_urls: return list(DEFAULT_OLLAMA_URLS) + from urllib.parse import urlsplit, urlunsplit + + from devops_cli.exceptions.config import ConfigurationError + cleaned: list[str] = [] for u in self.ollama_urls: raw = (u or "").strip().rstrip("/") if not raw: continue - cleaned.append(raw if raw.startswith(("http://", "https://")) else f"http://{raw}") + parts = urlsplit(raw) + scheme = parts.scheme.lower() + if scheme not in ("http", "https") or not parts.netloc or not parts.hostname: + raise ConfigurationError( + f"Invalid ai.ollama_urls entry '{u}': must have http or https scheme and host", + key="ai.ollama_urls", + ) + cleaned.append( + urlunsplit((scheme, parts.netloc, parts.path, parts.query, parts.fragment)).rstrip( + "/" + ) + ) return cleaned or list(DEFAULT_OLLAMA_URLS) def for_task(self, task: str) -> AIConfig: diff --git a/src/devops_cli/http/urls.py b/src/devops_cli/http/urls.py new file mode 100644 index 0000000000..b90f14b779 --- /dev/null +++ b/src/devops_cli/http/urls.py @@ -0,0 +1,106 @@ +"""URL parsing and origin resolution using sending client parsers.""" + +from __future__ import annotations + +import ipaddress +import urllib.parse +from typing import TYPE_CHECKING + +import httpx2 + +if TYPE_CHECKING: + from urllib.parse import SplitResult + + +def get_url_origin(value: str) -> httpx2.Origin | None: + """Return the HTTP origin for a URL, or None if unparseable or not absolute.""" + clean = value.strip() + try: + return httpx2.URL(clean).origin + except ValueError, httpx2.InvalidURL: + return None + + +def _bracket_bare_ipv6(s: str) -> str: + """Bracket bare IPv6 address literal if valid, else return unchanged.""" + try: + ip = ipaddress.ip_address(s) + if isinstance(ip, ipaddress.IPv6Address): + return f"[{ip}]" + except ValueError: + pass + return s + + +def _has_empty_port(netloc: str) -> bool: + """Check if netloc ends with a colon or has an empty port component.""" + host_port = netloc.split("@")[-1] + return host_port.endswith(":") + + +def _resolve_netloc_fallback(s: str, parsed: SplitResult) -> SplitResult: + """Apply //netloc fallback when urlsplit(s) found no netloc.""" + fallback = urllib.parse.urlsplit(f"//{s}") + if parsed.scheme: + try: + has_port = fallback.port is not None + except ValueError: + has_port = True + if has_port: + return fallback + return parsed + return fallback + + +def read_url_or_authority(s: str) -> SplitResult | None: + """Parse a URL or bare authority (host[:port]) into a SplitResult with a valid host.""" + if not isinstance(s, str): + return None + try: + clean = _bracket_bare_ipv6(s) + parsed = urllib.parse.urlsplit(clean) + + if not parsed.netloc: + parsed = _resolve_netloc_fallback(clean, parsed) + + if parsed.netloc and _has_empty_port(parsed.netloc): + return None + + host = parsed.hostname + if not host: + return None + return parsed + except ValueError: + return None + + +def extract_domain_target(s: str) -> str | None: + """Extract the hostname from a URL or bare host:port string.""" + parsed = read_url_or_authority(s) + if parsed is None: + return None + try: + return parsed.hostname + except ValueError: + return None + + +def append_path(base: httpx2.URL | str, reference: str) -> httpx2.URL: + """Append a relative path reference to a base URL without losing trailing path components.""" + url = httpx2.URL(base) if isinstance(base, str) else base + if not reference: + return url + raw_path = url.raw_path + if not raw_path.endswith(b"/"): + raw_path = raw_path + b"/" + base_with_slash = url.copy_with(raw_path=raw_path) + rel = "./" + reference.lstrip("/") + return base_with_slash.join(rel) + + +__all__ = [ + "append_path", + "extract_domain_target", + "get_url_origin", + "read_url_or_authority", +] diff --git a/src/devops_cli/k8s/credentials.py b/src/devops_cli/k8s/credentials.py index 2c9afd2278..0259776ad5 100644 --- a/src/devops_cli/k8s/credentials.py +++ b/src/devops_cli/k8s/credentials.py @@ -22,14 +22,23 @@ logger = logging.getLogger(__name__) -def _clean_service_base_url(base_url: str) -> str: - """Ensure base URL has scheme and no trailing slash.""" +def _clean_service_base_url(base_url: str, setting_name: str = "service URL") -> str: + """Ensure base URL has valid http/https scheme and host, returning urlunsplit without trailing slash.""" clean = (base_url or "").strip().rstrip("/") if not clean: return "" - if not clean.startswith(("http://", "https://")): - return f"http://{clean}" - return clean + from urllib.parse import urlsplit, urlunsplit + + from devops_cli.exceptions.config import ConfigurationError + + parts = urlsplit(clean) + scheme = parts.scheme.lower() + if scheme not in ("http", "https") or not parts.netloc or not parts.hostname: + raise ConfigurationError( + f"Invalid {setting_name} '{base_url}': must have http or https scheme and host", + key=setting_name, + ) + return urlunsplit((scheme, parts.netloc, parts.path, parts.query, parts.fragment)).rstrip("/") def _safe_keyring_set(key: str, value: str) -> bool: @@ -207,7 +216,7 @@ def mint_argocd_token( from devops_cli.http.validation import validate_service_url - clean_base = _clean_service_base_url(base_url) + clean_base = _clean_service_base_url(base_url, "argocd.url") if not clean_base or not password: return None try: @@ -302,7 +311,7 @@ def mint_grafana_token( from devops_cli.http.validation import validate_service_url - clean_base = _clean_service_base_url(base_url) + clean_base = _clean_service_base_url(base_url, "grafana.url") if not clean_base or not password: return None try: @@ -387,9 +396,13 @@ def verify_argocd_token( """Verify that an ArgoCD session token is valid and active.""" import httpx2 + from devops_cli.exceptions.config import ConfigurationError from devops_cli.http.validation import validate_service_url - clean_base = _clean_service_base_url(base_url) + try: + clean_base = _clean_service_base_url(base_url, "argocd.url") + except ConfigurationError: + return False if not clean_base or not token: return False try: @@ -418,9 +431,13 @@ def verify_grafana_token( """Verify that a Grafana API or Service Account token is valid and active.""" import httpx2 + from devops_cli.exceptions.config import ConfigurationError from devops_cli.http.validation import validate_service_url - clean_base = _clean_service_base_url(base_url) + try: + clean_base = _clean_service_base_url(base_url, "grafana.url") + except ConfigurationError: + return False if not clean_base or not token: return False try: diff --git a/src/devops_cli/sandbox/metrics.py b/src/devops_cli/sandbox/metrics.py index b1fd5f69b9..378ee88767 100644 --- a/src/devops_cli/sandbox/metrics.py +++ b/src/devops_cli/sandbox/metrics.py @@ -641,9 +641,26 @@ def _resolve_instance_port(instance: SandboxInstance) -> int: def _build_scrape_url(target: str, prom_endpoint: str) -> str: """Build normalized Prometheus scrape URL.""" - base = target if target.startswith("http") else f"http://{target}" - ep = prom_endpoint if prom_endpoint.startswith("/") else f"/{prom_endpoint}" - return f"{base.rstrip('/')}{ep}" + from devops_cli.http.urls import read_url_or_authority + + parsed = read_url_or_authority(target) + if parsed is None or not parsed.hostname: + raise ValueError(f"Scrape target '{target}' names no valid host.") + + scheme = parsed.scheme.lower() if parsed.scheme else "http" + if scheme not in ("http", "https"): + raise ValueError(f"Invalid scrape target scheme '{scheme}': must be http or https") + + try: + port = parsed.port + except ValueError as exc: + raise ValueError(f"Invalid scrape target port: {exc}") from exc + + target_path = parsed.path.rstrip("/") + ep = prom_endpoint.lstrip("/") + full_path = f"{target_path}/{ep}" if target_path else f"/{ep}" + + return str(httpx2.URL(scheme=scheme, host=parsed.hostname, port=port, path=full_path)) __all__ = [ diff --git a/src/devops_cli/sandbox/models.py b/src/devops_cli/sandbox/models.py index dd90f4cb50..c827ed70ee 100644 --- a/src/devops_cli/sandbox/models.py +++ b/src/devops_cli/sandbox/models.py @@ -9,7 +9,6 @@ from enum import StrEnum from pathlib import Path from typing import Any, Final -from urllib.parse import urlsplit from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator @@ -68,11 +67,16 @@ class SandboxNetworkMode(StrEnum): def _ip_entry_host(entry: str) -> str | None: """The address or CIDR a whitelist entry is, or None when it is neither.""" + try: + ip = ipaddress.ip_address(entry) + return str(ip) + except ValueError: + pass try: net = ipaddress.ip_network(entry, strict=False) + return str(net) except ValueError: return None - return str(net) if "/" in entry else str(net.network_address) def _parse_whitelist_entry(entry: str) -> tuple[str, int]: @@ -88,15 +92,20 @@ def _parse_whitelist_entry(entry: str) -> tuple[str, int]: ip_host = _ip_entry_host(clean) if ip_host is not None: return ip_host, CONST_SANDBOX_WHITELIST_DEFAULT_PORTS[""] - has_scheme = "://" in clean + + from devops_cli.http.urls import read_url_or_authority + + parts = read_url_or_authority(clean) + if parts is None or not parts.hostname: + raise ValueError(f"Whitelist entry '{entry}' names no host.") + + host = parts.hostname try: - parts = urlsplit(clean if has_scheme else f"//{clean}") - host, port = parts.hostname, parts.port + port = parts.port except ValueError as exc: raise ValueError(f"Whitelist entry '{entry}' is not a host, URL or CIDR: {exc}") from exc - if not host: - raise ValueError(f"Whitelist entry '{entry}' names no host.") - if not has_scheme and (parts.path or parts.query or parts.fragment): + + if not parts.scheme and (parts.path or parts.query or parts.fragment): raise ValueError( f"Whitelist entry '{entry}' has a path but no scheme; write host:port, or a URL." ) diff --git a/src/devops_cli/sandbox/probe.py b/src/devops_cli/sandbox/probe.py index b4f3eecf00..1b51ff2f6e 100644 --- a/src/devops_cli/sandbox/probe.py +++ b/src/devops_cli/sandbox/probe.py @@ -336,12 +336,15 @@ def probe_grpc( def _resolve_probe_target( target_or_instance: SandboxInstance | str, -) -> tuple[str | None, str, list[tuple[str, int]]]: +) -> tuple[str | None, str, list[httpx2.Origin]]: """Resolve target instance ID, display name, and network endpoints.""" if isinstance(target_or_instance, SandboxInstance): instance_id = target_or_instance.instance_id target_display = target_or_instance.name or target_or_instance.instance_id - endpoints = [("127.0.0.1", b.host_port) for b in target_or_instance.port_bindings] + endpoints = [ + httpx2.Origin(httpx2.URL(scheme="http", host="127.0.0.1", port=b.host_port)) + for b in target_or_instance.port_bindings + ] return instance_id, target_display, endpoints target_display = str(target_or_instance) @@ -397,10 +400,10 @@ def run_sandbox_probes( ctx = get_current_span_context() active_trace_id = ctx.get("trace_id") if ctx else None - for host, port in target_endpoints: + for origin in target_endpoints: _dispatch_probes_for_port( - host=host, - port=port, + host=origin.host, + port=origin.port or 80, protocols=selected_protocols, http_paths=http_paths or _DEFAULT_HTTP_PATHS, expected_statuses=expected_statuses, @@ -427,17 +430,31 @@ def run_sandbox_probes( ) -def _parse_target_endpoint(target_str: str) -> tuple[str, int]: - """Parse raw host:port or URL string into host and port.""" - if "://" in target_str: - parsed = urllib.parse.urlparse(target_str) - host = parsed.hostname or "127.0.0.1" - port = parsed.port or (443 if parsed.scheme == "https" else 80) - return host, port - if ":" in target_str: - parts = target_str.split(":", 1) - return parts[0], int(parts[1]) - return target_str, 80 +def _parse_target_endpoint(target_str: str) -> httpx2.Origin: + """Parse raw host:port or URL string into an httpx2.Origin.""" + from devops_cli.exceptions import ValidationError + from devops_cli.http.urls import get_url_origin, read_url_or_authority + + parsed = read_url_or_authority(target_str) + if parsed is None or not parsed.hostname: + raise ValidationError(f"Target '{target_str}' names no valid host.", field="target") + try: + port = parsed.port + except ValueError as exc: + raise ValidationError( + f"Target '{target_str}' has invalid port: {exc}", field="target" + ) from exc + + if parsed.scheme: + origin = get_url_origin(target_str) + if origin is None: + raise ValidationError( + f"Target '{target_str}' is not a valid URL or host:port.", field="target" + ) + return origin + + port = port or 80 + return httpx2.Origin(httpx2.URL(scheme="http", host=parsed.hostname, port=port)) def _dispatch_probes_for_port( diff --git a/src/devops_cli/security/vault_broker.py b/src/devops_cli/security/vault_broker.py index d5baa02ffb..6fb8ce7102 100644 --- a/src/devops_cli/security/vault_broker.py +++ b/src/devops_cli/security/vault_broker.py @@ -4,7 +4,7 @@ import os from typing import Any, Literal -from urllib.parse import urlparse +from urllib.parse import urldefrag, urlsplit import httpx2 from pydantic import BaseModel, ValidationError @@ -69,17 +69,13 @@ def parse_vault_uri(uri: str) -> tuple[str, str | None]: vault://secret/data/devops/creds#github_token -> ('secret/data/devops/creds', 'github_token') secret/data/ci/database -> ('secret/data/ci/database', None) """ - cleaned = uri.strip() - key: str | None = None - - if "#" in cleaned: - cleaned, key = cleaned.split("#", 1) - key = key.strip() or None + cleaned, frag = urldefrag(uri.strip()) + key = frag.strip() or None validate_no_path_traversal(cleaned, error_cls=VaultConfigurationError, label="Vault URI") - if cleaned.startswith("vault://"): - parsed = urlparse(cleaned) + parsed = urlsplit(cleaned) + if parsed.scheme.lower() == "vault": path = f"{parsed.netloc}{parsed.path}".lstrip("/") validate_no_path_traversal(path, error_cls=VaultConfigurationError, label="Vault URI") return path, key @@ -141,7 +137,7 @@ def __init__( or os.getenv("DEVOPS_CLI_VAULT_ADDR") or "http://127.0.0.1:8200" ).rstrip("/") - parsed = urlparse(self.vault_addr) + parsed = urlsplit(self.vault_addr) if parsed.scheme not in ("http", "https"): raise VaultConfigurationError( f"Invalid Vault address scheme '{parsed.scheme}'; expected 'http' or 'https'" diff --git a/src/devops_cli/security/vulnerability_lookup.py b/src/devops_cli/security/vulnerability_lookup.py index 3c462b9038..1a6445eaa4 100644 --- a/src/devops_cli/security/vulnerability_lookup.py +++ b/src/devops_cli/security/vulnerability_lookup.py @@ -8,7 +8,6 @@ import threading from collections import OrderedDict from typing import Any -from urllib.parse import urlparse import httpx2 from pydantic import ValidationError as PydanticValidationError @@ -484,9 +483,9 @@ def _query_radar_http( @staticmethod def _extract_domain_target(domain_or_url: str) -> str: """Extract canonical target hostname or domain from URL or string.""" - if "://" not in domain_or_url: - return domain_or_url - return urlparse(domain_or_url).hostname or domain_or_url + from devops_cli.http.urls import extract_domain_target + + return extract_domain_target(domain_or_url) or domain_or_url @staticmethod def _build_example_domain_record(domain_or_url: str) -> NetworkReputationRecord: diff --git a/src/devops_cli/telemetry/instruments.py b/src/devops_cli/telemetry/instruments.py index 416f26c1e1..751036958b 100644 --- a/src/devops_cli/telemetry/instruments.py +++ b/src/devops_cli/telemetry/instruments.py @@ -11,7 +11,6 @@ from dataclasses import dataclass from enum import StrEnum from typing import Any -from urllib.parse import urlparse class InstrumentKind(StrEnum): @@ -281,7 +280,9 @@ def backend_name(served_by: str | None) -> str: """A serving backend's short name: its host's first label, e.g. `vllm` or `ollama-0`.""" if not served_by: return "" - host = urlparse(served_by if "://" in served_by else f"//{served_by}").hostname or served_by + from devops_cli.http.urls import extract_domain_target + + host = extract_domain_target(served_by) or served_by return host.split(".", 1)[0] diff --git a/src/devops_cli/telemetry/tracer.py b/src/devops_cli/telemetry/tracer.py index 2f2250abbd..390347b79e 100644 --- a/src/devops_cli/telemetry/tracer.py +++ b/src/devops_cli/telemetry/tracer.py @@ -302,7 +302,9 @@ def _assign_waterfall_depth(node: SpanWaterfallNode, current_depth: int) -> None _assign_waterfall_depth(child, current_depth + 1) -def _link_waterfall_hierarchy(nodes: dict[str, SpanWaterfallNode]) -> list[SpanWaterfallNode]: +def _link_waterfall_hierarchy( + nodes: dict[str, SpanWaterfallNode], +) -> list[SpanWaterfallNode]: """Assemble flat nodes into parent-child tree hierarchy and order by start time.""" roots: list[SpanWaterfallNode] = [] for n in nodes.values(): @@ -701,15 +703,18 @@ def __init__( ) -> None: self.endpoint = endpoint.rstrip("/") env_protocol = os.getenv("OTEL_EXPORTER_OTLP_PROTOCOL") - self.protocol = ( - protocol - or env_protocol - or ( - "grpc" - if (":4317" in self.endpoint or self.endpoint.startswith("grpc://")) - else "http/json" - ) - ) + from devops_cli.http.urls import read_url_or_authority + + parsed_target = read_url_or_authority(self.endpoint) + is_grpc = False + if parsed_target: + try: + ep_port = parsed_target.port + except ValueError: + ep_port = None + is_grpc = parsed_target.scheme.lower() == "grpc" or ep_port == 4317 + + self.protocol = protocol or env_protocol or ("grpc" if is_grpc else "http/json") self.service_name = service_name self.service_version = service_version or self._detect_version() self.host_name = platform.node() or "localhost" @@ -741,9 +746,15 @@ def __init__( {"key": "os.type", "value": {"stringValue": self.os_type}}, {"key": "os.description", "value": {"stringValue": platform.platform()}}, {"key": "process.pid", "value": {"stringValue": str(os.getpid())}}, - {"key": "process.executable.name", "value": {"stringValue": Path(sys.executable).name}}, + { + "key": "process.executable.name", + "value": {"stringValue": Path(sys.executable).name}, + }, {"key": "process.runtime.name", "value": {"stringValue": "cpython"}}, - {"key": "process.runtime.version", "value": {"stringValue": platform.python_version()}}, + { + "key": "process.runtime.version", + "value": {"stringValue": platform.python_version()}, + }, {"key": "telemetry.sdk.name", "value": {"stringValue": "devops-cli-otel"}}, {"key": "telemetry.sdk.language", "value": {"stringValue": "python"}}, *vcs_res_attrs, @@ -1105,20 +1116,15 @@ def _get_grpc_exporter(self) -> Any: """Get or initialize thread-safe gRPC span exporter with persistent multiplexed connection.""" with self._client_lock: if self._grpc_exporter is None: + from urllib.parse import urlsplit + from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import ( OTLPSpanExporter, ) - clean_ep = ( - self.endpoint.replace("http://", "") - .replace("https://", "") - .replace("grpc://", "") - ) - if not clean_ep: - clean_ep = "localhost:4317" - insecure = not self.endpoint.startswith("https://") + insecure = urlsplit(self.endpoint).scheme.lower() != "https" self._grpc_exporter = OTLPSpanExporter( - endpoint=clean_ep, + endpoint=self.endpoint, insecure=insecure, timeout=DEFAULT_OTEL_HTTP_TIMEOUT_SECONDS, ) @@ -1129,17 +1135,18 @@ def test_connection( ) -> tuple[bool, str, float]: """Test reachability of the OTLP collector endpoint and measure latency.""" start = time.perf_counter() - if self.protocol == "grpc" or ":4317" in self.endpoint: + if self.protocol == "grpc": try: import socket - clean_ep = ( - self.endpoint.replace("http://", "") - .replace("https://", "") - .replace("grpc://", "") - ) - host, _, port_str = clean_ep.partition(":") - port = int(port_str) if port_str else 4317 + from devops_cli.http.urls import read_url_or_authority + + parsed = read_url_or_authority(self.endpoint) + host = parsed.hostname if parsed else "localhost" + try: + port = (parsed.port if parsed else None) or 4317 + except ValueError: + port = 4317 sock = socket.create_connection((host, port), timeout=timeout) sock.close() elapsed_ms = (time.perf_counter() - start) * 1000 diff --git a/tests/test_ai_benchmark.py b/tests/test_ai_benchmark.py index 26df407104..7171dd8bc6 100644 --- a/tests/test_ai_benchmark.py +++ b/tests/test_ai_benchmark.py @@ -219,6 +219,15 @@ def test_benchmark_runner_concurrent_execution() -> None: ("gateway", None, "m@https://example.com:8443", "sk-test-configured"), ("openai", None, f"m@{CONST_URL_OPENAI_API_BASE}/v1", "sk-test-configured"), ("claude", None, f"m@{CONST_URL_OPENAI_API_BASE}/v1", ""), + ("openai", "https://example.com/v1", "m@https://example.com\\@192.0.2.1/v1", ""), + ("openai", "https://example.com/v1", "m@https://example.com:443/v1", "sk-test-configured"), + ( + "openai", + "https://xn--bcher-kva.example.com/v1", + "m@https://bücher.example.com/v1", + "sk-test-configured", + ), + ("openai", "localhost:8000/v1", "m@https://example.com/v1", ""), ], ids=[ "named-endpoint", @@ -226,6 +235,10 @@ def test_benchmark_runner_concurrent_execution() -> None: "gateway-sends-to-gateway-url", "configured-provider-api", "another-provider-api", + "backslash-userinfo-host-mismatch", + "default-https-port-matches", + "idn-punycode-origin-matches", + "schemeless-api-base-url-fails-closed", ], ) @pytest.mark.usefixtures("mock_keyring") @@ -250,6 +263,45 @@ def test_benchmark_client_gets_key_only_for_configured_endpoint( assert b_runner._client_for_model(model)._api_key == key +def test_key_for_endpoint_direct_unparseable_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None: + """Verify _key_for_endpoint fails closed and raises nothing for unparseable URLs.""" + from devops_cli.ai.benchmark.runner import _key_for_endpoint + from devops_cli.config.settings import AIConfig, load_settings + + monkeypatch.setenv("DEVOPS_CLI_AI_API_KEY", "sk-test-configured") + settings = load_settings() + settings.ai.provider = "openai" + + cfg_malformed = AIConfig( + provider="openai", model="m", api_base_url="https://example.com:abc/v1" + ) + assert _key_for_endpoint(settings, cfg_malformed) == "" + + settings.ai.api_base_url = "localhost:8000/v1" + cfg_valid = AIConfig(provider="openai", model="m", api_base_url="https://example.com/v1") + assert _key_for_endpoint(settings, cfg_valid) == "" + + settings.ai.provider = "gateway" + settings.ai.gateway_url = "localhost:8000/v1" + cfg_gateway = AIConfig(provider="gateway", model="m") + assert _key_for_endpoint(settings, cfg_gateway) == "" + + +def test_parse_model_spec() -> None: + """Verify parse_model_spec splits model@endpoint and preserves userinfo.""" + from devops_cli.ai.benchmark.model_spec import parse_model_spec + + assert ( + parse_model_spec("m@https://user:password@example.com/v1"), + parse_model_spec("m"), + parse_model_spec("m@"), + ) == ( + ("m", "https://user:password@example.com/v1"), + ("m", None), + ("m", ""), + ) + + def test_benchmark_filtering_invalid_defaults_and_judge_weighting() -> None: """Verify that 0-default evaluations are discarded and judge weighting applies.""" tasks = [BENCHMARK_TASKS[0]] diff --git a/tests/test_ai_client_security.py b/tests/test_ai_client_security.py index 2da85e4527..e41b83163d 100644 --- a/tests/test_ai_client_security.py +++ b/tests/test_ai_client_security.py @@ -142,12 +142,27 @@ def test_ollama_non_thinking_400_raises_ai_client_error( def test_get_ollama_urls_parsing() -> None: + from devops_cli.ai.models.ollama import normalize_ollama_base_url + from devops_cli.exceptions import InvalidURLError + from devops_cli.exceptions.config import ConfigurationError + cfg1 = AIConfig(ollama_urls=["http://172.16.0.1:11434", "http://172.16.0.2:11434/"]) assert cfg1.get_ollama_urls == ["http://172.16.0.1:11434", "http://172.16.0.2:11434"] cfg2 = AIConfig(ollama_urls=["http://10.0.0.1:11434/", "http://10.0.0.2:11434"]) assert cfg2.get_ollama_urls == ["http://10.0.0.1:11434", "http://10.0.0.2:11434"] + cfg_upper = AIConfig(ollama_urls=["HTTP://example.com:11434"]) + assert cfg_upper.get_ollama_urls == ["http://example.com:11434"] + + cfg_schemeless = AIConfig(ollama_urls=["example.com:11434"]) + with pytest.raises(ConfigurationError) as exc_info: + _ = cfg_schemeless.get_ollama_urls + assert "ai.ollama_urls" in str(exc_info.value) + + with pytest.raises(InvalidURLError): + normalize_ollama_base_url("example.com:11434") + def test_ollama_multiserver_failover(monkeypatch: pytest.MonkeyPatch) -> None: import httpx2 diff --git a/tests/test_docs_ingester.py b/tests/test_docs_ingester.py index fe44e28dc8..71dadc134b 100644 --- a/tests/test_docs_ingester.py +++ b/tests/test_docs_ingester.py @@ -249,5 +249,77 @@ def mock_get(url: str) -> MagicMock: output_dir=tmp_path, max_pages=2, ) - assert result.total_pages == 2 - assert result.total_chunks >= 2 + assert (result.total_pages, result.total_chunks >= 2) == (2, True) + + +def test_ingest_remote_docs_origin_filtering(tmp_path: Path) -> None: + """Ensure links are only followed when origin matches start URL origin.""" + ingester = DocsIngester() + + page1_html = """ +

Root Page

+ Upper Host Same Origin + Explicit Default Port Same Origin + Downgrade Scheme Different Origin + Backslash Host Different Origin + Invalid Tab Link + """ + + visited_urls: list[str] = [] + + def mock_get(url: str) -> MagicMock: + visited_urls.append(url) + resp = MagicMock() + resp.status_code = 200 + resp.headers = {"content-type": "text/html"} + resp.text = page1_html + return resp + + with ( + patch("devops_cli.ai.library.docs_ingester.validate_service_url"), + patch("httpx2.Client.get", side_effect=mock_get), + ): + result = ingester.ingest_remote_docs( + "https://example.com/root", + output_dir=tmp_path, + max_pages=10, + ) + assert ( + "https://example.com/a" in visited_urls, + "https://example.com/b" in visited_urls, + "http://example.com/c" in visited_urls, + any("192.0.2.1" in u for u in visited_urls), + result.total_pages, + ) == (True, True, False, False, 3) + + +def test_ingest_remote_docs_slug_sanitization() -> None: + """Ensure userinfo is stripped from directory slug and %2e%2e does not escape ingest root.""" + from devops_cli.core.repo import resolve_store_path + + ingester = DocsIngester() + resp = MagicMock() + resp.status_code = 200 + resp.headers = {"content-type": "text/html"} + resp.text = "

Doc

Content

" + + with ( + patch("devops_cli.ai.library.docs_ingester.validate_service_url"), + patch("httpx2.Client.get", return_value=resp), + ): + res1 = ingester.ingest_remote_docs( + "https://myuser:secrettoken@example.com", + max_pages=1, + ) + res2 = ingester.ingest_remote_docs( + "https://example.com/%2e%2e", + max_pages=1, + ) + out_path = Path(res2.output_dir).resolve() + ingest_root = resolve_store_path(Path("docs_ingest")).resolve() + + assert ( + "myuser" not in res1.output_dir, + "secrettoken" not in res1.output_dir, + out_path.parent == ingest_root, + ) == (True, True, True) diff --git a/tests/test_embedding_benchmark.py b/tests/test_embedding_benchmark.py index e88d7ec609..b0e81d2814 100644 --- a/tests/test_embedding_benchmark.py +++ b/tests/test_embedding_benchmark.py @@ -168,12 +168,19 @@ def test_cli_benchmark_document_option(tmp_path: Path) -> None: """Ensure --document option processes custom document file.""" doc_file = tmp_path / "test_doc.md" doc_file.write_text( - "# Test Title\nThis is a test document for embedding retrieval.\n", encoding="utf-8" + "# Test Title\nThis is a test document for embedding retrieval.\n", + encoding="utf-8", ) result = runner.invoke( app, - ["--models", "nomic-embed-text:latest", "--document", str(doc_file), "--dry-run"], + [ + "--models", + "nomic-embed-text:latest", + "--document", + str(doc_file), + "--dry-run", + ], ) assert result.exit_code == 0 assert "test_doc.md" in result.stdout @@ -207,7 +214,8 @@ def test_infer_category_exact_word_boundaries_and_domain_classification() -> Non # 4. CI/CD domain (must not trigger on words containing 'pr', 'ci', or 'cd' like 'practice') cicd_cat = InMemoryDocumentTokenizer._infer_category( - "GitHub Actions Workflows", "Run actionlint and pre-commit checks on pull request branch." + "GitHub Actions Workflows", + "Run actionlint and pre-commit checks on pull request branch.", ) assert cicd_cat == "ci_cd" @@ -219,7 +227,8 @@ def test_infer_category_exact_word_boundaries_and_domain_classification() -> Non # 5. Infrastructure fallback infra_cat = InMemoryDocumentTokenizer._infer_category( - "OpenTofu State", "Provision S3 backend with DynamoDB locking and Jaeger tracing." + "OpenTofu State", + "Provision S3 backend with DynamoDB locking and Jaeger tracing.", ) assert infra_cat == "infrastructure" @@ -242,7 +251,10 @@ def test_embedding_engine_resolution_and_live_eval(tmp_path: Path) -> None: # 2. evaluate_model with mocked embeddings mock_vec = [0.1] * 384 with ( - patch("devops_cli.ai.rag.embeddings.EmbeddingsEngine.embed_query", return_value=mock_vec), + patch( + "devops_cli.ai.rag.embeddings.EmbeddingsEngine.embed_query", + return_value=mock_vec, + ), patch( "devops_cli.ai.rag.embeddings.EmbeddingsEngine.embed_texts", return_value=[mock_vec, mock_vec], @@ -261,9 +273,35 @@ def test_embedding_engine_resolution_and_live_eval(tmp_path: Path) -> None: ["target passage text for evaluation", "distractor text"], server_url="http://localhost:11434", ) - assert res.model == "test-embed" - assert res.dimension == 384 - assert res.recall_at_1 >= 0.0 + assert (res.model, res.dimension, res.recall_at_1 >= 0.0) == ("test-embed", 384, True) + + +def test_embedding_engine_provider_resolution() -> None: + """Verify provider selection for explicit endpoints: origin match or gateway refusal.""" + from devops_cli.exceptions import ValidationError + + runner = EmbeddingBenchmarkRunner( + models=["m"], + is_dry_run=False, + ) + runner.settings.ai.provider = "gateway" + runner.settings.ai.gateway_url = "https://example.com:4000/v1" + runner.settings.ai.ollama_urls = ["http://example.com:11434", "example.com:11434"] + runner.provider = "gateway" + + with pytest.raises(ValidationError) as exc_info: + runner._engine_for_model("m@https://example.com:8080") + assert "--provider" in str(exc_info.value) + + engine_ollama = runner._engine_for_model("m@http://example.com:11434") + engine_gw = runner._engine_for_model("m@https://example.com:4000/v1") + assert (engine_ollama.ai_config.provider, engine_gw.ai_config.provider) == ( + "ollama", + "gateway", + ) + + with pytest.raises(ValidationError): + runner._engine_for_model("m@https://ollama.example.com") def test_compute_ndcg_and_report_rendering() -> None: @@ -362,7 +400,10 @@ def test_compute_ndcg_and_report_rendering() -> None: ) @pytest.mark.usefixtures("mock_keyring") def test_override_endpoint_gets_no_key( - monkeypatch: pytest.MonkeyPatch, stub_web: StubWeb, server: str, authorization: str | None + monkeypatch: pytest.MonkeyPatch, + stub_web: StubWeb, + server: str, + authorization: str | None, ) -> None: """Verify the AI key goes only to the configured api_base_url: an endpoint the model names gets no Authorization header, and the engine takes no OPENAI_API_KEY in its place (#954).""" @@ -395,7 +436,9 @@ def _unreachable(texts: list[str], *, is_query: bool = False) -> list[list[float raise EmbeddingsError("Embedding model dead-model failed: ConnectError: connection refused") -def test_unreachable_server_is_reported_failed(capsys: pytest.CaptureFixture[str]) -> None: +def test_unreachable_server_is_reported_failed( + capsys: pytest.CaptureFixture[str], +) -> None: """Verify a model whose embeddings fail is reported failed with the reason and no latency, ranked after every scored model and left out of the server summary and the recommendations, where a p50 of 0.0 made it the lowest-latency model (#954).""" @@ -421,7 +464,13 @@ def test_unreachable_server_is_reported_failed(capsys: pytest.CaptureFixture[str dead = next(result for result in report.models if result.model == "dead-model") assert ( [result.model for result in report.models], - (dead.failed, dead.error, dead.latency_ms_p50, dead.latency_ms_p95, dead.overall_score), + ( + dead.failed, + dead.error, + dead.latency_ms_p50, + dead.latency_ms_p95, + dead.overall_score, + ), [rec for rec in report.recommendations if "dead-model" in rec], [(srv.models_evaluated_count, srv.fastest_model) for srv in report.server_benchmarks], "✗ dead-model" in capsys.readouterr().out, @@ -493,13 +542,18 @@ def test_refused_endpoint_is_reported_failed() -> None: ] -def test_report_shows_a_failed_run_without_metrics(capsys: pytest.CaptureFixture[str]) -> None: +def test_report_shows_a_failed_run_without_metrics( + capsys: pytest.CaptureFixture[str], +) -> None: """Verify the leaderboards give a failed run no medal and no metrics, and the Markdown report says why it failed (#954).""" from devops_cli.models.benchmark import EmbeddingServerSummary scored = EmbeddingBenchmarkResult( - model="live-model", server="http://localhost:11434", dimension=3, overall_score=70.0 + model="live-model", + server="http://localhost:11434", + dimension=3, + overall_score=70.0, ) failed = EmbeddingBenchmarkResult( model="dead-model", diff --git a/tests/test_k8s_credentials.py b/tests/test_k8s_credentials.py index e4c51b7e1c..0ba797c50b 100644 --- a/tests/test_k8s_credentials.py +++ b/tests/test_k8s_credentials.py @@ -5,6 +5,7 @@ import base64 from unittest.mock import MagicMock, patch +import pytest from typer.testing import CliRunner from devops_cli.commands.k8s import app as k8s_app @@ -42,7 +43,9 @@ def test_fetch_argocd_password_success(mock_keyring: MagicMock, mock_subproc: Ma @patch("devops_cli.k8s.credentials.run_subprocess") def test_fetch_argocd_password_not_found(mock_subproc: MagicMock) -> None: mock_subproc.return_value = MagicMock( - returncode=1, stdout="", stderr="Error from server (NotFound): secrets not found" + returncode=1, + stdout="", + stderr="Error from server (NotFound): secrets not found", ) pw = fetch_argocd_password(namespace="argocd", save_to_keyring=True) @@ -78,7 +81,10 @@ def test_sync_k8s_credentials_summary(mock_keyring_get: MagicMock, mock_argocd: def test_cli_k8s_sync_secrets_dry_run() -> None: res = runner.invoke(k8s_app, ["sync-secrets", "--dry-run"]) - assert (res.exit_code, "sync_secrets" in res.output or "argocd" in res.output) == (0, True) + assert (res.exit_code, "sync_secrets" in res.output or "argocd" in res.output) == ( + 0, + True, + ) @patch("devops_cli.k8s.credentials._keyring_set") @@ -98,6 +104,57 @@ def test_mint_argocd_token_failure(mock_post: MagicMock) -> None: assert (token_401, token_empty) == (None, None) +@patch("httpx2.Client.post") +def test_mint_tokens_url_validation(mock_post: MagicMock) -> None: + """Ensure scheme-less service URLs fail with ConfigurationError and HTTPS is normalized.""" + from devops_cli.exceptions.config import ConfigurationError + + with pytest.raises(ConfigurationError) as exc_argo: + mint_argocd_token("example.com", "admin-pass") + service_calls_1 = [ + c[0][0] for c in mock_post.call_args_list if not c[0][0].endswith("/v1/traces") + ] + assert ("argocd.url" in str(exc_argo.value), len(service_calls_1)) == (True, 0) + + mock_post.reset_mock() + mock_post.return_value = MagicMock(status_code=200, json=lambda: {"token": "argo-jwt-123"}) + mint_argocd_token("HTTPS://example.com:8080", "admin-pass", save_to_keyring=False) + service_calls_2 = [ + c[0][0] for c in mock_post.call_args_list if not c[0][0].endswith("/v1/traces") + ] + assert ( + len(service_calls_2) > 0, + service_calls_2[0].startswith("https://example.com:8080/"), + ) == (True, True) + + mock_post.reset_mock() + with pytest.raises(ConfigurationError) as exc_grafana: + mint_grafana_token("example.com", "admin-pass") + service_calls_3 = [ + c[0][0] for c in mock_post.call_args_list if not c[0][0].endswith("/v1/traces") + ] + assert ("grafana.url" in str(exc_grafana.value), len(service_calls_3)) == (True, 0) + + mock_post.reset_mock() + + def fake_post(url: str, **kwargs: object) -> MagicMock: + if url.endswith("/api/serviceaccounts"): + return MagicMock(status_code=201, json=lambda: {"id": 10}) + if "/tokens" in url: + return MagicMock(status_code=200, json=lambda: {"key": "glsa-token-xyz"}) + return MagicMock(status_code=200, json=lambda: {}) + + mock_post.side_effect = fake_post + mint_grafana_token("HTTPS://example.com:3000", "admin-pass", save_to_keyring=False) + service_calls_4 = [ + c[0][0] for c in mock_post.call_args_list if not c[0][0].endswith("/v1/traces") + ] + assert ( + len(service_calls_4) > 0, + service_calls_4[0].startswith("https://example.com:3000/"), + ) == (True, True) + + @patch("devops_cli.k8s.credentials._keyring_set") @patch("httpx2.Client.post") def test_mint_grafana_token_sa_success(mock_post: MagicMock, mock_keyring: MagicMock) -> None: @@ -142,12 +199,19 @@ def fake_post(url: str, **kwargs: object) -> MagicMock: mock_post.side_effect = fake_post mock_get.return_value = MagicMock( status_code=200, - json=lambda: [{"id": 1, "name": "devops-cli-old-1"}, {"id": 2, "name": "devops-cli-old-2"}], + json=lambda: [ + {"id": 1, "name": "devops-cli-old-1"}, + {"id": 2, "name": "devops-cli-old-2"}, + ], ) mock_delete.return_value = MagicMock(status_code=200) token = mint_grafana_token("http://example.com:3000", "admin-pass", save_to_keyring=True) - assert (token, mock_delete.call_count, mock_keyring.called) == ("glsa-new-token", 2, True) + assert (token, mock_delete.call_count, mock_keyring.called) == ( + "glsa-new-token", + 2, + True, + ) @patch("devops_cli.k8s.credentials._keyring_set", side_effect=Exception("Keyring locked")) @@ -201,7 +265,10 @@ def test_get_or_mint_grafana_auth() -> None: with ( patch("devops_cli.config.settings.get_grafana_token", return_value=None), patch("devops_cli.config.settings.get_grafana_password", return_value="admin-pw"), - patch("devops_cli.k8s.credentials.mint_grafana_token", return_value="minted-graf-tok"), + patch( + "devops_cli.k8s.credentials.mint_grafana_token", + return_value="minted-graf-tok", + ), ): tok, basic = get_or_mint_grafana_auth(settings) assert (tok, basic) == ("minted-graf-tok", None) diff --git a/tests/test_mcp.py b/tests/test_mcp.py index c7a2973be0..bf5da4cf35 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -496,6 +496,7 @@ def test_k8s_pods_lists_the_pods_of_the_namespace_it_names() -> None: [ ("openai", "x@https://example.com", "model"), ("openai", "bge-m3,x@https://example.com", "model"), + ("openai", "x@", "model"), ("ollama", "https://example.com/bge-m3", "model"), ("example", "bge-m3", "provider"), ], @@ -514,6 +515,20 @@ def test_benchmark_tools_reject_endpoint_override(provider: str, model: str, fie assert (refused.value.details["field"], dispatcher.called) == (field, False) +@pytest.mark.parametrize( + "model", + ["bge-m3,nomic-embed-text", "hf.co/org/model:Q4"], +) +def test_benchmark_tools_accept_valid_models(model: str) -> None: + """Verify valid multi-model and registry model strings are accepted and dispatched.""" + from devops_cli.ai.mcp.server import benchmark_embeddings + + with patch("devops_cli.ai.mcp.server._run_mcp_cmd", return_value="output") as dispatcher: + res = benchmark_embeddings(provider="ollama", model=model) + + assert (res, dispatcher.called) == ("output", True) + + def test_ai_architecture_tool_is_removed() -> None: """Verify the tool that ran the never-existing `devops analyze architecture` is gone, with no shim left behind.""" diff --git a/tests/test_sandbox_metrics.py b/tests/test_sandbox_metrics.py index 5cf976961c..f89491a6b3 100644 --- a/tests/test_sandbox_metrics.py +++ b/tests/test_sandbox_metrics.py @@ -42,6 +42,28 @@ # ───────────────────────────────────────────────────────────────────────────── +def test_build_scrape_url_variations() -> None: + """Test _build_scrape_url with hostnames starting with http, IPv6, scheme normalisation, and path prefixes.""" + from devops_cli.sandbox.metrics import _build_scrape_url + + assert ( + _build_scrape_url("httpbin.example.com:8080", "metrics"), + _build_scrape_url("HTTP://example.com", "metrics"), + _build_scrape_url("[::1]:8080", "metrics"), + _build_scrape_url("http://example.com:9100/prefix", "metrics"), + _build_scrape_url("http://example.com:9100/prefix", "/metrics"), + ) == ( + "http://httpbin.example.com:8080/metrics", + "http://example.com/metrics", + "http://[::1]:8080/metrics", + "http://example.com:9100/prefix/metrics", + "http://example.com:9100/prefix/metrics", + ) + + with pytest.raises(ValueError, match="scheme"): + _build_scrape_url("ftp://example.com", "metrics") + + def test_cgroup_v2_metrics_model() -> None: """Test CgroupV2Metrics model instantiation and calculations.""" metrics = CgroupV2Metrics( diff --git a/tests/test_sandbox_policy_properties.py b/tests/test_sandbox_policy_properties.py index a6efd1a103..4fa7b1d852 100644 --- a/tests/test_sandbox_policy_properties.py +++ b/tests/test_sandbox_policy_properties.py @@ -10,6 +10,7 @@ from pathlib import Path from typing import Any +import pytest from hypothesis import Phase, example, given, settings from hypothesis import strategies as st @@ -63,7 +64,14 @@ def _check_raises(func: Any, *args: Any, expected_exc: type[Exception], **kwargs # ============================================================================= _TRAVERSAL_PREFIXES = ("../", "..\\", "%2e%2e/", "%2e%2e\\", "%2E%2E/", "%2E%2E\\") -_TRAVERSAL_SEGMENTS = ("/../", "\\..\\", "/%2e%2e/", "\\%2e%2e\\", "/%2E%2E/", "\\%2E%2E\\") +_TRAVERSAL_SEGMENTS = ( + "/../", + "\\..\\", + "/%2e%2e/", + "\\%2e%2e\\", + "/%2E%2E/", + "\\%2E%2E\\", +) @_DERANDOMIZED @@ -148,7 +156,9 @@ def test_property_nul_bytes_in_subpath_raise_error_cls(head: str, tail: str) -> ) @example(path_suffix="etc/passwd") @example(path_suffix=".ssh/id_rsa") -def test_property_absolute_tilde_and_file_schemes_denied_when_not_allowed(path_suffix: str) -> None: +def test_property_absolute_tilde_and_file_schemes_denied_when_not_allowed( + path_suffix: str, +) -> None: """Property: Absolute paths, tilde, and file:// URIs are denied when allow_absolute=False.""" disallowed_forms = [ f"/{path_suffix}", @@ -236,6 +246,36 @@ def test_property_parse_whitelist_entry_reads_ipv6_hosts_and_ports_oracle( ) +def test_parse_whitelist_entry_host_extraction_and_rejections() -> None: + """Verify lowercase normalization, userinfo stripping, and empty port rejection in whitelist entries.""" + from devops_cli.sandbox.models import ( + _parse_whitelist_entry, + _validate_public_whitelist_item, + ) + + assert ( + _parse_whitelist_entry("Example.COM"), + _parse_whitelist_entry("user@example.com:22"), + ) == ( + ("example.com", 443), + ("example.com", 22), + ) + + for entry in ( + "http://:8080", + "https://", + "http:///x", + "example.com:", + "example.com:/x", + ): + with pytest.raises(ValueError, match="Whitelist entry"): + _parse_whitelist_entry(entry) + + for invalid_item in ("example.com:", "example.com:/x"): + with pytest.raises(ValueError, match="Whitelist entry"): + _validate_public_whitelist_item(invalid_item) + + # ============================================================================= # 3. Cloud Metadata & Link-Local Containment Oracle Across All Six Sites # ============================================================================= @@ -263,7 +303,9 @@ def test_property_parse_whitelist_entry_reads_ipv6_hosts_and_ports_oracle( @_DERANDOMIZED @given(target=st.sampled_from(_METADATA_ORACLE_TARGETS)) -def test_property_cloud_metadata_superset_containment_at_all_six_sites(target: str) -> None: +def test_property_cloud_metadata_superset_containment_at_all_six_sites( + target: str, +) -> None: """Property: Unified cloud metadata superset is rejected with 1.0 containment at every site. The sandbox probe and Jaeger no longer keep checks of their own: both dial through the @@ -290,12 +332,18 @@ def test_property_cloud_metadata_superset_containment_at_all_six_sites(target: s # 4. http/egress.py: the connect-time policy, at the loopback level connect_blocked = _check_raises( - vet_addresses, clean_host, 80, EgressLevel.LOOPBACK, expected_exc=SSRFBlockedError + vet_addresses, + clean_host, + 80, + EgressLevel.LOOPBACK, + expected_exc=SSRFBlockedError, ) # 5. sandbox/models.py: local whitelist and local host whitelist_blocked = _check_raises( - _validate_local_whitelist_item, f"http://{url_target}:80", expected_exc=ValueError + _validate_local_whitelist_item, + f"http://{url_target}:80", + expected_exc=ValueError, ) models_host_blocked = _check_raises(_resolve_local_host, target, expected_exc=ValueError) diff --git a/tests/test_sandbox_probe.py b/tests/test_sandbox_probe.py index f4476d9384..0f8039caa6 100644 --- a/tests/test_sandbox_probe.py +++ b/tests/test_sandbox_probe.py @@ -491,20 +491,29 @@ def test_engine_probe_raises_when_not_found() -> None: def test_parse_target_endpoint_variations() -> None: - """Test _parse_target_endpoint with multiple formats and schemes.""" + """Test _parse_target_endpoint returns httpx2.Origin with scheme, host, and port.""" + from devops_cli.exceptions import ValidationError from devops_cli.sandbox.probe import _parse_target_endpoint - h1, p1 = _parse_target_endpoint("https://example.com") - assert h1 == "example.com" - assert p1 == 443 - - h2, p2 = _parse_target_endpoint("127.0.0.1:9090") - assert h2 == "127.0.0.1" - assert p2 == 9090 + cases = [ + ("https://example.com", ("https", "example.com", 443)), + ("127.0.0.1:9090", ("http", "127.0.0.1", 9090)), + ("localhost", ("http", "localhost", 80)), + ("[::1]:8080", ("http", "::1", 8080)), + ("HTTPS://example.com:8443", ("https", "example.com", 8443)), + ] + for target, (expected_scheme, expected_host, expected_port) in cases: + orig = _parse_target_endpoint(target) + assert (orig.scheme, orig.host, orig.port) == ( + expected_scheme, + expected_host, + expected_port, + ) - h3, p3 = _parse_target_endpoint("localhost") - assert h3 == "localhost" - assert p3 == 80 + for invalid_target in ("http://:8080", "example.com:abc"): + with pytest.raises(ValidationError) as exc_info: + _parse_target_endpoint(invalid_target) + assert invalid_target in str(exc_info.value) def test_run_sandbox_probes_with_openapi_and_grpc() -> None: diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py index a56c6e2839..8cd4278859 100644 --- a/tests/test_telemetry.py +++ b/tests/test_telemetry.py @@ -425,40 +425,74 @@ def test_telemetry_keyboard_interrupt_handling(monkeypatch: pytest.MonkeyPatch) def test_telemetry_grpc_client(monkeypatch: pytest.MonkeyPatch) -> None: """Test OTelTelemetryClient initialized with gRPC endpoint and protocol.""" - client = OTelTelemetryClient(endpoint="localhost:4317", protocol="grpc", enabled=True) - assert client.protocol == "grpc" + c1 = OTelTelemetryClient(endpoint="http://example.com:43170") + assert c1.protocol == "http/json" - # Test lazy gRPC exporter initialization from unittest.mock import MagicMock - mock_exporter = MagicMock() + exporter_calls: list[dict[str, Any]] = [] + + def mock_exporter_factory(**kw: Any) -> MagicMock: + exporter_calls.append(kw) + return MagicMock() + monkeypatch.setattr( "opentelemetry.exporter.otlp.proto.grpc.trace_exporter.OTLPSpanExporter", - lambda **kw: mock_exporter, + mock_exporter_factory, ) - exp = client._get_grpc_exporter() - assert exp is mock_exporter - # Should reuse cached exporter - assert client._get_grpc_exporter() is mock_exporter - - client.shutdown() - mock_exporter.shutdown.assert_called_once() + cases = [ + ("grpc://example.com:4317", True), + ("http://example.com:4317", True), + ("example.com:4317", True), + ("https://example.com:4317", False), + ("HTTPS://example.com:4317", False), + ] + for ep, expected_insecure in cases: + client = OTelTelemetryClient(endpoint=ep, protocol="grpc", enabled=True) + exporter_calls.clear() + client._get_grpc_exporter() + assert (exporter_calls[0]["endpoint"], exporter_calls[0]["insecure"]) == ( + ep, + expected_insecure, + ) def test_telemetry_grpc_connection_mock(monkeypatch: pytest.MonkeyPatch) -> None: - """Test test_connection probe on gRPC endpoint.""" + """Test test_connection probe on gRPC endpoint dials expected host and port.""" from unittest.mock import MagicMock - client = OTelTelemetryClient(endpoint="localhost:4317", protocol="grpc", enabled=True) - mock_socket = MagicMock() - monkeypatch.setattr("socket.create_connection", lambda *a, **kw: mock_socket) + dialled: list[tuple[str, int]] = [] - ok, msg, latency = client.test_connection(timeout=1.0) - assert ok is True - assert "gRPC connection OK" in msg - assert latency >= 0 - mock_socket.close.assert_called_once() + def mock_create_connection(address: tuple[str, int], timeout: float = 1.0) -> MagicMock: + dialled.append(address) + return MagicMock() + + monkeypatch.setattr("socket.create_connection", mock_create_connection) + + c1 = OTelTelemetryClient(endpoint="grpc://[::1]:4317", enabled=True) + ok1, msg1, _ = c1.test_connection(timeout=1.0) + + c2 = OTelTelemetryClient(endpoint="HTTP://example.com:4317", enabled=True) + ok2, msg2, _ = c2.test_connection(timeout=1.0) + + assert ( + c1.protocol, + ok1, + "gRPC connection OK" in msg1, + c2.protocol, + ok2, + "gRPC connection OK" in msg2, + dialled, + ) == ( + "grpc", + True, + True, + "grpc", + True, + True, + [("::1", 4317), ("example.com", 4317)], + ) def test_telemetry_grpc_connection_failure(monkeypatch: pytest.MonkeyPatch) -> None: diff --git a/tests/test_vault_broker.py b/tests/test_vault_broker.py index 2fb859ee3c..d1700428d7 100644 --- a/tests/test_vault_broker.py +++ b/tests/test_vault_broker.py @@ -107,10 +107,12 @@ def test_parse_vault_uri() -> None: parse_vault_uri("vault://secret/data/devops/creds#github_token"), parse_vault_uri("vault://secret/data/ci/database"), parse_vault_uri("secret/data/plain"), + parse_vault_uri("VAULT://secret/data/x#k"), ) == ( ("secret/data/devops/creds", "github_token"), ("secret/data/ci/database", None), ("secret/data/plain", None), + ("secret/data/x", "k"), ) diff --git a/tests/test_vulnerability_lookup.py b/tests/test_vulnerability_lookup.py index d36a623847..c261ccf948 100644 --- a/tests/test_vulnerability_lookup.py +++ b/tests/test_vulnerability_lookup.py @@ -348,3 +348,14 @@ def test_no_text_claims_a_vulnerability_lookup_devops_cli_does_not_make() -> Non hasattr(vulnerability_lookup, "NVDClient"), hasattr(devops_cli.security, "NVDClient"), ) == ([], False, False) + + +def test_extract_domain_target() -> None: + """Verify _extract_domain_target extracts host without port.""" + from devops_cli.http.urls import extract_domain_target + from devops_cli.security.vulnerability_lookup import CloudflareRadarClient + + assert ( + CloudflareRadarClient._extract_domain_target("example.com:8080"), + extract_domain_target("example.com:8080"), + ) == ("example.com", "example.com") From 293fcac79042007d766de24051a050bc9af475e1 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 9 Oct 2026 10:07:14 -0600 Subject: [PATCH 07/15] fix(ci): ci jobs run on a named ubuntu-24.04 runner and always use uv's managed python, never the runner's own python (#1494) (#1507) All nine runs-on selections name ubuntu-24.04 instead of ubuntu-latest, each with a comment linking #1501 (the move to ubuntu-26.04, which waits for actionlint to accept the label); codeql.yml's becomes a plain label. ci.yml and release.yml set UV_MANAGED_PYTHON: "1" at workflow level, so uv runs only its own CPython builds and never takes a runner image's own Python 3.14 for setup-uv's UV_PYTHON=3.14. UV_PYTHON_PREFERENCE is not also set: uv refuses to run with both. test_github_workflows_name_their_runner_and_use_managed_python in tests/test_ci.py fails on a -latest runner label and on a workflow that reaches setup-uv, directly or through a local composite action, without the setting. --- .github/workflows/ci.yml | 16 ++++-- .github/workflows/cleanup-devcontainer.yml | 2 +- .github/workflows/codeql.yml | 2 +- .github/workflows/release.yml | 10 +++- changelog.d/1494.md | 2 + ...ask-1494-ci-named-runner-managed-python.md | 36 +++++++++++++ tests/test_ci.py | 50 +++++++++++++++++++ 7 files changed, 109 insertions(+), 9 deletions(-) create mode 100644 changelog.d/1494.md create mode 100644 docs/agent/tasks/task-1494-ci-named-runner-managed-python.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1335a899c3..daefd8ab41 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,13 +19,19 @@ concurrency: group: ci-${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true +env: + # uv runs only its own CPython builds, never the runner image's Python: setup-uv exports + # UV_PYTHON=3.14, which a runner's own 3.14 would otherwise satisfy (#1494). Never also set + # UV_PYTHON_PREFERENCE; uv refuses to run with both. + UV_MANAGED_PYTHON: "1" + jobs: # Fast-failing static gates. Split from the test suite so lint, typing, and formatting # errors surface in roughly a minute instead of queuing behind the full suite. static: name: Static Analysis if: github.event_name != 'schedule' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 # moves to ubuntu-26.04 in #1501 timeout-minutes: 15 permissions: contents: read @@ -45,7 +51,7 @@ jobs: test: name: Tests & Coverage if: github.event_name != 'schedule' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 # moves to ubuntu-26.04 in #1501 timeout-minutes: 30 permissions: contents: read @@ -69,7 +75,7 @@ jobs: devcontainer: name: DevContainer Image if: github.event_name == 'pull_request' && github.base_ref == 'main' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 # moves to ubuntu-26.04 in #1501 timeout-minutes: 30 permissions: contents: read @@ -164,7 +170,7 @@ jobs: if: >- github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && github.base_ref == 'main') - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 # moves to ubuntu-26.04 in #1501 timeout-minutes: 30 permissions: contents: read @@ -256,7 +262,7 @@ jobs: dependency-freshness: name: Dependency Freshness if: github.event_name == 'schedule' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 # moves to ubuntu-26.04 in #1501 timeout-minutes: 15 permissions: contents: read diff --git a/.github/workflows/cleanup-devcontainer.yml b/.github/workflows/cleanup-devcontainer.yml index e33913a158..e784c18769 100644 --- a/.github/workflows/cleanup-devcontainer.yml +++ b/.github/workflows/cleanup-devcontainer.yml @@ -31,7 +31,7 @@ concurrency: jobs: cleanup: name: Prune PR DevContainer Images - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 # moves to ubuntu-26.04 in #1501 timeout-minutes: 10 permissions: packages: write diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 63dd2d12a2..7fad33ea03 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -27,7 +27,7 @@ jobs: # - https://gh.io/supported-runners-and-hardware-resources # - https://gh.io/using-larger-runners (GitHub.com only) # Consider using larger runners or machines with greater resources for possible analysis time improvements. - runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} + runs-on: ubuntu-24.04 # moves to ubuntu-26.04 in #1501 permissions: # required for all workflows security-events: write diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6d7ba5e8b2..79c691dddb 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -16,10 +16,16 @@ concurrency: group: release-${{ github.ref }} cancel-in-progress: false +env: + # uv runs only its own CPython builds, never the runner image's Python: setup-uv exports + # UV_PYTHON=3.14, which a runner's own 3.14 would otherwise satisfy (#1494). Never also set + # UV_PYTHON_PREFERENCE; uv refuses to run with both. + UV_MANAGED_PYTHON: "1" + jobs: release: name: Build & Publish Release - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 # moves to ubuntu-26.04 in #1501 timeout-minutes: 30 outputs: version: ${{ steps.ver.outputs.version }} @@ -158,7 +164,7 @@ jobs: # scans, pushes by digest and attests service:vX.Y.Z, then tags it vX.Y.Z and latest; Image # Updater rolls the cluster onto the new digest (#1486). if: github.ref == 'refs/heads/main' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 # moves to ubuntu-26.04 in #1501 timeout-minutes: 30 permissions: contents: read diff --git a/changelog.d/1494.md b/changelog.d/1494.md new file mode 100644 index 0000000000..dd65fabb9a --- /dev/null +++ b/changelog.d/1494.md @@ -0,0 +1,2 @@ +### Fixed +- CI jobs name their runner image, `ubuntu-24.04`, instead of `ubuntu-latest`, and uv in `ci.yml` and `release.yml` uses only its own CPython builds (`UV_MANAGED_PYTHON`). GitHub moves `ubuntu-latest` to Ubuntu 26.04 from 2026-10-19, where uv would have used the image's own Python 3.14 instead of the 3.14.7 that `.python-version` pins. The move to `ubuntu-26.04` waits for the workflow linter to accept the label (#1501) (#1494). diff --git a/docs/agent/tasks/task-1494-ci-named-runner-managed-python.md b/docs/agent/tasks/task-1494-ci-named-runner-managed-python.md new file mode 100644 index 0000000000..faf57b8b65 --- /dev/null +++ b/docs/agent/tasks/task-1494-ci-named-runner-managed-python.md @@ -0,0 +1,36 @@ +# Task: CI jobs run on a named ubuntu-24.04 runner and always use uv's managed Python, never the runner's own Python (#1494) + +**Issue**: [#1494](https://github.com/dan-petty/devops-cli/issues/1494) +**Status**: Done +**Milestone**: v0.2.32 +**Priority**: P2-Medium (set by intake on 2026-10-09) +**Scope**: type/bug, scope/ci + +## Description + +GitHub moves the `ubuntu-latest` label to Ubuntu 26.04 between 2026-10-19 and 2026-11-19 (actions/runner-images#14748), and every job of ours showed the migration notice. Nine `runs-on` selections used `ubuntu-latest`: five in `ci.yml`, two in `release.yml`, one in `cleanup-devcontainer.yml`, and the non-swift arm of a template expression in `codeql.yml`, whose matrix has only `actions` and `python`. + +On 26.04, CI would stop using the pinned Python: + +- Both setup-uv steps (the `setup-toolchain` composite action that `ci.yml` uses, and `release.yml`'s release job) pass `python-version: "3.14"`. setup-uv exports it as `UV_PYTHON=3.14`, which overrides `.python-version` (3.14.7). +- Ubuntu 24.04's own Python is 3.12, so uv installs its managed CPython 3.14.7. Ubuntu 26.04 ships Python 3.14 as `/usr/bin/python3`. setup-uv's cache key includes the OS version, so the first 26.04 run of each job has no managed Python, and uv's default preference takes the matching system interpreter. setup-uv then skips the Python cache save, so every later run stays on Ubuntu's build. +- Reproduced with uv 0.12.16, offline, with an empty `UV_PYTHON_INSTALL_DIR`: `UV_PYTHON=3.14 uv python find --system` returns the system interpreter. With `UV_MANAGED_PYTHON=1`, uv finds no interpreter in managed installations and refuses the system one, while an explicit interpreter path (`uv python find /usr/bin/python3`) still works. +- uv refuses to run when `UV_MANAGED_PYTHON` and `UV_PYTHON_PREFERENCE` are both set ("cannot be used with `--python-preference`"), so only `UV_MANAGED_PYTHON` is set, not the `UV_PYTHON_PREFERENCE=only-managed` spelling setup-uv's warning names. + +The issue asked for `ubuntu-26.04`, but actionlint 1.7.12, which `devops ci` and the pre-push hook run, rejects `ubuntu-26.04` as an unknown runner label (9 errors), and upstream actionlint has released nothing since 2026-03-30. By the owner's decision of 2026-10-09, every job names `ubuntu-24.04` instead. A named label is not migrated, so no job lands on 26.04 without review, and `UV_MANAGED_PYTHON` is already in place when the jobs move. + +## Acceptance Criteria + +- [x] No workflow job runs on `ubuntu-latest`. All nine selections name `ubuntu-24.04` with a comment linking #1501, and `codeql.yml`'s is a plain label. +- [x] `ci.yml` and `release.yml` set `UV_MANAGED_PYTHON: "1"` in their workflow-level `env`, which reaches the composite action's `uv sync` and every later `uv run`. `test_github_workflows_name_their_runner_and_use_managed_python` in `tests/test_ci.py`, next to `test_github_workflows_caching_configuration`, fails when a job's `runs-on` is a `-latest` label, or when a workflow that reaches setup-uv, directly or through a local composite action, lacks the setting. It failed on the tree before the change with the nine jobs, and fails when `ci.yml`'s setting is removed. +- [x] This repository's workflow runs no longer show the "ubuntu-latest label will migrate" notice, which GitHub shows for jobs that request `ubuntu-latest`. Runs on `main` (Renovate pull requests into `main`, the schedules, dispatches) use `main`'s workflows and show it until v0.2.32's release pull request merges. +- [x] actionlint 1.7.12 reports 0 errors on the workflows, and `uv run devops ci` passes. +- The move to `ubuntu-26.04` and its checks on 26.04 (managed CPython 3.14.7 and the `-python` cache save, the Tests & Coverage skip count, Docker 29 builds of the Service and DevContainer images, Trivy): moved to #1501, which waits for the workflow linter to accept the label. + +## Deliverables + +- [x] `.github/workflows/ci.yml`, `release.yml`, `cleanup-devcontainer.yml` and `codeql.yml`: `runs-on: ubuntu-24.04` in all nine jobs, each with a comment linking #1501. +- [x] `.github/workflows/ci.yml` and `release.yml`: workflow-level `env` with `UV_MANAGED_PYTHON: "1"`. +- [x] `tests/test_ci.py`: `test_github_workflows_name_their_runner_and_use_managed_python`. +- [x] `changelog.d/1494.md`. +- Replacing actionlint with a source that knows `ubuntu-26.04`: #1119. diff --git a/tests/test_ci.py b/tests/test_ci.py index 0fd1e7e8ba..20aa257476 100644 --- a/tests/test_ci.py +++ b/tests/test_ci.py @@ -611,6 +611,56 @@ def test_github_workflows_caching_configuration() -> None: _validate_devcontainer_step(step, context_tag) +def _installs_uv(uses: str) -> bool: + """A step installs uv through setup-uv, directly or through a local composite action.""" + import yaml + + if "astral-sh/setup-uv" in uses: + return True + if not uses.startswith("./"): + return False + action = yaml.safe_load((Path(uses) / "action.yml").read_text(encoding="utf-8")) or {} + return any( + "astral-sh/setup-uv" in str(step.get("uses", "")) for step in action["runs"]["steps"] + ) + + +def test_github_workflows_name_their_runner_and_use_managed_python() -> None: + """Every job names its runner image, and uv in CI runs only its own CPython builds. + + A `-latest` label moves to a new image without review, as ubuntu-latest moves to Ubuntu + 26.04 from 2026-10-19. setup-uv exports `UV_PYTHON=3.14`, so on an image whose own Python + is a 3.14 uv would take that interpreter over the managed build `.python-version` pins + unless `UV_MANAGED_PYTHON` restricts it (#1494). + """ + import yaml + + latest_runners: list[str] = [] + uv_workflows: dict[str, bool] = {} + for wf_file in sorted(Path(".github/workflows").glob("*.yml")): + workflow = yaml.safe_load(wf_file.read_text(encoding="utf-8")) or {} + jobs = {name: job for name, job in workflow["jobs"].items() if isinstance(job, dict)} + latest_runners += [ + f"{wf_file.name}:{name}" + for name, job in jobs.items() + if "-latest" in str(job.get("runs-on", "")) + ] + if any( + _installs_uv(str(step.get("uses", ""))) + for job in jobs.values() + for step in job.get("steps", []) + if isinstance(step, dict) + ): + uv_workflows[wf_file.name] = workflow.get("env", {}).get("UV_MANAGED_PYTHON") == "1" + + assert latest_runners == [], f"jobs on a -latest runner: {latest_runners}" + # ci.yml reaches setup-uv only through the setup-toolchain composite action. + assert {"ci.yml", "release.yml"} <= uv_workflows.keys() + assert [name for name, managed in uv_workflows.items() if not managed] == [], ( + "workflows that run uv must set UV_MANAGED_PYTHON: '1' in their workflow-level env" + ) + + def test_ci_workflow_has_tooling_cache_step() -> None: """Validate the shared toolchain action caches incremental tool state with a stable key. From eeb544b6325307819eba936f43dcf48849fdc1b8 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 9 Oct 2026 10:26:59 -0600 Subject: [PATCH 08/15] fix(k8s): the ollama tier DaemonSets drop privilege escalation and capabilities, use RuntimeDefault seccomp and a read-only root filesystem, and run as non-root where the model directory allows (#1060) (#1508) --- changelog.d/1060.md | 2 + .../task-1060-ollama-daemonset-hardening.md | 118 +++++ k8s/README.md | 2 + k8s/llm/profiles/ollama-profiles.yaml | 441 +++++++++++++++++- tests/test_k8s_llm_gateway.py | 91 ++++ 5 files changed, 636 insertions(+), 18 deletions(-) create mode 100644 changelog.d/1060.md create mode 100644 docs/agent/tasks/task-1060-ollama-daemonset-hardening.md diff --git a/changelog.d/1060.md b/changelog.d/1060.md new file mode 100644 index 0000000000..2053eef944 --- /dev/null +++ b/changelog.d/1060.md @@ -0,0 +1,2 @@ +### Fixed +- The ollama tier DaemonSets no longer run ollama as root: every tier runs it as UID and GID 10001 with RuntimeDefault seccomp, no privilege escalation, all capabilities dropped and a read-only root filesystem, with `/tmp` on an emptyDir (#1060). `HOME` is `/home/ollama`, so the key and models stay on the hostPath `/var/lib/ollama` and nothing is downloaded again. A root initContainer, `own-model-directory`, holding `CAP_CHOWN` alone, gives that directory to UID 10001 at every start, because `fsGroup` does not apply to hostPath volumes; it is the one `run-as-non-root` exception kube-linter reports, recorded in the manifest and `k8s/README.md`. `test_every_ollama_tier_runs_unprivileged` pins these settings for all 9 tiers. diff --git a/docs/agent/tasks/task-1060-ollama-daemonset-hardening.md b/docs/agent/tasks/task-1060-ollama-daemonset-hardening.md new file mode 100644 index 0000000000..b5cf54173b --- /dev/null +++ b/docs/agent/tasks/task-1060-ollama-daemonset-hardening.md @@ -0,0 +1,118 @@ +# Task: The Ollama Tier DaemonSets Run as Non-Root, With No Privilege Escalation or Capabilities, RuntimeDefault Seccomp and a Read-Only Root Filesystem (#1060) + +**Issue**: [#1060](https://github.com/dan-petty/devops-cli/issues/1060) +**Status**: Done +**Milestone**: v0.2.32 +**Priority**: priority/p2-medium +**Scope**: scope/k8s, scope/security + +## Description +None of the 9 ollama tier DaemonSets in `k8s/llm/profiles/ollama-profiles.yaml` set a pod or container `securityContext`. ollama ran as root with the default capabilities, privilege escalation allowed, no seccomp profile and a writable root filesystem. It wrote to the hostPath `/var/lib/ollama`, mounted at `/root/.ollama`. The llm stack's first-party workloads (gateway, portkey, valkey, cloudflared, jaeger) already ran as non-root. + +The live cluster, read with `kubectl get` and `kubectl describe` only, matched the manifest: +- Four tiers are scheduled and Ready: 16gib, 48gib, 48gib-slow and 64gib. Each pod has an empty pod `securityContext`, no container `securityContext` and no initContainers. Each mounts the hostPath `/var/lib/ollama` (`DirectoryOrCreate`) at `/root/.ollama`, with `OLLAMA_MODELS=/root/.ollama/models`. +- Argo CD Application `llm` tracks `main` (path `k8s/llm`, automated prune and selfHeal). Nothing deploys from `release/v0.2.32`, and every tier rolls at once when the release PR merges. +- `get` and `describe` cannot show file ownership on a node. Every writer so far ran as UID 0, and kubelet creates a `DirectoryOrCreate` hostPath owned by root, so the directory is taken to be root-owned. The design does not rely on that, because `chown -R` re-owns whatever is there at every start. + +Every DaemonSet now carries the same settings. A kustomize patch is not used, because `devops k8s deploy-stack` applies this file with `kubectl apply -f`: +- **Pod:** `runAsNonRoot: true`, `runAsUser: 10001`, `runAsGroup: 10001`, `seccompProfile: RuntimeDefault`. The owner chose UID 10001 because no host login account uses it, so neither the model directory's owner nor an escaped process maps to a person's account on a GPU node. +- **Container `ollama`:** `allowPrivilegeEscalation: false`, `readOnlyRootFilesystem: true`, `capabilities.drop: [ALL]`, and `/tmp` on an emptyDir (`tmp`). +- **Paths:** `HOME=/home/ollama`, with the hostPath mounted at `/home/ollama/.ollama` and `OLLAMA_MODELS=/home/ollama/.ollama/models`. + - `ollama serve` reads or creates its key at `$HOME/.ollama/id_ed25519`. A UID that is not in the image's passwd file would otherwise get `HOME=/`. + - `/root` cannot be reached by a non-root UID. + - With these paths, the key and `models/` stay where they were on the host (`/var/lib/ollama`), so nothing is downloaded again. The hostPath and its type are unchanged. +- **initContainer `own-model-directory`:** runs `chown -R 10001:10001 /home/ollama/.ollama` from the same `ollama/ollama:0.34.4` image, so no second image lands on a node. + - Security context: `runAsUser: 0`, `runAsNonRoot: false`, `allowPrivilegeEscalation: false`, `readOnlyRootFilesystem: true`, `capabilities: {drop: [ALL], add: [CHOWN]}`. + - Resources: `requests.cpu: 10m` and `limits.memory: 64Mi`. The memory request defaults to the limit, so kube-linter reports nothing new for it. + - Why it is needed: `fsGroup` does not apply to hostPath volumes; a non-root container loses an added `CAP_CHOWN` at execve, because containerd sets no ambient capabilities; and a DaemonSet cannot give each node its own PVC. Under chown(2), `CAP_CHOWN` alone lets root re-own the files, so `FOWNER` is not needed. This is the Grafana chart's `initChownData` pattern, with a read-only root filesystem added. +- **Header comment:** the manifest header and `k8s/README.md` ("GPU Placement: Ollama tiers") record the UID and the initContainer as the one exception to kube-linter's `run-as-non-root`. No ignore-check annotation is used. + +**Re-scope accepted by the owner on 2026-10-09 (the issue's "Update 2026-10-09").** +- AC4 changes: some container must run as root once to give the hostPath to the ollama UID. kube-linter therefore reports `run-as-non-root` for that initContainer, one per DaemonSet, and nothing else new. +- ollama runs as UID and GID 10001, not 1000. +- The UID cannot be named once in the manifest: YAML anchors do not cross `---` documents, and `kubectl apply -f` would skip a kustomize patch. The test names it once (`OLLAMA_UID`) and asserts it for all 9 tiers. + +## Acceptance Criteria +- [x] Every ollama DaemonSet's `ollama` container sets `allowPrivilegeEscalation: false`, `capabilities.drop: [ALL]` and `readOnlyRootFilesystem: true`, with `seccompProfile: RuntimeDefault` at pod level and an emptyDir at `/tmp`. No other emptyDir is added: the person-run checks below look for "read-only file system" errors, and each such path gets an emptyDir. +- [x] Every ollama DaemonSet runs as UID and GID 10001 with `runAsNonRoot: true`. The model directory is given to that UID by `own-model-directory`, which holds `CAP_CHOWN` alone. `OLLAMA_MODELS` and the data mount moved off `/root`, and `HOME=/home/ollama` keeps the existing hostPath layout. +- [x] `test_every_ollama_tier_runs_unprivileged` in `tests/test_k8s_llm_gateway.py` loads every DaemonSet in `ollama-profiles.yaml`. For each one, it asserts: + - the pod and container security contexts; + - `HOME` and `OLLAMA_MODELS`; + - the container's mounts; + - the volumes, including the unchanged hostPath `/var/lib/ollama` (`DirectoryOrCreate`); + - exactly one initContainer, `own-model-directory`, with the ollama container's image, its `chown` command, its security context and its mount. + + A new tier is covered without editing the test, and `test_ollama_profiles_define_standard_vram_tiers` still pins the 9 names. On the previous manifest the test failed with an assertion diff for every tier, not a `KeyError`. It runs no kubectl, kube-linter or network call. +- [x] kube-linter 0.8.3 over `k8s/llm/profiles/ollama-profiles.yaml` (run locally; the suite does not run it): + - Before: 27 reports, `no-read-only-root-fs` x9, `run-as-non-root` x9 and `unset-memory-requirements` x9. + - After: 18 reports, `run-as-non-root` x9, all `container "own-model-directory"` (the recorded exception), and `unset-memory-requirements` x9, all `container "ollama"` (out of scope: #209 removed the memory limits on purpose). + - `no-read-only-root-fs` is 0, nothing new appears, and no ignore-check annotation is used. +- [x] `changelog.d/1060.md` records the change under `### Fixed`. `CHANGELOG.md` and `docs/ROADMAP.md` are not edited. +- [x] Locally, these pass: + - the tests that read this manifest or scan every manifest: `tests/test_k8s_llm_gateway.py`, `tests/test_k8s_gpu_matrix.py`, `tests/test_ai_gateway_portkey.py`, `tests/test_k8s.py::test_k8s_workload_resource_limits_and_probes`, `tests/test_k8s_valkey_stack.py`, `tests/test_k8s_push_secrets.py`, `tests/test_k8s_manifest_validation.py`, `tests/test_k8s_network_policies.py` and `tests/test_review_project_conventions.py`; + - `tests/test_agent_task_files.py` and `tests/test_release_changelog_fragments.py`; + - `ruff check` and `ruff format --check` on the test file, and `devops docs check`. + + No `src/` file changed, so mypy has nothing new to check. `uv run devops ci` runs as the pull request's CI check. +- Pending a person: the canary on one node, after this PR merges into `release/v0.2.32` and before the v0.2.32 release PR merges into `main` (Argo CD rolls every tier at once from `main`): + 1. From a checkout of `release/v0.2.32`, record each scheduled tier's models for the later comparison, and confirm that the 16gib tier has no model loaded (`ollama ps` lists none), so the canary has the GPU to itself: + ```bash + for t in ollama-16gib ollama-48gib ollama-48gib-slow ollama-64gib; do kubectl -n llm exec ds/$t -c ollama -- ollama list | awk '{print $1, $2}' > /tmp/$t.models; done + kubectl -n llm exec ds/ollama-16gib -c ollama -- ollama ps + ``` + 2. Create the canary as a bare Pod named and labelled `ollama-canary`, with `restartPolicy: Never`. It must not carry the template's labels: the DaemonSet would adopt and delete a pod matching its selector, and the `ollama-16gib` Services would send gateway traffic to it. If it stays Pending for lack of CPU or memory next to the live pod, the canary cannot run on that node: delete it (`kubectl -n llm delete pod ollama-canary`) and rely on the rollout checks. + ```bash + uv run python -c 'import json,yaml; ds=next(d for d in yaml.safe_load_all(open("k8s/llm/profiles/ollama-profiles.yaml")) if d and d["metadata"]["name"]=="ollama-16gib"); print(json.dumps({"apiVersion":"v1","kind":"Pod","metadata":{"name":"ollama-canary","namespace":"llm","labels":{"app.kubernetes.io/name":"ollama-canary"}},"spec":{**ds["spec"]["template"]["spec"],"restartPolicy":"Never"}}))' | kubectl apply -f - + kubectl -n llm wait --for=condition=Ready pod/ollama-canary --timeout=10m + kubectl -n llm get pod ollama-canary -o jsonpath='{.status.initContainerStatuses[0].state.terminated.exitCode}' # 0 + kubectl -n llm exec ollama-canary -c ollama -- id # uid=10001 gid=10001 + kubectl -n llm exec ollama-canary -c ollama -- sh -c 'ls -ln /dev/nvidia*' # crw-rw-rw-, or a group the pod is in + kubectl -n llm exec ollama-canary -c ollama -- ollama list | awk '{print $1, $2}' | diff /tmp/ollama-16gib.models - # no output + kubectl -n llm exec ollama-canary -c ollama -- ollama run gpt-oss:20b 'Reply with ok' + kubectl -n llm exec ollama-canary -c ollama -- ollama ps # PROCESSOR shows GPU + kubectl -n llm logs ollama-canary -c ollama | grep -E 'inference compute|read-only|permission denied' # a CUDA line, no errors + kubectl -n llm delete pod ollama-canary + ``` + The canary leaves that node's directory owned by 10001 while the live pod still runs as root, which keeps writing it (root holds `CAP_DAC_OVERRIDE`). + 3. If the canary fails, fix it in `release/v0.2.32` before the release PR merges, and change the test with it: + - `/dev/nvidia*` is 0660 to a group and the log shows no CUDA line: add pod `supplementalGroups: []` to all 9 tiers. + - A "read-only file system" error at a path: add an emptyDir at that path. + - Only a demonstrated need for root: keep root with every other control set, with a manifest comment and a `k8s/README.md` note. The initContainer must stay and chown to `0:0`, because root with all capabilities dropped cannot write the 10001-owned directory the canary left. + - Anything else, such as the NVIDIA hook failing on a read-only root: stop and return it to the owner. +- Pending a person: the rollout, after the v0.2.32 release PR merges and Argo CD syncs `llm`: + 1. Argo CD and the DaemonSets: + ```bash + kubectl -n argocd get application llm -o jsonpath='{.status.sync.status} {.status.health.status} {.status.sync.revision}{"\n"}' # Synced Healthy + kubectl -n llm get ds -l llm.devops.io/provider=ollama # READY == DESIRED; 16gib, 48gib, 48gib-slow and 64gib at 1 + ``` + 2. Each scheduled tier's pod is Ready, runs as 10001, sees its GPU and still has its models. Expected per tier: `0 0` (init exit code, restarts), `uid=10001 gid=10001`, a GPU name, no `diff` output, and a CUDA `inference compute` line with no "read-only" or "permission denied": + ```bash + for t in ollama-16gib ollama-48gib ollama-48gib-slow ollama-64gib; do + kubectl -n llm get pods -l app.kubernetes.io/name=$t -o jsonpath='{.items[0].status.initContainerStatuses[0].state.terminated.exitCode} {.items[0].status.containerStatuses[0].restartCount}{"\n"}' + kubectl -n llm exec ds/$t -c ollama -- id + kubectl -n llm exec ds/$t -c ollama -- nvidia-smi --query-gpu=name,memory.total --format=csv,noheader + kubectl -n llm exec ds/$t -c ollama -- ollama list | awk '{print $1, $2}' | diff /tmp/$t.models - + kubectl -n llm logs ds/$t -c ollama | grep -E 'inference compute|read-only|permission denied' + done + ``` + 3. A restart re-owns a directory that 10001 already owns: `kubectl -n llm rollout restart ds/ollama-16gib && kubectl -n llm rollout status ds/ollama-16gib --timeout=10m` completes, and the first command of step 2 then prints `0 0` for `ollama-16gib`. + 4. Each tier loads and answers a model through the gateway. Use models that each route to one tier only (`k8s/llm/gateway/configmap.yaml`): `gpt-oss:20b` (16gib), `devops-coder` (48gib), `deepseek-r1:70b` (64gib), and `devops-background` and `bge-m3:latest` (48gib-slow). Each call returns a `choices` entry (the embedding, a vector length), and `kubectl -n llm exec ds/ -c ollama -- ollama ps` then shows the model on 100% GPU: + ```bash + kubectl -n llm port-forward svc/llm-gateway 4000:4000 & + KEY=$(kubectl -n llm get secret llm-gateway-secrets -o jsonpath='{.data.master-key}' | base64 -d) + for m in gpt-oss:20b devops-coder deepseek-r1:70b devops-background; do + curl -s localhost:4000/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \ + -d "{\"model\":\"$m\",\"max_tokens\":64,\"messages\":[{\"role\":\"user\",\"content\":\"Reply with ok\"}]}" | jq '.choices[0].message // .error' + done + curl -s localhost:4000/v1/embeddings -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \ + -d '{"model":"bge-m3:latest","input":"ok"}' | jq '.data[0].embedding | length' + ``` + 5. Record the result per tier in this item's pull request. + +## Deliverables +- [x] `k8s/llm/profiles/ollama-profiles.yaml`: the pod and container security contexts, `HOME`, the moved mount and `OLLAMA_MODELS`, the `/tmp` emptyDir and the `own-model-directory` initContainer in all 9 DaemonSets, and the header comment that records the exception. +- [x] `tests/test_k8s_llm_gateway.py`: `OLLAMA_UID`, `_ollama_privileges` and `test_every_ollama_tier_runs_unprivileged`. +- [x] `k8s/README.md`, "GPU Placement: Ollama tiers": a paragraph on the UID, the controls, the initContainer and the kube-linter exception. +- [x] `changelog.d/1060.md`. +- Out of scope, as the issue records: memory limits for the `ollama` container (kube-linter `unset-memory-requirements` x9), which #209 removed on purpose. +- Not in this item, as the issue's key question decides: raising the `llm` namespace's Pod Security `enforce` level. The tiers keep it at `privileged` regardless, because Pod Security's baseline level forbids hostPath volumes. diff --git a/k8s/README.md b/k8s/README.md index 1fdcaabb5c..18ff56cf6a 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -129,6 +129,8 @@ Open WebUI uses the same key: on a fresh install it connects to the gateway auto ### GPU Placement: Ollama tiers Ollama runs as one DaemonSet per total-VRAM tier (`ollama-16gib` … `ollama-128gib`, `llm/profiles/ollama-profiles.yaml`), scheduled by the node label `nvidia.com/gpu.total-vram-gib`. The gateway reaches each tier through its ClusterIP Service `ollama-gib`. +Every tier runs ollama as UID and GID 10001, which no host login account uses, with RuntimeDefault seccomp, no privilege escalation, all capabilities dropped and a read-only root filesystem; `/tmp` is an emptyDir. `HOME` is `/home/ollama`, so the key and `models/` stay in the hostPath `/var/lib/ollama` on each GPU node, mounted at `/home/ollama/.ollama`. `fsGroup` does not apply to a hostPath volume, so the initContainer `own-model-directory` gives that directory to 10001 at every start (`chown -R`). It runs as root with `CAP_CHOWN` alone, no privilege escalation and a read-only root filesystem, and exits before ollama starts. It is the one exception to kube-linter's `run-as-non-root` in `ollama-profiles.yaml`, recorded in the manifest's header rather than suppressed with an ignore annotation. + Inference workloads pull models directly and are reachable inside the cluster through the gateway. ## Port Forwarding & Automated Configuration diff --git a/k8s/llm/profiles/ollama-profiles.yaml b/k8s/llm/profiles/ollama-profiles.yaml index b11ff06aaf..813889851e 100644 --- a/k8s/llm/profiles/ollama-profiles.yaml +++ b/k8s/llm/profiles/ollama-profiles.yaml @@ -5,6 +5,15 @@ # little VRAM to load (#1061). The exception is ollama-48gib-slow, the background tier: it keeps # its embedding model and one background model loaded, since with one loaded each evicted the # other on every switch (#1064). +# +# Every tier runs ollama as UID and GID 10001, which no host login account uses, with RuntimeDefault +# seccomp, no privilege escalation, all capabilities dropped and a read-only root filesystem; /tmp is +# an emptyDir. HOME is /home/ollama, so the key and models/ stay in the hostPath /var/lib/ollama, +# mounted at /home/ollama/.ollama. fsGroup does not apply to a hostPath volume, so the +# own-model-directory initContainer gives that directory to 10001 at every start. It runs as root +# with CAP_CHOWN alone, no privilege escalation and a read-only root filesystem, and exits before +# ollama starts. It is the one exception to kube-linter's run-as-non-root, recorded here and in +# k8s/README.md rather than suppressed (#1060). --- apiVersion: apps/v1 kind: DaemonSet @@ -37,6 +46,12 @@ spec: llm.devops.io/speed-tier: fast spec: runtimeClassName: nvidia + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + seccompProfile: + type: RuntimeDefault affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: @@ -51,14 +66,48 @@ spec: - key: nvidia.com/gpu.total-vram-gib operator: In values: ["16Gi", "20Gi"] + initContainers: + - name: own-model-directory + image: ollama/ollama:0.34.4 + securityContext: + runAsUser: 0 + runAsNonRoot: false + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL + add: + - CHOWN + command: + - chown + - -R + - "10001:10001" + - /home/ollama/.ollama + resources: + requests: + cpu: 10m + limits: + memory: 64Mi + volumeMounts: + - name: ollama-data + mountPath: /home/ollama/.ollama containers: - name: ollama image: ollama/ollama:0.34.4 + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL env: - name: OLLAMA_HOST value: 0.0.0.0:11434 + - name: HOME + value: /home/ollama - name: OLLAMA_MODELS - value: /root/.ollama/models + value: /home/ollama/.ollama/models - name: OLLAMA_CONTEXT_LENGTH value: "48000" - name: OLLAMA_MAX_LOADED_MODELS @@ -102,12 +151,16 @@ spec: failureThreshold: 6 volumeMounts: - name: ollama-data - mountPath: /root/.ollama + mountPath: /home/ollama/.ollama + - name: tmp + mountPath: /tmp volumes: - name: ollama-data hostPath: path: /var/lib/ollama type: DirectoryOrCreate + - name: tmp + emptyDir: {} --- apiVersion: apps/v1 kind: DaemonSet @@ -140,6 +193,12 @@ spec: llm.devops.io/speed-tier: slow spec: runtimeClassName: nvidia + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + seccompProfile: + type: RuntimeDefault affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: @@ -151,14 +210,48 @@ spec: - key: nvidia.com/gpu.total-vram-gib operator: In values: ["24Gi", "28Gi"] + initContainers: + - name: own-model-directory + image: ollama/ollama:0.34.4 + securityContext: + runAsUser: 0 + runAsNonRoot: false + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL + add: + - CHOWN + command: + - chown + - -R + - "10001:10001" + - /home/ollama/.ollama + resources: + requests: + cpu: 10m + limits: + memory: 64Mi + volumeMounts: + - name: ollama-data + mountPath: /home/ollama/.ollama containers: - name: ollama image: ollama/ollama:0.34.4 + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL env: - name: OLLAMA_HOST value: 0.0.0.0:11434 + - name: HOME + value: /home/ollama - name: OLLAMA_MODELS - value: /root/.ollama/models + value: /home/ollama/.ollama/models - name: OLLAMA_CONTEXT_LENGTH value: "48000" - name: OLLAMA_MAX_LOADED_MODELS @@ -202,12 +295,16 @@ spec: failureThreshold: 6 volumeMounts: - name: ollama-data - mountPath: /root/.ollama + mountPath: /home/ollama/.ollama + - name: tmp + mountPath: /tmp volumes: - name: ollama-data hostPath: path: /var/lib/ollama type: DirectoryOrCreate + - name: tmp + emptyDir: {} --- apiVersion: apps/v1 kind: DaemonSet @@ -238,6 +335,12 @@ spec: llm.devops.io/total-vram-gib: "32" spec: runtimeClassName: nvidia + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + seccompProfile: + type: RuntimeDefault affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: @@ -252,14 +355,48 @@ spec: - key: nvidia.com/gpu.total-vram-gib operator: In values: ["32Gi", "36Gi", "40Gi", "44Gi"] + initContainers: + - name: own-model-directory + image: ollama/ollama:0.34.4 + securityContext: + runAsUser: 0 + runAsNonRoot: false + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL + add: + - CHOWN + command: + - chown + - -R + - "10001:10001" + - /home/ollama/.ollama + resources: + requests: + cpu: 10m + limits: + memory: 64Mi + volumeMounts: + - name: ollama-data + mountPath: /home/ollama/.ollama containers: - name: ollama image: ollama/ollama:0.34.4 + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL env: - name: OLLAMA_HOST value: 0.0.0.0:11434 + - name: HOME + value: /home/ollama - name: OLLAMA_MODELS - value: /root/.ollama/models + value: /home/ollama/.ollama/models - name: OLLAMA_CONTEXT_LENGTH value: "48000" - name: OLLAMA_MAX_LOADED_MODELS @@ -305,12 +442,16 @@ spec: failureThreshold: 6 volumeMounts: - name: ollama-data - mountPath: /root/.ollama + mountPath: /home/ollama/.ollama + - name: tmp + mountPath: /tmp volumes: - name: ollama-data hostPath: path: /var/lib/ollama type: DirectoryOrCreate + - name: tmp + emptyDir: {} --- apiVersion: apps/v1 kind: DaemonSet @@ -343,6 +484,12 @@ spec: llm.devops.io/speed-tier: fast spec: runtimeClassName: nvidia + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + seccompProfile: + type: RuntimeDefault affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: @@ -354,14 +501,48 @@ spec: - key: nvidia.com/gpu.total-vram-gib operator: In values: ["48Gi", "52Gi", "56Gi", "60Gi"] + initContainers: + - name: own-model-directory + image: ollama/ollama:0.34.4 + securityContext: + runAsUser: 0 + runAsNonRoot: false + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL + add: + - CHOWN + command: + - chown + - -R + - "10001:10001" + - /home/ollama/.ollama + resources: + requests: + cpu: 10m + limits: + memory: 64Mi + volumeMounts: + - name: ollama-data + mountPath: /home/ollama/.ollama containers: - name: ollama image: ollama/ollama:0.34.4 + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL env: - name: OLLAMA_HOST value: 0.0.0.0:11434 + - name: HOME + value: /home/ollama - name: OLLAMA_MODELS - value: /root/.ollama/models + value: /home/ollama/.ollama/models - name: OLLAMA_CONTEXT_LENGTH value: "128000" - name: OLLAMA_MAX_LOADED_MODELS @@ -407,12 +588,16 @@ spec: failureThreshold: 6 volumeMounts: - name: ollama-data - mountPath: /root/.ollama + mountPath: /home/ollama/.ollama + - name: tmp + mountPath: /tmp volumes: - name: ollama-data hostPath: path: /var/lib/ollama type: DirectoryOrCreate + - name: tmp + emptyDir: {} --- apiVersion: apps/v1 kind: DaemonSet @@ -445,6 +630,12 @@ spec: llm.devops.io/speed-tier: slow spec: runtimeClassName: nvidia + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + seccompProfile: + type: RuntimeDefault affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: @@ -456,14 +647,48 @@ spec: - key: nvidia.com/gpu.total-vram-gib operator: In values: ["48Gi", "52Gi", "56Gi", "60Gi"] + initContainers: + - name: own-model-directory + image: ollama/ollama:0.34.4 + securityContext: + runAsUser: 0 + runAsNonRoot: false + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL + add: + - CHOWN + command: + - chown + - -R + - "10001:10001" + - /home/ollama/.ollama + resources: + requests: + cpu: 10m + limits: + memory: 64Mi + volumeMounts: + - name: ollama-data + mountPath: /home/ollama/.ollama containers: - name: ollama image: ollama/ollama:0.34.4 + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL env: - name: OLLAMA_HOST value: 0.0.0.0:11434 + - name: HOME + value: /home/ollama - name: OLLAMA_MODELS - value: /root/.ollama/models + value: /home/ollama/.ollama/models - name: OLLAMA_CONTEXT_LENGTH value: "128000" - name: OLLAMA_MAX_LOADED_MODELS @@ -511,12 +736,16 @@ spec: failureThreshold: 6 volumeMounts: - name: ollama-data - mountPath: /root/.ollama + mountPath: /home/ollama/.ollama + - name: tmp + mountPath: /tmp volumes: - name: ollama-data hostPath: path: /var/lib/ollama type: DirectoryOrCreate + - name: tmp + emptyDir: {} --- apiVersion: apps/v1 kind: DaemonSet @@ -549,6 +778,12 @@ spec: llm.devops.io/speed-tier: standard spec: runtimeClassName: nvidia + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + seccompProfile: + type: RuntimeDefault affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: @@ -563,14 +798,48 @@ spec: - key: nvidia.com/gpu.total-vram-gib operator: In values: ["64Gi", "68Gi"] + initContainers: + - name: own-model-directory + image: ollama/ollama:0.34.4 + securityContext: + runAsUser: 0 + runAsNonRoot: false + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL + add: + - CHOWN + command: + - chown + - -R + - "10001:10001" + - /home/ollama/.ollama + resources: + requests: + cpu: 10m + limits: + memory: 64Mi + volumeMounts: + - name: ollama-data + mountPath: /home/ollama/.ollama containers: - name: ollama image: ollama/ollama:0.34.4 + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL env: - name: OLLAMA_HOST value: 0.0.0.0:11434 + - name: HOME + value: /home/ollama - name: OLLAMA_MODELS - value: /root/.ollama/models + value: /home/ollama/.ollama/models - name: OLLAMA_CONTEXT_LENGTH value: "160000" - name: OLLAMA_MAX_LOADED_MODELS @@ -616,12 +885,16 @@ spec: failureThreshold: 6 volumeMounts: - name: ollama-data - mountPath: /root/.ollama + mountPath: /home/ollama/.ollama + - name: tmp + mountPath: /tmp volumes: - name: ollama-data hostPath: path: /var/lib/ollama type: DirectoryOrCreate + - name: tmp + emptyDir: {} --- apiVersion: apps/v1 kind: DaemonSet @@ -652,6 +925,12 @@ spec: llm.devops.io/total-vram-gib: "72" spec: runtimeClassName: nvidia + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + seccompProfile: + type: RuntimeDefault affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: @@ -666,14 +945,48 @@ spec: - key: nvidia.com/gpu.total-vram-gib operator: In values: ["72Gi", "76Gi", "80Gi", "84Gi", "88Gi", "92Gi"] + initContainers: + - name: own-model-directory + image: ollama/ollama:0.34.4 + securityContext: + runAsUser: 0 + runAsNonRoot: false + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL + add: + - CHOWN + command: + - chown + - -R + - "10001:10001" + - /home/ollama/.ollama + resources: + requests: + cpu: 10m + limits: + memory: 64Mi + volumeMounts: + - name: ollama-data + mountPath: /home/ollama/.ollama containers: - name: ollama image: ollama/ollama:0.34.4 + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL env: - name: OLLAMA_HOST value: 0.0.0.0:11434 + - name: HOME + value: /home/ollama - name: OLLAMA_MODELS - value: /root/.ollama/models + value: /home/ollama/.ollama/models - name: OLLAMA_CONTEXT_LENGTH value: "192000" - name: OLLAMA_MAX_LOADED_MODELS @@ -719,12 +1032,16 @@ spec: failureThreshold: 6 volumeMounts: - name: ollama-data - mountPath: /root/.ollama + mountPath: /home/ollama/.ollama + - name: tmp + mountPath: /tmp volumes: - name: ollama-data hostPath: path: /var/lib/ollama type: DirectoryOrCreate + - name: tmp + emptyDir: {} --- apiVersion: apps/v1 kind: DaemonSet @@ -755,6 +1072,12 @@ spec: llm.devops.io/total-vram-gib: "96" spec: runtimeClassName: nvidia + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + seccompProfile: + type: RuntimeDefault affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: @@ -779,14 +1102,48 @@ spec: "120Gi", "124Gi", ] + initContainers: + - name: own-model-directory + image: ollama/ollama:0.34.4 + securityContext: + runAsUser: 0 + runAsNonRoot: false + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL + add: + - CHOWN + command: + - chown + - -R + - "10001:10001" + - /home/ollama/.ollama + resources: + requests: + cpu: 10m + limits: + memory: 64Mi + volumeMounts: + - name: ollama-data + mountPath: /home/ollama/.ollama containers: - name: ollama image: ollama/ollama:0.34.4 + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL env: - name: OLLAMA_HOST value: 0.0.0.0:11434 + - name: HOME + value: /home/ollama - name: OLLAMA_MODELS - value: /root/.ollama/models + value: /home/ollama/.ollama/models - name: OLLAMA_CONTEXT_LENGTH value: "224000" - name: OLLAMA_MAX_LOADED_MODELS @@ -832,12 +1189,16 @@ spec: failureThreshold: 6 volumeMounts: - name: ollama-data - mountPath: /root/.ollama + mountPath: /home/ollama/.ollama + - name: tmp + mountPath: /tmp volumes: - name: ollama-data hostPath: path: /var/lib/ollama type: DirectoryOrCreate + - name: tmp + emptyDir: {} --- apiVersion: apps/v1 kind: DaemonSet @@ -868,6 +1229,12 @@ spec: llm.devops.io/total-vram-gib: "128" spec: runtimeClassName: nvidia + securityContext: + runAsNonRoot: true + runAsUser: 10001 + runAsGroup: 10001 + seccompProfile: + type: RuntimeDefault affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: @@ -882,14 +1249,48 @@ spec: - key: nvidia.com/gpu.total-vram-gib operator: In values: ["128Gi"] + initContainers: + - name: own-model-directory + image: ollama/ollama:0.34.4 + securityContext: + runAsUser: 0 + runAsNonRoot: false + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL + add: + - CHOWN + command: + - chown + - -R + - "10001:10001" + - /home/ollama/.ollama + resources: + requests: + cpu: 10m + limits: + memory: 64Mi + volumeMounts: + - name: ollama-data + mountPath: /home/ollama/.ollama containers: - name: ollama image: ollama/ollama:0.34.4 + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL env: - name: OLLAMA_HOST value: 0.0.0.0:11434 + - name: HOME + value: /home/ollama - name: OLLAMA_MODELS - value: /root/.ollama/models + value: /home/ollama/.ollama/models - name: OLLAMA_CONTEXT_LENGTH value: "256000" - name: OLLAMA_MAX_LOADED_MODELS @@ -935,9 +1336,13 @@ spec: failureThreshold: 6 volumeMounts: - name: ollama-data - mountPath: /root/.ollama + mountPath: /home/ollama/.ollama + - name: tmp + mountPath: /tmp volumes: - name: ollama-data hostPath: path: /var/lib/ollama type: DirectoryOrCreate + - name: tmp + emptyDir: {} diff --git a/tests/test_k8s_llm_gateway.py b/tests/test_k8s_llm_gateway.py index 5e702aa18a..4d7b182ad8 100644 --- a/tests/test_k8s_llm_gateway.py +++ b/tests/test_k8s_llm_gateway.py @@ -29,6 +29,8 @@ GATEWAY_IMAGE = "ghcr.io/berriai/litellm:v1.103.0" GATEWAY_SECRET = "llm-gateway-secrets" GATEWAY_SECRET_KEY = "master-key" +# The UID and GID every ollama tier runs as; no host login account uses it (#1060). +OLLAMA_UID = 10001 def _load_kind(path: Path, kind: str) -> dict[str, Any]: @@ -87,6 +89,42 @@ def _kustomized_files(directory: Path) -> set[Path]: } +def _mounts(container: dict[str, Any]) -> dict[str, str]: + """Return a container's volume mounts as {mountPath: volume name}.""" + return {mount["mountPath"]: mount["name"] for mount in container.get("volumeMounts", [])} + + +def _ollama_privileges(pod: dict[str, Any]) -> tuple[Any, ...]: + """Return who an ollama tier's pod runs as and where it may write. + + In order: the pod and `ollama` container security contexts, HOME and OLLAMA_MODELS, the + container's mounts, the pod's volumes, and each initContainer as (name, runs the `ollama` + image, command, security context, mounts). + """ + ollama = next(c for c in pod.get("containers", []) if c.get("name") == "ollama") + env = {var["name"]: var.get("value") for var in ollama.get("env", [])} + return ( + pod.get("securityContext"), + ollama.get("securityContext"), + (env.get("HOME"), env.get("OLLAMA_MODELS")), + _mounts(ollama), + { + volume["name"]: {key: value for key, value in volume.items() if key != "name"} + for volume in pod.get("volumes", []) + }, + [ + ( + init.get("name"), + init.get("image") == ollama.get("image"), + init.get("command"), + init.get("securityContext"), + _mounts(init), + ) + for init in pod.get("initContainers", []) + ], + ) + + class TestK8sLLMGatewayManifests: """Validate Kubernetes manifests and zero-trust policies for LiteLLM Gateway.""" @@ -447,6 +485,59 @@ def test_every_ollama_tier_keeps_one_model_and_serves_one_request(self) -> None: assert settings == expected + def test_every_ollama_tier_runs_unprivileged(self) -> None: + """Verify every tier runs ollama as one non-root UID with no privilege to gain (#1060). + + The one root step is the `own-model-directory` initContainer: fsGroup does not reach a + hostPath volume, so it hands the model directory to that UID holding CAP_CHOWN alone. + HOME keeps the key and models on the same hostPath, so nothing is downloaded again. The + initContainer runs the ollama image, so a tag bump cannot leave two images on a node. + """ + docs = yaml.safe_load_all(OLLAMA_PROFILES_MANIFEST.read_text(encoding="utf-8")) + observed = { + d["metadata"]["name"]: _ollama_privileges(d["spec"]["template"]["spec"]) + for d in docs + if d and d.get("kind") == "DaemonSet" + } + expected = ( + { + "runAsNonRoot": True, + "runAsUser": OLLAMA_UID, + "runAsGroup": OLLAMA_UID, + "seccompProfile": {"type": "RuntimeDefault"}, + }, + { + "allowPrivilegeEscalation": False, + "readOnlyRootFilesystem": True, + "capabilities": {"drop": ["ALL"]}, + }, + ("/home/ollama", "/home/ollama/.ollama/models"), + {"/home/ollama/.ollama": "ollama-data", "/tmp": "tmp"}, + { + "ollama-data": { + "hostPath": {"path": "/var/lib/ollama", "type": "DirectoryOrCreate"} + }, + "tmp": {"emptyDir": {}}, + }, + [ + ( + "own-model-directory", + True, + ["chown", "-R", f"{OLLAMA_UID}:{OLLAMA_UID}", "/home/ollama/.ollama"], + { + "runAsUser": 0, + "runAsNonRoot": False, + "allowPrivilegeEscalation": False, + "readOnlyRootFilesystem": True, + "capabilities": {"drop": ["ALL"], "add": ["CHOWN"]}, + }, + {"/home/ollama/.ollama": "ollama-data"}, + ) + ], + ) + + assert observed == {name: expected for name in observed} + @pytest.mark.parametrize("service_name", ["ollama-16gib", "ollama-48gib"]) def test_ollama_services_stay_behind_the_gateway(self, service_name: str) -> None: """Verify Ollama Services are cluster-internal; LAN clients use the authenticated gateway.""" From 0efe7c8351684864ef047769ad3cd13eda6a8a6e Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 9 Oct 2026 11:04:13 -0600 Subject: [PATCH 09/15] fix(git): GitHub clones trust GitHub's published host keys through OpenSSH (#1114) (#1510) --- changelog.d/1114.md | 9 + docs/KNOWN_ISSUES.md | 8 +- .../tasks/task-1114-github-ssh-host-keys.md | 38 + src/devops_cli/commands/repos.py | 5 +- src/devops_cli/config/constants.py | 45 +- src/devops_cli/crypto/host_keys.py | 163 ---- src/devops_cli/crypto/known_hosts.py | 272 ------- src/devops_cli/git/operations.py | 141 ++-- tests/test_git_operations.py | 126 +--- tests/test_ssh_host_keys.py | 699 ++++-------------- 10 files changed, 292 insertions(+), 1214 deletions(-) create mode 100644 changelog.d/1114.md create mode 100644 docs/agent/tasks/task-1114-github-ssh-host-keys.md delete mode 100644 src/devops_cli/crypto/host_keys.py delete mode 100644 src/devops_cli/crypto/known_hosts.py diff --git a/changelog.d/1114.md b/changelog.d/1114.md new file mode 100644 index 0000000000..7dea4f9048 --- /dev/null +++ b/changelog.d/1114.md @@ -0,0 +1,9 @@ +### Security +- GitHub clones append GitHub's published host keys directly to `~/.ssh/known_hosts`, ensuring junk known_hosts lines no longer skip pinning and failed keyscans no longer skip host-key verification silently. + +### Changed +- Failed repository clones wrap `gitlib.GitCommandError` into `GitOperationError` and report masked stderr from git and OpenSSH without exposing credentials. +- Pinned GitHub host keys are seeded across all clone operations, including HTTPS clones. + +### Removed +- In-process `known_hosts` parser and runtime `ssh-keyscan` invocation, delegating host key validation to OpenSSH. diff --git a/docs/KNOWN_ISSUES.md b/docs/KNOWN_ISSUES.md index 8ecc7884fb..d1c5ae9bec 100644 --- a/docs/KNOWN_ISSUES.md +++ b/docs/KNOWN_ISSUES.md @@ -26,9 +26,9 @@ Captures operational edge cases, intentional design trade-offs, and mitigations - **Context**: Designed specifically for local DevOps workstations. Uses high timeouts (`DEFAULT_REVIEW_TIMEOUT_SECONDS = 3600.0`) for CPU/GPU Ollama, bind-mounts host `~/.ssh` into `.devcontainer` for key rotation and SSH agent usage, and uses OS keyring for secret isolation. Direct bind mounts of host SSH configuration serve developer convenience in local dev environments. - **Mitigation**: Defer to Environment & Modernization Policy in `AGENTS.md`. High workstation timeouts and host SSH mounts are accepted design trade-offs for local devcontainers. -### 6. SSH Host Key Scanning (ssh-keyscan) Fingerprint Verification -- **Context**: `_ensure_known_host()` uses `ssh-keyscan` to automatically retrieve public SSH host keys during initial clone operations. Without pre-configured host fingerprints, initial trust-on-first-use occurs over the network. -- **Mitigation**: Pre-populate `~/.ssh/known_hosts` with trusted host fingerprints (e.g. GitHub/GitLab public keys) on developer workstations or build images. +### 6. GitHub SSH Host Key Pinning & OpenSSH Native Verification +- **Context**: GitHub's published OpenSSH host keys (`CONST_GITHUB_KNOWN_HOSTS_LINES`) are written directly to `~/.ssh/known_hosts` on clone operations, allowing OpenSSH to natively verify host keys against pinned values rather than performing dynamic network scans. +- **Mitigation**: Pinned keys are automatically seeded into `~/.ssh/known_hosts` once per process. For third-party or custom git hosts, pre-populate `~/.ssh/known_hosts` on developer workstations or container build images. ### 7. AI Review False-Positive Detection & Invalidation Feedback Loop - **Context**: LLM review personas may occasionally hallucinate legacy syntax (e.g. Python 2 comma-separated exception handling), flag pre-submission secret redaction placeholders (``, `[REDACTED]`, `{% raw %}${{ secrets.* }}{% endraw %}`), or cite historical research/evidence notes (`evidence/`, `docs/agent/archive/`) as live vulnerabilities. @@ -49,6 +49,6 @@ Captures operational edge cases, intentional design trade-offs, and mitigations | **3. Large Workspace Iteration** | Low (performance edge case) | Low | **Keep Path Guards**: `iter_workspace_repos()` and `.gitignore` bounds filtering. | | **4. Optional SDK Dependencies** | Low (setup error) | Low | **Keep Env Guard**: `uv sync` ensures full SDK availability. | | **5. Local Workstation Design Policy** | Low (architectural trade-off) | Low | **Keep DevContainer Policy**: Workspace bounds secure file access; SSH mounts serve local model. | -| **6. SSH Host Key Scanning (TOFU)** | Medium (network MITM on initial clone) | Low | **Pre-seed Known Hosts**: Pre-populate `known_hosts` for critical git hosts. | +| **6. GitHub SSH Host Key Pinning** | Low (OpenSSH enforces pinned keys natively) | Low | **Automated Pinning**: GitHub published keys are seeded to `~/.ssh/known_hosts` on clone. | | **7. AI Review False-Positive Tuning** | Low (prompt noise on non-code assets) | Low | **Verification Feedback**: Use `devops ai review verify` and `export-feedback` to tune prompts. | | **8. Multi-Exception Syntax & Model Defaults** | Low (LLM hallucination on PEP 758) | Low | **PEP 758 Awareness**: Permit `except A, B:` without brackets in Python 3.14+; enforce `Field(default_factory=...)`. | diff --git a/docs/agent/tasks/task-1114-github-ssh-host-keys.md b/docs/agent/tasks/task-1114-github-ssh-host-keys.md new file mode 100644 index 0000000000..7d960f2872 --- /dev/null +++ b/docs/agent/tasks/task-1114-github-ssh-host-keys.md @@ -0,0 +1,38 @@ +# Task: GitHub clones trust GitHub's published host keys through OpenSSH (#1114) + +**Issue**: [#1114](https://github.com/dan-petty/devops-cli/issues/1114) +**Status**: Done +**Milestone**: v0.2.32 +**Priority**: priority/p2-medium +**Scope**: scope/security + +## Description +Prior to this change, `clone_repo` attempted in-process SSH host key verification by invoking `ssh-keyscan` and parsing `~/.ssh/known_hosts` with a custom in-process parser (`crypto/known_hosts.py` and `crypto/host_keys.py`). This led to two critical security fail-opens: +1. Malformed or junk lines in `~/.ssh/known_hosts` (such as unparseable tokens or invalid entries) caused the in-process parser to reject or skip lines, silently failing open and skipping host-key pinning. +2. If `ssh-keyscan` failed (e.g. during intermittent network timeouts or firewall restrictions), the scan error was caught and ignored, silently skipping host-key pinning before cloning. +3. Hand-rolled parsing duplicated OpenSSH's native configuration and marker handling, failing to properly model `@revoked`, `@cert-authority`, hashing, negated patterns, or alternate ports. + +This deliverable replaces the custom parser and runtime key scanning with GitHub's published, pinned host keys written directly to `~/.ssh/known_hosts`, letting OpenSSH perform native verification: +1. Replaced custom crypto parsing with `CONST_GITHUB_KNOWN_HOSTS_LINES` in `src/devops_cli/config/constants.py` containing GitHub's 3 published known_hosts lines (ed25519, ecdsa-sha2-nistp256, and ssh-rsa). +2. Removed hand-rolled `src/devops_cli/crypto/host_keys.py` and `src/devops_cli/crypto/known_hosts.py`. +3. In `src/devops_cli/git/operations.py`, implemented `_ensure_known_host` decorated with `@functools.cache` to append missing pinned lines to `~/.ssh/known_hosts` with mode `0600` and directory mode `0700`. +4. If `~/.ssh` or `known_hosts` is unwritable, `_ensure_known_host` logs a warning once and allows the operation to proceed without crashing. +5. Invoked `_ensure_known_host()` unconditionally in `_prepare_clone_url` for all repository clone operations. +6. Wrapped `gitlib.GitCommandError` in `GitOperationError` during `clone_repo`, masking secrets from stdout and stderr. +7. Wrapped `clone_repo` in `src/devops_cli/commands/repos.py` with `with exit_on_error(GitOperationError):` to report clean error diagnostics. +8. Updated `docs/KNOWN_ISSUES.md` documenting native OpenSSH host key verification and pinned host keys. +9. Rewrote `tests/test_ssh_host_keys.py` to test pinned line structure via `cryptography`, match GitHub's published fingerprints, verify file permissions and newline handling, and test error masking. + +## Acceptance Criteria Checklist +- [x] Pinned host key lines in `CONST_GITHUB_KNOWN_HOSTS_LINES` parse into valid public keys via `cryptography.hazmat.primitives.serialization.load_ssh_public_key`. +- [x] Fingerprints of pinned lines match GitHub's published SHA256 fingerprints for ed25519, ecdsa-sha2-nistp256, and ssh-rsa. +- [x] `_ensure_known_host` creates `~/.ssh` (mode 0700) and `known_hosts` (mode 0600) and appends missing lines preserving existing contents. +- [x] Existing un-terminated files get a newline before appended lines. +- [x] Junk, malformed, or comment lines in `~/.ssh/known_hosts` do not prevent pinned lines from being appended. +- [x] Unwritable `~/.ssh` directory logs a warning once and does not raise. +- [x] `clone_repo` calls `_ensure_known_host` for both SSH and HTTPS clone URLs. +- [x] Failed clone commands raise `GitOperationError` with masked stderr. +- [x] `devops repos clone` CLI command handles `GitOperationError` cleanly via `exit_on_error`. +- [x] Hand-rolled `crypto/host_keys.py` and `crypto/known_hosts.py` modules are deleted. +- [x] All tests run offline with no external network or live ssh binary required. +- Pending a person: with an empty `~/.ssh` and OpenSSH's default `StrictHostKeyChecking ask`, `devops repos clone git@github.com:/.git` clones with no host-key prompt. It does the same with an `@cert-authority github.com …` line already in `~/.ssh/known_hosts`. diff --git a/src/devops_cli/commands/repos.py b/src/devops_cli/commands/repos.py index dfdc052b26..55a08e7355 100755 --- a/src/devops_cli/commands/repos.py +++ b/src/devops_cli/commands/repos.py @@ -25,7 +25,7 @@ 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.exceptions.git import GitHubOperationError +from devops_cli.exceptions.git import GitHubOperationError, GitOperationError from devops_cli.git.operations import clone_repo, fetch_all, iter_workspace_repos, pull_tracking from devops_cli.lang import HELP, MESSAGES from devops_cli.output import ( @@ -277,7 +277,8 @@ def clone( dest_dir.mkdir(parents=True, exist_ok=True) masked_url = mask_secrets(url) print_info(MESSAGES.repos.cloning_repo.format(url=masked_url, dest=dest), prefix=False) - clone_repo(url, dest) + with exit_on_error(GitOperationError): + clone_repo(url, dest) _sync_and_reload_workspace(root, settings.workspace.file) print_success(MESSAGES.repos.done, prefix=False) diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 513c6334a4..5e77a52a7d 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -3108,38 +3108,21 @@ # clear error rather than recursing until the interpreter stops it. CONST_SUPPRESSION_MAX_INHERITANCE_DEPTH: Final[int] = 10 -# ── OpenSSH known_hosts ────────────────────────────────────────────────────── -# Hashed host fields are written as |1||. -CONST_KNOWN_HOSTS_HASH_PREFIX: Final[str] = "|1|" -CONST_KNOWN_HOSTS_MARKER_REVOKED: Final[str] = "@revoked" -CONST_KNOWN_HOSTS_MARKER_CERT_AUTHORITY: Final[str] = "@cert-authority" - -# ── SSH Host Key Verification ──────────────────────────────────────────────── -CONST_SSH_FINGERPRINT_PREFIX: Final[str] = "SHA256:" -# Host key algorithms accepted from a scan. Types outside this set are ignored rather than -# written to known_hosts, where an unusable entry silently breaks later connections. -CONST_SSH_HOST_KEY_TYPES: Final[frozenset[str]] = frozenset( - { - "ssh-ed25519", - "ecdsa-sha2-nistp256", - "ecdsa-sha2-nistp384", - "ecdsa-sha2-nistp521", - "ssh-rsa", - "rsa-sha2-256", - "rsa-sha2-512", - } -) -# GitHub publishes these at https://api.github.com/meta over TLS, so pinning them lets the -# SSH host key be verified against a channel that is already authenticated rather than -# trusting whatever answers the first connection. Refresh with `devops git host-keys`. -CONST_GITHUB_HOST_KEY_FINGERPRINTS: Final[frozenset[str]] = frozenset( - { - "SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU", # ssh-ed25519 - "SHA256:p2QAMXNIC1TJYWeIOttrVc98/R1BUFWu3/LiyKgUfQM", # ecdsa-sha2-nistp256 - "SHA256:uNiVztksCsDhcc0u9e8BujQXVUpKZIDTMczCvj3tD2s", # ssh-rsa - } +# ── GitHub SSH Host Keys ───────────────────────────────────────────────────── +# GitHub's published OpenSSH known_hosts lines, published at https://api.github.com/meta +# (.ssh_keys) and documented at "GitHub's SSH key fingerprints": +# https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/githubs-ssh-key-fingerprints +CONST_GITHUB_KNOWN_HOSTS_LINES: Final[tuple[str, ...]] = ( + "github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl", + ( + "github.com ecdsa-sha2-nistp256" + " AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEmKSENjQEezOmxkZMy7opKgwFB9nkt5YRrYMjNuG5N87uRgg6CLrbo5wAdT/y6v0mKV0U2w0WZ2YB/++Tpockg=" + ), + ( + "github.com ssh-rsa" + " AAAAB3NzaC1yc2EAAAADAQABAAABgQCj7ndNxQowgcQnjshcLrqPEiiphnt+VTTvDP6mHBL9j1aNUkY4Ue1gvwnGLVlOhGeYrnZaMgRK6+PKCUXaDbC7qtbW8gIkhL7aGCsOr/C56SJMy/BCZfxd1nWzAOxSDPgVsmerOBYfNqltV9/hWCqBywINIR+5dIg6JTJ72pcEpEjcYgXkE2YEFXV1JHnsKgbLWNlhScqb2UmyRkQyytRLtL+38TGxkxCflmO+5Z8CSSNY7GidjMIZ7Q4zMjA2n1nGrlTDkzwDCsw+wqFPGQA179cnfGWOWRVruj16z6XyvxvjJwbz0wQZ75XK5tKSb7FNyeIEs4TT4jk+S4dhPeAUC5y+bDYirYgM4GC7uEnztnZyaVWQ7B381AK4Qdrwt51ZqExKbQpTUNn+EjqoTwvqNj4kqx5QUCI0ThS/YkOxJCXmPUWZbhjpCg56i+2aB6CmK2JGhn57K5mj0MNdBXA4/WnwH6XoPWJzK5Nyu2zB3nAZp+S5hpQs+p1vN1/wsjk=" + ), ) -CONST_GITHUB_META_URL: Final[str] = "https://api.github.com/meta" # ── Issue Closure From Merged Pull Requests ────────────────────────────────── # GitHub's closing keywords. A pull request body using any of these links the issue, but diff --git a/src/devops_cli/crypto/host_keys.py b/src/devops_cli/crypto/host_keys.py deleted file mode 100644 index 1705730498..0000000000 --- a/src/devops_cli/crypto/host_keys.py +++ /dev/null @@ -1,163 +0,0 @@ -"""SSH host key parsing, fingerprinting, and verification against pinned values. - -`ssh-keyscan` reports whatever key the network hands back. It performs no verification -- -that is the caller's job, and it was not being done: a scanned key was appended to -`known_hosts` unconditionally, so anyone able to intercept the first connection to a host -had their key pinned permanently and silently. - -This module supplies the missing half. It computes the SHA256 fingerprint OpenSSH displays -and compares it against fingerprints published by the host's operator over a channel that -is already authenticated, so trust is established by TLS PKI rather than by assuming the -first answer received is honest. -""" - -from __future__ import annotations - -import base64 -import hashlib -import hmac -import logging -from dataclasses import dataclass - -from devops_cli.config.constants import ( - CONST_GITHUB_HOST, - CONST_GITHUB_HOST_KEY_FINGERPRINTS, - CONST_SSH_FINGERPRINT_PREFIX, - CONST_SSH_HOST_KEY_TYPES, -) - -logger = logging.getLogger(__name__) - - -class HostKeyVerificationError(ValueError): - """Raised when a host key cannot be verified against its published fingerprints.""" - - -@dataclass(frozen=True) -class HostKey: - """One SSH host key as advertised by a server.""" - - hostname: str - key_type: str - key_data: str - comment: str = "" - - @property - def fingerprint(self) -> str: - """The SHA256 fingerprint in the form OpenSSH prints. - - OpenSSH renders it as unpadded standard base64 of the SHA256 digest of the raw key - blob. Padding or hex would not compare equal to what a user reads from the - publisher's documentation, which is the entire point of showing it. - """ - digest = hashlib.sha256(base64.b64decode(self.key_data, validate=True)).digest() - encoded = base64.b64encode(digest).decode("ascii").rstrip("=") - return f"{CONST_SSH_FINGERPRINT_PREFIX}{encoded}" - - def to_known_hosts_line(self) -> str: - """Render this key as a `known_hosts` entry.""" - line = f"{self.hostname} {self.key_type} {self.key_data}" - return f"{line} {self.comment}".rstrip() - - -def parse_host_key_line(line: str) -> HostKey | None: - """Parse one line of `ssh-keyscan` output, returning ``None`` if unusable. - - The key material is base64-decoded during parsing rather than trusted as a string: a - line that is not decodable is not a key, and accepting it would write an unusable entry - into `known_hosts` that silently breaks every later connection to that host. - """ - stripped = line.strip() - if not stripped or stripped.startswith("#"): - return None - - fields = stripped.split() - if len(fields) < 3: - return None - - hostname, key_type, key_data = fields[0], fields[1], fields[2] - if key_type not in CONST_SSH_HOST_KEY_TYPES: - logger.debug("Ignoring unsupported host key type '%s'.", key_type) - return None - - try: - base64.b64decode(key_data, validate=True) - except ValueError: - logger.debug("Ignoring host key with undecodable key material.") - return None - - return HostKey( - hostname=hostname, - key_type=key_type, - key_data=key_data, - comment=" ".join(fields[3:]), - ) - - -def parse_host_keys(output: str) -> list[HostKey]: - """Parse the full output of `ssh-keyscan` into host keys.""" - parsed = (parse_host_key_line(line) for line in output.splitlines()) - return [key for key in parsed if key is not None] - - -def published_fingerprints(hostname: str) -> frozenset[str]: - """Return the fingerprints published for a host, empty if none are pinned.""" - return CONST_GITHUB_HOST_KEY_FINGERPRINTS if hostname == CONST_GITHUB_HOST else frozenset() - - -def is_pinned_host(hostname: str) -> bool: - """Report whether this host's keys can be verified against published fingerprints.""" - return bool(published_fingerprints(hostname)) - - -def verify_fingerprint(key: HostKey, expected: frozenset[str]) -> bool: - """Report whether a key's fingerprint is among the expected set. - - Compared with a constant-time primitive. The comparison is not secret, but the habit of - short-circuiting on the first differing character is one worth not forming in a - verification path. - """ - actual = key.fingerprint - return any(hmac.compare_digest(actual, candidate) for candidate in expected) - - -def select_verified_key(keys: list[HostKey], hostname: str) -> HostKey: - """Return the first scanned key whose fingerprint matches what the host publishes. - - Raises when no key matches. Failing closed is the point: the alternative is the previous - behaviour, where an unverifiable key was pinned anyway and the check may as well not - have existed. A legitimate key rotation surfaces here as a refusal the operator can - resolve deliberately, rather than as a silent acceptance they never see. - """ - expected = published_fingerprints(hostname) - if not expected: - raise HostKeyVerificationError( - f"No published fingerprints are pinned for '{hostname}', so its host key " - f"cannot be verified automatically." - ) - if not keys: - raise HostKeyVerificationError(f"No usable host key was returned for '{hostname}'.") - - for key in keys: - if verify_fingerprint(key, expected): - return key - - offered = ", ".join(sorted({key.fingerprint for key in keys})) or "none" - raise HostKeyVerificationError( - f"Host key for '{hostname}' does not match any published fingerprint. " - f"Offered: {offered}. This is expected after a legitimate key rotation, and is " - f"also what an interception attempt looks like: verify against the operator's " - f"published fingerprints before trusting it." - ) - - -__all__ = [ - "HostKey", - "HostKeyVerificationError", - "is_pinned_host", - "parse_host_key_line", - "parse_host_keys", - "published_fingerprints", - "select_verified_key", - "verify_fingerprint", -] diff --git a/src/devops_cli/crypto/known_hosts.py b/src/devops_cli/crypto/known_hosts.py deleted file mode 100644 index 197d5d4e12..0000000000 --- a/src/devops_cli/crypto/known_hosts.py +++ /dev/null @@ -1,272 +0,0 @@ -"""Pure-Python parsing and matching of OpenSSH `known_hosts` files. - -Membership was previously tested by shelling out to `ssh-keygen -F`, which requires the -OpenSSH client to be installed and costs a process spawn per check. Replacing it with a -naive substring search is not equivalent: OpenSSH supports hashed hostnames, bracketed -`[host]:port` forms, comma-separated alias lists, wildcard patterns, negations, and -`@revoked` markers. A check that missed any of those would either fail to find a host that -is present, and re-add it, or — in the case of `@revoked` — report a key as trusted that -has been explicitly withdrawn. - -Reference: sshd(8), "SSH_KNOWN_HOSTS FILE FORMAT". -""" - -from __future__ import annotations - -import base64 -import hashlib -import hmac -import logging -import os -import re -from dataclasses import dataclass -from functools import lru_cache -from pathlib import Path - -from devops_cli.config.constants import ( - CONST_KNOWN_HOSTS_HASH_PREFIX, - CONST_KNOWN_HOSTS_MARKER_CERT_AUTHORITY, - CONST_KNOWN_HOSTS_MARKER_REVOKED, - CONST_PERM_PRIVATE_KEY, -) - -logger = logging.getLogger(__name__) - - -@dataclass(frozen=True) -class KnownHostEntry: - """One parsed line of a `known_hosts` file.""" - - patterns: tuple[str, ...] - key_type: str - key_data: str - marker: str | None = None - comment: str = "" - hashed_salt: str = "" - hashed_digest: str = "" - line_number: int = 0 - - @property - def is_revoked(self) -> bool: - """Whether this line withdraws trust from the key rather than granting it.""" - return self.marker == CONST_KNOWN_HOSTS_MARKER_REVOKED - - @property - def is_cert_authority(self) -> bool: - """Whether this line delegates trust to a certificate authority key.""" - return self.marker == CONST_KNOWN_HOSTS_MARKER_CERT_AUTHORITY - - @property - def is_hashed(self) -> bool: - """Whether the hostname is stored hashed rather than in the clear.""" - return bool(self.hashed_salt and self.hashed_digest) - - def matches(self, hostname: str, port: int | None = None) -> bool: - """Report whether this entry applies to a host. - - A negated pattern anywhere in the list excludes the host outright, which is how - OpenSSH lets a wildcard entry carve out exceptions. - """ - if self.is_hashed: - return self._matches_hashed(hostname, port) - - candidates = _candidate_names(hostname, port) - matched = False - for pattern in self.patterns: - if pattern.startswith("!"): - if _pattern_matches(pattern[1:], candidates): - return False - elif _pattern_matches(pattern, candidates): - matched = True - return matched - - def _matches_hashed(self, hostname: str, port: int | None) -> bool: - """Compare a hashed entry against the candidate spellings of a host. - - OpenSSH hashes the host with HMAC-SHA1 keyed by a per-entry random salt, so the - only way to test membership is to recompute the digest for each spelling the host - could have been stored under. - """ - try: - salt = base64.b64decode(self.hashed_salt, validate=True) - expected = base64.b64decode(self.hashed_digest, validate=True) - except ValueError: # binascii.Error subclasses ValueError - logger.debug("Malformed hashed known_hosts entry on line %d.", self.line_number) - return False - - for candidate in _candidate_names(hostname, port): - digest = hmac.new(salt, candidate.encode("utf-8"), hashlib.sha1).digest() - if hmac.compare_digest(digest, expected): - return True - return False - - -def _candidate_names(hostname: str, port: int | None) -> tuple[str, ...]: - """Return the spellings a host may be recorded under. - - OpenSSH writes a non-default port as `[host]:port` and the default port bare, so both - have to be considered or a host recorded one way is missed when looked up the other. - """ - host = hostname.strip() - if port is None or port == 22: - return (host,) - return (f"[{host}]:{port}", host) - - -@lru_cache(maxsize=512) -def _compile_pattern(pattern: str) -> re.Pattern[str]: - """Compile an OpenSSH host pattern, which supports only `*` and `?`. - - `fnmatch` cannot be used here: it also honours `[...]` as a character class, and OpenSSH - writes a non-default port as the literal `[host]:port`. Under `fnmatch` that bracket is - a one-character class, so an entry recorded for a non-default port never matches itself - and the host is rescanned and re-added on every connection. - """ - translated = "".join( - ".*" if char == "*" else "." if char == "?" else re.escape(char) for char in pattern - ) - return re.compile(f"{translated}\\Z", re.IGNORECASE) - - -def _pattern_matches(pattern: str, candidates: tuple[str, ...]) -> bool: - """Match a single `known_hosts` pattern against candidate host spellings. - - Matching is case-insensitive because hostnames are; treating `GitHub.com` and - `github.com` as different hosts would split one host across two entries. - """ - compiled = _compile_pattern(pattern) - return any(compiled.match(candidate) is not None for candidate in candidates) - - -def parse_line(line: str, line_number: int = 0) -> KnownHostEntry | None: - """Parse one `known_hosts` line, returning ``None`` for blanks and comments.""" - stripped = line.strip() - if not stripped or stripped.startswith("#"): - return None - - fields = stripped.split() - marker: str | None = None - if fields and fields[0].startswith("@"): - marker = fields[0] - fields = fields[1:] - - # A usable line needs at least a host field, a key type and the key itself. - if len(fields) < 3: - logger.debug("Skipping malformed known_hosts line %d.", line_number) - return None - - host_field, key_type, key_data = fields[0], fields[1], fields[2] - comment = " ".join(fields[3:]) - - salt, digest = "", "" - patterns: tuple[str, ...] = () - if host_field.startswith(CONST_KNOWN_HOSTS_HASH_PREFIX): - parts = host_field.split("|") - # Format is |1||, which splits into ['', '1', salt, digest]. - if len(parts) != 4: - logger.debug("Skipping malformed hashed host on line %d.", line_number) - return None - salt, digest = parts[2], parts[3] - else: - patterns = tuple(part for part in host_field.split(",") if part) - - return KnownHostEntry( - patterns=patterns, - key_type=key_type, - key_data=key_data, - marker=marker, - comment=comment, - hashed_salt=salt, - hashed_digest=digest, - line_number=line_number, - ) - - -def parse_known_hosts(path: Path) -> list[KnownHostEntry]: - """Parse a `known_hosts` file, skipping lines that cannot be read. - - A single malformed line must not discard the rest of the file: the consequence would be - re-adding hosts that are already trusted, or worse, ignoring a `@revoked` marker - recorded further down. - """ - try: - raw = path.read_text(encoding="utf-8", errors="replace") - except OSError as exc: - logger.debug("Cannot read known_hosts '%s': %s", path, exc) - return [] - - entries: list[KnownHostEntry] = [] - for number, line in enumerate(raw.splitlines(), start=1): - entry = parse_line(line, number) - if entry is not None: - entries.append(entry) - return entries - - -def find_host_entries(path: Path, hostname: str, port: int | None = None) -> list[KnownHostEntry]: - """Return every entry applying to a host, the pure-Python `ssh-keygen -F`.""" - if not path.exists(): - return [] - return [entry for entry in parse_known_hosts(path) if entry.matches(hostname, port)] - - -def has_trusted_host_key(path: Path, hostname: str, port: int | None = None) -> bool: - """Report whether a host already has a usable, non-revoked key on file. - - A host whose only entries are `@revoked` is deliberately *not* trusted. Treating a - revocation as evidence of trust would skip the verification that follows and leave the - withdrawn key in place. - """ - entries = find_host_entries(path, hostname, port) - return any(not entry.is_revoked for entry in entries) - - -def is_key_revoked(path: Path, hostname: str, key_data: str) -> bool: - """Report whether a specific key has been revoked for a host.""" - return any( - entry.is_revoked and entry.key_data == key_data - for entry in find_host_entries(path, hostname) - ) - - -def format_entry(hostname: str, key_type: str, key_data: str, comment: str = "") -> str: - """Render a `known_hosts` line.""" - line = f"{hostname} {key_type} {key_data}" - return f"{line} {comment}".rstrip() - - -def append_entry(path: Path, entry_line: str) -> None: - """Append a line to `known_hosts`, preserving line integrity and file permissions. - - A file not ending in a newline would otherwise have the new entry concatenated onto the - last one, corrupting both. - """ - cleaned = entry_line.strip() - if not cleaned: - return - try: - path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) - needs_newline = False - if path.is_file() and path.stat().st_size > 0: - with path.open("rb") as handle: - handle.seek(-1, os.SEEK_END) - needs_newline = handle.read(1) != b"\n" - with path.open("a", encoding="utf-8") as handle: - if needs_newline: - handle.write("\n") - handle.write(f"{cleaned}\n") - path.chmod(CONST_PERM_PRIVATE_KEY) - except OSError as exc: - logger.debug("Failed updating known_hosts '%s': %s", path, exc) - - -__all__ = [ - "KnownHostEntry", - "append_entry", - "find_host_entries", - "format_entry", - "has_trusted_host_key", - "is_key_revoked", - "parse_known_hosts", - "parse_line", -] diff --git a/src/devops_cli/git/operations.py b/src/devops_cli/git/operations.py index 07b305dad7..91fde41c02 100755 --- a/src/devops_cli/git/operations.py +++ b/src/devops_cli/git/operations.py @@ -9,6 +9,7 @@ from __future__ import annotations +import functools import logging from collections.abc import Generator from datetime import datetime @@ -25,24 +26,17 @@ CONST_GITHUB_HOST, CONST_GITHUB_HTTP_PREFIX, CONST_GITHUB_HTTPS_PREFIX, + CONST_GITHUB_KNOWN_HOSTS_LINES, CONST_GITHUB_SSH_PREFIX, CONST_GITHUB_SSH_URL_PREFIX, CONST_MAX_ERROR_DETAIL_LENGTH, CONST_PERM_DIR, + CONST_PERM_PRIVATE_KEY, CONST_SAFE_GIT_REF_PATTERN, CONST_URL_SCHEME_HTTP, CONST_URL_SCHEME_HTTPS, ) -from devops_cli.config.defaults import DEFAULT_SUBPROCESS_TIMEOUT_SECONDS from devops_cli.core.process import run_subprocess -from devops_cli.crypto.host_keys import ( - HostKey, - HostKeyVerificationError, - is_pinned_host, - parse_host_keys, - select_verified_key, -) -from devops_cli.crypto.known_hosts import append_entry, format_entry, has_trusted_host_key from devops_cli.exceptions import ( BranchAlreadyExistsError, GitOperationError, @@ -80,96 +74,44 @@ def iter_workspace_repos(root: Path) -> Generator[Path]: yield repo_dir -def _is_host_in_known_hosts(hostname: str, known_hosts: Path) -> bool: - """Check whether *hostname* already has a trusted key on file. - - Parsed in-process rather than through `ssh-keygen -F`: that required the OpenSSH client - to be installed and cost a process spawn per check. A key carrying an `@revoked` marker - does not count as trusted, so a withdrawn key is re-verified rather than relied upon. - """ - return has_trusted_host_key(known_hosts, hostname) - - -def _scan_host_key(hostname: str) -> str | None: - """Scan the ed25519 host key for *hostname* via ssh-keyscan.""" - result = run_subprocess( - ["ssh-keyscan", "-t", "ed25519", hostname], - capture_output=True, - text=True, - check=False, - quiet=True, - timeout=DEFAULT_SUBPROCESS_TIMEOUT_SECONDS, - ) - if result.returncode != 0 or not result.stdout.strip() or hostname not in result.stdout: - logger.debug( - "Failed scanning SSH host key for %s (exit code %s)", hostname, result.returncode - ) - return None - return result.stdout - - -def _append_known_host_entry(known_hosts: Path, entry: str) -> None: - """Safely append a host key entry to known_hosts with secure file permissions.""" - append_entry(known_hosts, entry) +def _read_existing_lines(path: Path) -> tuple[set[str], bool]: + """Read existing lines and check whether trailing newline is missing.""" + if not path.is_file(): + return set(), False + content = path.read_text(encoding="utf-8", errors="replace") + needs_newline = bool(content and not content.endswith("\n")) + return set(content.splitlines()), needs_newline -def _verified_host_key(hostname: str, scan_output: str) -> HostKey: - """Select the scanned key whose fingerprint matches what the host's operator publishes. +@functools.cache +def _ensure_known_host(known_hosts: Path | None = None) -> None: + """Ensure GitHub's published host keys are present in known_hosts. - Raises :class:`GitOperationError` when none does. `ssh-keyscan` reports whatever the - network returns and verifies nothing, so without this step an intercepted first - connection pins the interceptor's key permanently and silently. + Compares lines verbatim with pathlib/os only, appending any missing keys. + Runs once per process via caching. An unwritable directory logs a warning + and allows execution to continue. """ + path = known_hosts or (Path.home() / ".ssh" / "known_hosts") try: - return select_verified_key(parse_host_keys(scan_output), hostname) - except HostKeyVerificationError as exc: - raise GitOperationError(str(exc)) from exc - - -def _ensure_known_host( - hostname: str = CONST_GITHUB_HOST, - *, - allow_unverified: bool = False, - known_hosts: Path | None = None, -) -> None: - """Add *hostname* to ~/.ssh/known_hosts, verifying the key before trusting it. - - Verification fails closed. A key that cannot be checked against published fingerprints - is not written, because accepting it anyway is indistinguishable from having no check: - that was the previous behaviour, and it meant anyone able to intercept the first - connection had their key trusted for every clone afterwards. - - `allow_unverified` restores trust-on-first-use for hosts that publish no fingerprints, - and is refused for hosts that do -- there, an unverifiable key is a signal, not a gap. - """ - known_hosts_file = known_hosts or (Path.home() / ".ssh" / "known_hosts") - known_hosts_file.parent.mkdir(mode=CONST_PERM_DIR, parents=True, exist_ok=True) - if _is_host_in_known_hosts(hostname, known_hosts_file): - return - - scan_output = _scan_host_key(hostname) - if not scan_output: - return + path.parent.mkdir(mode=CONST_PERM_DIR, parents=True, exist_ok=True) + try: + path.parent.chmod(CONST_PERM_DIR) + except OSError: + pass - if allow_unverified and not is_pinned_host(hostname): - keys = parse_host_keys(scan_output) - if not keys: + existing_lines, needs_newline = _read_existing_lines(path) + missing = [line for line in CONST_GITHUB_KNOWN_HOSTS_LINES if line not in existing_lines] + if not missing: return - logger.warning( - "Trusting unverified host key for '%s' (%s); no published fingerprints are " - "pinned for this host.", - hostname, - keys[0].fingerprint, - ) - _append_known_host_entry( - known_hosts_file, format_entry(hostname, keys[0].key_type, keys[0].key_data) - ) - return - key = _verified_host_key(hostname, scan_output) - # Written under the hostname that was requested, not the one the scan claimed, so a - # response naming a different host cannot pin a key under that name. - _append_known_host_entry(known_hosts_file, format_entry(hostname, key.key_type, key.key_data)) + with path.open("a", encoding="utf-8") as handle: + if needs_newline: + handle.write("\n") + for line in missing: + handle.write(f"{line}\n") + path.chmod(CONST_PERM_PRIVATE_KEY) + except OSError as exc: + logger.warning("Could not update known_hosts '%s': %s", path, exc) def _validate_clone_dest(dest: Path) -> None: @@ -190,18 +132,23 @@ def _validate_clone_dest(dest: Path) -> None: def _prepare_clone_url(url: str) -> str: - """Normalize clone url and ensure host key is known for SSH clones.""" - normalized_url = _normalize_clone_url(url) - if normalized_url.startswith((CONST_GITHUB_SSH_PREFIX, CONST_GITHUB_SSH_URL_PREFIX)): - _ensure_known_host() - return normalized_url + """Normalize clone url and ensure GitHub host keys are known.""" + _ensure_known_host() + return _normalize_clone_url(url) def clone_repo(url: str, dest: Path) -> None: """Clone a repository to *dest*.""" _validate_clone_dest(dest) normalized_url = _prepare_clone_url(url) - gitlib.Repo.clone_from(normalized_url, str(dest)) + try: + gitlib.Repo.clone_from(normalized_url, str(dest)) + except gitlib.GitCommandError as exc: + from devops_cli.security.sanitizer import mask_secrets + + stderr = exc.stderr if isinstance(exc.stderr, str) else "" + msg = mask_secrets(stderr.strip() or str(exc)) + raise GitOperationError(msg) from exc def fetch_all(repo_dir: Path) -> None: diff --git a/tests/test_git_operations.py b/tests/test_git_operations.py index ce558367b5..11623650c0 100644 --- a/tests/test_git_operations.py +++ b/tests/test_git_operations.py @@ -75,46 +75,41 @@ def test_iter_workspace_repos(tmp_path: Path) -> None: assert discovered == [repo_1] -GITHUB_ED25519_KEY = "AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl" - - def test_ensure_known_host(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """Verify _ensure_known_host checks membership and writes only verified host keys.""" + """Verify _ensure_known_host writes GitHub's pinned lines and sets permissions.""" + from devops_cli.config.constants import CONST_GITHUB_KNOWN_HOSTS_LINES + + _ensure_known_host.cache_clear() fake_home = tmp_path / "home" monkeypatch.setattr("pathlib.Path.home", lambda: fake_home) - # 1. Host already known in known_hosts: no scan is attempted at all. Membership is - # now determined in-process, so ssh-keygen is never spawned for the check either. known_hosts = fake_home / ".ssh" / "known_hosts" - known_hosts.parent.mkdir(parents=True, exist_ok=True) - known_hosts.write_text(f"github.com ssh-ed25519 {GITHUB_ED25519_KEY}\n", encoding="utf-8") - - with patch("devops_cli.git.operations.run_subprocess") as mock_run: - _ensure_known_host("github.com") - mock_run.assert_not_called() - - # 2. Host missing from known_hosts -> scan, verify against GitHub's published - # fingerprints, then record it. - known_hosts.write_text("", encoding="utf-8") - with patch("devops_cli.git.operations.run_subprocess") as mock_run: - mock_run.return_value = MagicMock( - returncode=0, stdout=f"github.com ssh-ed25519 {GITHUB_ED25519_KEY}\n" - ) - _ensure_known_host("github.com") + _ensure_known_host() - content = known_hosts.read_text(encoding="utf-8") - assert GITHUB_ED25519_KEY in content + content = known_hosts.read_text(encoding="utf-8") + for line in CONST_GITHUB_KNOWN_HOSTS_LINES: + assert line in content + assert ( + oct(known_hosts.stat().st_mode & 0o777), + oct(known_hosts.parent.stat().st_mode & 0o777), + ) == ("0o600", "0o700") + # A second run adds nothing + _ensure_known_host.cache_clear() + _ensure_known_host() + assert known_hosts.read_text(encoding="utf-8") == content -def test_clone_repo_ensures_github_known_host_for_ssh_urls(tmp_path: Path) -> None: + +def test_clone_repo_ensures_github_known_host_for_all_urls(tmp_path: Path) -> None: + """Verify clone_repo ensures host keys are known for all clone URLs.""" with ( patch("devops_cli.git.operations._ensure_known_host") as mock_known_host, patch("devops_cli.git.operations.gitlib.Repo.clone_from") as mock_clone_from, ): clone_repo("git@github.com:example/repo.git", tmp_path / "repo") + clone_repo("https://github.com/example/repo2.git", tmp_path / "repo2") - mock_known_host.assert_called_once_with() - mock_clone_from.assert_called_once() + assert (mock_known_host.call_count, mock_clone_from.call_count) == (2, 2) def test_fetch_all(tmp_path: Path) -> None: @@ -305,76 +300,13 @@ def test_git_operations_edge_cases(tmp_path: Path) -> None: mock_repo_cls.return_value = mock_repo assert delete_merged_branches(tmp_path) == [] - # 3. _ensure_known_host when keyscan fails - with patch("devops_cli.git.operations.run_subprocess") as mock_run: - mock_run.side_effect = [MagicMock(returncode=1), MagicMock(returncode=1, stdout="")] - _ensure_known_host("example.com", known_hosts=tmp_path / ".ssh" / "known_hosts") - - -def test_append_known_host_entry(tmp_path: Path) -> None: - """Verify _append_known_host_entry safely writes host keys and sets permissions.""" - from devops_cli.git.operations import _append_known_host_entry - - known_hosts = tmp_path / "known_hosts" - _append_known_host_entry(known_hosts, "example.com ssh-ed25519 AAAAC3NzaC1\n") - assert "example.com" in known_hosts.read_text(encoding="utf-8") - assert oct(known_hosts.stat().st_mode & 0o777) == "0o600" - - # Append second entry when existing content already ends with newline (prevent blank lines) - _append_known_host_entry(known_hosts, "example.com key2\n") - content = known_hosts.read_text(encoding="utf-8") - assert content == "example.com ssh-ed25519 AAAAC3NzaC1\nexample.com key2\n" - assert "\n\n" not in content - - # Append third entry when existing content lacks trailing newline - known_hosts.write_text("example.com key1", encoding="utf-8") - _append_known_host_entry(known_hosts, "example.com key3\n") - content = known_hosts.read_text(encoding="utf-8") - assert content == "example.com key1\nexample.com key3\n" - - # Empty or whitespace entry should be a no-op - _append_known_host_entry(known_hosts, " \n") - assert known_hosts.read_text(encoding="utf-8") == content - # Gracefully handle OS error when directory is read-only - invalid_path = tmp_path / "nonexistent_dir" / "known_hosts" - _append_known_host_entry(invalid_path, "example.com key4\n") - - -def test_host_key_and_clone_prep_helpers(tmp_path: Path) -> None: - """Verify _is_host_in_known_hosts, _scan_host_key, _validate_clone_dest, and _prepare_clone_url.""" +def test_validate_clone_dest_and_prepare_clone_url(tmp_path: Path) -> None: + """Verify _validate_clone_dest traversal checks and _prepare_clone_url host key seeding.""" from devops_cli.exceptions import GitOperationError - from devops_cli.git.operations import ( - _is_host_in_known_hosts, - _prepare_clone_url, - _scan_host_key, - _validate_clone_dest, - ) - - # 1. _is_host_in_known_hosts when file missing - missing_file = tmp_path / "nonexistent_known_hosts" - assert not _is_host_in_known_hosts("github.com", missing_file) - - # 2. _is_host_in_known_hosts reads the file directly rather than spawning ssh-keygen - existing_file = tmp_path / "known_hosts" - existing_file.write_text("github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5\n", encoding="utf-8") - assert _is_host_in_known_hosts("github.com", existing_file) - assert not _is_host_in_known_hosts("gitlab.example.com", existing_file) - - # 3. _scan_host_key successes and failures - with patch("devops_cli.git.operations.run_subprocess") as mock_run: - mock_run.return_value = MagicMock(returncode=0, stdout="github.com ssh-ed25519 AAAAC3N\n") - assert _scan_host_key("github.com") == "github.com ssh-ed25519 AAAAC3N\n" - - mock_run.return_value = MagicMock(returncode=1, stdout="") - assert _scan_host_key("github.com") is None - - mock_run.return_value = MagicMock( - returncode=0, stdout="otherhost.com ssh-ed25519 AAAAC3N\n" - ) - assert _scan_host_key("github.com") is None + from devops_cli.git.operations import _prepare_clone_url, _validate_clone_dest - # 4. _validate_clone_dest path traversal rejection + # Path traversal rejection with pytest.raises(GitOperationError, match="Path traversal detected"): _validate_clone_dest(Path("../unsafe_path")) @@ -397,16 +329,14 @@ def test_host_key_and_clone_prep_helpers(tmp_path: Path) -> None: with pytest.raises(GitOperationError, match="forbidden system path"): _validate_clone_dest(Path("/etc/git-dest")) - # 5. _prepare_clone_url + # _prepare_clone_url calls _ensure_known_host for both SSH and HTTPS with patch("devops_cli.git.operations._ensure_known_host") as mock_ensure: url_ssh = _prepare_clone_url("git@github.com:org/repo.git") - assert url_ssh == "git@github.com:org/repo.git" - mock_ensure.assert_called_once() + assert (url_ssh, mock_ensure.call_count) == ("git@github.com:org/repo.git", 1) with patch("devops_cli.git.operations._ensure_known_host") as mock_ensure: url_https = _prepare_clone_url("https://github.com/org/repo.git") - assert url_https == "https://github.com/org/repo.git" - mock_ensure.assert_not_called() + assert (url_https, mock_ensure.call_count) == ("https://github.com/org/repo.git", 1) def test_read_file_at_revision_reads_the_base_revision(symbol_removal_repo: Path) -> None: diff --git a/tests/test_ssh_host_keys.py b/tests/test_ssh_host_keys.py index 6dce3ad7e5..16a53dc79f 100644 --- a/tests/test_ssh_host_keys.py +++ b/tests/test_ssh_host_keys.py @@ -1,614 +1,219 @@ -"""Test suite for known_hosts parsing and SSH host key verification.""" +"""Test suite for GitHub SSH known_hosts pinning, OpenSSH trust, and clone error wrapping.""" from __future__ import annotations import base64 -import hashlib -import hmac +import stat from pathlib import Path -from typing import Any -from unittest.mock import MagicMock, patch +from unittest.mock import patch +import git as gitlib import pytest +from cryptography.hazmat.primitives import hashes, serialization +from typer.testing import CliRunner -from devops_cli.config.constants import CONST_GITHUB_HOST_KEY_FINGERPRINTS -from devops_cli.crypto.host_keys import ( - HostKey, - HostKeyVerificationError, - is_pinned_host, - parse_host_key_line, - parse_host_keys, - published_fingerprints, - select_verified_key, - verify_fingerprint, -) -from devops_cli.crypto.known_hosts import ( - append_entry, - find_host_entries, - format_entry, - has_trusted_host_key, - is_key_revoked, - parse_known_hosts, - parse_line, -) +from devops_cli.commands.repos import app as repos_app +from devops_cli.config.constants import CONST_GITHUB_KNOWN_HOSTS_LINES from devops_cli.exceptions import GitOperationError -from devops_cli.git.operations import _ensure_known_host, _is_host_in_known_hosts - -# GitHub's published host keys, as served by https://api.github.com/meta over TLS. -GITHUB_ED25519 = "AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl" -GITHUB_ED25519_FINGERPRINT = "SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU" -GITHUB_ECDSA = ( - "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEmKSENjQEezOmxkZMy7opKgwFB9" - "nkt5YRrYMjNuG5N87uRgg6CLrbo5wAdT/y6v0mKV0U2w0WZ2YB/++Tpockg=" -) -# A syntactically valid key that is not GitHub's: what an interception would look like. -HOSTILE_ED25519 = "AAAAC3NzaC1lZDI1NTE5AAAAIBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" - +from devops_cli.git.operations import _ensure_known_host, clone_repo -def hashed_host(hostname: str, salt: bytes = b"0123456789abcdef0123") -> str: - """Build the hashed host field OpenSSH writes with `HashKnownHosts yes`.""" - digest = hmac.new(salt, hostname.encode(), hashlib.sha1).digest() - return f"|1|{base64.b64encode(salt).decode()}|{base64.b64encode(digest).decode()}" +runner = CliRunner() - -def write_known_hosts(path: Path, *lines: str) -> Path: - """Write a known_hosts file from the given lines.""" - path.write_text("\n".join(lines) + "\n", encoding="utf-8") - return path +# Published fingerprints from https://api.github.com/meta (.ssh_key_fingerprints) +# and https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/githubs-ssh-key-fingerprints +_PUBLISHED_FINGERPRINTS: dict[str, str] = { + "ssh-ed25519": "+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU", + "ecdsa-sha2-nistp256": "p2QAMXNIC1TJYWeIOttrVc98/R1BUFWu3/LiyKgUfQM", + "ssh-rsa": "uNiVztksCsDhcc0u9e8BujQXVUpKZIDTMczCvj3tD2s", +} # ============================================================================= -# known_hosts Parsing +# 1. Structure & Fingerprint Tests # ============================================================================= -def test_a_plain_entry_is_parsed_into_its_fields() -> None: - """The ordinary case: one host, one key type, one key.""" - entry = parse_line(f"github.com ssh-ed25519 {GITHUB_ED25519} comment here") - assert entry is not None - assert (entry.patterns, entry.key_type, entry.key_data, entry.comment) == ( - ("github.com",), - "ssh-ed25519", - GITHUB_ED25519, - "comment here", - ) - - -@pytest.mark.parametrize( - ("description", "line"), - [ - ("blank", ""), - ("whitespace", " "), - ("comment", "# a comment"), - ("too few fields", "github.com ssh-ed25519"), - ("host only", "github.com"), - ("malformed hash", "|1|onlysalt ssh-ed25519 AAAA"), - ], -) -def test_unusable_lines_are_skipped(description: str, line: str) -> None: - """A line that is not an entry yields nothing rather than a half-built one.""" - assert parse_line(line) is None, description - - -def test_a_comma_separated_alias_list_matches_every_alias() -> None: - """OpenSSH records a host and its addresses on one line.""" - entry = parse_line(f"github.com,140.82.121.4 ssh-ed25519 {GITHUB_ED25519}") - assert entry is not None - assert (entry.matches("github.com"), entry.matches("140.82.121.4")) == (True, True) - - -def test_a_wildcard_pattern_matches_subdomains() -> None: - """Wildcards are why a substring search is not equivalent to ssh-keygen -F.""" - entry = parse_line(f"*.example.com ssh-ed25519 {GITHUB_ED25519}") - assert entry is not None - assert (entry.matches("git.example.com"), entry.matches("example.com")) == (True, False) - - -def test_a_negated_pattern_excludes_a_host_from_a_wildcard() -> None: - """A negation anywhere in the list excludes the host outright.""" - entry = parse_line(f"*.example.com,!secret.example.com ssh-ed25519 {GITHUB_ED25519}") - assert entry is not None - assert (entry.matches("git.example.com"), entry.matches("secret.example.com")) == ( - True, - False, - ) - - -def test_host_matching_is_case_insensitive() -> None: - """Hostnames are case-insensitive; treating them otherwise splits one host in two.""" - entry = parse_line(f"GitHub.com ssh-ed25519 {GITHUB_ED25519}") - assert entry is not None - assert entry.matches("github.com") is True - - -def test_a_non_default_port_is_matched_in_its_bracketed_form() -> None: - """OpenSSH records a non-default port as [host]:port.""" - entry = parse_line(f"[git.example.com]:2222 ssh-ed25519 {GITHUB_ED25519}") - assert entry is not None - assert (entry.matches("git.example.com", 2222), entry.matches("git.example.com")) == ( - True, - False, - ) - - -def test_the_default_port_is_matched_bare() -> None: - """Port 22 is written without brackets, so both spellings must resolve.""" - entry = parse_line(f"git.example.com ssh-ed25519 {GITHUB_ED25519}") - assert entry is not None - assert entry.matches("git.example.com", 22) is True - - -def test_a_hashed_hostname_is_matched_by_recomputing_its_digest() -> None: - """With HashKnownHosts enabled the hostname is not present in the file at all. - - A substring search finds nothing, so the host is scanned and re-added on every - operation -- and never verified against what is already recorded. - """ - entry = parse_line(f"{hashed_host('github.com')} ssh-ed25519 {GITHUB_ED25519}") - assert entry is not None - assert (entry.is_hashed, entry.matches("github.com"), entry.matches("gitlab.com")) == ( - True, - True, - False, - ) +def test_github_known_hosts_lines_structure() -> None: + """Each pinned line has host github.com and round-trips through cryptography.""" + assert len(CONST_GITHUB_KNOWN_HOSTS_LINES) == 3 + for line in CONST_GITHUB_KNOWN_HOSTS_LINES: + host, sep, rest = line.partition(" ") + assert (host, sep) == ("github.com", " ") + key = serialization.load_ssh_public_key(rest.encode("ascii")) + reencoded = key.public_bytes( + serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH + ).decode("ascii") + assert reencoded == rest -def test_a_hashed_entry_with_undecodable_material_matches_nothing() -> None: - """A corrupt hash must not raise on every lookup.""" - entry = parse_line(f"|1|!!!notbase64!!!|alsobad ssh-ed25519 {GITHUB_ED25519}") - assert entry is not None - assert entry.matches("github.com") is False - - -def test_a_revoked_marker_is_recognised() -> None: - """A revocation withdraws trust rather than granting it.""" - entry = parse_line(f"@revoked github.com ssh-ed25519 {HOSTILE_ED25519}") - assert entry is not None - assert (entry.is_revoked, entry.is_cert_authority) == (True, False) - - -def test_a_cert_authority_marker_is_recognised() -> None: - """A CA line delegates trust and is not itself a host key.""" - entry = parse_line(f"@cert-authority *.example.com ssh-ed25519 {GITHUB_ED25519}") - assert entry is not None - assert entry.is_cert_authority is True - - -def test_a_file_is_parsed_line_by_line_with_numbers(tmp_path: Path) -> None: - """Line numbers make a malformed entry findable.""" - path = write_known_hosts( - tmp_path / "known_hosts", - "# comment", - f"github.com ssh-ed25519 {GITHUB_ED25519}", - "", - f"gitlab.com ssh-ed25519 {GITHUB_ECDSA}", - ) - entries = parse_known_hosts(path) - assert [(entry.patterns[0], entry.line_number) for entry in entries] == [ - ("github.com", 2), - ("gitlab.com", 4), - ] - - -def test_one_malformed_line_does_not_discard_the_file(tmp_path: Path) -> None: - """Losing the rest of the file would drop a @revoked marker recorded further down.""" - path = write_known_hosts( - tmp_path / "known_hosts", - "garbage", - f"github.com ssh-ed25519 {GITHUB_ED25519}", - ) - assert len(parse_known_hosts(path)) == 1 - - -def test_an_unreadable_file_yields_no_entries(tmp_path: Path) -> None: - """A missing or unreadable file is not an error at this layer.""" - assert parse_known_hosts(tmp_path / "absent") == [] +def test_github_known_hosts_lines_fingerprints() -> None: + """Each pinned key reproduces GitHub's published SHA256 fingerprint.""" + for line in CONST_GITHUB_KNOWN_HOSTS_LINES: + _, _, rest = line.partition(" ") + key_type = rest.split()[0] + key = serialization.load_ssh_public_key(rest.encode("ascii")) + raw_fp = serialization.ssh_key_fingerprint(key, hashes.SHA256()) + b64_fp = base64.b64encode(raw_fp).decode("ascii").rstrip("=") + assert (key_type, b64_fp) == (key_type, _PUBLISHED_FINGERPRINTS[key_type]) # ============================================================================= -# Membership +# 2. Writing Pinned Lines to known_hosts # ============================================================================= -def test_a_recorded_host_is_found(tmp_path: Path) -> None: - """The pure-Python replacement for `ssh-keygen -F`.""" - path = write_known_hosts(tmp_path / "kh", f"github.com ssh-ed25519 {GITHUB_ED25519}") - assert has_trusted_host_key(path, "github.com") is True - - -def test_an_unrecorded_host_is_not_found(tmp_path: Path) -> None: - """A host with no entry is not trusted.""" - path = write_known_hosts(tmp_path / "kh", f"github.com ssh-ed25519 {GITHUB_ED25519}") - assert has_trusted_host_key(path, "gitlab.com") is False - - -def test_a_missing_file_means_no_host_is_trusted(tmp_path: Path) -> None: - """A fresh machine has no known_hosts at all.""" - assert has_trusted_host_key(tmp_path / "absent", "github.com") is False - - -def test_a_host_with_only_a_revoked_key_is_not_trusted(tmp_path: Path) -> None: - """Treating a revocation as trust would skip verification and keep the withdrawn key. - - This is the case `ssh-keygen -F` gets right and a substring search gets exactly - backwards: the host *is* mentioned in the file, but not as trusted. - """ - path = write_known_hosts(tmp_path / "kh", f"@revoked github.com ssh-ed25519 {HOSTILE_ED25519}") - assert has_trusted_host_key(path, "github.com") is False - - -def test_a_host_with_a_revoked_and_a_valid_key_is_trusted(tmp_path: Path) -> None: - """One withdrawn key does not invalidate a good one recorded alongside it.""" - path = write_known_hosts( - tmp_path / "kh", - f"@revoked github.com ssh-ed25519 {HOSTILE_ED25519}", - f"github.com ssh-ed25519 {GITHUB_ED25519}", - ) - assert has_trusted_host_key(path, "github.com") is True - - -def test_a_specific_revoked_key_is_identifiable(tmp_path: Path) -> None: - """Revocation applies to a key, not to the host.""" - path = write_known_hosts(tmp_path / "kh", f"@revoked github.com ssh-ed25519 {HOSTILE_ED25519}") - assert ( - is_key_revoked(path, "github.com", HOSTILE_ED25519), - is_key_revoked(path, "github.com", GITHUB_ED25519), - ) == (True, False) - - -def test_every_entry_for_a_host_is_returned(tmp_path: Path) -> None: - """A host commonly has several key types on file.""" - path = write_known_hosts( - tmp_path / "kh", - f"github.com ssh-ed25519 {GITHUB_ED25519}", - f"github.com ecdsa-sha2-nistp256 {GITHUB_ECDSA}", - ) - assert len(find_host_entries(path, "github.com")) == 2 - - -# ============================================================================= -# Writing Entries -# ============================================================================= +def test_ensure_known_host_writes_file_and_dir_modes(tmp_path: Path) -> None: + """Verify lines are written with file mode 0600 and directory mode 0700.""" + _ensure_known_host.cache_clear() + known_hosts = tmp_path / ".ssh" / "known_hosts" + with patch("subprocess.run") as mock_subproc, patch("subprocess.Popen") as mock_popen: + _ensure_known_host(known_hosts) + assert (mock_subproc.called, mock_popen.called) == (False, False) -def test_an_entry_is_appended_with_restrictive_permissions(tmp_path: Path) -> None: - """known_hosts is written into the user's ssh directory.""" - path = tmp_path / "kh" - append_entry(path, format_entry("github.com", "ssh-ed25519", GITHUB_ED25519)) - assert (GITHUB_ED25519 in path.read_text(), oct(path.stat().st_mode & 0o777)) == ( - True, - "0o600", - ) + content = known_hosts.read_text(encoding="utf-8") + for line in CONST_GITHUB_KNOWN_HOSTS_LINES: + assert line in content + file_mode = oct(stat.S_IMODE(known_hosts.stat().st_mode)) + dir_mode = oct(stat.S_IMODE(known_hosts.parent.stat().st_mode)) + assert (file_mode, dir_mode) == ("0o600", "0o700") -def test_appending_to_a_file_without_a_trailing_newline_does_not_corrupt_it( - tmp_path: Path, -) -> None: - """Concatenating onto the previous entry would break both lines.""" - path = tmp_path / "kh" - path.write_text("gitlab.com ssh-ed25519 AAAA", encoding="utf-8") - append_entry(path, "github.com ssh-ed25519 BBBB") - assert path.read_text() == "gitlab.com ssh-ed25519 AAAA\ngithub.com ssh-ed25519 BBBB\n" + # A second run adds nothing + _ensure_known_host.cache_clear() + _ensure_known_host(known_hosts) + assert known_hosts.read_text(encoding="utf-8") == content -def test_appending_does_not_introduce_blank_lines(tmp_path: Path) -> None: - """A file already ending in a newline needs no extra one.""" - path = tmp_path / "kh" - path.write_text("gitlab.com ssh-ed25519 AAAA\n", encoding="utf-8") - append_entry(path, "github.com ssh-ed25519 BBBB") - assert "\n\n" not in path.read_text() +def test_ensure_known_host_preserves_file_without_trailing_newline(tmp_path: Path) -> None: + """A file missing a trailing newline is not corrupted by appending.""" + _ensure_known_host.cache_clear() + known_hosts = tmp_path / ".ssh" / "known_hosts" + known_hosts.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + known_hosts.write_text("example.com ssh-ed25519 AAAApreexisting", encoding="utf-8") + _ensure_known_host(known_hosts) + content = known_hosts.read_text(encoding="utf-8") + assert content.startswith("example.com ssh-ed25519 AAAApreexisting\n") + for line in CONST_GITHUB_KNOWN_HOSTS_LINES: + assert line in content -def test_appending_an_empty_entry_is_a_no_op(tmp_path: Path) -> None: - """A blank line carries no key and must not be written.""" - path = tmp_path / "kh" - path.write_text("existing\n", encoding="utf-8") - append_entry(path, " ") - assert path.read_text() == "existing\n" +def test_ensure_known_host_unwritable_directory_logs_warning(tmp_path: Path) -> None: + """An unwritable directory logs one warning and allows clone to continue.""" + _ensure_known_host.cache_clear() + unwritable = tmp_path / "read_only_ssh" / "known_hosts" -def test_appending_creates_the_ssh_directory(tmp_path: Path) -> None: - """A fresh machine has no ~/.ssh yet.""" - path = tmp_path / "nested" / "kh" - append_entry(path, "github.com ssh-ed25519 AAAA") - assert path.exists() + with patch("pathlib.Path.mkdir", side_effect=PermissionError("Read-only filesystem")): + with patch("devops_cli.git.operations.logger.warning") as mock_warn: + _ensure_known_host(unwritable) + # Second call in same process is cached and logs no additional warning + _ensure_known_host(unwritable) + assert mock_warn.call_count == 1 # ============================================================================= -# Fingerprints +# 3. Regression: Fail-Open Junk Lines Do Not Prevent Pinning # ============================================================================= -def test_a_fingerprint_matches_what_the_host_operator_publishes() -> None: - """Computed independently from the raw key and compared with GitHub's own value. - - If this implementation disagreed with OpenSSH's, every comparison against a published - fingerprint would fail and verification would be useless. - """ - key = HostKey("github.com", "ssh-ed25519", GITHUB_ED25519) - assert key.fingerprint == GITHUB_ED25519_FINGERPRINT - - -def test_a_fingerprint_is_unpadded_base64_as_openssh_prints_it() -> None: - """Padding or hex would not compare equal to what a user reads from documentation.""" - fingerprint = HostKey("h", "ssh-ed25519", GITHUB_ED25519).fingerprint - assert (fingerprint.startswith("SHA256:"), fingerprint.endswith("=")) == (True, False) - - -def test_every_published_github_key_verifies_against_the_pinned_set() -> None: - """The pinned fingerprints must actually match the keys GitHub serves.""" - keys = [ - HostKey("github.com", "ssh-ed25519", GITHUB_ED25519), - HostKey("github.com", "ecdsa-sha2-nistp256", GITHUB_ECDSA), - ] - assert all(verify_fingerprint(key, CONST_GITHUB_HOST_KEY_FINGERPRINTS) for key in keys) - - -def test_a_key_that_is_not_githubs_does_not_verify() -> None: - """The check has to actually reject something.""" - hostile = HostKey("github.com", "ssh-ed25519", HOSTILE_ED25519) - assert verify_fingerprint(hostile, CONST_GITHUB_HOST_KEY_FINGERPRINTS) is False - - -def test_github_is_a_pinned_host_and_an_arbitrary_host_is_not() -> None: - """Only hosts publishing fingerprints can be verified automatically.""" - assert (is_pinned_host("github.com"), is_pinned_host("git.example.com")) == (True, False) +@pytest.mark.parametrize( + "junk_line", + [ + "@cert-authority github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICA", + "@cert-authority * ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICA", + "@foo github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICA", + "github.com ssh-ed25519 AAAA", + "github.com ssh-ed25519 not_valid_base64!!!", + "github.com ssh-dss AAAAB3NzaC1kc3MAAACBA", + "@revoked github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOldRevoked", + "|1|0123456789abcdef0123|abcdefghijklmnopqrstuvwx= ssh-ed25519 AAAAC3NzaC1", + ], +) +def test_junk_known_hosts_lines_do_not_skip_pinning(junk_line: str, tmp_path: Path) -> None: + """Existing junk, marker, or revoked lines are preserved verbatim and pinned lines appended.""" + _ensure_known_host.cache_clear() + known_hosts = tmp_path / ".ssh" / "known_hosts" + known_hosts.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + known_hosts.write_text(f"{junk_line}\n", encoding="utf-8") + _ensure_known_host(known_hosts) -def test_an_unpinned_host_has_no_published_fingerprints() -> None: - """An empty set is what makes verification fail closed for unknown hosts.""" - assert published_fingerprints("git.example.com") == frozenset() + content = known_hosts.read_text(encoding="utf-8") + assert content.startswith(f"{junk_line}\n") + for line in CONST_GITHUB_KNOWN_HOSTS_LINES: + assert line in content # ============================================================================= -# Host Key Parsing +# 4. Every URL Spelling Triggers Pinning # ============================================================================= -def test_a_keyscan_line_is_parsed() -> None: - """The ordinary output of ssh-keyscan.""" - key = parse_host_key_line(f"github.com ssh-ed25519 {GITHUB_ED25519}") - assert key is not None - assert (key.hostname, key.key_type, key.key_data) == ( - "github.com", - "ssh-ed25519", - GITHUB_ED25519, - ) - - @pytest.mark.parametrize( - ("description", "line"), + "url", [ - ("blank", ""), - ("comment banner", "# github.com:22 SSH-2.0-babeld"), - ("too few fields", "github.com ssh-ed25519"), - ("unsupported key type", "github.com ssh-dss AAAAB3NzaC1kc3M="), - ("undecodable key material", "github.com ssh-ed25519 !!!not-base64!!!"), + "git@GitHub.com:org/repo.git", + "ssh://git@github.com:22/org/repo.git", + "ssh://GIT@GITHUB.COM/org/repo.git", + "ssh://github.com/org/repo.git", + "git+ssh://git@github.com/org/repo.git", + "github.com:org/repo", + "org-123@github.com:org/repo.git", + "gh-work:org/repo.git", + "https://github.com/org/repo.git", ], ) -def test_unusable_keyscan_lines_are_rejected(description: str, line: str) -> None: - """An entry that is not a usable key must not reach known_hosts. - - Writing one silently breaks every later connection to that host, which presents as an - unrelated failure long after the cause. - """ - assert parse_host_key_line(line) is None, description - - -def test_keyscan_output_with_banners_yields_only_the_keys() -> None: - """ssh-keyscan interleaves informational comments with the keys.""" - output = ( - "# github.com:22 SSH-2.0-babeld\n" - f"github.com ssh-ed25519 {GITHUB_ED25519}\n" - "# github.com:22 SSH-2.0-babeld\n" - f"github.com ecdsa-sha2-nistp256 {GITHUB_ECDSA}\n" - ) - assert [key.key_type for key in parse_host_keys(output)] == [ - "ssh-ed25519", - "ecdsa-sha2-nistp256", - ] - - -def test_a_host_key_renders_as_a_known_hosts_line() -> None: - """What is verified is what gets written.""" - key = HostKey("github.com", "ssh-ed25519", GITHUB_ED25519) - assert key.to_known_hosts_line() == f"github.com ssh-ed25519 {GITHUB_ED25519}" +def test_clone_repo_pins_known_hosts_for_all_spellings(url: str, tmp_path: Path) -> None: + """The write runs for every URL passed to clone_repo with no URL filtering.""" + with ( + patch("devops_cli.git.operations._ensure_known_host") as mock_ensure, + patch("devops_cli.git.operations.gitlib.Repo.clone_from"), + ): + clone_repo(url, tmp_path / "dest") + assert mock_ensure.call_count == 1 # ============================================================================= -# Verification +# 5. Clone Error Wrapping & Credential Masking # ============================================================================= -def test_the_genuine_key_is_selected_from_a_scan() -> None: - """Verification picks the key that matches a published fingerprint.""" - keys = parse_host_keys( - f"github.com ssh-ed25519 {HOSTILE_ED25519}\ngithub.com ssh-ed25519 {GITHUB_ED25519}\n" +def test_clone_repo_wraps_git_command_error_with_masked_stderr(tmp_path: Path) -> None: + """GitCommandError is wrapped in GitOperationError carrying masked stderr.""" + ssh_err = ( + "Host key for github.com has changed and you have requested strict checking.\n" + "Host key verification failed.\n" + "fatal: Could not read from remote repository 'https://user:secret@example.com/o/r.git'." ) - assert select_verified_key(keys, "github.com").key_data == GITHUB_ED25519 - - -def test_a_scan_returning_only_an_unrecognised_key_is_refused() -> None: - """Failing closed is the point; accepting anyway is the defect this replaces.""" - keys = parse_host_keys(f"github.com ssh-ed25519 {HOSTILE_ED25519}") - with pytest.raises(HostKeyVerificationError, match="does not match any published"): - select_verified_key(keys, "github.com") - - -def test_the_refusal_names_the_fingerprint_that_was_offered() -> None: - """An operator resolving a legitimate rotation needs to see what was presented.""" - keys = parse_host_keys(f"github.com ssh-ed25519 {HOSTILE_ED25519}") - with pytest.raises(HostKeyVerificationError, match="SHA256:"): - select_verified_key(keys, "github.com") - - -def test_a_host_with_no_published_fingerprints_cannot_be_verified() -> None: - """Silently succeeding would make the check meaningless for unknown hosts.""" - keys = parse_host_keys(f"git.example.com ssh-ed25519 {GITHUB_ED25519}") - with pytest.raises(HostKeyVerificationError, match="No published fingerprints"): - select_verified_key(keys, "git.example.com") - - -def test_an_empty_scan_is_refused() -> None: - """No key is not a verified key.""" - with pytest.raises(HostKeyVerificationError, match="No usable host key"): - select_verified_key([], "github.com") - - -# ============================================================================= -# Integration: _ensure_known_host -# ============================================================================= + fake_cmd_err = gitlib.GitCommandError("clone", 128, stderr=ssh_err) + with ( + patch("devops_cli.git.operations._ensure_known_host"), + patch("devops_cli.git.operations.gitlib.Repo.clone_from", side_effect=fake_cmd_err), + ): + with pytest.raises(GitOperationError) as exc_info: + clone_repo("git@github.com:org/repo.git", tmp_path / "dest") -@pytest.fixture -def fake_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: - """Redirect ~/.ssh into a temporary directory.""" - home = tmp_path / "home" - monkeypatch.setattr("pathlib.Path.home", lambda: home) - return home + msg = str(exc_info.value) + assert ( + "Host key for github.com has changed and you have requested strict checking." in msg, + "Host key verification failed." in msg, + "user:secret" not in msg, + ) == (True, True, True) -def _scan_returning(output: str) -> Any: - """Patch the subprocess runner so ssh-keyscan returns the given output.""" - return patch( - "devops_cli.git.operations.run_subprocess", - return_value=MagicMock(returncode=0, stdout=output), +def test_devops_repos_clone_cli_exits_nonzero_with_no_traceback(tmp_path: Path) -> None: + """CLI devops repos clone exits non-zero with clean error and no traceback on failure.""" + fake_cmd_err = gitlib.GitCommandError( + "clone", 128, stderr="Host key verification failed for github.com" ) - -def test_a_genuine_github_key_is_recorded(fake_home: Path) -> None: - """The ordinary path still works.""" - with _scan_returning(f"github.com ssh-ed25519 {GITHUB_ED25519}\n"): - _ensure_known_host("github.com") - assert GITHUB_ED25519 in (fake_home / ".ssh" / "known_hosts").read_text() - - -def test_an_intercepted_key_is_refused_and_nothing_is_written(fake_home: Path) -> None: - """The defect this task fixes. - - Previously the scanned key was appended unconditionally, so anyone able to intercept - the first connection had their key pinned permanently and silently, for every clone - afterwards. - """ - known_hosts = fake_home / ".ssh" / "known_hosts" - with _scan_returning(f"github.com ssh-ed25519 {HOSTILE_ED25519}\n"): - with pytest.raises(GitOperationError, match="does not match any published"): - _ensure_known_host("github.com") - assert known_hosts.exists() is False or known_hosts.read_text().strip() == "" - - -def test_an_already_trusted_host_is_not_rescanned(fake_home: Path) -> None: - """A host on file needs no network round trip at all.""" - known_hosts = fake_home / ".ssh" / "known_hosts" - known_hosts.parent.mkdir(parents=True, exist_ok=True) - write_known_hosts(known_hosts, f"github.com ssh-ed25519 {GITHUB_ED25519}") - with patch("devops_cli.git.operations.run_subprocess") as mock_run: - _ensure_known_host("github.com") - mock_run.assert_not_called() - - -def test_a_revoked_key_on_file_triggers_reverification(fake_home: Path) -> None: - """A withdrawn key must not be mistaken for a trusted one.""" - known_hosts = fake_home / ".ssh" / "known_hosts" - known_hosts.parent.mkdir(parents=True, exist_ok=True) - write_known_hosts(known_hosts, f"@revoked github.com ssh-ed25519 {HOSTILE_ED25519}") - with _scan_returning(f"github.com ssh-ed25519 {GITHUB_ED25519}\n"): - _ensure_known_host("github.com") - assert GITHUB_ED25519 in known_hosts.read_text() - - -def test_a_failed_scan_writes_nothing(fake_home: Path) -> None: - """An unreachable host is not a verification failure.""" - with patch( - "devops_cli.git.operations.run_subprocess", - return_value=MagicMock(returncode=1, stdout=""), + with ( + patch("devops_cli.git.operations._ensure_known_host"), + patch("devops_cli.git.operations.gitlib.Repo.clone_from", side_effect=fake_cmd_err), + patch("devops_cli.commands.repos.load_settings"), ): - _ensure_known_host("github.com") - assert (fake_home / ".ssh" / "known_hosts").exists() is False - - -def test_an_unpinned_host_is_refused_by_default(fake_home: Path) -> None: - """Trust-on-first-use is no longer the silent default.""" - with _scan_returning(f"git.example.com ssh-ed25519 {GITHUB_ED25519}\n"): - with pytest.raises(GitOperationError, match="No published fingerprints"): - _ensure_known_host("git.example.com") - - -def test_an_unpinned_host_can_be_trusted_on_request(fake_home: Path) -> None: - """Trust-on-first-use remains available, but the caller has to ask for it.""" - with _scan_returning(f"git.example.com ssh-ed25519 {GITHUB_ED25519}\n"): - _ensure_known_host("git.example.com", allow_unverified=True) - assert "git.example.com" in (fake_home / ".ssh" / "known_hosts").read_text() - - -def test_opting_into_unverified_trust_does_not_weaken_a_pinned_host(fake_home: Path) -> None: - """For a host that publishes fingerprints, an unverifiable key is a signal, not a gap. - - Letting the flag override verification would reintroduce the defect behind an option. - """ - with _scan_returning(f"github.com ssh-ed25519 {HOSTILE_ED25519}\n"): - with pytest.raises(GitOperationError): - _ensure_known_host("github.com", allow_unverified=True) - known_hosts = fake_home / ".ssh" / "known_hosts" - assert known_hosts.exists() is False or known_hosts.read_text().strip() == "" - - -def test_the_entry_is_written_under_the_requested_hostname(fake_home: Path) -> None: - """The recorded name comes from the request, not from whatever the scan line said. - - ssh-keyscan reports the host and addresses it resolved; pinning the key under those - names would trust the key for hosts that were never asked about. - """ - with _scan_returning(f"github.com,140.82.121.4 ssh-ed25519 {GITHUB_ED25519}\n"): - _ensure_known_host("github.com") - content = (fake_home / ".ssh" / "known_hosts").read_text().strip() - assert content == f"github.com ssh-ed25519 {GITHUB_ED25519}" - - -def test_a_scan_naming_a_different_host_is_rejected(fake_home: Path) -> None: - """A response that does not mention the host asked about is not an answer about it.""" - with _scan_returning(f"evil.example.com ssh-ed25519 {GITHUB_ED25519}\n"): - _ensure_known_host("github.com") - assert (fake_home / ".ssh" / "known_hosts").exists() is False - - -def test_an_unusable_scan_for_an_unpinned_host_writes_nothing(fake_home: Path) -> None: - """Banner-only output contains no key to trust.""" - with _scan_returning("# git.example.com:22 SSH-2.0-OpenSSH\n"): - _ensure_known_host("git.example.com", allow_unverified=True) - assert (fake_home / ".ssh" / "known_hosts").exists() is False - - -def test_membership_is_checked_without_spawning_a_process(tmp_path: Path) -> None: - """The check no longer requires the OpenSSH client to be installed.""" - path = write_known_hosts(tmp_path / "kh", f"github.com ssh-ed25519 {GITHUB_ED25519}") - with patch("devops_cli.git.operations.run_subprocess") as mock_run: - found = _is_host_in_known_hosts("github.com", path) - mock_run.assert_not_called() - assert found is True - - -def test_a_hashed_known_hosts_file_is_matched_without_rescanning(fake_home: Path) -> None: - """With HashKnownHosts enabled the host is absent from the file as plain text. - - A substring check finds nothing and rescans on every clone; recomputing the HMAC finds - the entry that is genuinely there. - """ - known_hosts = fake_home / ".ssh" / "known_hosts" - known_hosts.parent.mkdir(parents=True, exist_ok=True) - write_known_hosts(known_hosts, f"{hashed_host('github.com')} ssh-ed25519 {GITHUB_ED25519}") - with patch("devops_cli.git.operations.run_subprocess") as mock_run: - _ensure_known_host("github.com") - mock_run.assert_not_called() - - -def test_an_unwritable_known_hosts_does_not_crash_the_clone(tmp_path: Path) -> None: - """A read-only home directory should degrade, not abort the operation. - - The clone will fail its own host key check afterwards, which is the correct and visible - outcome; raising here would obscure it with an unrelated filesystem error. - """ - path = tmp_path / "kh" - with patch("pathlib.Path.open", side_effect=OSError("read-only file system")): - append_entry(path, "github.com ssh-ed25519 AAAA") - assert path.exists() is False + dest = tmp_path / "clone_target" + res = runner.invoke(repos_app, ["clone", "git@github.com:org/repo.git", str(dest)]) + assert (res.exit_code != 0, "Traceback" not in res.output) == (True, True) From cc3bae80d1269f31878a4324946315b52ef71953 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 9 Oct 2026 11:07:20 -0600 Subject: [PATCH 10/15] feat(ci): changed-line coverage on pull requests (diff-cover) (#850) (#1511) --- .github/workflows/ci.yml | 21 ++++++ RELEASE_CYCLE.md | 3 +- changelog.d/850.md | 2 + ...-changed-line-coverage-on-pull-requests.md | 64 +++++++++++++++++++ pyproject.toml | 1 + tests/test_ci.py | 43 +++++++++++++ uv.lock | 46 +++++++++++++ 7 files changed, 179 insertions(+), 1 deletion(-) create mode 100644 changelog.d/850.md create mode 100644 docs/agent/tasks/task-850-changed-line-coverage-on-pull-requests.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index daefd8ab41..f63c1a89e6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -57,8 +57,11 @@ jobs: contents: read steps: + # Full history so the changed-line coverage step can find the merge base. - name: Check out repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 0 - name: Set up uv toolchain uses: ./.github/actions/setup-toolchain @@ -70,6 +73,24 @@ jobs: - name: Tests & Coverage Quality Gate run: uv run devops ci --check --no-cache --only test + # Advisory changed-line coverage against the pull request's own base branch (#850). + # No --fail-under: it reports in the job summary and never fails on the figure. + # diff-cover truncates its output file, so it writes first and the pragma list + # is appended after it. + - name: Changed-Line Coverage + if: github.event_name == 'pull_request' + env: + BASE_REF: ${{ github.base_ref }} + run: | + git fetch --no-tags origin "$BASE_REF" + uv run diff-cover .data/coverage.xml --compare-branch="origin/${BASE_REF}" --format "markdown:${GITHUB_STEP_SUMMARY}" + { + echo "### Added pragma: no cover lines" + echo "~~~diff" + git diff --unified=0 -G 'pragma: no cover' "origin/${BASE_REF}...HEAD" -- src | grep -e '^+++ ' -e '^+.*pragma: no cover' || echo 'None.' + echo "~~~" + } >> "$GITHUB_STEP_SUMMARY" + # The published image packages devops-cli itself, so it is rebuilt only for pull # requests targeting main, and only when the change actually alters image content. devcontainer: diff --git a/RELEASE_CYCLE.md b/RELEASE_CYCLE.md index c51d5d85f2..be11390247 100644 --- a/RELEASE_CYCLE.md +++ b/RELEASE_CYCLE.md @@ -127,7 +127,7 @@ uv run devops ci 12. **Lockfile Validation (`uv lock --check`)**: Verifies `uv.lock` remains strictly synchronized with `pyproject.toml`. 13. **Dependency Freshness (`uv tree --outdated`)**: Inspects dependency tree for outdated packages. -CI (`ci.yml`) additionally runs `devops devcontainer validate --workspace .`. +CI (`ci.yml`) additionally runs `devops devcontainer validate --workspace .`. On pull requests, the Tests & Coverage job also writes an advisory changed-line coverage report (diff-cover) against the base branch to its job summary. --- @@ -203,6 +203,7 @@ uv run devops release prepare X.Y.Z --create-pr - Mypy strict type checking (`mypy --strict src`) - Documentation freshness (`devops docs check`) - Pytest unit tests and test coverage thresholds + - Changed-line coverage against the pull request's base branch (diff-cover, advisory, in the job summary) - Bandit static security scanning 2. `ci.yml`'s **Service Image** job builds, smoke-tests and scans the release PR's image without pushing; `release.yml` publishes it after the merge (Step 5). 3. Maintainers review the release diff, changelog, and documentation updates. diff --git a/changelog.d/850.md b/changelog.d/850.md new file mode 100644 index 0000000000..8e0c161516 --- /dev/null +++ b/changelog.d/850.md @@ -0,0 +1,2 @@ +### Added +- Pull requests show changed-line coverage against their base branch (diff-cover), plus any added `pragma: no cover` lines, in the Tests & Coverage job summary. The report is advisory and sets no coverage threshold (#850). diff --git a/docs/agent/tasks/task-850-changed-line-coverage-on-pull-requests.md b/docs/agent/tasks/task-850-changed-line-coverage-on-pull-requests.md new file mode 100644 index 0000000000..9d5d634a1f --- /dev/null +++ b/docs/agent/tasks/task-850-changed-line-coverage-on-pull-requests.md @@ -0,0 +1,64 @@ +# Task: Changed-Line Coverage on Pull Requests (diff-cover) (#850) + +**Issue**: [#850](https://github.com/dan-petty/devops-cli/issues/850) +**Status**: Done +**Milestone**: v0.2.32 +**Priority**: priority/p2-medium +**Scope**: scope/ci, scope/github + +## Description + +Coverage is gated only in total (`[tool.coverage.report] fail_under = 90`), so an untested new function inside a well-covered module passes every gate. On pull requests, the `Tests & Coverage` job now runs diff-cover 10.6.0 (dev group) over the `.data/coverage.xml` that its gate step already writes. It measures against the pull request's own base branch (`origin/${BASE_REF}`, with `BASE_REF` taken from `github.base_ref` through `env`) and writes the markdown report to the job summary. It then appends the `pragma: no cover` lines the pull request adds under `src`, with their file names. diff-cover truncates its output file, so it writes first and the pragma list is appended after it. The checkout fetches full history (`fetch-depth: 0`) so the merge base is always found. + +The report is advisory. It has no `--fail-under`, and it is not a check row, so `uv run devops ci` and the pre-push gate are unchanged. The step fails the job only when git or diff-cover itself fails, never because of the coverage figure. + +## Backtest + +The last 10 merged pull requests into `release/**` that change `src`, measured at each squash commit. Each suite ran in a scratch worktree with `pytest -n 4 --cov=src --cov-report=xml`, with `HOME` and `TMPDIR` on fresh scratch directories, followed by `diff-cover .data/coverage.xml --compare-branch=^` (diff-cover 10.6.0). "Changed lines" counts only the lines diff-cover can measure. It skips lines that carry no coverage information, such as comments, docstrings and continuation lines inside one statement. + +| PR | Commit | Changed lines | Missing | Changed-line coverage | Below 90 | Test failures at the commit | +| :--- | :--- | ---: | ---: | ---: | :--- | :--- | +| #1488 | `0b06ff409` | 79 | 6 | 92.4% | no | none | +| #1487 | `a525a81c0` | 256 | 52 | 79.7% | yes | none | +| #1484 | `8dfb0c1a7` | 27 | 8 | 70.4% | yes | 1: `test_no_direct_data_dir_path_construction_in_src` flags `ai/client/network.py` at this commit | +| #1483 | `0f945db4e` | 131 | 14 | 89.3% | yes | none | +| #1482 | `b7edb8f8a` | 0 | 0 | n/a (two entries inside one list literal) | no | none | +| #1481 | `f8ebd601a` | 101 | 3 | 97.0% | no | none | +| #1480 | `b22837db9` | 23 | 3 | 87.0% | yes | none | +| #1479 | `a01fdacfd` | 46 | 10 | 78.3% | yes | none | +| #1477 | `fb3bad1e7` | 0 | 0 | n/a (docstring and comments only) | no | none | +| #1476 | `95ced1a17` | 1 | 0 | 100.0% | no | none | + +- Rule (owner decision D4): the step becomes blocking, with `--fail-under` set to `[tool.coverage.report] fail_under` (90), once a backtest over the last 10 merged pull requests shows that fewer than 1 in 10 would fail. That change adds a test that reads the value through `tomllib`, so the step and `pyproject.toml` cannot drift. +- Result: not met, so the step stays advisory. 5 of 10 pull requests (#1487, #1484, #1483, #1480, #1479) fall below 90. + +## Acceptance Criteria + +- [x] On a pull request into `release/**`, the summary measures coverage against that release branch. The step runs diff-cover with `--compare-branch="origin/${BASE_REF}"`, and `BASE_REF` is `github.base_ref`. Run locally under `bash --noprofile --norc -eo pipefail` with `BASE_REF=release/v0.2.32`, the step's script wrote a summary headed `Diff: origin/release/v0.2.32...HEAD`, and it listed an added `pragma: no cover` line under its file name. +- [x] `uv run devops ci` is unchanged: no `src` file changes, and no check row runs diff-cover. +- [x] `test_changed_line_coverage_step_is_advisory_on_pull_requests` in `tests/test_ci.py` parses `ci.yml` and asserts that the step follows the gate step, runs only on `pull_request`, takes the base ref through `env`, reads `.data/coverage.xml`, writes the summary and the pragma list, and has no `--fail-under` and no `${{` in its script. It also asserts that the checkout fetches full history and that no check row runs diff-cover. +- [x] The CI parity check (`_validate_ci_workflow_parity`) allowlists the step as an advisory report that is never a check row. +- [x] actionlint (with shellcheck), `uv lock --check` and `uv audit` pass. +- [x] The step adds under 15 s. diff-cover took 0-3 s per commit in the backtest, and the whole script ran in under 1 s locally. +- Pending a person: the pull request's `Tests & Coverage` run summary shows `Diff: origin/release/v0.2.32...HEAD`, followed by the "Added pragma: no cover lines" section. + - `gh pr checks `, then open the `Tests & Coverage` run's Summary page (`gh run view --web`). +- Pending a person: the step takes under 15 s on GitHub. + - `gh api repos/dan-petty/devops-cli/actions/jobs/ --jq '.steps[]|select(.name=="Changed-Line Coverage")|[.started_at,.completed_at]'` +- Pending a person (owner settings, the same step #842 already lists as "without `code_coverage`"): remove the inert `code_coverage` rule from rulesets 21466414 and 23059172, since nothing feeds it. + - `gh api repos/dan-petty/devops-cli/rulesets/ --jq '{name,target,enforcement,conditions,bypass_actors,rules:[.rules[]|select(.type!="code_coverage")]}' > /tmp/rs.json && gh api -X PUT repos/dan-petty/devops-cli/rulesets/ --input /tmp/rs.json` + +## Deliverables + +- [x] `pyproject.toml`: `diff-cover==10.6.0` in the dev group. `uv.lock` adds diff-cover 10.6.0 and chardet 7.6.0. +- [x] `.github/workflows/ci.yml`: the `test` job checks out full history and runs the `Changed-Line Coverage` step after `Tests & Coverage Quality Gate`, on pull requests only. +- [x] `tests/test_ci.py`: the step's shape test, and the step's entry on the CI parity allowlist. +- [x] `RELEASE_CYCLE.md`: Step 3 lists the advisory report, and the CI note says the `Tests & Coverage` job writes it to its job summary on pull requests. +- [x] `changelog.d/850.md` under `### Added`. +- Dropped: the threshold constant in `config/constants.py`. Nothing would read it while the step is advisory, and the blocking threshold is `[tool.coverage.report] fail_under`, so a constant would duplicate it. +- Dropped: marking the `docs/ROADMAP.md:1010` entry rescoped. `docs/ROADMAP.md` is generated and the entry no longer exists. No issue tracks its vanished-test report, so that report needs its own issue if it is still wanted. + +## Known Limits + +- `workflow_dispatch` runs, such as those from `devops pr update --dispatch-ci`, skip the step, because they carry no base ref. +- `Tests & Coverage` is not yet a required check on either ruleset. Until #842's owner settings step lands, a blocking step would block nothing. +- The step is skipped when the gate step fails, because no complete `.data/coverage.xml` exists then. diff --git a/pyproject.toml b/pyproject.toml index 57d26341d6..f660fd2b43 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -83,6 +83,7 @@ dev = [ "mypy==2.3.1", "types-PyYAML==6.0.12.20260906", "pytest-cov==7.1.0", + "diff-cover==10.6.0", "pytest-xdist==3.8.0", "bandit==1.9.4", "actionlint-py==1.7.12.25", diff --git a/tests/test_ci.py b/tests/test_ci.py index 20aa257476..a4a2a3ecee 100644 --- a/tests/test_ci.py +++ b/tests/test_ci.py @@ -700,6 +700,45 @@ def test_ci_workflow_has_tooling_cache_step() -> None: assert ".pytest_cache" in str(setup.get("with", {}).get("tooling-cache-paths", "")) +def test_changed_line_coverage_step_is_advisory_on_pull_requests() -> None: + """Pull requests get an advisory diff-cover report against their own base branch (#850). + + The step reads the coverage.xml the gate already wrote, runs only on pull requests, + takes the base ref through env rather than an inline expression, and stays advisory + (no --fail-under). It is never part of the pre-push gate, so no check row runs it. + """ + import yaml + + ci = yaml.safe_load(Path(".github/workflows/ci.yml").read_text(encoding="utf-8")) or {} + steps = ci["jobs"]["test"]["steps"] + names = [s.get("name") for s in steps] + step = steps[names.index("Changed-Line Coverage")] + run = str(step.get("run", "")) + checkout = next(s for s in steps if "actions/checkout" in str(s.get("uses", ""))) + + assert ( + names.index("Changed-Line Coverage") > names.index("Tests & Coverage Quality Gate"), + step.get("if"), + step.get("env"), + "diff-cover .data/coverage.xml" in run and '--compare-branch="origin/${BASE_REF}"' in run, + "GITHUB_STEP_SUMMARY" in run and "pragma: no cover" in run, + "--fail-under" in run, + "${{" in run, + checkout.get("with", {}).get("fetch-depth"), + any("diff-cover" in " ".join(s.cmd) for s in get_check_specs()), + ) == ( + True, + "github.event_name == 'pull_request'", + {"BASE_REF": "${{ github.base_ref }}"}, + True, + True, + False, + False, + 0, + False, + ) + + def test_ci_workflow_parallelizes_quality_gates() -> None: """Static analysis, tests, and the image build run as independent parallel jobs. @@ -1920,6 +1959,10 @@ def _validate_ci_workflow_parity(workflow_data: dict[str, Any]) -> None: "Detect Image Content Changes", ): "Git diff to check changed service image sources", ("service-image", "Run Service Image Smoke Test"): "Docker container curl/smoke tests", + ( + "test", + "Changed-Line Coverage", + ): "Advisory diff-cover report in the job summary, never a check table row", } all_specs = get_check_specs() diff --git a/uv.lock b/uv.lock index 91b85d569e..e06d4d2419 100644 --- a/uv.lock +++ b/uv.lock @@ -402,6 +402,35 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/db/3c/33bac158f8ab7f89b2e59426d5fe2e4f63f7ed25df84c036890172b412b5/cfgv-3.5.0-py2.py3-none-any.whl", hash = "sha256:a8dc6b26ad22ff227d2634a65cb388215ce6cc96bbcc5cfde7641ae87e8dacc0", size = 7445, upload-time = "2025-11-19T20:55:50.744Z" }, ] +[[package]] +name = "chardet" +version = "7.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b1/51/cd61c567092a6cec796144510a68aff158ebfc1df82950a45bae65f28413/chardet-7.6.0.tar.gz", hash = "sha256:93d9df6089ded42ed1fe9f57e272c0b74bd0464d45c0c7d50f09f26f31105c3c", size = 914462, upload-time = "2026-08-14T20:36:59.305Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cf/78/e14991c9487277ed7d006fff58f3084ac792ed94cced081788abb95df70c/chardet-7.6.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:c6061adf247ab5dda173b67010e13904c6071717660c7c8077fb50aca362b264", size = 1087678, upload-time = "2026-08-14T20:36:43.2Z" }, + { url = "https://files.pythonhosted.org/packages/7a/40/0f95e04cb1820e0a582cd6d86bbf26be8302a94ccf330f8ba5f69735389d/chardet-7.6.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:fc1e1571321baf8927582fe34363ad7f02279f11c8c2839c14b4c76894148db6", size = 1065310, upload-time = "2026-08-14T20:36:44.489Z" }, + { url = "https://files.pythonhosted.org/packages/3b/a1/04404dcc9d6e1253b02583e562d2c7ddca50a7e91f460d62eff7e1d07c92/chardet-7.6.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8900f6c7cf6b015b17a51767cc6144689059ba1cdceaa383d29eb037ac28579e", size = 1485028, upload-time = "2026-08-14T20:36:45.797Z" }, + { url = "https://files.pythonhosted.org/packages/f4/88/360064c4c7d9d0664561dae03b74c871d2f5332b329f5c99f1c997fb869a/chardet-7.6.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cedbc584789eb2edfde20fd03669972a833ce6019e60014ae613f9bfc440e8e3", size = 1510242, upload-time = "2026-08-14T20:36:47.206Z" }, + { url = "https://files.pythonhosted.org/packages/43/4c/302869fa1c69a5a41e4e78782680b12552ffd4286c3ae3c839b7b8df53d4/chardet-7.6.0-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d5dc835e40e0e09c2c3eab43731a8b5127834f42786dda09ba2f4b699ccd527a", size = 1456456, upload-time = "2026-08-14T20:36:48.668Z" }, + { url = "https://files.pythonhosted.org/packages/7c/a9/ff4fef15ed25fc3f945a3b981ae0f43c8559b3fbedb40267e59e583d105b/chardet-7.6.0-cp314-cp314-win_amd64.whl", hash = "sha256:0f304de7041afaec0195ad6464937cd112392002e9d72ed15d55f20a9abd3a13", size = 1159103, upload-time = "2026-08-14T20:36:50.107Z" }, + { url = "https://files.pythonhosted.org/packages/31/44/94e6f89485ce6c630e8fec6d388e3fa747e58b7246b0cc8c5c532ba98650/chardet-7.6.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:a4f0a368ad04d5def08bdfaa17c7e15e71552f93923dc2aa9b2f7d9dee02fbb6", size = 1120302, upload-time = "2026-08-14T20:36:51.484Z" }, + { url = "https://files.pythonhosted.org/packages/e0/cd/8e68ba12f13aaf4ee82d54ef8a1f83d62942e7a6bc1e579dd2d530a3e26e/chardet-7.6.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:75d6c3a4d2046d49e83d2d2206eb073a1f390743e856d90c1bbc19949b26acf4", size = 1093157, upload-time = "2026-08-14T20:36:52.987Z" }, + { url = "https://files.pythonhosted.org/packages/f3/f6/6a35342b9efa69dcceab0ea8966571c6442a59c336bf460f0a2af95ed234/chardet-7.6.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:459e2b1c98f9a86a4698112aa42dffa802bbbff883c1ff144071f87224125862", size = 1521213, upload-time = "2026-08-14T20:36:54.812Z" }, + { url = "https://files.pythonhosted.org/packages/df/8c/8f09bfabbaedae45caa72b996e96d5e3f6436dfddc55c1311ffa2f6bd7d2/chardet-7.6.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0bdb6f03107b7ace3f44e0edd91aa24456ee558787df265cc19daf45785b31c7", size = 1528427, upload-time = "2026-08-14T20:36:56.224Z" }, + { url = "https://files.pythonhosted.org/packages/0c/3d/2540627b193112e08b8045f3cad9295570866208555aa6625b63cc69c6cd/chardet-7.6.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:0c44a32da32cc8b23d6b20d98ace15ec7600950e4955d1bf5ab1f849b0187fdb", size = 1087374, upload-time = "2026-08-14T21:04:14.994Z" }, + { url = "https://files.pythonhosted.org/packages/fe/de/dac4f550cde73c4732b4916e72ec489ae36933fbbd1697e4122d3ae2e9dd/chardet-7.6.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:7bbc8a9652c7f859c593847f220c1d264f25749369abb1a267b404ee8cceb209", size = 1064688, upload-time = "2026-08-14T21:04:16.806Z" }, + { url = "https://files.pythonhosted.org/packages/06/45/f4f3f288496797d2cf1d1e9036f920ed2b4c79787b21c42a3314f4a6d532/chardet-7.6.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:83512a475a2f3886166aa0bca1bbb39343a4eb3186dd5532127d6f2591d09118", size = 1486320, upload-time = "2026-08-14T21:04:18.535Z" }, + { url = "https://files.pythonhosted.org/packages/c0/81/3ca30c16e6c6015b737fca22d9342957cc617d8a65329d3e963ad754a31b/chardet-7.6.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:271ab71ec1be61dbbce0436de0848895c03eae051c379e937a39573d9ce403d9", size = 1515374, upload-time = "2026-08-14T21:04:20.724Z" }, + { url = "https://files.pythonhosted.org/packages/6e/98/163a75b8b3372a6b6503f5f5a4154a222ac135c7a706b5d176f8e4b237a2/chardet-7.6.0-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:da86fc1b40ff5996fbb5e4c2d2dca770eac2c893cef157dacc050b8b4d929846", size = 1469504, upload-time = "2026-08-14T21:04:22.352Z" }, + { url = "https://files.pythonhosted.org/packages/d7/4f/3ad1b1bd27ae7f0d3d13cf711366525cd781a9e067950d8a09aa280916cb/chardet-7.6.0-cp315-cp315-win_amd64.whl", hash = "sha256:b73f277c1ac09c4f8076c4214b816c7aa78a0a2f0cb7156742f4303f856bedc3", size = 1158551, upload-time = "2026-08-14T21:04:24.259Z" }, + { url = "https://files.pythonhosted.org/packages/8d/92/22a609c68c5123ebdccd8fe1a80e423609012ce20166de19a2ed3955b2f7/chardet-7.6.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:61238d5945b36af9a2ad13494f8969b7deb3c3b4abe223e54670c064e73f5328", size = 1119186, upload-time = "2026-08-14T21:04:25.761Z" }, + { url = "https://files.pythonhosted.org/packages/29/35/75a90143e4200e197f4f6cf5895d379e22bc785d0c7711120df18fa5347c/chardet-7.6.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:f2ec3c78cc6b54bf8e091ec4ee885473078b5d7ef18ab1b01c86ae1e98bf88f7", size = 1092596, upload-time = "2026-08-14T21:04:27.884Z" }, + { url = "https://files.pythonhosted.org/packages/d1/2c/b6d5f47d878c46e04ae6fcb58e0969467925bc0819b333c682e0c41bbc5c/chardet-7.6.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:167d7ba3ee08b654e36d7b43ebd9a36606c9a12e2fabdb361757a095ca3b7e3d", size = 1516644, upload-time = "2026-08-14T21:04:29.624Z" }, + { url = "https://files.pythonhosted.org/packages/25/d2/2bc3f1066c6f27bc3fa3a98dfd8a2a9c1e969a9d6bdc1edcd35278791fc4/chardet-7.6.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f14f46ef1977e41ce1f4814ca6984cea7f8b6baf8cbc6626ef7bf3d13cf7ea13", size = 1533221, upload-time = "2026-08-14T21:04:31.39Z" }, + { url = "https://files.pythonhosted.org/packages/cf/6e/5a0b348fa4cd7847567a28c6e697ccf58391960bfd13a6e7473ee23ca2f2/chardet-7.6.0-py3-none-any.whl", hash = "sha256:4076d795897ce45239825956a1334e134322ecc4bfe84dbb12acd5390de0fbc1", size = 680279, upload-time = "2026-08-14T20:36:57.763Z" }, +] + [[package]] name = "charset-normalizer" version = "3.5.1" @@ -756,6 +785,7 @@ dev = [ { name = "actionlint-py" }, { name = "bandit" }, { name = "deptry" }, + { name = "diff-cover" }, { name = "h11" }, { name = "hypothesis" }, { name = "mypy" }, @@ -838,6 +868,7 @@ dev = [ { name = "actionlint-py", specifier = "==1.7.12.25" }, { name = "bandit", specifier = "==1.9.4" }, { name = "deptry", specifier = "==0.25.1" }, + { name = "diff-cover", specifier = "==10.6.0" }, { name = "h11", specifier = "==0.16.0" }, { name = "hypothesis", specifier = "==6.168.3" }, { name = "mypy", specifier = "==2.3.1" }, @@ -851,6 +882,21 @@ dev = [ { name = "types-pyyaml", specifier = "==6.0.12.20260906" }, ] +[[package]] +name = "diff-cover" +version = "10.6.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "chardet" }, + { name = "jinja2" }, + { name = "pluggy" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/63/ef/479d5b18c5cd61c4fbb769c60d4829ea9d70aef1267e302d6de60deed7f3/diff_cover-10.6.0.tar.gz", hash = "sha256:8d1194dfb537f70480ac97c9c45dd40721cf4c326c9903fbe997db67a4db6195", size = 107697, upload-time = "2026-09-22T00:43:00.885Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/47/04/7130707bb385835cca7f168c80d812c9b42af9ae8230a26b3e21c9437c98/diff_cover-10.6.0-py3-none-any.whl", hash = "sha256:a701553060f72d59b81f9cb1645b75ef66204427eb9dd99873c91092220e52ce", size = 63351, upload-time = "2026-09-22T00:42:59.593Z" }, +] + [[package]] name = "distlib" version = "0.4.3" From dff7004087ebeed22889dc8a5abfb1dfee55989b Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 9 Oct 2026 11:12:35 -0600 Subject: [PATCH 11/15] fix(k8s): service URLs bracket IPv6 hosts and proxy boundaries (#1111) (#1509) * fix(security): URL and host:port reads use the sending client's parser (#1112) * fix(k8s): service URLs bracket IPv6 hosts and proxy boundaries (#1111) --- changelog.d/1111.md | 6 + ...-ipv6-service-urls-and-proxy-boundaries.md | 32 ++ src/devops_cli/commands/k8s/networking.py | 92 +++- src/devops_cli/k8s/service.py | 10 +- src/devops_cli/k8s/service_http.py | 15 +- src/devops_cli/k8s/service_proxy.py | 80 ++- src/devops_cli/sandbox/probe.py | 21 +- src/devops_cli/telemetry/collector.py | 4 +- tests/test_k8s_ipv6_and_proxy_boundaries.py | 457 ++++++++++++++++++ 9 files changed, 670 insertions(+), 47 deletions(-) create mode 100644 changelog.d/1111.md create mode 100644 docs/agent/tasks/task-1111-ipv6-service-urls-and-proxy-boundaries.md create mode 100644 tests/test_k8s_ipv6_and_proxy_boundaries.py diff --git a/changelog.d/1111.md b/changelog.d/1111.md new file mode 100644 index 0000000000..b9f58aae1e --- /dev/null +++ b/changelog.d/1111.md @@ -0,0 +1,6 @@ +### Fixed +- Kubernetes service, node, LoadBalancer, and telemetry collector URL builders bracket IPv6 host addresses using `httpx2.URL`, preventing URL parser failures. +- `configure-urls` handles IPv6 cluster endpoints and falls back safely to loopback when endpoints are unreachable, including port-80 LoadBalancers. +- Kubernetes Service proxy addressing validates namespace, service, and port identifiers and refuses dot segments (`..`, `.`, `%2e%2e`), preventing path traversal and credential leakage beyond the Service boundary. +- Target resolution for Kubernetes API proxies preserves server path prefixes, raw URI encodings, and cleanly separates connection base URLs and path prefixes. +- Sandbox network probe targets using `https://` are probed over HTTPS with paths appended via `append_path`, preserving path queries and IPv6 bracketing. diff --git a/docs/agent/tasks/task-1111-ipv6-service-urls-and-proxy-boundaries.md b/docs/agent/tasks/task-1111-ipv6-service-urls-and-proxy-boundaries.md new file mode 100644 index 0000000000..c2ae56d617 --- /dev/null +++ b/docs/agent/tasks/task-1111-ipv6-service-urls-and-proxy-boundaries.md @@ -0,0 +1,32 @@ +# Task: Service URLs bracket IPv6 hosts; k8s:// addresses reach only their Service (#1111) + +**Issue**: [#1111](https://github.com/dan-petty/devops-cli/issues/1111) +**Status**: Done +**Milestone**: v0.2.32 +**Priority**: priority/p2-medium +**Scope**: scope/k8s + +## Description +Service, node, and API-proxy URLs previously assembled with f-strings and string concatenation produced unbracketed IPv6 URLs (such as `http://2001:db8::1:30080`), causing URL parsers in `httpx2` and `urllib.parse` to raise invalid port exceptions. In addition, `configure-urls` failed when inspecting IPv6 clusters, Kubernetes Service proxy paths accepted unvalidated identifiers and dot segments (`..`, `.`, `%2e%2e`) that traversed outside the Service proxy boundary carrying kubeconfig credentials, and HTTPS probe targets were probed over HTTP. + +This deliverable resolves these defects: +1. URL builders across `commands/k8s/networking.py`, `k8s/service.py`, `telemetry/collector.py`, and `sandbox/probe.py` construct URLs using `httpx2.URL(scheme=..., host=..., port=...)`, which brackets IPv6 addresses (including `::ffff:192.0.2.1` and `fe80::1%eth0`). +2. `_resolve_accessible_url` resolves ports via `httpx2.URL(url).origin.port` (retaining scheme default ports like port 80 for LoadBalancers) and handles unbracketed IPv6 inputs gracefully without raising. +3. `ServiceRef` validates namespace, service, and port identifiers against Kubernetes RFC 1123 label constraints (`validate_k8s_identifier(..., namespace=True)`), raising `ServiceAddressError`. +4. Refuses dot segments (`_has_dot_segments`) across `ServiceRef`, `proxy_path`, and `get_json` for direct and `k8s://` addresses, preventing directory traversal escapes. +5. `resolve_proxy_target` and `resolve_proxy_connection` preserve API server path prefixes and raw encodings, cleanly splitting base URL and prefix. +6. Sandbox probe uses `httpx2.Origin` to probe `https://` targets over HTTPS and appends paths via `append_path`. +7. `port_forward` formats addresses using `httpx2.URL` before `subprocess.Popen` with fallback to `{address}:{lport}` on `InvalidURL`, preventing detached orphan processes. + +## Acceptance Criteria Checklist +- [x] Offline table test verifies IPv6 bracketing across node, LoadBalancer, collector, Jaeger OTel, and probe builders. +- [x] `::ffff:192.0.2.1` and `fe80::1%eth0` bracket and round-trip cleanly with `urlsplit` and `httpx2.URL`. +- [x] Port-forward message prints bracketed IPv6 and raw address lists without raising. +- [x] `configure-urls` handles IPv6 NodePort and LoadBalancer endpoints and falls back safely to loopback. +- [x] Unreachable port-80 LoadBalancer falls back to `http://localhost:80`. +- [x] Proxy URL target resolution and Qdrant base/prefix split preserve cluster paths and raw prefixes. +- [x] Suffixes `foo:bar`, `.hidden`, and `a..b` pass dot segment checks; dot segments (`..`, `.`, `%2e%2e`) and invalid identifiers are refused with `ServiceAddressError`. +- [x] `devops k8s service-url` CLI exits 1 with no traceback on invalid identifiers. +- [x] Probe dispatches over HTTPS for HTTPS targets, preserves paths and query parameters, and brackets IPv6. +- [x] Existing IPv4 and proxy test suites pass without regression. +- Pending a person: on a dual-stack or IPv6-only cluster, if one is available, `devops k8s configure-urls` writes bracketed URLs that the dashboard reaches. diff --git a/src/devops_cli/commands/k8s/networking.py b/src/devops_cli/commands/k8s/networking.py index 45969fe70d..487c4fb7eb 100644 --- a/src/devops_cli/commands/k8s/networking.py +++ b/src/devops_cli/commands/k8s/networking.py @@ -17,7 +17,6 @@ CONST_ADDRESSING_NODEPORT, CONST_ADDRESSING_PROXY, CONST_AI_GATEWAY_PROVIDER, - CONST_K8S_URL_SCHEME, CONST_LOCAL_DOMAIN_SUFFIXES, CONST_PLACEHOLDER_NODE, CONST_PLACEHOLDER_PORT, @@ -40,8 +39,10 @@ DEFAULT_VALKEY_PORT, ) from devops_cli.config.settings import load_settings, save_settings +from devops_cli.core.cli import exit_on_error from devops_cli.core.validation import is_loopback_host from devops_cli.dry_run import is_dry_run, render_dry_run_result +from devops_cli.k8s.service_proxy import ServiceRef from devops_cli.lang import HELP, MESSAGES from devops_cli.output import ( format_json, @@ -119,7 +120,9 @@ def _resolve_k8s_node_port_url(ctx_args: list[str], node_port: int) -> str | Non if _is_node_ready(item): node_ip = _extract_first_node_ip(item) if node_ip: - return f"http://{node_ip}:{node_port}" + import httpx2 + + return str(httpx2.URL(scheme="http", host=node_ip, port=int(node_port))) except Exception as exc: logger.debug("Failed to resolve k8s node port URL: %s", exc) return None @@ -162,7 +165,9 @@ def _extract_service_ingress_or_nodeport( if ingress: lb_host = ingress[0].get("ip") or ingress[0].get("hostname") if lb_host and port_num: - return f"http://{lb_host}:{port_num}" + import httpx2 + + return str(httpx2.URL(scheme="http", host=lb_host, port=int(port_num))) if node_port: return _resolve_k8s_node_port_url(ctx_args, int(node_port)) @@ -336,6 +341,26 @@ def _update_ollama_urls( configured["ai.ollama_urls"] = ", ".join(settings.ai.ollama_urls) +def _extract_loopback_fallback(detected_url: str, default_scheme: str) -> str | None: + """Extract scheme and port from detected URL and resolve loopback fallback.""" + import httpx2 + + try: + u = httpx2.URL(detected_url) + port = u.origin.port + scheme = u.scheme or default_scheme + except httpx2.InvalidURL, ValueError: + scheme = default_scheme + port = None + if ":" in detected_url: + _, _, port_str = detected_url.rpartition(":") + if port_str.isdigit(): + port = int(port_str) + if port: + return _resolve_loopback_fallback(scheme, port) + return None + + def _resolve_accessible_url( detected_url: str | None, preferred_localhost_ports: list[int] | None = None, @@ -356,9 +381,9 @@ def _resolve_accessible_url( return preferred if detected_url: - parsed = urlparse(detected_url) - if parsed.port: - return _resolve_loopback_fallback(parsed.scheme or scheme, parsed.port) + fallback = _extract_loopback_fallback(detected_url, scheme) + if fallback: + return fallback return detected_url @@ -369,7 +394,6 @@ def _configure_infra_stack_urls( configured: dict[str, str], ) -> None: """Detect and configure accessible URLs for infrastructure stack services.""" - from urllib.parse import urlparse from devops_cli.config.settings import dotted_set @@ -408,8 +432,23 @@ def _configure_infra_stack_urls( if jaeger_url and _should_update_url(getattr(settings.jaeger, "url", None), jaeger_url): dotted_set(settings, "jaeger.url", jaeger_url) configured["jaeger.url"] = jaeger_url - j_host = urlparse(jaeger_url).hostname or "localhost" - otel_url = f"http://{j_host}:4318" + import httpx2 + + from devops_cli.config.constants import CONST_OTEL_OTLP_HTTP_PORT + + try: + j_host = httpx2.URL(jaeger_url).host + except httpx2.InvalidURL, ValueError: + from urllib.parse import urlparse + + j_host = urlparse(jaeger_url).hostname or "localhost" + otel_url = str( + httpx2.URL( + scheme="http", + host=j_host, + port=CONST_OTEL_OTLP_HTTP_PORT, + ) + ) telemetry_endpoint = getattr(getattr(settings, "telemetry", None), "endpoint", None) if _should_update_url(telemetry_endpoint, otel_url): dotted_set(settings, "otel.endpoint", otel_url) @@ -560,8 +599,9 @@ def _preview_proxy_addresses(stacks: Sequence[str]) -> dict[str, str]: preview: dict[str, str] = {} for key, namespace, patterns, port_hints in targets: - port = next((hint for hint in port_hints if hint.isdigit()), CONST_PLACEHOLDER_PORT) - preview[key] = f"{CONST_K8S_URL_SCHEME}://{namespace}/{patterns[0]}:{port}" + port = next(hint for hint in port_hints if hint.isdigit()) + ref = ServiceRef(namespace=namespace, service=patterns[0], port=port) + preview[key] = ref.describe() return preview @@ -670,7 +710,9 @@ def _search_ingress_hosts( if _ingress_matches(key, hosts, service_pattern): chosen = _select_best_ingress_host(hosts, preferred_domain=preferred_domain) if chosen: - return f"https://{chosen}" + import httpx2 + + return str(httpx2.URL(scheme="https", host=chosen)) return None @@ -999,6 +1041,13 @@ def _launch_port_forwards( svc, f"{lport}:{rport}", ] + ctx_args + import httpx2 + + try: + target_url = str(httpx2.URL(scheme="http", host=address, port=lport)) + except httpx2.InvalidURL: + target_url = f"{address}:{lport}" + # Its own session, so the forward outlives the command that started it and does # not take a terminal's SIGINT along with the CLI. `devops k8s port-forward status` # lists these as background daemons, which is only true if they are detached. @@ -1020,7 +1069,7 @@ def _launch_port_forwards( start_ticks=process_start_ticks(proc.pid), ) ) - print_success(f"Forwarding {svc} ({ns}) to http://{address}:{lport} (pid {proc.pid})") + print_success(f"Forwarding {svc} ({ns}) to {target_url} (pid {proc.pid})") daemon_mgr.save_forwards(active_forwards) @@ -1184,14 +1233,15 @@ def service_url( ) request_path, _, request_query = path.partition("?") - ref = ServiceRef( - namespace=namespace, - service=service, - port=port, - tls=tls, - path=request_path, - query=request_query, - ) + with exit_on_error(ServiceAddressError): + ref = ServiceRef( + namespace=namespace, + service=service, + port=port, + tls=tls, + path=request_path, + query=request_query, + ) if not fetch: try: diff --git a/src/devops_cli/k8s/service.py b/src/devops_cli/k8s/service.py index bddbb56680..8830be2104 100644 --- a/src/devops_cli/k8s/service.py +++ b/src/devops_cli/k8s/service.py @@ -358,14 +358,20 @@ def resolve_service_endpoint( if ingress and port: lb_host = ingress[0].ip or ingress[0].hostname if lb_host: - return f"http://{lb_host}:{port}" + import httpx2 + + return str(httpx2.URL(scheme="http", host=lb_host, port=int(port))) if node_port: + import httpx2 + nodes = self.list_nodes(context=context) for node in nodes: for addr in node.status.addresses or []: if addr.type in ("InternalIP", "ExternalIP") and addr.address: - return f"http://{addr.address}:{node_port}" + return str( + httpx2.URL(scheme="http", host=addr.address, port=int(node_port)) + ) except Exception as exc: logger.debug("Failed to resolve service endpoint for %s: %s", service, exc) diff --git a/src/devops_cli/k8s/service_http.py b/src/devops_cli/k8s/service_http.py index 50cfb2a207..bcdfa09345 100644 --- a/src/devops_cli/k8s/service_http.py +++ b/src/devops_cli/k8s/service_http.py @@ -10,7 +10,6 @@ import json import logging from typing import Any -from urllib.parse import urlparse from devops_cli.config.defaults import DEFAULT_K8S_PROXY_TIMEOUT_SECONDS from devops_cli.core.validation import validate_url_egress @@ -32,8 +31,10 @@ def _transport_key(url: str) -> str: The path is deliberately excluded. Every path on one host shares a connection, so keying on it would create a client per endpoint and reinstate the churn. """ - parsed = urlparse(url) - return f"{parsed.scheme}://{parsed.netloc}" + import httpx2 + + origin = httpx2.URL(url).origin + return str(httpx2.URL(scheme=origin.scheme, host=origin.host, port=origin.port)) def get_json( @@ -45,6 +46,12 @@ def get_json( purpose: str = "cluster service", ) -> Any: """Fetch JSON from a plain URL or a `k8s://` Service reference.""" + from devops_cli.http.urls import append_path + from devops_cli.k8s.service_proxy import _has_dot_segments + + if path is not None and _has_dot_segments(path): + raise ServiceAddressError(f"Path '{path}' contains dot segments.") + if is_service_url(url): ref = parse_service_url(url) target = resolve_proxy_target(ref, path, context) @@ -63,7 +70,7 @@ def get_json( # A direct URL is validated for egress. The endpoint is operator-configured and # ordinarily private, which is the case SSRF protection is not aimed at; the connect still # refuses a cloud metadata address, as it does for the API server proxy above. - full_url = f"{url.rstrip('/')}/{path.lstrip('/')}" if path else url + full_url = str(append_path(url, path)) if path else url validate_url_egress(full_url, purpose=purpose, allow_private=True) client = get_shared_client(f"direct:{_transport_key(full_url)}", EgressLevel.PRIVATE) response = client.get(full_url, timeout=timeout) diff --git a/src/devops_cli/k8s/service_proxy.py b/src/devops_cli/k8s/service_proxy.py index 8ac3829325..a900984118 100644 --- a/src/devops_cli/k8s/service_proxy.py +++ b/src/devops_cli/k8s/service_proxy.py @@ -46,6 +46,23 @@ class ServiceAddressError(KubernetesError): """Raised when a cluster service address cannot be resolved.""" +def _has_dot_segments(path: str) -> bool: + """Check whether a path contains dot segments that would cause path rewriting.""" + if not path: + return False + path_part = path.partition("?")[0].lstrip("/") + if not path_part: + return False + import urllib.parse + + import httpx2 + + test_path = "/" + urllib.parse.quote(urllib.parse.unquote(path_part), safe="/") + u_rel = httpx2.URL(path=test_path) + u_abs = u_rel.copy_with(scheme="http", host="example.com") + return u_rel.raw_path != u_abs.raw_path + + @dataclass(frozen=True) class ServiceRef: """A Service addressed through the API server proxy.""" @@ -60,6 +77,23 @@ class ServiceRef: # call that the API server rejects with 400. query: str = "" + def __post_init__(self) -> None: + from devops_cli.core.validation import validate_k8s_identifier + from devops_cli.exceptions.validation import ValidationError + + for value, label in ( + (self.namespace, "namespace"), + (self.service, "service"), + (self.port, "port"), + ): + try: + validate_k8s_identifier(value, label=label, namespace=True) + except ValidationError as exc: + raise ServiceAddressError(str(exc)) from exc + + if self.path and _has_dot_segments(self.path): + raise ServiceAddressError(f"Path '{self.path}' contains dot segments.") + @property def target(self) -> str: """The `[scheme:]name:port` segment the proxy endpoint expects. @@ -75,23 +109,41 @@ def proxy_path(self, path: str | None = None) -> str: An override may carry its own query string, which replaces this reference's. """ + import httpx2 + + from devops_cli.http.urls import append_path + prefix = CONST_K8S_SERVICE_PROXY_TEMPLATE.format( namespace=self.namespace, target=self.target ) if path is None: - suffix, query = self.path.lstrip("/"), self.query + suffix, query = self.path, self.query else: - suffix, _, query = path.lstrip("/").partition("?") + if _has_dot_segments(path): + raise ServiceAddressError(f"Path '{path}' contains dot segments.") + suffix, _, query = path.partition("?") - resolved = f"{prefix}/{suffix}" if suffix else prefix + if suffix: + base = append_path(httpx2.URL(path=prefix), suffix) + resolved = base.raw_path.decode("ascii").partition("?")[0] + else: + resolved = prefix return f"{resolved}?{query}" if query else resolved def describe(self) -> str: """Render this reference the way it is written in configuration.""" + import httpx2 + + from devops_cli.http.urls import append_path + scheme = CONST_K8S_URL_SCHEME_TLS if self.tls else CONST_K8S_URL_SCHEME - suffix = f"/{self.path.lstrip('/')}" if self.path else "" - query = f"?{self.query}" if self.query else "" - return f"{scheme}://{self.namespace}/{self.service}:{self.port}{suffix}{query}" + base = httpx2.URL(path=f"/{self.service}:{self.port}") + if self.path: + base = append_path(base, self.path) + kwargs: dict[str, Any] = {"scheme": scheme, "host": self.namespace} + if self.query: + kwargs["query"] = self.query.encode("utf-8") + return str(base.copy_with(**kwargs)) def is_service_url(url: str) -> bool: @@ -247,12 +299,14 @@ def resolve_proxy_target( ref: ServiceRef, path: str | None = None, context: str | None = None ) -> ProxyTarget: """Resolve a Service reference into a concrete API server URL and credentials.""" + from devops_cli.http.urls import append_path + configuration = _kube_configuration(context) host = str(getattr(configuration, "host", "") or "").rstrip("/") if not host: raise ServiceAddressError("The Kubernetes configuration has no API server host.") return ProxyTarget( - url=f"{host}{ref.proxy_path(path)}", + url=str(append_path(host, ref.proxy_path(path))), headers=_auth_headers(configuration), ssl_context=_ssl_context(configuration), ) @@ -290,13 +344,17 @@ class ProxyConnection: def resolve_proxy_connection(ref: ServiceRef, context: str | None = None) -> ProxyConnection: """Resolve a Service reference into the parts a URL-and-prefix client needs.""" - from urllib.parse import urlparse + import urllib.parse + + import httpx2 target = resolve_proxy_target(ref, path="", context=context) - parsed = urlparse(target.url) + origin = httpx2.URL(target.url).origin + base_url = str(httpx2.URL(scheme=origin.scheme, host=origin.host, port=origin.port)) + prefix = urllib.parse.urlsplit(target.url).path.strip("/") return ProxyConnection( - base_url=f"{parsed.scheme}://{parsed.netloc}", - prefix=parsed.path.strip("/"), + base_url=base_url, + prefix=prefix, headers=target.headers, ssl_context=target.ssl_context, ) diff --git a/src/devops_cli/sandbox/probe.py b/src/devops_cli/sandbox/probe.py index 1b51ff2f6e..81e5df6611 100644 --- a/src/devops_cli/sandbox/probe.py +++ b/src/devops_cli/sandbox/probe.py @@ -402,8 +402,7 @@ def run_sandbox_probes( for origin in target_endpoints: _dispatch_probes_for_port( - host=origin.host, - port=origin.port or 80, + origin=origin, protocols=selected_protocols, http_paths=http_paths or _DEFAULT_HTTP_PATHS, expected_statuses=expected_statuses, @@ -458,8 +457,7 @@ def _parse_target_endpoint(target_str: str) -> httpx2.Origin: def _dispatch_probes_for_port( - host: str, - port: int, + origin: httpx2.Origin, protocols: list[ProbeProtocol], http_paths: list[str], expected_statuses: list[int] | None, @@ -468,13 +466,21 @@ def _dispatch_probes_for_port( latency_budget_ms: float | None, collector: list[EndpointProbeResult], ) -> None: - """Execute configured protocols for a specific host:port endpoint.""" + """Execute configured protocols for a specific endpoint origin.""" + host = origin.host + port = origin.port or 80 + if ProbeProtocol.TCP in protocols: collector.append(probe_tcp(host, port, timeout=timeout)) + probe_scheme = "https" if origin.scheme == "https" else "http" + base_url = httpx2.URL(scheme=probe_scheme, host=host, port=port) + if ProbeProtocol.HTTP in protocols: + from devops_cli.http.urls import append_path + for path in http_paths: - url = f"http://{host}:{port}/{path.lstrip('/')}" + url = str(append_path(base_url, path)) collector.append( probe_http( url, @@ -486,8 +492,7 @@ def _dispatch_probes_for_port( ) if ProbeProtocol.OPENAPI in protocols: - base_url = f"http://{host}:{port}" - collector.extend(probe_openapi(base_url, timeout=timeout)) + collector.extend(probe_openapi(str(base_url), timeout=timeout)) if ProbeProtocol.GRPC in protocols: collector.append(probe_grpc(host, port, timeout=timeout)) diff --git a/src/devops_cli/telemetry/collector.py b/src/devops_cli/telemetry/collector.py index 08825870a0..9bd6737450 100644 --- a/src/devops_cli/telemetry/collector.py +++ b/src/devops_cli/telemetry/collector.py @@ -21,8 +21,10 @@ def collector_endpoint(context: str | None, namespace: str, service: str) -> str: """The OTLP HTTP endpoint of the cluster's collector, as a workstation reaches it.""" + import httpx2 + host, port = node_port_address(context, namespace, service, OTLP_HTTP) - return f"http://{host}:{port}" + return str(httpx2.URL(scheme="http", host=host, port=port)) __all__ = ["OTLP_HTTP", "collector_endpoint"] diff --git a/tests/test_k8s_ipv6_and_proxy_boundaries.py b/tests/test_k8s_ipv6_and_proxy_boundaries.py new file mode 100644 index 0000000000..bec3a715e9 --- /dev/null +++ b/tests/test_k8s_ipv6_and_proxy_boundaries.py @@ -0,0 +1,457 @@ +"""Tests for IPv6 URL bracketing, k8s:// service proxy boundaries, and probe protocols. + +Verifies #1111: +- Service URLs bracket IPv6 addresses across networking, service, collector, and probe. +- Proxy URLs reject dot segments, path escapes, and invalid identifiers with ServiceAddressError. +- Proxy URL target resolution and Qdrant base/prefix split preserve cluster paths and raw prefixes. +- Probe dispatches over HTTPS for HTTPS targets, preserves paths, and brackets IPv6. +""" + +from __future__ import annotations + +import json +from typing import Any +from unittest.mock import MagicMock, patch +from urllib.parse import urlsplit + +import httpx2 +import pytest +from typer.testing import CliRunner + +from devops_cli.commands.k8s import app as k8s_app +from devops_cli.commands.k8s.networking import ( + _configure_infra_stack_urls, + _dry_run_preview, + _extract_service_ingress_or_nodeport, + _resolve_accessible_url, + _resolve_k8s_node_port_url, + _search_ingress_hosts, + port_forward, +) +from devops_cli.config.settings import Settings +from devops_cli.k8s.service import KubernetesService +from devops_cli.k8s.service_http import _transport_key, get_json +from devops_cli.k8s.service_proxy import ( + ServiceAddressError, + ServiceRef, + parse_service_url, + resolve_proxy_connection, + resolve_proxy_target, +) +from devops_cli.sandbox.models import ProbeProtocol +from devops_cli.sandbox.probe import _dispatch_probes_for_port, _parse_target_endpoint +from devops_cli.telemetry.collector import collector_endpoint + +runner = CliRunner() + + +# ============================================================================= +# 1. IPv6 Builders & Bracketing Table Test +# ============================================================================= + + +def test_ipv6_builders_and_bracketing() -> None: + """Verify IPv6 addresses produce bracketed URLs across all discovery and probe sites.""" + # 1. networking.py node address via _resolve_k8s_node_port_url + node_res = MagicMock( + returncode=0, + stdout=json.dumps( + { + "items": [ + { + "status": { + "conditions": [{"type": "Ready", "status": "True"}], + "addresses": [{"type": "InternalIP", "address": "2001:db8::1"}], + } + } + ] + } + ), + ) + with patch("devops_cli.commands.k8s.networking.runtime.run_subprocess", return_value=node_res): + node_url = _resolve_k8s_node_port_url([], 30080) + + # 2. networking.py LoadBalancer ingress via _extract_service_ingress_or_nodeport + lb_svc_data = { + "spec": {"ports": [{"port": 9090}]}, + "status": {"loadBalancer": {"ingress": [{"ip": "2001:db8::1"}]}}, + } + lb_url = _extract_service_ingress_or_nodeport(lb_svc_data, []) + + # 3. k8s/service.py list_nodes node address and LoadBalancer ingress + mgr = KubernetesService() + mgr._core_v1 = MagicMock() + mock_node = MagicMock() + mock_node.status.addresses = [MagicMock(type="InternalIP", address="2001:db8::1")] + mgr.list_nodes = MagicMock(return_value=[mock_node]) # type: ignore[method-assign] + mgr.load_config = MagicMock(return_value=True) # type: ignore[method-assign] + + mock_svc = MagicMock() + mock_svc.status.load_balancer.ingress = [MagicMock(ip="2001:db8::1", hostname=None)] + mock_svc.spec.ports = [MagicMock(port=9090, node_port=30080)] + mgr._core_v1.read_namespaced_service.return_value = mock_svc + k8s_lb_url = mgr.resolve_service_endpoint("prom", "monitoring") + + mock_svc_nodeport = MagicMock() + mock_svc_nodeport.status.load_balancer.ingress = [] + mock_svc_nodeport.spec.ports = [MagicMock(port=9090, node_port=30080)] + mgr._core_v1.read_namespaced_service.return_value = mock_svc_nodeport + k8s_np_url = mgr.resolve_service_endpoint("prom", "monitoring") + + # 4. telemetry/collector.py endpoint + with patch( + "devops_cli.telemetry.collector.node_port_address", return_value=("2001:db8::1", 30080) + ): + collector_url = collector_endpoint(None, "otel", "collector") + + # 5. Ingress host builder in networking.py + ingress_url = _search_ingress_hosts( + [("monitoring:grafana", ["2001:db8::1"])], "grafana", preferred_domain=None + ) + + assert ( + node_url, + lb_url, + k8s_lb_url, + k8s_np_url, + collector_url, + ingress_url, + ) == ( + "http://[2001:db8::1]:30080", + "http://[2001:db8::1]:9090", + "http://[2001:db8::1]:9090", + "http://[2001:db8::1]:30080", + "http://[2001:db8::1]:30080", + "https://[2001:db8::1]", + ) + + +def test_special_ipv6_and_scoped_address_parsing() -> None: + """Verify ::ffff:192.0.2.1 and fe80::1%eth0 bracket and round-trip cleanly.""" + for raw in ("::ffff:192.0.2.1", "fe80::1%eth0"): + url_str = str(httpx2.URL(scheme="http", host=raw, port=8080)) + assert url_str == f"http://[{raw}]:8080" + parsed_split = urlsplit(url_str) + parsed_httpx = httpx2.URL(url_str) + assert ( + parsed_split.hostname, + parsed_split.port, + parsed_httpx.host, + parsed_httpx.port, + ) == ( + raw, + 8080, + raw, + 8080, + ) + + +def test_jaeger_to_otel_endpoint_conversion() -> None: + """Verify Jaeger URL with userinfo and query string yields clean otel.endpoint.""" + settings = Settings() + configured: dict[str, str] = {} + jaeger_raw = "http://user:pass@[2001:db8::2]:16686/?x=1" + + with ( + patch( + "devops_cli.commands.k8s.networking._detect_service_url", + side_effect=lambda svc, ns, context=None: jaeger_raw if svc == "jaeger" else None, + ), + patch( + "devops_cli.commands.k8s.networking._resolve_accessible_url", + side_effect=lambda raw, **kw: raw, + ), + ): + _configure_infra_stack_urls(None, settings, configured) + + assert ( + configured.get("jaeger.url"), + configured.get("otel.endpoint"), + ) == ( + jaeger_raw, + "http://[2001:db8::2]:4318", + ) + + +def test_dry_run_preview_matches_service_ref_describe() -> None: + """Verify proxy-mode dry-run preview exactly matches ServiceRef.describe().""" + preview = _dry_run_preview(["infra", "llm"], "proxy") + for _key, addr in preview.items(): + ref = parse_service_url(addr) + assert ref.describe() == addr + + +# ============================================================================= +# 2. Port-forward message formatting & error safety +# ============================================================================= + + +def test_port_forward_message_formatting() -> None: + """Verify port-forward messages handle IPv6 and lists without raising.""" + cases = [ + ("::1", "http://[::1]:8080"), + ("0.0.0.0", "http://0.0.0.0:8080"), + ("localhost,::1", "localhost,::1:8080"), + ] + for addr, expected_target in cases: + mock_proc = MagicMock(pid=12345) + saved: list[Any] = [] + mock_mgr = MagicMock() + mock_mgr.load_forwards.return_value = [] + mock_mgr.locked.return_value = MagicMock(__enter__=MagicMock(), __exit__=MagicMock()) + mock_mgr.save_forwards.side_effect = saved.extend + + with ( + patch( + "devops_cli.commands.k8s.networking.runtime._cluster_reachable", return_value=True + ), + patch("time.sleep"), + patch("subprocess.Popen", return_value=mock_proc), + patch("devops_cli.k8s.port_forward_daemon.process_start_ticks", return_value=100), + patch("devops_cli.k8s.port_forward_daemon.get_daemon_manager", return_value=mock_mgr), + patch("devops_cli.commands.k8s.networking.print_success") as mock_print, + ): + port_forward(stack="infra", argocd_port=8080, address=addr) + all_printed = " ".join(call[0][0] for call in mock_print.call_args_list) + assert (expected_target in all_printed, len(saved) > 0) == (True, True) + + +# ============================================================================= +# 3. configure-urls on IPv6 Cluster & Fallback +# ============================================================================= + + +def test_configure_urls_on_ipv6_cluster_and_fallbacks() -> None: + """Verify configure-urls handles IPv6 NodePort and LoadBalancer fallbacks.""" + # 1. Reachable IPv6 node + with patch("socket.create_connection") as mock_conn: + + def mock_connect(addr_tuple: tuple[str, int], timeout: float = 1.0) -> Any: + host, _port = addr_tuple + if host in ("localhost", "127.0.0.1", "::1"): + raise OSError("Connection refused") + return MagicMock() + + mock_conn.side_effect = mock_connect + + assert ( + _resolve_accessible_url("http://[2001:db8::1]:30080", preferred_localhost_ports=[8080]), + _resolve_accessible_url("http://[2001:db8::1]:9090", preferred_localhost_ports=[9090]), + ) == ( + "http://[2001:db8::1]:30080", + "http://[2001:db8::1]:9090", + ) + + # 2. Unreachable IPv6 node falls back to loopback + with patch("socket.create_connection", side_effect=OSError("Refused")): + assert ( + _resolve_accessible_url("http://[2001:db8::1]:30080", preferred_localhost_ports=[8080]), + _resolve_accessible_url("http://2001:db8::1:30080", preferred_localhost_ports=[8080]), + _resolve_accessible_url("http://[2001:db8::1]:80", preferred_localhost_ports=[80]), + ) == ( + "http://localhost:30080", + "http://localhost:30080", + "http://localhost:80", + ) + + +# ============================================================================= +# 4. Proxy URL Resolution, Paths, and Boundaries +# ============================================================================= + + +def test_proxy_target_resolution_and_path_prefix() -> None: + """Verify resolve_proxy_target and resolve_proxy_connection preserve API server paths.""" + mock_config = MagicMock() + mock_config.host = "https://example.com/k8s/clusters/c-1" + mock_config.api_key = {} + mock_config.api_key_prefix = {} + mock_config.ssl_ca_cert = None + mock_config.cert_file = None + mock_config.key_file = None + mock_config.verify_ssl = False + + ref = ServiceRef( + namespace="monitoring", + service="prometheus", + port="9090", + path="api/v1/query", + query="query=up", + ) + + with patch("devops_cli.k8s.service_proxy._kube_configuration", return_value=mock_config): + target = resolve_proxy_target(ref) + conn = resolve_proxy_connection(ref) + + assert ( + target.url, + conn.base_url, + conn.prefix, + ) == ( + "https://example.com/k8s/clusters/c-1/api/v1/namespaces/monitoring/services/prometheus:9090/proxy/api/v1/query?query=up", + "https://example.com", + "k8s/clusters/c-1/api/v1/namespaces/monitoring/services/prometheus:9090/proxy", + ) + + +def test_proxy_path_suffixes_and_encoded_segments() -> None: + """Verify raw encoded characters (%2F) and valid suffixes are preserved.""" + ref = ServiceRef( + namespace="argocd", + service="argocd-server", + port="443", + tls=True, + ) + assert ( + ref.proxy_path("a%2Fb"), + ref.proxy_path("foo:bar"), + ref.proxy_path(".hidden"), + ref.proxy_path("a..b"), + ) == ( + "/api/v1/namespaces/argocd/services/https:argocd-server:443/proxy/a%2Fb", + "/api/v1/namespaces/argocd/services/https:argocd-server:443/proxy/foo:bar", + "/api/v1/namespaces/argocd/services/https:argocd-server:443/proxy/.hidden", + "/api/v1/namespaces/argocd/services/https:argocd-server:443/proxy/a..b", + ) + + +def test_proxy_boundaries_refuse_dot_segments_and_escapes() -> None: + """Verify ServiceRef, proxy_path, and get_json refuse dot segments and invalid identifiers.""" + refused_paths = ( + "../../../secrets/foo", + "/../grafana:80/api/health", + "a/../b", + ".", + "./x", + "%2e%2e/x", + ".%2e/x", + "%2E/x", + ) + for bad_path in refused_paths: + with pytest.raises(ServiceAddressError): + ServiceRef(namespace="monitoring", service="prometheus", port="9090", path=bad_path) + + valid_ref = ServiceRef(namespace="monitoring", service="prometheus", port="9090") + with pytest.raises(ServiceAddressError): + valid_ref.proxy_path(bad_path) + + with pytest.raises(ServiceAddressError): + get_json("k8s://monitoring/prometheus:9090", path=bad_path) + + with pytest.raises(ServiceAddressError): + get_json("https://example.com", path=bad_path) + + # Invalid identifiers + for bad_id, label in ( + ("..", "namespace"), + ("..", "service"), + ("9090?", "port"), + ("9090/../../secrets/foo?", "port"), + ): + with pytest.raises(ServiceAddressError): + ServiceRef( + namespace=bad_id if label == "namespace" else "monitoring", + service=bad_id if label == "service" else "prometheus", + port=bad_id if label == "port" else "9090", + ) + + +def test_service_url_cli_command_refuses_invalid_identifier_with_exit_1() -> None: + """devops k8s service-url .. -n .. prints the error and exits 1 with no traceback.""" + res = runner.invoke(k8s_app, ["service-url", "..", "-n", ".."]) + assert res.exit_code == 1 + assert res.exception is not None + assert isinstance(res.exception, SystemExit) + + +def test_transport_key_unification() -> None: + """_transport_key gives identical key across casing, default ports, and userinfo.""" + urls = ( + "https://example.com/a", + "https://EXAMPLE.com:443/b", + "https://user:password@example.com/c", + ) + keys = {_transport_key(u) for u in urls} + assert len(keys) == 1 + assert "example.com" in next(iter(keys)) + + +# ============================================================================= +# 5. Probe Target, Paths, and Protocols +# ============================================================================= + + +def test_probe_https_scheme_and_paths() -> None: + """Verify HTTPS targets are probed over HTTPS and probe paths preserve relative semantics.""" + collected: list[Any] = [] + with ( + patch("devops_cli.sandbox.probe.probe_tcp") as mock_tcp, + patch("devops_cli.sandbox.probe.probe_http") as mock_http, + patch("devops_cli.sandbox.probe.probe_openapi", return_value=[]) as mock_openapi, + ): + origin_https = _parse_target_endpoint("https://example.com:8443") + _dispatch_probes_for_port( + origin=origin_https, + protocols=[ProbeProtocol.TCP, ProbeProtocol.HTTP, ProbeProtocol.OPENAPI], + http_paths=[ + "health", + "/health", + "api?x=1", + "foo:bar", + "//other.example.com/x", + "http://other.example.com/x", + ], + expected_statuses=None, + regex=None, + timeout=5.0, + latency_budget_ms=None, + collector=collected, + ) + + mock_tcp.assert_called_once_with("example.com", 8443, timeout=5.0) + mock_openapi.assert_called_once_with("https://example.com:8443", timeout=5.0) + + http_calls = [call[0][0] for call in mock_http.call_args_list] + assert ( + http_calls[0], + http_calls[1], + http_calls[2], + http_calls[3], + http_calls[4], + ) == ( + "https://example.com:8443/health", + "https://example.com:8443/health", + "https://example.com:8443/api?x=1", + "https://example.com:8443/foo:bar", + "https://example.com:8443/other.example.com/x", + ) + assert http_calls[5].startswith("https://example.com:8443/") + + +def test_probe_ipv6_target_url_construction() -> None: + """Verify IPv6 probe targets build bracketed URLs.""" + collected: list[Any] = [] + with ( + patch("devops_cli.sandbox.probe.probe_tcp"), + patch("devops_cli.sandbox.probe.probe_http") as mock_http, + patch("devops_cli.sandbox.probe.probe_openapi", return_value=[]) as mock_openapi, + ): + origin_v6 = _parse_target_endpoint("[2001:db8::1]:8080") + _dispatch_probes_for_port( + origin=origin_v6, + protocols=[ProbeProtocol.HTTP, ProbeProtocol.OPENAPI], + http_paths=["health"], + expected_statuses=None, + regex=None, + timeout=5.0, + latency_budget_ms=None, + collector=collected, + ) + + assert ( + mock_http.call_args[0][0], + mock_openapi.call_args[0][0], + ) == ( + "http://[2001:db8::1]:8080/health", + "http://[2001:db8::1]:8080", + ) From a9d7fd88e8aa3c2b05dcaf193ce21faea1f13bde Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 9 Oct 2026 11:17:53 -0600 Subject: [PATCH 12/15] feat(ci): shuffled repeat runs of a pull request's changed test files (#852) (#1512) --- .github/workflows/ci.yml | 46 +++ RELEASE_CYCLE.md | 1 + changelog.d/852.md | 5 + docs/CLI_REFERENCE.md | 2 + ...ffled-repeat-runs-of-changed-test-files.md | 52 ++++ docs/cheatsheets/ci_and_quality.md | 1 + docs/commands/ci.md | 2 + pyproject.toml | 5 +- .../devops_cli/libraries/ruff_mypy_pytest.md | 4 +- .../devops_cli/python_packages.md | 1 + src/devops_cli/commands/ci.py | 38 +++ src/devops_cli/config/defaults.py | 2 + src/devops_cli/lang/en/help.py | 9 + src/devops_cli/lang/en/messages.py | 6 + tests/test_ci.py | 4 + tests/test_ci_repeat.py | 265 ++++++++++++++++++ uv.lock | 14 + 17 files changed, 454 insertions(+), 3 deletions(-) create mode 100644 changelog.d/852.md create mode 100644 docs/agent/tasks/task-852-shuffled-repeat-runs-of-changed-test-files.md create mode 100644 tests/test_ci_repeat.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f63c1a89e6..2d36735f1e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -299,3 +299,49 @@ jobs: - name: Report Outdated Dependencies run: uv run devops ci outdated + + # Advisory: reruns the pull request's added or modified test files three times, one run after + # another, each in a shuffled order, to catch tests that depend on the order they run in. + # Shuffling the whole suite waits for thread-leak isolation. + changed-tests: + name: Changed-Test Independence + if: github.event_name == 'pull_request' + runs-on: ubuntu-24.04 # moves to ubuntu-26.04 in #1501 + timeout-minutes: 30 + permissions: + contents: read + + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 0 + + - name: Detect Changed Test Files + id: changed_tests + env: + BASE_REF: ${{ github.base_ref }} + run: | + git fetch --no-tags origin "$BASE_REF" + git diff --name-only --diff-filter=AMR "origin/${BASE_REF}...HEAD" -- ':(glob)tests/**/test_*.py' > "$RUNNER_TEMP/changed-tests.txt" + if [ -s "$RUNNER_TEMP/changed-tests.txt" ]; then + cat "$RUNNER_TEMP/changed-tests.txt" + echo "changed=true" >> "$GITHUB_OUTPUT" + else + echo "No test file changed; skipping." + echo "changed=false" >> "$GITHUB_OUTPUT" + fi + + - name: Set up uv toolchain + if: steps.changed_tests.outputs.changed == 'true' + uses: ./.github/actions/setup-toolchain + with: + cache-suffix: changed-tests + tooling-cache-paths: | + .pytest_cache + + - name: Run Changed Tests in Shuffled Order + if: steps.changed_tests.outputs.changed == 'true' + run: | + readarray -t CHANGED_TESTS < "$RUNNER_TEMP/changed-tests.txt" + uv run devops ci test --repeat 3 -- "${CHANGED_TESTS[@]}" diff --git a/RELEASE_CYCLE.md b/RELEASE_CYCLE.md index be11390247..27e8f8fcf5 100644 --- a/RELEASE_CYCLE.md +++ b/RELEASE_CYCLE.md @@ -205,6 +205,7 @@ uv run devops release prepare X.Y.Z --create-pr - Pytest unit tests and test coverage thresholds - Changed-line coverage against the pull request's base branch (diff-cover, advisory, in the job summary) - Bandit static security scanning + - On pull requests, the advisory **Changed-Test Independence** job: each added or modified test file runs three times, one run after another, each in a shuffled order (`devops ci test --repeat 3`) 2. `ci.yml`'s **Service Image** job builds, smoke-tests and scans the release PR's image without pushing; `release.yml` publishes it after the merge (Step 5). 3. Maintainers review the release diff, changelog, and documentation updates. diff --git a/changelog.d/852.md b/changelog.d/852.md new file mode 100644 index 0000000000..0832023887 --- /dev/null +++ b/changelog.d/852.md @@ -0,0 +1,5 @@ +### Added + +- pytest-randomly 5.0.0 joins the dev dependency group. `addopts` blocks it with `-p no:randomly`, so `pytest`, `devops ci` and every other run keep file order, and `uv run pytest --co -q` collects the same order as before (#852). +- `devops ci test --repeat N --seed S` runs the selected test files N times, one run after another on one process (`-n 0`), each shuffled by pytest-randomly with seeds S to S+N-1. S defaults to a seed derived from HEAD's commit hash. The first failing run stops the command and prints its seed with the command that reproduces it. `--repeat` refuses a run that no test file narrows, since shuffling the whole suite waits for thread-leak isolation (#852). +- The advisory **Changed-Test Independence** pull-request job in `ci.yml` runs `devops ci test --repeat 3` over the pull request's added or modified test files, and skips its toolchain and test steps when no test file changed (#852). diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index 3e0a9be6ac..00476a92bd 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -2401,6 +2401,8 @@ devops ci test [OPTIONS] | `-x` | `boolean` | - | Stop after first failure. | | `-n`, `--numprocesses` | `string` | - | Number of parallel worker processes. | | `--fallback` / `--no-fallback` | `boolean` | `True` | Run the full suite when a changed source has no covering tests, rather than reporting success without verifying it. | +| `--repeat` | `integer` | `0` | Run the selected test files N times, one run after another on one process (-n is ignored), each in a shuffled order, with seeds counting up from --seed. 0 runs them once in file order. Refuses the whole suite. | +| `--seed` | `integer` | - | First shuffle seed for --repeat. Defaults to one derived from HEAD's commit hash; has no effect without --repeat. | | `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. | ### `devops ci coverage` diff --git a/docs/agent/tasks/task-852-shuffled-repeat-runs-of-changed-test-files.md b/docs/agent/tasks/task-852-shuffled-repeat-runs-of-changed-test-files.md new file mode 100644 index 0000000000..8978ff66b2 --- /dev/null +++ b/docs/agent/tasks/task-852-shuffled-repeat-runs-of-changed-test-files.md @@ -0,0 +1,52 @@ +# Task: Shuffled repeat runs of a pull request's changed test files (#852) + +**Issue**: [#852](https://github.com/dan-petty/devops-cli/issues/852) +**Status**: Done +**Milestone**: `v0.2.32` +**Priority**: `priority/p2-medium` +**Scope**: `type/feature`, `scope/cli`, `scope/ci`, `priority/p2-medium` + +## Description + +AGENTS.md sets zero tolerance for flaky tests, but nothing reordered or repeated a test, so a test that passes only after another one stayed hidden until xdist's load scheduling put the two in a different order. This item makes order dependence visible where it is cheap to find: in the test files a pull request adds or changes. + +- **pytest-randomly 5.0.0** (pytest-dev) joins the dev group. `addopts` blocks it with `-p no:randomly`, so `pytest`, `devops ci` and the gate keep file order. A `-p randomly` on the command line comes after `addopts` and turns it back on. +- **`devops ci test --repeat N --seed S`** runs the selected test files N times, one run after another, each as `uv run pytest -n 0 [-v] [-k K] [-x] -p randomly --randomly-seed= `. S defaults to HEAD's commit hash, its first eight hex digits read as an integer (`git rev-parse HEAD`). The first failing run stops the command, which prints `Run i/N failed with seed S+i` and the command that reproduces it. pytest-randomly prints `Using --randomly-seed=` at the top of every run. `-n` is ignored, since the runs are serial. The default N, `DEFAULT_CI_TEST_REPEAT_RUNS` in `config/defaults.py`, is 0: a single run in file order. +- **The Changed-Test Independence job** in `ci.yml` runs on `pull_request` only, with `contents: read` and no `needs`. It lists the added, modified and renamed test files against the base branch (`git diff --name-only --diff-filter=AMR "origin/${BASE_REF}...HEAD" -- ':(glob)tests/**/test_*.py'`), then runs `uv run devops ci test --repeat 3 -- `. When no test file changed, its toolchain and test steps are skipped. The job is advisory: the rulesets require only Static Analysis and Tests & Coverage (ADR 0004). + +The code is two helpers next to `_build_test_cmd` in `commands/ci.py`, `_head_seed` and `_run_shuffled_repeats`. Both reach git and pytest through `run_subprocess`, the seam the existing `ci test` tests double. + +## Acceptance Criteria + +- [x] A pytester project with two tests that share module state passes in plain order and fails under a seed that reverses them, and the output prints that seed. `test_repeat_stops_at_the_seed_that_breaks_order_dependent_tests` (`tests/test_ci_repeat.py`) runs `devops ci test --repeat 3 --seed 2 tests/test_shared.py` with each run going to an in-process `pytester.runpytest`. Seed 2 keeps file order and passes; seed 3 reverses it and fails; seed 4 never runs. The output holds `Run 2/3 failed with seed 3` and `uv run pytest -n 0 -p randomly --randomly-seed=3 tests/test_shared.py`. The inner project blocks randomly in its own `addopts`, as the repository does, so the test also shows `-p randomly` overriding the block. +- [x] The argv of every repeat run is asserted, and the full-gate argv has no randomly option. `test_each_repeat_runs_the_targets_serially_with_the_next_seed` asserts the three argvs and their working directory for `--repeat 3 --seed 10 -n 4 -v -k unit -x -- tests/test_x.py`. `test_the_gate_and_a_plain_run_stay_in_file_order` asserts that no `get_check_specs()` command and no run without `--repeat` names randomly, and that the default is 0. +- [x] With the plugin installed, `uv run pytest --co -q` gives the same collection order as before. On this branch's base, 10,277 tests collected; with the change, 10,288. After removing the 11 additions (the 10 tests of `tests/test_ci_repeat.py` and this task file's own check in `tests/test_agent_task_files.py`), the two lists are identical (`diff` prints nothing). `test_pytest_randomly_is_installed_and_blocked_by_default` pins the pin and the block. +- [x] The job is skipped when no test file changed: the detect step writes `changed=false`, and the toolchain and test steps run only `if: steps.changed_tests.outputs.changed == 'true'`. `test_the_changed_test_job_reruns_added_or_modified_test_files` pins the job's trigger, permissions, diff filter, pathspec, step conditions, cache inputs and command, and that no run script expands `${{ }}`. +- [x] The unit tests take at most 1 s: measured at 0.65 s to 0.89 s call duration in total on one worker (`uv run pytest -n 0 --durations=0 tests/test_ci_repeat.py`) in six of seven runs, at load average 12 to 15 on 16 cores; the seventh, during a burst of other worktrees' suites on the same host, measured 1.58 s. The pytester test is 0.39 s to 0.46 s of the total, and each CLI case 0.03 s to 0.06 s. The module builds the `ci` command group once, as `tests/test_k8s_run_job.py` does, rather than Typer rebuilding it on every invoke; before that, the same command measured 0.90 s to 0.96 s. +- [x] Without paths, or when a trigger file such as `tests/conftest.py` sends the run to the whole suite, `--repeat` exits 1 and starts nothing (`test_repeat_refuses_to_shuffle_the_whole_suite`). When HEAD cannot be read it exits 1, names `--seed` and starts no test run (`test_an_unreadable_head_asks_for_a_seed`). The HEAD seed is `int("deadbeef", 16)` for HEAD `deadbeef…` (`test_the_first_seed_defaults_to_heads_commit_hash`). `--dry-run` plans every run and starts no process (`test_a_dry_run_plans_every_repeat_and_starts_no_process`). +- Pending a person: on the pull request that delivers this item, which changes `tests/test_ci.py` and `tests/test_ci_repeat.py`, `uv run devops pr checks ` lists **Changed-Test Independence**. With the run ID from `uv run devops gh runs list --branch feat/852-shuffled-repeat-changed-test-files`, `uv run devops gh runs view --log | grep '^Changed-Test Independence' | grep -E 'tests/test_ci(_repeat)?\.py$|Using --randomly-seed='` prints both file names from the **Detect Changed Test Files** step and three `Using --randomly-seed=` lines whose values are consecutive. +- Pending a person: on the first pull request into `release/v0.2.32` that changes no test file, `uv run devops gh runs view --log | grep '^Changed-Test Independence'`, with the run ID from `uv run devops gh runs list --branch `, prints "No test file changed; skipping." and no line from the **Set up uv toolchain** or **Run Changed Tests in Shuffled Order** steps, which the run's summary page shows as skipped. + +## Decisions and Interpretations + +- **"Skipped" is a step-level skip.** The job always starts and runs its checkout and detect steps, then skips the toolchain and test steps, as the DevContainer Image and Service Image jobs do. A workflow-level `paths` filter would skip every job in `ci.yml`. +- **The default N is 0, meaning off.** `ci.yml` passes `--repeat 3`; a person passes any N. +- **The whole suite is refused.** `--repeat` needs test files to narrow the run, so a run with no paths, or one a trigger file widens to the whole suite, exits 1 with "--repeat needs test files to narrow the run". Shuffling the whole suite waits for per-test thread-leak isolation, as the issue's constraint says. +- **`--repeat` shuffles what `ci test` selects.** It takes the issue's "selected targets" literally and uses `ci test`'s own selection, coverage-index drift included. Locally, with a built coverage index, the run also takes the tests covering every file changed since the index was built. If a trigger file (`conftest.py`, `pyproject.toml`, `uv.lock` or `.python-version`) has drifted, the selection widens to the whole suite and `--repeat` refuses, even with test files named, until `devops ci coverage --build-index` runs again; the trigger warning printed first says which file. CI has no index, so the job shuffles exactly the changed test files. Shuffling only the named files would need a second selection path, which is a re-scope for the owner, not part of this item. +- **A pull request that changes many test files** runs each three times, one run after another; the job's `timeout-minutes: 30` bounds it, and it is not a required check. No cap was added. +- **`--seed` without `--repeat` does nothing.** Its help says so, rather than a guard refusing it. +- **`--dry-run` reads HEAD.** Without `--seed`, a dry run still runs `git rev-parse HEAD`, a local read, so the planned commands carry the real seeds; each repeat run prints as its own one-step plan. +- **The job's toolchain caches `.pytest_cache` under its own `changed-tests` key.** The default paths, `.mypy_cache` and `.ruff_cache`, do not exist in this job, and actions/cache would warn about them on every run. +- **The pytester test loads only the plugins it needs.** It sets `PYTEST_DISABLE_PLUGIN_AUTOLOAD=1` and loads xdist with `-p xdist`: autoloading every installed plugin cost seconds and raised pytest-asyncio's unset-loop-scope deprecation warning. Its inner `addopts` adds `--tb=no`, since formatting the failing run's traceback scanned every module the test process had imported (about 1 s). pytest-randomly 5.0.0 orders tests by `crc32(f"{seed}::{nodeid}")`; for `tests/test_shared.py`, seed 2 keeps the order and seed 3 reverses it, so a change of pin or path means re-checking the seeds. +- **The pytester test puts the global RNGs back.** pytest-randomly reseeds the global `random` and numpy RNGs in the process it runs in, and pytester restores `sys.modules`, not RNG state, so the `global_rngs_restored` fixture saves both states before the test and restores them after it. Without it, every later test on that worker would start from a fixed seed. Running the inner runs in a subprocess instead would not fit the 1 s budget. + +## Deliverables + +- [x] `pyproject.toml` and `uv.lock`: `pytest-randomly==5.0.0` in the dev group; `-p no:randomly` in `addopts`. +- [x] `src/devops_cli/commands/ci.py`: `--repeat` and `--seed` on `devops ci test`, `_head_seed` and `_run_shuffled_repeats`. +- [x] `src/devops_cli/config/defaults.py`: `DEFAULT_CI_TEST_REPEAT_RUNS = 0`. +- [x] `src/devops_cli/lang/en/help.py` and `messages.py`: the two options' help and the `repeat_failed`, `repeat_needs_targets` and `repeat_seed_unavailable` messages. +- [x] `.github/workflows/ci.yml`: the Changed-Test Independence job. +- [x] `tests/test_ci_repeat.py`; `tests/test_ci.py`'s workflow parity allowlist names the job's detect step. +- [x] `docs/commands/ci.md` and `docs/CLI_REFERENCE.md` (generated), `RELEASE_CYCLE.md` Step 3, `docs/cheatsheets/ci_and_quality.md`, and the knowledge-base pages `python_packages.md` and `libraries/ruff_mypy_pytest.md`. +- [x] `changelog.d/852.md`. diff --git a/docs/cheatsheets/ci_and_quality.md b/docs/cheatsheets/ci_and_quality.md index 386abdfce8..cc94d94c2f 100644 --- a/docs/cheatsheets/ci_and_quality.md +++ b/docs/cheatsheets/ci_and_quality.md @@ -13,6 +13,7 @@ Compare disparate linters, formatters, type checkers, and test runners with the | **Lint Codebase** | `ruff check . --fix` | `devops ci lint [--fix]` | Validates and auto-fixes lint errors, import ordering, and modernization rules. | | **Strict Type Checking** | `mypy src --strict` | `devops ci typecheck` | Runs Mypy strict type checking across all packages. | | **Unit & Integration Tests**| `pytest -n auto --maxprocesses=8` | `devops ci test` | Executes parallel pytest suite with auto-configured process pooling. | +| **Order-Dependence Check** | `pytest -n 0 -p randomly --randomly-seed=S `, N times | `devops ci test --repeat N [--seed S] ` | Runs the files N times, one run after another, each shuffled with the next seed (S from HEAD by default), and prints the failing seed with a reproduction command. | | **Coverage Measurement** | `pytest --cov=src --cov-report=html` | `devops ci coverage [--html]` | Computes coverage percentages and generates interactive HTML coverage reports in `.data/coverage/`. | | **GitHub Actions Linting** | `actionlint .github/workflows/*.yml` | `devops ci actionlint` | Validates YAML syntax, context expressions, and security permissions in GitHub Actions workflows. | | **Doc Freshness Check** | `python tools/check_docs.py` | `devops ci docs` | Asserts that CLI command reference and README command matrix match live Typer definitions. | diff --git a/docs/commands/ci.md b/docs/commands/ci.md index 061e833944..b031a7fea3 100644 --- a/docs/commands/ci.md +++ b/docs/commands/ci.md @@ -32,6 +32,8 @@ devops ci test [OPTIONS] | `-x` | `boolean` | - | Stop after first failure. | | `-n`, `--numprocesses` | `string` | - | Number of parallel worker processes. | | `--fallback` / `--no-fallback` | `boolean` | `True` | Run the full suite when a changed source has no covering tests, rather than reporting success without verifying it. | +| `--repeat` | `integer` | `0` | Run the selected test files N times, one run after another on one process (-n is ignored), each in a shuffled order, with seeds counting up from --seed. 0 runs them once in file order. Refuses the whole suite. | +| `--seed` | `integer` | - | First shuffle seed for --repeat. Defaults to one derived from HEAD's commit hash; has no effect without --repeat. | | `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. | --- diff --git a/pyproject.toml b/pyproject.toml index f660fd2b43..ec0eaf6592 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -85,6 +85,7 @@ dev = [ "pytest-cov==7.1.0", "diff-cover==10.6.0", "pytest-xdist==3.8.0", + "pytest-randomly==5.0.0", "bandit==1.9.4", "actionlint-py==1.7.12.25", "pre-commit==4.6.2", @@ -147,7 +148,9 @@ asyncio_mode = "auto" testpaths = ["tests"] pythonpath = ["src"] # Pytest workers: logical cores (ext4 benchmark: 8 workers ~4.2s vs 4 workers ~6.8s) -addopts = "-n logical -p no:logfire -p no:pytest_logfire" +# pytest-randomly is installed for `devops ci test --repeat` and blocked here (-p no:randomly), +# so every other run keeps file order. +addopts = "-n logical -p no:logfire -p no:pytest_logfire -p no:randomly" markers = [ "bwrap: live sandbox tests requiring bubblewrap; skipped where bwrap is not installed", ] diff --git a/src/devops_cli/ai/knowledge_base/devops_cli/libraries/ruff_mypy_pytest.md b/src/devops_cli/ai/knowledge_base/devops_cli/libraries/ruff_mypy_pytest.md index 4543d8bf7f..e154d24bfb 100644 --- a/src/devops_cli/ai/knowledge_base/devops_cli/libraries/ruff_mypy_pytest.md +++ b/src/devops_cli/ai/knowledge_base/devops_cli/libraries/ruff_mypy_pytest.md @@ -6,7 +6,7 @@ | :--- | :--- | | **Official Documentation** | [docs.astral.sh/ruff/](https://docs.astral.sh/ruff/) • [mypy.readthedocs.io](https://mypy.readthedocs.io/) • [docs.pytest.org](https://docs.pytest.org/) | | **Public Git Repository** | [github.com/astral-sh/ruff](https://github.com/astral-sh/ruff) • [github.com/python/mypy](https://github.com/python/mypy) • [github.com/pytest-dev/pytest](https://github.com/pytest-dev/pytest) | -| **Official PyPI Packages** | `ruff==0.16.8`, `mypy==2.3.1`, `pytest==9.1.1`, `pytest-cov==7.1.0`, `pytest-xdist==3.8.0`, `pytest-asyncio==1.4.0`, `pytest-mock==3.16.0` | +| **Official PyPI Packages** | `ruff==0.16.8`, `mypy==2.3.1`, `pytest==9.1.1`, `pytest-cov==7.1.0`, `pytest-xdist==3.8.0`, `pytest-asyncio==1.4.0`, `pytest-mock==3.16.0`, `pytest-randomly==5.0.0` | | **DevOps CLI Integration** | [`src/devops_cli/commands/ci.py`](../../../../../../src/devops_cli/commands/ci.py) • [`pyproject.toml`](../../../../../../pyproject.toml) | --- @@ -16,7 +16,7 @@ **Ruff**, **Mypy**, and **Pytest** form the foundational three-pillar quality assurance suite powering the `devops ci` quality gate. - **Ruff**: An extremely fast Python linter and formatter written in Rust that replaces Flake8, Black, isort, and pyupgrade, running 10x–100x faster than traditional tools. - **Mypy**: The static type checker validating 100% strict type safety across all function signatures with `mypy --strict`. -- **Pytest**: The industry-standard testing framework combined with `pytest-xdist` (multi-core parallel testing), `pytest-cov` ($\ge 90\%$ coverage enforcement), `pytest-asyncio`, and `pytest-mock`. +- **Pytest**: The industry-standard testing framework combined with `pytest-xdist` (multi-core parallel testing), `pytest-cov` ($\ge 90\%$ coverage enforcement), `pytest-asyncio`, `pytest-mock`, and `pytest-randomly` (shuffled repeat runs through `devops ci test --repeat`, blocked in every other run). --- diff --git a/src/devops_cli/ai/knowledge_base/devops_cli/python_packages.md b/src/devops_cli/ai/knowledge_base/devops_cli/python_packages.md index 3bb9c2acc2..7aa456d0aa 100644 --- a/src/devops_cli/ai/knowledge_base/devops_cli/python_packages.md +++ b/src/devops_cli/ai/knowledge_base/devops_cli/python_packages.md @@ -254,6 +254,7 @@ The development environment leverages modern Python engineering tools managed vi | **`pytest-mock`** | `3.16.0` | Thin wrapper around standard library `unittest.mock` for clean fixture patching. | Included in pytest suite | | **`pytest-cov`** | `7.1.0` | Code coverage measurement enforcing strict $\ge 90\%$ minimum threshold project-wide. | `uv run pytest --cov=src` | | **`pytest-xdist`** | `3.8.0` | Multi-core parallel test execution distribution across worker subprocesses. | `uv run pytest -n auto` | +| **`pytest-randomly`** | `5.0.0` | Shuffles test order and reseeds `random` for each test; blocked in `addopts` (`-p no:randomly`) and enabled only by `devops ci test --repeat`. | `uv run devops ci test --repeat 3 ` | | **`bandit`** | `1.9.4` | AST-based Python security analyzer detecting insecure patterns (CWE checks). | `uv run bandit -r src/` | | **`actionlint-py`** | `1.7.12.25` | GitHub Actions workflow syntax and expression validation engine. | `uv run actionlint` | | **`pre-commit`** | `4.6.2` | Multi-hook manager orchestrating git commit quality gates. | `uv run pre-commit run --all-files` | diff --git a/src/devops_cli/commands/ci.py b/src/devops_cli/commands/ci.py index 402fddc74e..ac0028fe76 100644 --- a/src/devops_cli/commands/ci.py +++ b/src/devops_cli/commands/ci.py @@ -25,6 +25,7 @@ ) from devops_cli.config.defaults import ( DEFAULT_BANDIT_SEVERITY, + DEFAULT_CI_TEST_REPEAT_RUNS, DEFAULT_PYTHON_VERSION, DEFAULT_SUBPROCESS_TIMEOUT_SECONDS, ) @@ -1363,6 +1364,35 @@ def _build_test_cmd( return cmd +def _head_seed(root: Path) -> int: + """A shuffle seed derived from HEAD: its commit hash's leading eight hex digits.""" + result = _get("run_subprocess")(["git", "rev-parse", "HEAD"], cwd=root, quiet=True) + if result.returncode != 0: + _get("print_error")(MESSAGES.ci.repeat_seed_unavailable, prefix=False) + raise typer.Exit(1) + return int(result.stdout[:8], 16) + + +def _run_shuffled_repeats( + base_cmd: list[str], targets: list[str] | None, runs: int, seed: int | None +) -> None: + """Run the targets `runs` times, one run after another, shuffled by pytest-randomly with + seeds `seed` to `seed + runs - 1`, stopping at the first failure with its seed and command. + """ + if targets is None: + _get("print_error")(MESSAGES.ci.repeat_needs_targets, prefix=False) + raise typer.Exit(1) + first = _head_seed(_get_project_root()) if seed is None else seed + for run, run_seed in enumerate(range(first, first + runs), start=1): + cmd = [*base_cmd, "-p", "randomly", f"--randomly-seed={run_seed}", *targets] + if not _run(cmd): + failed = MESSAGES.ci.repeat_failed.format( + run=run, runs=runs, seed=run_seed, command=shlex.join(cmd) + ) + _get("print_error")(failed, prefix=False, safe=True) + raise typer.Exit(1) + + @app.command() def test( paths: Annotated[list[Path] | None, typer.Argument(help=HELP.ci.test_paths)] = None, @@ -1375,6 +1405,10 @@ def test( fallback: Annotated[ bool, typer.Option("--fallback/--no-fallback", help=HELP.ci.selection_fallback) ] = True, + repeat: Annotated[ + int, typer.Option("--repeat", min=0, help=HELP.ci.repeat) + ] = DEFAULT_CI_TEST_REPEAT_RUNS, + seed: Annotated[int | None, typer.Option("--seed", help=HELP.ci.seed)] = None, dry_run: Annotated[ bool, typer.Option("--dry-run", help=HELP.options.dry_run), @@ -1400,6 +1434,10 @@ def test( _get("print_error")("Invalid keyword filter expression.", prefix=False) raise typer.Exit(1) + if repeat: + _run_shuffled_repeats(_build_test_cmd("0", verbose, k, x, None), targets, repeat, seed) + return + cmd = _build_test_cmd(numprocesses, verbose, k, x, targets) if not _run(cmd): raise typer.Exit(1) diff --git a/src/devops_cli/config/defaults.py b/src/devops_cli/config/defaults.py index 62790fd26c..2dbc23267d 100644 --- a/src/devops_cli/config/defaults.py +++ b/src/devops_cli/config/defaults.py @@ -448,6 +448,8 @@ DEFAULT_REVIEW_RATE_CAPACITY: float = 10.0 DEFAULT_INVALIDATED_STATUS: str = "INVALIDATED" DEFAULT_BANDIT_SEVERITY: str = "medium" +# `devops ci test --repeat`: 0 is a single run in file order; ci.yml's pull-request job passes 3. +DEFAULT_CI_TEST_REPEAT_RUNS: Final[int] = 0 DEFAULT_TRIVY_HIGH_SEVERITY: str = "HIGH,CRITICAL" DEFAULT_KUBECONFORM_VERSION: str = "master" DEFAULT_PACKAGE_ECOSYSTEM: str = "PyPI" diff --git a/src/devops_cli/lang/en/help.py b/src/devops_cli/lang/en/help.py index f1be70e483..26d6900ead 100644 --- a/src/devops_cli/lang/en/help.py +++ b/src/devops_cli/lang/en/help.py @@ -578,6 +578,15 @@ class CICommandHelp: "Run the full suite when a changed source has no covering tests, rather than " "reporting success without verifying it." ) + repeat: str = ( + "Run the selected test files N times, one run after another on one process (-n is " + "ignored), each in a shuffled order, with seeds counting up from --seed. 0 runs them " + "once in file order. Refuses the whole suite." + ) + seed: str = ( + "First shuffle seed for --repeat. Defaults to one derived from HEAD's commit hash; " + "has no effect without --repeat." + ) html_report: str = "Generate HTML coverage report in .data/htmlcov/." build_index: str = "Build on-demand coverage reverse index for fast test selection." auto_fix: str = "Auto-fix violations where possible." diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py index 98f4bf15ed..a54f166875 100644 --- a/src/devops_cli/lang/en/messages.py +++ b/src/devops_cli/lang/en/messages.py @@ -851,6 +851,12 @@ class CIMessages: "Refusing to report success without running any tests. Re-run with --fallback " "to verify via the full suite, or add a covering test." ) + repeat_failed: str = "Run {run}/{runs} failed with seed {seed}. Reproduce it with: {command}" + repeat_needs_targets: str = ( + "--repeat needs test files to narrow the run; shuffling the whole suite is not " + "supported yet." + ) + repeat_seed_unavailable: str = "Could not read HEAD to derive a shuffle seed; pass --seed." pytest_coverage: str = "pytest & coverage" ruff_check: str = "ruff check" ruff_format: str = "ruff format" diff --git a/tests/test_ci.py b/tests/test_ci.py index a4a2a3ecee..759eb041df 100644 --- a/tests/test_ci.py +++ b/tests/test_ci.py @@ -1963,6 +1963,10 @@ def _validate_ci_workflow_parity(workflow_data: dict[str, Any]) -> None: "test", "Changed-Line Coverage", ): "Advisory diff-cover report in the job summary, never a check table row", + ( + "changed-tests", + "Detect Changed Test Files", + ): "Git diff to list the pull request's changed test files", } all_specs = get_check_specs() diff --git a/tests/test_ci_repeat.py b/tests/test_ci_repeat.py new file mode 100644 index 0000000000..11bed99c08 --- /dev/null +++ b/tests/test_ci_repeat.py @@ -0,0 +1,265 @@ +"""Tests for `devops ci test --repeat`: shuffled, serial repeat runs of selected test files.""" + +from __future__ import annotations + +import random +import shlex +import subprocess +import tomllib +from collections.abc import Iterator +from itertools import pairwise +from pathlib import Path +from typing import Any +from unittest.mock import patch + +import pytest +import typer +import yaml +from click.testing import CliRunner, Result +from numpy import random as np_random + +from devops_cli.commands import ci as ci_module +from devops_cli.commands.ci import get_check_specs +from devops_cli.config.defaults import DEFAULT_CI_TEST_REPEAT_RUNS +from devops_cli.lang import MESSAGES + +pytest_plugins = ("pytester",) + +# Typer builds the `ci` group from its functions' signatures on every invoke; building it once +# keeps each CLI case to the command's own run. +CI = typer.main.get_command(ci_module.app) +runner = CliRunner() +REPO_ROOT = Path(__file__).resolve().parents[1] +UV_RUN_PYTEST = ["uv", "--preview-features", "malware-check,check-command", "run", "pytest"] +HEAD = (0, "deadbeef" + 32 * "0" + "\n") + +SHARED_STATE_TESTS = """ +SEEN: list[str] = [] + + +def test_first() -> None: + SEEN.append("first") + + +def test_second() -> None: + assert SEEN == ["first"] +""" + + +def _flat(output: str) -> str: + """The output with each run of whitespace, line wraps included, collapsed to one space.""" + return " ".join(output.split()) + + +def _invoke(*args: str, head: tuple[int, str] = HEAD) -> tuple[Result, list[tuple[list[str], Any]]]: + """Run `devops ci test` with every process it starts recorded, answering `git rev-parse`.""" + calls: list[tuple[list[str], Any]] = [] + + def record(cmd: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]: + calls.append((cmd, kwargs.get("cwd"))) + code, stdout = head if cmd[:2] == ["git", "rev-parse"] else (0, "") + return subprocess.CompletedProcess(cmd, code, stdout, "") + + with patch.object(ci_module, "run_subprocess", record): + result = runner.invoke(CI, ["test", *args]) + return result, calls + + +@pytest.fixture +def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """A checked tree holding one test file, as the root the CI command verifies.""" + (tmp_path / "tests").mkdir() + (tmp_path / "tests" / "test_x.py").write_text("def test_x() -> None: ...\n", encoding="utf-8") + monkeypatch.setattr(ci_module, "_get_project_root", lambda: tmp_path) + return tmp_path + + +@pytest.fixture +def global_rngs_restored() -> Iterator[None]: + """Put back the global `random` and numpy RNG states, which pytest-randomly reseeds when it + runs in this process, so the tests this worker runs next do not start from a fixed seed.""" + state, numpy_state = random.getstate(), np_random.get_state() + yield + random.setstate(state) + np_random.set_state(numpy_state) + + +@pytest.mark.usefixtures("global_rngs_restored") +def test_repeat_stops_at_the_seed_that_breaks_order_dependent_tests( + pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch +) -> None: + """Two tests sharing module state pass in file order and fail under a reversing seed; the + repeat stops at that run and prints its seed with the command that reproduces it.""" + # pytest-randomly 5.0.0 orders tests by crc32(f"{seed}::{nodeid}"). For these nodeids, seed 2 + # keeps file order and seed 3 reverses it; re-check the seeds if the pin or the path changes. + # The inner runs load only xdist and, through -p randomly, pytest-randomly: autoloading every + # installed plugin costs seconds and warns about pytest-asyncio's unset loop scope. --tb=no + # skips the failure's source lookup, which scans this process's every imported module. + monkeypatch.setenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "1") + pytester.makepyprojecttoml( + "[tool.pytest.ini_options]\n" + 'addopts = "-p xdist -p no:randomly -p no:logfire -p no:pytest_logfire --tb=no"\n' + ) + pytester.mkdir("tests") + (pytester.path / "tests" / "test_shared.py").write_text(SHARED_STATE_TESTS, encoding="utf-8") + monkeypatch.setattr(ci_module, "_get_project_root", lambda: pytester.path) + plain = pytester.runpytest("-n", "0", "tests/test_shared.py") + seeds: list[str] = [] + + def run_inner_pytest(cmd: list[str], **_kwargs: Any) -> subprocess.CompletedProcess[str]: + argv = cmd[cmd.index("pytest") + 1 :] + seeds.extend(arg for arg in argv if arg.startswith("--randomly-seed=")) + return subprocess.CompletedProcess(cmd, int(pytester.runpytest(*argv).ret)) + + with patch.object(ci_module, "run_subprocess", run_inner_pytest): + result = runner.invoke(CI, ["test", "--repeat", "3", "--seed", "2", "tests/test_shared.py"]) + + reproduce = "uv run pytest -n 0 -p randomly --randomly-seed=3 tests/test_shared.py" + failure = MESSAGES.ci.repeat_failed.format(run=2, runs=3, seed=3, command=reproduce) + assert ( + plain.parseoutcomes(), + result.exit_code, + seeds, + failure in _flat(result.output), + ) == ({"passed": 2}, 1, ["--randomly-seed=2", "--randomly-seed=3"], True) + + +def test_each_repeat_runs_the_targets_serially_with_the_next_seed(project: Path) -> None: + """Run i of N runs the targets in the project root on one process (-n gives way to -n 0) + with seed S+i, keeping -v, -k and -x ahead of the shuffle options.""" + result, calls = _invoke(*"--repeat 3 --seed 10 -n 4 -v -k unit -x -- tests/test_x.py".split()) + + assert (result.exit_code, calls) == ( + 0, + [ + ( + [*UV_RUN_PYTEST, "-n", "0", "-v", "-k", "unit", "-x", "-p", "randomly"] + + [f"--randomly-seed={seed}", "tests/test_x.py"], + project, + ) + for seed in (10, 11, 12) + ], + ) + + +def test_the_first_seed_defaults_to_heads_commit_hash(project: Path) -> None: + """Without --seed, the first seed is HEAD's leading eight hex digits read as an integer.""" + result, calls = _invoke("--repeat", "2", "tests/test_x.py") + + assert (result.exit_code, calls[0], [cmd[-2] for cmd, _cwd in calls[1:]]) == ( + 0, + (["git", "rev-parse", "HEAD"], project), + ["--randomly-seed=3735928559", "--randomly-seed=3735928560"], + ) + + +def test_an_unreadable_head_asks_for_a_seed(project: Path) -> None: + """When HEAD cannot be read, the command names --seed and runs no tests.""" + result, calls = _invoke("--repeat", "2", "tests/test_x.py", head=(128, "")) + + assert ( + result.exit_code, + [cmd for cmd, _cwd in calls], + MESSAGES.ci.repeat_seed_unavailable in _flat(result.output), + "--seed" in MESSAGES.ci.repeat_seed_unavailable, + ) == (1, [["git", "rev-parse", "HEAD"]], True, True) + + +def test_the_gate_and_a_plain_run_stay_in_file_order(project: Path) -> None: + """No gate check and no run without --repeat enables pytest-randomly; --repeat is off by + default.""" + result, calls = _invoke("tests/test_x.py") + + assert ( + [spec.name for spec in get_check_specs() if "randomly" in shlex.join(spec.cmd)], + result.exit_code, + [cmd for cmd, _cwd in calls], + DEFAULT_CI_TEST_REPEAT_RUNS, + ) == ([], 0, [[*UV_RUN_PYTEST, "tests/test_x.py"]], 0) + + +@pytest.mark.parametrize("paths", [(), ("tests/conftest.py",)], ids=["no-paths", "trigger-file"]) +def test_repeat_refuses_to_shuffle_the_whole_suite(project: Path, paths: tuple[str, ...]) -> None: + """When nothing narrows the run to test files, --repeat exits 1 and starts no process.""" + (project / "tests" / "conftest.py").write_text("", encoding="utf-8") + + result, calls = _invoke("--repeat", "2", *paths) + + assert ( + result.exit_code, + calls, + MESSAGES.ci.repeat_needs_targets in _flat(result.output), + ) == (1, [], True) + + +def test_pytest_randomly_is_installed_and_blocked_by_default() -> None: + """The dev group pins pytest-randomly and addopts blocks it, so ordinary runs keep file order.""" + pyproject = tomllib.loads((REPO_ROOT / "pyproject.toml").read_text(encoding="utf-8")) + addopts = shlex.split(pyproject["tool"]["pytest"]["ini_options"]["addopts"]) + + assert ( + ("-p", "no:randomly") in pairwise(addopts), + "pytest-randomly==5.0.0" in pyproject["dependency-groups"]["dev"], + ) == (True, True) + + +def test_the_changed_test_job_reruns_added_or_modified_test_files() -> None: + """ci.yml's advisory pull-request job lists changed test files and repeats them shuffled, + skipping its toolchain and run steps when no test file changed.""" + workflow = yaml.safe_load( + (REPO_ROOT / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8") + ) + job = workflow["jobs"]["changed-tests"] + steps = {step["name"]: step for step in job["steps"]} + detect = steps["Detect Changed Test Files"] + toolchain = steps["Set up uv toolchain"] + rerun = steps["Run Changed Tests in Shuffled Order"] + changed = "steps.changed_tests.outputs.changed == 'true'" + + assert ( + (job["name"], job["if"], job["permissions"], "needs" in job), + (detect["id"], detect["env"]["BASE_REF"]), + ("--diff-filter=AMR" in detect["run"], ":(glob)tests/**/test_*.py" in detect["run"]), + (toolchain.get("if"), rerun.get("if")), + (toolchain["with"]["cache-suffix"], toolchain["with"]["tooling-cache-paths"].split()), + "devops ci test --repeat 3" in rerun["run"], + [step["name"] for step in job["steps"] if "${{" in step.get("run", "")], + ) == ( + ( + "Changed-Test Independence", + "github.event_name == 'pull_request'", + {"contents": "read"}, + False, + ), + ("changed_tests", "${{ github.base_ref }}"), + (True, True), + (changed, changed), + ("changed-tests", [".pytest_cache"]), + True, + [], + ) + + +def test_a_dry_run_plans_every_repeat_and_starts_no_process( + project: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """--dry-run prints the planned command of each repeat run and runs none of them.""" + started: list[list[str]] = [] + + def record(cmd: list[str], *_args: Any, **_kwargs: Any) -> subprocess.CompletedProcess[str]: + started.append(list(cmd)) + return subprocess.CompletedProcess(cmd, 0, "", "") + + monkeypatch.setattr("subprocess.run", record) + + result = runner.invoke( + CI, ["test", "--repeat", "2", "--seed", "7", "--dry-run", "tests/test_x.py"] + ) + + planned = "uv --preview-features malware-check,check-command run pytest -n 0 -p randomly" + assert ( + result.exit_code, + started, + f"{planned} --randomly-seed=7 tests/test_x.py" in _flat(result.output), + f"{planned} --randomly-seed=8 tests/test_x.py" in _flat(result.output), + ) == (0, [], True, True) diff --git a/uv.lock b/uv.lock index e06d4d2419..9772659075 100644 --- a/uv.lock +++ b/uv.lock @@ -794,6 +794,7 @@ dev = [ { name = "pytest-asyncio" }, { name = "pytest-cov" }, { name = "pytest-mock" }, + { name = "pytest-randomly" }, { name = "pytest-xdist" }, { name = "ruff" }, { name = "types-pyyaml" }, @@ -877,6 +878,7 @@ dev = [ { name = "pytest-asyncio", specifier = "==1.4.0" }, { name = "pytest-cov", specifier = "==7.1.0" }, { name = "pytest-mock", specifier = "==3.16.0" }, + { name = "pytest-randomly", specifier = "==5.0.0" }, { name = "pytest-xdist", specifier = "==3.8.0" }, { name = "ruff", specifier = "==0.16.8" }, { name = "types-pyyaml", specifier = "==6.0.12.20260906" }, @@ -2933,6 +2935,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/db/5b/b83a9bf1a3b4ec222f9fa083147ff6816245223da0ab92370e7e056f113f/pytest_mock-3.16.0-py3-none-any.whl", hash = "sha256:007cfeb257801d88d9c0b2a7b5a15a15e73b71968dfd72e7bf8c4a2f8393aec8", size = 10016, upload-time = "2026-09-27T14:57:54.283Z" }, ] +[[package]] +name = "pytest-randomly" +version = "5.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/01/3b/6a40e1b9d925651e601e056a97f60d8a1daeddeac03d5609be60cb4362ce/pytest_randomly-5.0.0.tar.gz", hash = "sha256:e9c575a5873ef168ddbe340ed9e97ce9edb4492ccc821e4b2ac6bb1f0ed515d2", size = 8542, upload-time = "2026-09-01T22:34:20.441Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/b4/47e939285caad9a623d021512912ac08dc92a467ad075d179f43729d2934/pytest_randomly-5.0.0-py3-none-any.whl", hash = "sha256:8a0d4703115c0c25b38b6e129fc16b1947b9643ff26a41bc1d185d7e5a7689c1", size = 8920, upload-time = "2026-09-01T22:34:19.227Z" }, +] + [[package]] name = "pytest-xdist" version = "3.8.0" From ed0baa3f54516fb1f38e08c16d12005c9ee7d854 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 9 Oct 2026 12:27:44 -0600 Subject: [PATCH 13/15] feat(ci): on-demand mutation testing of changed functions (`devops ci mutate`) (#853) (#1513) --- .gitignore | 3 + README.md | 1 + changelog.d/853.md | 3 + docs/CLI_REFERENCE.md | 26 ++ ...d-mutation-testing-of-changed-functions.md | 118 ++++++ docs/cheatsheets/ci_and_quality.md | 1 + docs/commands/ci.md | 28 ++ pyproject.toml | 40 ++ .../devops_cli/cli_command_reference.md | 1 + src/devops_cli/ci/mutate.py | 243 ++++++++++++ src/devops_cli/commands/ci.py | 85 +++- src/devops_cli/config/constants.py | 23 ++ src/devops_cli/config/defaults.py | 4 + src/devops_cli/lang/en/help.py | 19 + src/devops_cli/lang/en/messages.py | 16 + tests/conftest.py | 10 +- tests/test_architectural_invariants.py | 29 ++ tests/test_ci_mutate.py | 370 ++++++++++++++++++ tests/test_ssh.py | 10 +- uv.lock | 114 ++++++ 20 files changed, 1134 insertions(+), 10 deletions(-) create mode 100644 changelog.d/853.md create mode 100644 docs/agent/tasks/task-853-on-demand-mutation-testing-of-changed-functions.md create mode 100644 src/devops_cli/ci/mutate.py create mode 100644 tests/test_ci_mutate.py diff --git a/.gitignore b/.gitignore index e48aed4955..a114d03d86 100644 --- a/.gitignore +++ b/.gitignore @@ -75,6 +75,9 @@ secrets/ .claude/* !.claude/settings.json +# mutmut's copy of the tree, mutated by `devops ci mutate`; `rm -rf mutants` resets it +/mutants/ + # Kilo Code .kilo/ diff --git a/README.md b/README.md index 4e7b1abf0f..8639b80524 100644 --- a/README.md +++ b/README.md @@ -276,6 +276,7 @@ The comprehensive Value vs. Effort Prioritization Matrix, phased milestone deliv | | `devops ci deps [OPTIONS]` | Validate dependency hygiene and imports via deptry. | | | `devops ci maintain [OPTIONS]` | Run automated toolchain, dependency freshness, and lockfile maintenance checks. | | | `devops ci run [OPTIONS]` | Run full CI and return a single pass/fail status. | +| | `devops ci mutate [OPTIONS] ` | Mutation-test functions with mutmut and show each mutant no test killed; never a gate. | | **uv** | `devops uv sync [OPTIONS]` | Sync project dependencies into the virtual environment. | | | `devops uv lock [OPTIONS]` | Regenerate the uv lockfile. | | | `devops uv python-install [OPTIONS]` | Install project Python version with uv. | diff --git a/changelog.d/853.md b/changelog.d/853.md new file mode 100644 index 0000000000..75778785be --- /dev/null +++ b/changelog.d/853.md @@ -0,0 +1,3 @@ +### Added +- `devops ci mutate [PATHS] [--changed] [--base REF]` mutation-tests functions with mutmut 3.8 on demand (#853). With `--changed` it maps the functions the working tree changed since its merge base with `--base` (default `main`), untracked files git does not ignore included, to mutmut's names, and a `--base` naming no commit is an error; PATHS alone select every function in those files. mutmut runs the tests covering each function in its own process, with xdist off, and the command shows each mutant no test killed, with its diff, then the killed, survived, timeout and no-tests counts. It prints no score, exits 0 whatever survives, and is neither a `devops ci` stage nor a `ci.yml` step. The first run mutates the whole source tree into the git-ignored `mutants/` and runs the test suite once, serially; later runs reuse it, and `rm -rf mutants` resets it. +- An architectural invariant fails on any `# pragma: no mutate` under `src`, so no line exempts itself from mutation (#853). diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index 00476a92bd..784322bd0e 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -2625,6 +2625,32 @@ devops ci run [OPTIONS] | `--fix` / `--no-fix` | `boolean` | `True` | Auto-fix lint/format before reporting status. | | `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. | +### `devops ci mutate` + +**Mutation-test functions with mutmut and show each mutant no test killed; never a gate.** + +Mutation-test functions with mutmut and show each mutant no test killed; never a gate. + +Each surviving mutant is shown with its diff, then the killed, survived, timeout and no-tests counts. There is no score, and the command exits 0 whatever survives. The first run copies the whole source tree into mutants/, mutates it and runs the test suite once, serially, which can take hours; later runs reuse mutants/ and its test stats. `rm -rf mutants` resets it. If none of the selected functions gives mutmut a mutant, as when their bodies are only `...`, mutmut fails with 'nothing matches'; on a first run, only after the test suite has run. + +```bash +devops ci mutate [OPTIONS] +``` + +**Arguments:** + +| Argument | Type | Required | Description | +|---|---|---|---| +| `` | `path` | No | Source files or directories under src/ to mutate: every function in them, or with --changed only the changed ones. | + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--changed` | `boolean` | - | Mutate the functions the working tree changed since its merge base with --base, untracked files included unless git ignores them. | +| `--base`, `-b` | `string` | `main` | Base git branch to diff against (default: main). | +| `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. | + --- ## devops uv diff --git a/docs/agent/tasks/task-853-on-demand-mutation-testing-of-changed-functions.md b/docs/agent/tasks/task-853-on-demand-mutation-testing-of-changed-functions.md new file mode 100644 index 0000000000..70deaae961 --- /dev/null +++ b/docs/agent/tasks/task-853-on-demand-mutation-testing-of-changed-functions.md @@ -0,0 +1,118 @@ +# Task: On-Demand Mutation Testing of Changed Functions (#853) + +**Issue**: [#853](https://github.com/dan-petty/devops-cli/issues/853) +**Status**: Done +**Milestone**: v0.2.32 +**Priority**: priority/p3-low +**Scope**: type/feature, priority/p3-low, scope/cli, scope/ci + +## Description + +Coverage shows that the tests run the code, not that they check it. `devops ci mutate [PATHS] +[--changed] [--base REF]` runs mutmut 3.8.0 on chosen functions and shows each mutant no test +killed, with its diff, then the killed, survived, timeout and no-tests counts. It prints no score, +exits 0 whatever survives, and is neither a `devops ci` stage nor a `ci.yml` step. + +`devops_cli.ci.mutate` picks the functions with `ast`. mutmut mutates the functions at a module's +top level and those directly in a top-level class, a decorated class's methods included, and +leaves out any function with a decorator other than one bare `staticmethod` or `classmethod`, and +`__new__`, `__getattribute__` and `__setattr__` (`file_mutation.py`, `_skip_node_and_children`, +`NEVER_MUTATE_FUNCTION_NAMES`). With `--changed`, a function is selected when the working tree's +syntax tree of it differs from the one at the merge base with `--base` (default `main`; item +branches pass their release branch), or the base lacks it; an untracked file under `src` that git +does not ignore counts as added. A `--base` that names no commit is an error, not an empty +selection. PATHS alone select every mutable function in the files they name or hold; with +`--changed`, they narrow the changed ones. + +## Key Changes + +- `pyproject.toml`: `mutmut==3.8.0` in the dev group (the lock adds libcst 1.9.0, mutmut 3.8.0 and + setproctitle 1.3.8), and a `[tool.mutmut]` table: `source_paths`, `pytest_add_cli_args = ["-n", + "0"]` (mutmut appends it after addopts, so it overrides `-n logical`), the test selection, and + `also_copy` for the top-level entries the tests read. +- `.gitignore`: `/mutants/`, so neither git nor the CI cache fingerprint sees mutmut's tree. +- `src/devops_cli/ci/mutate.py`: `mutmut_module`, `mutable_functions`, `changed_functions`, + `select_targets`, `MutationTarget` and `tally`, with stdlib `ast`, `fnmatch` and `Counter` and + the existing git helpers. It never imports mutmut, which is a dev dependency. +- `src/devops_cli/commands/ci.py`: the `mutate` command. It runs `uv run mutmut run ` + through `_run` with a 4-hour timeout, reads `mutmut results --all true` and runs + `mutmut show ` for each survivor through the `run_subprocess` seam. `--dry-run` lists + the three requests and starts no mutmut process; it still reads git locally to select the + functions, with no external request. +- `config/constants.py`: mutmut's naming (`x_`, `xǁ`, `ǁ`, `__mutmut_`), the decorators it mutates, + the names it never mutates and the statuses the report counts. `config/defaults.py`: `DEFAULT_CI_MUTATE_TIMEOUT_SECONDS`. +- `lang/en/help.py` and `lang/en/messages.py`: the command's help and messages. +- `tests/test_ci_mutate.py` and two tests in `tests/test_architectural_invariants.py`. +- Docs: `docs/CLI_REFERENCE.md`, `docs/commands/ci.md` and the README matrix (generated), a row in + `docs/cheatsheets/ci_and_quality.md` and in the knowledge base's CLI command reference. + +## Design Notes + +**The globs.** Each function is run with two globs, `.__mutmut_*` and +`*.`, where `` is `x_` or `xǁǁ`. mutmut matches +the globs against its mutants and, for the clean test run before it mutates, against its test +stats, which are keyed by the function's name alone (`tests_for_mutant_names`); when no glob +matches a stats key it runs the whole selected suite. The first glob matches only the function's +own mutants and no stats key; the second matches only its stats key, and starts with `*` because +mutmut reads a name without one as a mutant's. A single `.*` would also select a +function whose name the target's is a prefix of (`x_run` selects `x_run_all`). When no selected +function gives mutmut a mutant (a body of only `...`, say), mutmut fails with "nothing matches", +on a first run only after its stats pass; the help says so. + +**Fork mode, the network guard and the tripwire.** mutmut runs the suite in its own process and +forks one worker a mutant. The conftest network guard is a session fixture that is never undone, +so the workers inherit it, and each worker's pytest session installs it again on top. The #749 +tripwire runs, but its repository root is `mutants/`, where git tracks no file, so its +tracked-file check has nothing to compare; its worker-HOME isolation still applies. A full run +in fork mode completed the stats, clean-test, forced-fail and mutant steps, so the default +`process_isolation` (fork) is kept. + +**Which tests run inside `mutants/`.** The suite runs from `mutants/`, whose `src` holds mutmut's +generated code, with no git checkout and no `.venv`. A test is left out only when it reads `src` +as data (it sees the generated code, or scans the 475 MB tree), relies on git tracking the +checkout, or relies on its `.venv`. Whole modules of source-tree invariants are ignored +(`test_architectural_invariants`, `test_public_export_surface`, `test_docs`, +`test_docs_source_argv_collector`, `test_ai_task_loader`), and single tests elsewhere are +deselected: the Rich-import scan, the missing-header hallucination check that reads a provider +module, and the span caller test, which records mutmut's trampoline as its caller (generated +code); the kustomization, run-store commit and forbidden-constructs tests (git); and the +sandbox-binary test (`.venv`). The PR-head review test is deselected too: without the checkout's +git origin it fetches `refs/pull/7/head` from GitHub. A serial run of the rest of the suite from +`mutants/` took 20 minutes. + +**Measured.** Generating the tree mutated 549 files into 195,936 mutants in 506 s with 8 +processes at a load average of about 25, and `mutants/` is 475 MB. On the first run, mutmut then +runs the selected suite once, serially, to learn which tests cover which function. A later run +over `ci/mutate.py` itself made 135 mutants in 3 min 26 s: 117 killed, 18 survived. + +## Acceptance Criteria + +- [x] A unit test maps a fixture diff to the expected globs, which it builds with mutmut's own + `get_mutant_name` and `mangle_function_name`, and asserts that the run argv disables xdist + through `[tool.mutmut].pytest_add_cli_args`: + `test_changed_functions_map_to_the_globs_mutmut_names`, + `test_mutate_runs_mutmut_serially_on_the_changed_function_globs`. +- [x] `git check-ignore mutants/x` succeeds, and `test_gitignore_keeps_mutants_out_of_the_tree` + matches it with the gitignore rules. +- [x] Neither the `devops ci` stage list nor `ci.yml` contains a mutate step: + `test_mutate_is_no_gate_step`. +- [x] The pragma check fails on a fixture that uses the pragma: + `test_a_no_mutate_pragma_is_reported`; `test_no_source_line_exempts_itself_from_mutation` + passes on `src`. +- [x] Each new unit test takes at most 1 s. +- [x] `uv lock --check`, `uv audit` and `devops docs check` pass. +- [x] The key question is answered: the guard and the tripwire behave in fork mode (above). +- Pending a person: on a quiet machine, the first-run and incremental wall times of + `rm -rf mutants && time uv run devops ci mutate --changed --base release/v0.2.32`, then the same + command again without `rm -rf mutants`. + +## Deliverables + +- [x] `devops ci mutate [PATHS] [--changed] [--base REF] [--dry-run]`. +- [x] mutmut 3.8.0 in the dev group with its `[tool.mutmut]` table, and `/mutants/` ignored. +- [x] The invariant that no line under `src` carries a `no mutate` pragma. +- [x] `changelog.d/853.md`. +- [x] Two existing test-isolation bugs fixed, because mutmut's first run executes the whole suite serially in one process and stops at the first failure (owner decision, 2026-10-09: folded into this item): + - `tests/conftest.py`'s autouse `isolate_vault_token` now clears every ephemeral CI secret (`_EPHEMERAL_CI_SECRETS.clear()`), not only the Vault key. A secret `tests/test_config_commands.py` stored through `DEVOPS_CLI_HEADLESS_AUTH` leaked into `tests/test_embedding_benchmark.py` in serial order (`uv run pytest -n 0 tests/test_config_commands.py tests/test_embedding_benchmark.py` failed 1 of 30); xdist hid it. This is one slice of #1310 (reset all process-wide state after every test). + - `tests/test_ssh.py::test_crypto_ssh_keys_devcontainer_config_resolution` uses `monkeypatch.delenv("DEVOPS_CLI_CONFIG")` instead of patching `os.environ.get` process-wide, which broke mutmut's own `os.environ.get` call during its stats pass. + - With both, the real first run over the final selection finished with exit 0 (133 mutants: 126 killed, 7 survived). diff --git a/docs/cheatsheets/ci_and_quality.md b/docs/cheatsheets/ci_and_quality.md index cc94d94c2f..fc75adfbaf 100644 --- a/docs/cheatsheets/ci_and_quality.md +++ b/docs/cheatsheets/ci_and_quality.md @@ -17,6 +17,7 @@ Compare disparate linters, formatters, type checkers, and test runners with the | **Coverage Measurement** | `pytest --cov=src --cov-report=html` | `devops ci coverage [--html]` | Computes coverage percentages and generates interactive HTML coverage reports in `.data/coverage/`. | | **GitHub Actions Linting** | `actionlint .github/workflows/*.yml` | `devops ci actionlint` | Validates YAML syntax, context expressions, and security permissions in GitHub Actions workflows. | | **Doc Freshness Check** | `python tools/check_docs.py` | `devops ci docs` | Asserts that CLI command reference and README command matrix match live Typer definitions. | +| **Mutation Testing of Changed Functions** | `mutmut run ".x___mutmut_*" "*.x_"` | `devops ci mutate --changed --base release/vX.Y.Z` | On demand, never a gate: maps the functions changed since the merge base to mutmut's names and shows each surviving mutant with its diff, not a percentage. | --- diff --git a/docs/commands/ci.md b/docs/commands/ci.md index b031a7fea3..11547b7ed3 100644 --- a/docs/commands/ci.md +++ b/docs/commands/ci.md @@ -287,3 +287,31 @@ devops ci run [OPTIONS] | `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. | --- + +## `devops ci mutate` + +**Mutation-test functions with mutmut and show each mutant no test killed; never a gate.** + +Mutation-test functions with mutmut and show each mutant no test killed; never a gate. + +Each surviving mutant is shown with its diff, then the killed, survived, timeout and no-tests counts. There is no score, and the command exits 0 whatever survives. The first run copies the whole source tree into mutants/, mutates it and runs the test suite once, serially, which can take hours; later runs reuse mutants/ and its test stats. `rm -rf mutants` resets it. If none of the selected functions gives mutmut a mutant, as when their bodies are only `...`, mutmut fails with 'nothing matches'; on a first run, only after the test suite has run. + +```bash +devops ci mutate [OPTIONS] +``` + +**Arguments:** + +| Argument | Type | Required | Description | +|---|---|---|---| +| `` | `path` | No | Source files or directories under src/ to mutate: every function in them, or with --changed only the changed ones. | + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--changed` | `boolean` | - | Mutate the functions the working tree changed since its merge base with --base, untracked files included unless git ignores them. | +| `--base`, `-b` | `string` | `main` | Base git branch to diff against (default: main). | +| `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. | + +--- diff --git a/pyproject.toml b/pyproject.toml index ec0eaf6592..44da68741b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -92,6 +92,7 @@ dev = [ "hypothesis==6.168.3", "h11==0.16.0", "deptry==0.25.1", + "mutmut==3.8.0", ] [tool.hatch.build.targets.wheel] @@ -187,6 +188,45 @@ directory = ".data/htmlcov" [tool.coverage.json] output = ".data/coverage.json" +# `devops ci mutate` (#853). mutmut copies src, tests, pyproject.toml and uv.lock into mutants/ +# itself; `also_copy` adds the other top-level entries the tests read. `.claude` holds local +# worktrees and `.vscode` local settings, and mutmut 3.8.0 cannot copy a nested file path. +[tool.mutmut] +source_paths = ["src/devops_cli"] +# Appended after addopts, so `-n 0` overrides `-n logical`: mutmut runs the tests in its process. +pytest_add_cli_args = ["-n", "0"] +# The suite runs from mutants/, whose src holds mutmut's generated code, which holds no git +# checkout and no .venv. A test is left out only when it reads src as data (it sees the generated +# code, or scans the 475 MB tree), relies on git tracking the checkout, or relies on its .venv: +# whole modules of source-tree invariants, and single tests elsewhere. +pytest_add_cli_args_test_selection = [ + # src as data + "--ignore=tests/test_architectural_invariants.py", + "--ignore=tests/test_public_export_surface.py", + "--ignore=tests/test_docs.py", + "--ignore=tests/test_docs_source_argv_collector.py", + "--ignore=tests/test_ai_task_loader.py", + "--deselect=tests/test_output.py::test_rich_imports_confined_to_output_submodule", + "--deselect=tests/test_review_verification.py::test_check_missing_header_hallucination_requires_assignment_and_dispatch", + # The caller it records is mutmut's trampoline, generated code between the test and the span. + "--deselect=tests/test_telemetry.py::test_span_caller_location_and_runtime_attributes", + # git tracking of the checkout + "--deselect=tests/test_k8s_devops_runtime.py::test_kustomization_lists_every_manifest_and_pins_no_image_and_stays_out_of_the_root", + "--deselect=tests/test_run_store.py::test_a_record_names_its_setup_and_subject_by_content", + "--deselect=tests/test_url_credential_masking.py::test_no_forbidden_constructs_remain", + # Without the checkout's git origin it fetches the pull request's head from GitHub. + "--deselect=tests/test_review_scope.py::test_the_pr_command_reviews_against_the_pr_head", + # the checkout's .venv + "--deselect=tests/test_host_sandbox.py::test_every_allowlisted_criteria_binary_resolves_inside_the_sandbox_mounts", +] +also_copy = [ + ".devcontainer", ".devops", ".dockerignore", ".editorconfig", ".gitattributes", ".github", + ".gitignore", ".mcp.json", ".pre-commit-config.yaml", ".python-version", ".trivyignore", + "AGENTS.md", "ARCHITECTURE.md", "CHANGELOG.md", "CLAUDE.md", "CONTEXT.md", "CONTRIBUTING.md", + "Dockerfile", "LICENSE", "README.md", "RELEASE_CYCLE.md", "SECURITY.md", "changelog.d", + "config.example.yaml", "docs", "k8s", "tf", +] + [tool.uv] preview-features = ["malware-check", "check-command"] diff --git a/src/devops_cli/ai/knowledge_base/devops_cli/cli_command_reference.md b/src/devops_cli/ai/knowledge_base/devops_cli/cli_command_reference.md index 78804aece3..b2a1e98bb2 100644 --- a/src/devops_cli/ai/knowledge_base/devops_cli/cli_command_reference.md +++ b/src/devops_cli/ai/knowledge_base/devops_cli/cli_command_reference.md @@ -93,6 +93,7 @@ This document provides an overview of the main command groups implemented in `de | **`ci`** | `devops ci` | Run every check of the local quality gate | `--fix/--no-fix`, `--check`, `--cache`, `--force`, `--files` | | | `devops ci run` | Same as `devops ci` | `--fix` | | | `devops ci audit` | Check dependencies for known CVEs (uv audit) | | +| | `devops ci mutate` | Mutation-test changed functions with mutmut and show the survivors; never a gate | `paths`, `--changed`, `--base` | | **`release`** | `devops release prepare` | Bump version, update changelog, sync docs | `version`, `--create-pr`, `--type` | | | `devops release pr` | Create release branch and release PR | `--version`, `--base`, `--push` | | | `devops release check` | Verify release readiness | | diff --git a/src/devops_cli/ci/mutate.py b/src/devops_cli/ci/mutate.py new file mode 100644 index 0000000000..f01c39aeec --- /dev/null +++ b/src/devops_cli/ci/mutate.py @@ -0,0 +1,243 @@ +"""Which functions `devops ci mutate` hands to mutmut, and what mutmut found in them (#853). + +mutmut 3.8 mutates the functions defined at a module's top level and those directly in the body +of a top-level class, except a function carrying any decorator but one bare `staticmethod` or +`classmethod`, and `__new__`, `__getattribute__` and `__setattr__`. It names each function by its +module and a mangled name, and each mutant by that name, `__mutmut_` and a number. `mutmut run` +takes globs over those names, and `mutmut results --all true` prints one `: ` line +for every mutant. +""" + +from __future__ import annotations + +import ast +import fnmatch +from collections import Counter +from collections.abc import Iterator, Sequence +from pathlib import Path, PurePosixPath + +from pydantic import BaseModel, ConfigDict + +from devops_cli.config.constants import ( + CONST_GIT_NAME_STATUS_CHANGE_TYPES, + CONST_MUTMUT_CLASS_SEPARATOR, + CONST_MUTMUT_COUNTED_STATUSES, + CONST_MUTMUT_FUNCTION_PREFIX, + CONST_MUTMUT_METHOD_PREFIX, + CONST_MUTMUT_MUTABLE_DECORATORS, + CONST_MUTMUT_MUTANT_INFIX, + CONST_MUTMUT_NEVER_MUTATED_NAMES, + CONST_MUTMUT_SURVIVING_STATUSES, + CONST_PYTHON_FILE_SUFFIX, + CONST_SOURCE_ROOT_DIR, +) +from devops_cli.core.process import run_subprocess +from devops_cli.exceptions import GitOperationError +from devops_cli.git.operations import list_changed_files, read_file_at_revision, resolve_merge_base +from devops_cli.lang import MESSAGES + +FunctionNode = ast.FunctionDef | ast.AsyncFunctionDef +# A function's class, None at module level, and its name. +FunctionKey = tuple[str | None, str] + +_DELETED = CONST_GIT_NAME_STATUS_CHANGE_TYPES["D"] + + +def mutmut_module(path: str) -> str: + """The module mutmut names a source file by: its path under `src`, without `__init__`.""" + parts = PurePosixPath(path).relative_to(CONST_SOURCE_ROOT_DIR).with_suffix("").parts + return ".".join(parts[:-1] if parts[-1] == "__init__" else parts) + + +class MutationTarget(BaseModel): + """A function mutmut mutates: where it is defined, and the names mutmut gives it.""" + + model_config = ConfigDict(frozen=True) + + path: str + line: int + class_name: str | None + name: str + + @property + def qualname(self) -> str: + """The function's name, after its class's for a method.""" + return f"{self.class_name}.{self.name}" if self.class_name else self.name + + @property + def mangled(self) -> str: + """mutmut's name for the function within its module.""" + if self.class_name is None: + return f"{CONST_MUTMUT_FUNCTION_PREFIX}{self.name}" + return f"{CONST_MUTMUT_METHOD_PREFIX}{self.class_name}{CONST_MUTMUT_CLASS_SEPARATOR}{self.name}" + + @property + def mutant_pattern(self) -> str: + """The pattern matching the function's own mutants, and no other function's.""" + return f"{mutmut_module(self.path)}.{self.mangled}{CONST_MUTMUT_MUTANT_INFIX}*" + + @property + def run_globs(self) -> tuple[str, str]: + """The globs `mutmut run` takes for the function: its mutants, then its test stats entry. + + mutmut runs the tests of the stats entries the globs match before it mutates, and every + test when they match none; no mutant's name is a stats entry. The stats glob starts with + `*` because mutmut reads a name without one as a mutant's. + """ + return self.mutant_pattern, f"*{mutmut_module(self.path)}.{self.mangled}" + + +class MutationReport(BaseModel): + """What `mutmut results` says of the targets' mutants: how many have each counted status, + and each mutant no test killed, with its target.""" + + model_config = ConfigDict(frozen=True) + + counts: dict[str, int] + survivors: tuple[tuple[str, MutationTarget], ...] + + +def _is_mutable(function: FunctionNode) -> bool: + """mutmut leaves a function with a name it never mutates alone, and a decorated function + unless one bare decorator allows it.""" + if function.name in CONST_MUTMUT_NEVER_MUTATED_NAMES: + return False + match function.decorator_list: + case []: + return True + case [ast.Name(id=decorator)]: + return decorator in CONST_MUTMUT_MUTABLE_DECORATORS + case _: + return False + + +def _keyed_functions(module: ast.Module) -> Iterator[tuple[FunctionKey, FunctionNode]]: + """The module's top-level functions and its top-level classes' methods, in source order.""" + for node in module.body: + if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef): + yield (None, node.name), node + elif isinstance(node, ast.ClassDef): + yield from ( + ((node.name, method.name), method) + for method in node.body + if isinstance(method, ast.FunctionDef | ast.AsyncFunctionDef) + ) + + +def mutable_functions(text: str) -> dict[FunctionKey, FunctionNode]: + """The functions mutmut mutates in a module's text, keyed by class and name.""" + return {key: node for key, node in _keyed_functions(ast.parse(text)) if _is_mutable(node)} + + +def changed_functions(base_text: str, head_text: str) -> dict[FunctionKey, FunctionNode]: + """The mutable functions of `head_text` that `base_text` lacks or defines differently. + + Syntax trees are compared, so moving or reformatting a function does not change it, and an + empty base text selects every function. + """ + base = {key: ast.dump(node) for key, node in mutable_functions(base_text).items()} + return { + key: node + for key, node in mutable_functions(head_text).items() + if base.get(key) != ast.dump(node) + } + + +def _changed_since(root: Path, base: str) -> dict[str, str]: + """Each file the working tree changed since its merge base with `base`, and its text there. + + A file added since, untracked ones that git does not ignore included, has an empty text + there, so all of its functions count as changed. A `base` naming no commit is an error: + git would find no merge base and diff nothing. + """ + if (merge_base := resolve_merge_base(root, base)) is None: + raise GitOperationError(MESSAGES.ci.mutate_base_refused.format(base=base)) + verify = ["git", "rev-parse", "--verify", "--quiet", f"{base}^{{commit}}"] + if run_subprocess(verify, cwd=root, quiet=True).returncode != 0: + raise GitOperationError(MESSAGES.ci.mutate_base_missing.format(base=base)) + changed = { + change.path: read_file_at_revision(root, merge_base, change.base_path) or "" + for change in list_changed_files(root, merge_base) + if change.change_type != _DELETED + } + untracked = ["git", "ls-files", "--others", "--exclude-standard", "-z", "--"] + listed = run_subprocess([*untracked, CONST_SOURCE_ROOT_DIR], cwd=root, quiet=True).stdout + return changed | dict.fromkeys(filter(None, listed.split("\0")), "") + + +def _python_files(path: Path) -> list[Path]: + """The file `path` names, or the Python files under the directory it names.""" + if path.is_dir(): + return sorted(path.rglob(f"*{CONST_PYTHON_FILE_SUFFIX}")) + return [path] if path.is_file() else [] + + +def _named_sources(root: Path, wanted: Sequence[PurePosixPath]) -> dict[str, str]: + """Each Python file the paths name or hold, with an empty base text: all of its functions.""" + return { + file.relative_to(root).as_posix(): "" + for path in wanted + for file in _python_files(root / path) + } + + +def _is_mutated_source(path: PurePosixPath) -> bool: + """Whether mutmut mutates the file: a Python module under `src`.""" + return path.suffix == CONST_PYTHON_FILE_SUFFIX and path.is_relative_to(CONST_SOURCE_ROOT_DIR) + + +def _targets(root: Path, path: str, base_text: str) -> list[MutationTarget]: + head_text = (root / path).read_text(encoding="utf-8") + return [ + MutationTarget(path=path, line=node.lineno, class_name=class_name, name=name) + for (class_name, name), node in changed_functions(base_text, head_text).items() + ] + + +def select_targets( + root: Path, paths: Sequence[Path], *, changed: bool, base: str +) -> list[MutationTarget]: + """The functions to mutate under `src`. + + With `changed`, those the working tree changed since its merge base with `base`, kept to + `paths` when any are given; otherwise every function in the files `paths` name or hold. + """ + root = root.resolve() + wanted = [ + PurePosixPath(path.relative_to(root).as_posix()) + for path in (given.resolve() for given in paths) + if path.is_relative_to(root) + ] + sources = _changed_since(root, base) if changed else _named_sources(root, wanted) + return [ + target + for path, base_text in sources.items() + if _is_mutated_source(PurePosixPath(path)) + and (not paths or any(PurePosixPath(path).is_relative_to(each) for each in wanted)) + for target in _targets(root, path, base_text) + ] + + +def _result(line: str) -> tuple[str, str]: + """A `mutmut results` line's mutant name and status.""" + name, _, status = line.strip().rpartition(": ") + return name, status + + +def tally(results_text: str, targets: Sequence[MutationTarget]) -> MutationReport: + """Read `mutmut results --all true` output for the targets' mutants.""" + status_by_mutant = dict(map(_result, results_text.splitlines())) + mutants = [ + (name, status_by_mutant[name], target) + for target in targets + for name in fnmatch.filter(status_by_mutant, target.mutant_pattern) + ] + statuses = Counter(status for _, status, _ in mutants) + return MutationReport( + counts={status: statuses[status] for status in CONST_MUTMUT_COUNTED_STATUSES}, + survivors=tuple( + (name, target) + for name, status, target in mutants + if status in CONST_MUTMUT_SURVIVING_STATUSES + ), + ) diff --git a/src/devops_cli/commands/ci.py b/src/devops_cli/commands/ci.py index ac0028fe76..bc198e4c6f 100644 --- a/src/devops_cli/commands/ci.py +++ b/src/devops_cli/commands/ci.py @@ -12,7 +12,7 @@ import time from collections.abc import Sequence from pathlib import Path -from typing import Annotated, Any +from typing import TYPE_CHECKING, Annotated, Any import typer from pydantic import BaseModel, ConfigDict @@ -22,19 +22,24 @@ CONST_CI_SLOWEST_TESTS_SHOWN, CONST_CI_SUBCOMMAND_SHOWS_HELP_META_KEY, CONST_CI_TEST_BUDGET_SECONDS, + CONST_GIT_MAIN_BRANCH, ) from devops_cli.config.defaults import ( DEFAULT_BANDIT_SEVERITY, + DEFAULT_CI_MUTATE_TIMEOUT_SECONDS, DEFAULT_CI_TEST_REPEAT_RUNS, DEFAULT_PYTHON_VERSION, DEFAULT_SUBPROCESS_TIMEOUT_SECONDS, ) -from devops_cli.core.cli import new_typer +from devops_cli.core.cli import exit_on_error, new_typer from devops_cli.dry_run import is_dry_run, render_dry_run_result, set_dry_run from devops_cli.dry_run.requests import PlannedRequest, render_request_plan from devops_cli.lang import HELP, MESSAGES from devops_cli.output import print_error, print_info, print_success +if TYPE_CHECKING: + from devops_cli.ci.mutate import MutationTarget + def _asks_for_help(ctx: Any, args: list[str]) -> bool: """Whether a subcommand's arguments ask for its help, which Click prints without running it. @@ -1825,3 +1830,79 @@ def run( if not is_dry_run() and not any(res.dry_run for res in results): if not all(res.passed for res in results): raise typer.Exit(1) + + +_MUTMUT = ["uv", "run", "mutmut"] +_MUTMUT_RESULTS = [*_MUTMUT, "results", "--all", "true"] + + +def _capture(cmd: list[str]) -> subprocess.CompletedProcess[str]: + """Run a command in the checked tree as `_run` would, returning its captured output.""" + argv = list(_planned_request_for_cmd(cmd).argv) + completed: subprocess.CompletedProcess[str] = _get("run_subprocess")( + argv, cwd=_get_project_root(), capture_output=True + ) + return completed + + +def _plan_mutation(run_cmd: list[str]) -> None: + """The dry run's requests: the mutmut run, its results, and a show for each survivor.""" + requests = [ + _planned_request_for_cmd(run_cmd), + _planned_request_for_cmd(_MUTMUT_RESULTS), + _planned_request_for_cmd([*_MUTMUT, "show", ""], repeat="each surviving mutant"), + ] + render_request_plan(MESSAGES.ci.ci_dry_run_heading, requests) + + +def _report_mutation(results_text: str, targets: Sequence[MutationTarget]) -> None: + """Show each surviving mutant of the targets with its diff, then the status counts.""" + from devops_cli.ci.mutate import tally + + report = tally(results_text, targets) + for mutant, target in report.survivors: + location = MESSAGES.ci.mutate_survivor.format( + path=target.path, line=target.line, qualname=target.qualname + ) + _get("print_warning")(location, prefix=False, safe=True) + _get("write_stdout")(_capture([*_MUTMUT, "show", mutant]).stdout) + counts = ", ".join(f"{status} {count}" for status, count in report.counts.items()) + _get("print_info")(MESSAGES.ci.mutate_counts.format(counts=counts), prefix=False, safe=True) + + +@app.command(help=HELP.ci.mutate) +def mutate( + paths: Annotated[list[Path] | None, typer.Argument(help=HELP.ci.mutate_paths)] = None, + changed: Annotated[bool, typer.Option("--changed", help=HELP.ci.mutate_changed)] = False, + base: Annotated[ + str, typer.Option("--base", "-b", help=HELP.options.base_branch) + ] = CONST_GIT_MAIN_BRANCH, + dry_run: Annotated[bool, typer.Option("--dry-run", help=HELP.options.dry_run)] = False, +) -> None: + """Mutation-test the selected functions with mutmut and show what survives (#853).""" + if not (paths or changed): + _get("print_error")(MESSAGES.ci.mutate_needs_target, prefix=False) + raise typer.Exit(2) + if dry_run: + set_dry_run(True) + if not _verify_python_314_environment(): + raise typer.Exit(1) + from devops_cli.ci.mutate import select_targets + from devops_cli.exceptions import GitOperationError + + with exit_on_error(GitOperationError): + targets = select_targets(_get_project_root(), paths or [], changed=changed, base=base) + if not targets: + _get("print_muted")(MESSAGES.ci.mutate_nothing) + return + run_cmd = [*_MUTMUT, "run", *(glob for target in targets for glob in target.run_globs)] + if is_dry_run(): + _plan_mutation(run_cmd) + return + if not _run(run_cmd, timeout=DEFAULT_CI_MUTATE_TIMEOUT_SECONDS): + raise typer.Exit(1) + results = _capture(_MUTMUT_RESULTS) + if results.returncode != 0: + _get("write_stderr")(results.stderr) + raise typer.Exit(1) + _report_mutation(results.stdout, targets) diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 5e77a52a7d..0226eebb8a 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -2019,6 +2019,29 @@ CONST_PYTHON_FILE_SUFFIX: Final[str] = ".py" CONST_PYTHON_SOURCE_SUFFIXES: Final[frozenset[str]] = frozenset({".py", ".pyi"}) +# ── Mutation Testing (mutmut 3.8, `devops ci mutate`) ──────────────────────── +# How mutmut names what it mutates, a closed domain it defines (`mangle_function_name`): a +# module-level function is `.x_`, a method of a module-level class +# `.xǁǁ`, and each of their mutants that name, `__mutmut_` and a number. +CONST_MUTMUT_FUNCTION_PREFIX: Final[str] = "x_" +CONST_MUTMUT_CLASS_SEPARATOR: Final[str] = "ǁ" +CONST_MUTMUT_METHOD_PREFIX: Final[str] = f"x{CONST_MUTMUT_CLASS_SEPARATOR}" +CONST_MUTMUT_MUTANT_INFIX: Final[str] = "__mutmut_" +# mutmut leaves a decorated function alone unless this is its one, bare, decorator. +CONST_MUTMUT_MUTABLE_DECORATORS: Final[frozenset[str]] = frozenset({"staticmethod", "classmethod"}) +# The function names mutmut never mutates (`NEVER_MUTATE_FUNCTION_NAMES`). +CONST_MUTMUT_NEVER_MUTATED_NAMES: Final[frozenset[str]] = frozenset( + {"__getattribute__", "__setattr__", "__new__"} +) +# `mutmut results` statuses: those the report counts, and those of a mutant no test killed. +CONST_MUTMUT_COUNTED_STATUSES: Final[tuple[str, ...]] = ( + "killed", + "survived", + "timeout", + "no tests", +) +CONST_MUTMUT_SURVIVING_STATUSES: Final[tuple[str, ...]] = ("survived", "no tests") + # ── Terraform / OpenTofu HCL AST Analysis ──────────────────────────────────── # HCL configuration file extensions recognised by Terraform and OpenTofu. CONST_HCL_FILE_EXTENSIONS: Final[tuple[str, ...]] = (".tf",) diff --git a/src/devops_cli/config/defaults.py b/src/devops_cli/config/defaults.py index 2dbc23267d..e8465ff2ce 100644 --- a/src/devops_cli/config/defaults.py +++ b/src/devops_cli/config/defaults.py @@ -307,6 +307,10 @@ DEFAULT_REVIEW_WINDOW_SIZE_FACTOR: float = 0.8 DEFAULT_REVIEW_OVERLAP_FACTOR: float = 0.1 DEFAULT_SUBPROCESS_TIMEOUT_SECONDS: float = 1800.0 # 30 minutes (kubectl, helm, minikube, git, gh) +# `devops ci mutate`'s `mutmut run`. The first run mutates the whole source tree (about 196,000 +# mutants, 506 s with 8 processes at a load average of 25) and then runs the test suite once, +# serially, for its stats. +DEFAULT_CI_MUTATE_TIMEOUT_SECONDS: float = 14400.0 # 4 hours DEFAULT_HTTP_TIMEOUT_SECONDS: float = 3600.0 # 1 hour (API requests & downloads) DEFAULT_HTTP_MAX_REDIRECTS: int = 10 # hops the HTTP broker follows; httpx2 allows 20 DEFAULT_DNS_TIMEOUT_SECONDS: float = 15.0 # 15 seconds (socket DNS resolution) diff --git a/src/devops_cli/lang/en/help.py b/src/devops_cli/lang/en/help.py index 26d6900ead..9223518540 100644 --- a/src/devops_cli/lang/en/help.py +++ b/src/devops_cli/lang/en/help.py @@ -610,6 +610,25 @@ class CICommandHelp: "Reuse a cached verdict when the codebase is unchanged. Results are recorded either way." ) force: str = "Bypass CI execution cache and force re-execution of all quality gates." + mutate: str = ( + "Mutation-test functions with mutmut and show each mutant no test killed; never a gate." + "\n\n" + "Each surviving mutant is shown with its diff, then the killed, survived, timeout and " + "no-tests counts. There is no score, and the command exits 0 whatever survives. The " + "first run copies the whole source tree into mutants/, mutates it and runs the test " + "suite once, serially, which can take hours; later runs reuse mutants/ and its test " + "stats. `rm -rf mutants` resets it. If none of the selected functions gives mutmut a " + "mutant, as when their bodies are only `...`, mutmut fails with 'nothing matches'; on a " + "first run, only after the test suite has run." + ) + mutate_paths: str = ( + "Source files or directories under src/ to mutate: every function in them, or with " + "--changed only the changed ones." + ) + mutate_changed: str = ( + "Mutate the functions the working tree changed since its merge base with --base, " + "untracked files included unless git ignores them." + ) @dataclass(frozen=True) diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py index a54f166875..34a348796a 100644 --- a/src/devops_cli/lang/en/messages.py +++ b/src/devops_cli/lang/en/messages.py @@ -914,6 +914,22 @@ class CIMessages: "Refusing to narrow tests because {file} changed. Run without --no-fallback " "or run the full suite." ) + mutate_needs_target: str = ( + "Name the source files to mutate, or pass --changed to mutate the functions changed " + "since the merge base with --base." + ) + mutate_nothing: str = ( + "Nothing to mutate: the selection holds no function mutmut mutates. mutmut leaves out " + "__new__, __getattribute__, __setattr__ and a decorated function unless its one " + "decorator is @staticmethod or @classmethod." + ) + mutate_base_refused: str = "Refusing to diff against '{base}': it is not a git revision name." + mutate_base_missing: str = ( + "Cannot diff against '{base}': it names no commit in this clone. Fetch it, or pass " + "--base a branch, tag or commit the clone has." + ) + mutate_survivor: str = "{path}:{line} {qualname}" + mutate_counts: str = "Mutants of the selected functions: {counts}." @dataclass(frozen=True) diff --git a/tests/conftest.py b/tests/conftest.py index b76ddf9792..4a799cbb06 100755 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -392,20 +392,22 @@ def isolate_own_source_repository(monkeypatch: pytest.MonkeyPatch) -> None: @pytest.fixture(autouse=True) def isolate_vault_token() -> Iterator[None]: - """Keep a Vault token from outliving the test that left it (#709). + """Keep a Vault token, or any other ephemeral CI secret, from outliving the test that left + it (#709). Brokers read the `devops vault login` record from the in-process secret store, the process-wide resolver's `VaultProvider` keeps the broker it built, token and all, and `vault leases` keeps its session registry. Each would let a later test reach Vault with a token. The store is cleared in place, since tests hold the dict itself; the registry is dropped only once - something has imported the command. + something has imported the command. Every secret in the store is cleared, not only the Vault + record: in a serial run, a `DEVOPS_CLI_HEADLESS_AUTH` secret `test_config_commands` stored + reached `test_embedding_benchmark` (#853, one slice of #1310). """ yield - from devops_cli.config.constants import CONST_VAULT_LOGIN_KEYRING_KEY from devops_cli.config.settings import _EPHEMERAL_CI_SECRETS from devops_cli.security.secrets import reset_resolver - _EPHEMERAL_CI_SECRETS.pop(CONST_VAULT_LOGIN_KEYRING_KEY, None) + _EPHEMERAL_CI_SECRETS.clear() reset_resolver() vault_commands = sys.modules.get("devops_cli.commands.vault") if vault_commands is not None: diff --git a/tests/test_architectural_invariants.py b/tests/test_architectural_invariants.py index 3ff911b98d..94ff5b88bd 100644 --- a/tests/test_architectural_invariants.py +++ b/tests/test_architectural_invariants.py @@ -1469,3 +1469,32 @@ def test_data_dir_invariant_detects_violations() -> None: if (violation := _inspect_data_path_node(node, "sample.py")) is not None ] assert len(detected) == 3 + + +# mutmut reads a comment holding both as a `no mutate` pragma (`_parse_pragma_token`). They stay +# here, not in src, where a line holding both would itself be one. +_MUTMUT_PRAGMA_MARKERS = ("# pragma:", "no mutate") + + +def _no_mutate_pragmas(root: Path) -> list[str]: + """Each `file:line` under `root/src` holding a mutmut `no mutate` pragma.""" + return [ + f"{path.relative_to(root).as_posix()}:{number}" + for path in sorted((root / "src").rglob("*.py")) + for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1) + if all(marker in line for marker in _MUTMUT_PRAGMA_MARKERS) + ] + + +def test_no_source_line_exempts_itself_from_mutation() -> None: + """`devops ci mutate` reports what survives; a pragma under src would hide it (#853).""" + assert _no_mutate_pragmas(Path(__file__).resolve().parents[1]) == [] + + +def test_a_no_mutate_pragma_is_reported(tmp_path: Path) -> None: + """The check names the file and line of a pragma, and passes a line without one.""" + (tmp_path / "src").mkdir() + (tmp_path / "src" / "mod.py").write_text( + "y = 2 # pragma: no cover\nx = 1 # pragma: no mutate\n", encoding="utf-8" + ) + assert _no_mutate_pragmas(tmp_path) == ["src/mod.py:2"] diff --git a/tests/test_ci_mutate.py b/tests/test_ci_mutate.py new file mode 100644 index 0000000000..3697027db0 --- /dev/null +++ b/tests/test_ci_mutate.py @@ -0,0 +1,370 @@ +"""Tests for `devops ci mutate`: changed functions mapped to mutmut globs, and its report (#853).""" + +from __future__ import annotations + +import shlex +import subprocess +import tomllib +from collections.abc import Callable +from pathlib import Path + +import pathspec +import pytest +import yaml +from typer.testing import CliRunner + +from devops_cli.ci.mutate import MutationTarget, select_targets, tally +from devops_cli.commands.ci import app, get_check_specs +from devops_cli.config.constants import CONST_GITIGNORE_PATTERN_STYLE + +runner = CliRunner() +REPO_ROOT = Path(__file__).resolve().parents[1] +MODULE_PATH = "src/devops_cli/pkg/mod.py" +PACKAGE_PATH = "src/devops_cli/pkg/__init__.py" +UNTRACKED_PATH = "src/devops_cli/pkg/fresh.py" +TEST_PATH = "tests/test_mod.py" +UV_RUN = ["uv", "--preview-features", "malware-check,check-command", "run"] + +BASE_MODULE = """\ +import dataclasses + + +def changed(a, b): + return a + b + + +def unchanged(a): + return a * 2 + + +@app.command() +def command(a): + return a + 1 + + +class Holder: + def method(self, a): + return a - 1 + + @staticmethod + def static(a): + return a > 1 + + +@dataclasses.dataclass +class Record: + value: int + + def doubled(self): + return self.value * 2 +""" + +HEAD_MODULE = """\ +import dataclasses + + +def changed(a, b): + return a + b + 1 + + +def unchanged(a): + return a * 2 + + +def added(a): + return a or 1 + + +@app.command() +def command(a): + return a + 2 + + +class Holder: + def method(self, a): + return a - 2 + + @staticmethod + def static(a): + return a >= 1 + + +@dataclasses.dataclass +class Record: + value: int + + def doubled(self): + return self.value * 3 +""" + +UNTRACKED_MODULE = """\ +class Fresh: + def __new__(cls): + return object.__new__(cls) + + def size(self): + return 2 +""" + +# The (function, class) pairs mutmut mutates among HEAD_MODULE's changes, and the package's. +CHANGED_IN_MODULE = [ + ("changed", None), + ("added", None), + ("method", "Holder"), + ("static", "Holder"), + ("doubled", "Record"), +] +CHANGED_IN_PACKAGE = [("version", None)] + +RESULTS = """\ + devops_cli.pkg.mod.x_changed__mutmut_1: killed + devops_cli.pkg.mod.x_changed__mutmut_2: survived + devops_cli.pkg.mod.x_changed_other__mutmut_1: survived + devops_cli.pkg.mod.x_unchanged__mutmut_1: survived + devops_cli.pkg.mod.xǁHolderǁmethod__mutmut_1: timeout + devops_cli.pkg.mod.xǁRecordǁdoubled__mutmut_1: no tests + devops_cli.pkg.mod.xǁRecordǁdoubled__mutmut_2: killed +""" +COUNTS = "killed 2, survived 1, timeout 1, no tests 1" +SHOW = "--- src/devops_cli/pkg/mod.py\n+++ src/devops_cli/pkg/mod.py\n- return a + b + 1\n+ return a - b + 1\n" + + +def _mutmut_globs(path: str, name: str, class_name: str | None) -> list[str]: + """The globs built from mutmut 3.8's own stats key for a function: its mutants, then the key.""" + from mutmut.mutation.trampoline_templates import mangle_function_name + from mutmut.utils.format_utils import get_mutant_name + + key = get_mutant_name(Path(path), mangle_function_name(name=name, class_name=class_name)) + return [f"{key}__mutmut_*", f"*{key}"] + + +def _write(root: Path, rel_path: str, text: str) -> None: + target = root / rel_path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(text, encoding="utf-8") + + +@pytest.fixture +def mutation_repo(tmp_path: Path, git: Callable[..., None]) -> Path: + """A repository whose `feature` branch changes the module, the package's `__init__` and + a test module, which is no source mutmut mutates.""" + git(tmp_path, "init", "--quiet", "-b", "main") + _write(tmp_path, MODULE_PATH, BASE_MODULE) + _write(tmp_path, PACKAGE_PATH, "") + _write(tmp_path, TEST_PATH, "def test_mod():\n assert True\n") + git(tmp_path, "add", ".") + git(tmp_path, "commit", "--quiet", "-m", "base") + git(tmp_path, "switch", "--quiet", "-c", "feature") + _write(tmp_path, MODULE_PATH, HEAD_MODULE) + _write(tmp_path, PACKAGE_PATH, "def version():\n return 1\n") + _write(tmp_path, TEST_PATH, "def test_mod():\n assert 1\n") + git(tmp_path, "commit", "--quiet", "-am", "head") + return tmp_path + + +@pytest.fixture +def mutmut_calls( + mutation_repo: Path, monkeypatch: pytest.MonkeyPatch +) -> Callable[..., list[list[str]]]: + """Run from the repository with the ci subprocess seam answering as mutmut would.""" + monkeypatch.chdir(mutation_repo) + + def install(*, run_code: int = 0, results_code: int = 0) -> list[list[str]]: + calls: list[list[str]] = [] + replies = {"run": (run_code, ""), "results": (results_code, RESULTS), "show": (0, SHOW)} + + def fake(cmd: list[str], **_kwargs: object) -> subprocess.CompletedProcess[str]: + calls.append(list(cmd)) + code, stdout = replies[cmd[cmd.index("mutmut") + 1]] + return subprocess.CompletedProcess(cmd, code, stdout=stdout, stderr="mutmut failed") + + monkeypatch.setattr("devops_cli.commands.ci.run_subprocess", fake) + return calls + + return install + + +def test_changed_functions_map_to_the_globs_mutmut_names(mutation_repo: Path) -> None: + """Changed module functions and methods, a new function, a staticmethod, a decorated + class's method and an untracked module's functions are selected; unchanged and decorated + functions, and a `__new__` mutmut never mutates, are not.""" + _write(mutation_repo, UNTRACKED_PATH, UNTRACKED_MODULE) + targets = select_targets(mutation_repo, [], changed=True, base="main") + expected = [ + glob + for path, name, cls in [*_changed(), (UNTRACKED_PATH, "size", "Fresh")] + for glob in _mutmut_globs(path, name, cls) + ] + assert [glob for target in targets for glob in target.run_globs] == expected + + +def test_paths_select_every_function_and_narrow_changed_ones(mutation_repo: Path) -> None: + """PATHS alone select every mutable function in the files they name or hold, a missing + path naming none; with --changed, they keep the changed functions inside them.""" + + def qualnames(paths: list[str], *, changed: bool) -> list[str]: + named = [mutation_repo / path for path in paths] + targets = select_targets(mutation_repo, named, changed=changed, base="main") + return [f"{target.path}:{target.qualname}" for target in targets] + + in_module = [ + "changed", + "unchanged", + "added", + "Holder.method", + "Holder.static", + "Record.doubled", + ] + every_in_module = [f"{MODULE_PATH}:{name}" for name in in_module] + assert ( + qualnames([MODULE_PATH, "src/devops_cli/gone.py"], changed=False), + qualnames(["src/devops_cli/pkg"], changed=False), + qualnames([MODULE_PATH], changed=True), + ) == ( + every_in_module, + [f"{PACKAGE_PATH}:version", *every_in_module], + [f"{MODULE_PATH}:{f'{cls}.' if cls else ''}{name}" for name, cls in CHANGED_IN_MODULE], + ) + + +def test_mutate_runs_mutmut_serially_on_the_changed_function_globs( + mutmut_calls: Callable[..., list[list[str]]], +) -> None: + """The run argv names each changed function's globs, and the suite runs without xdist.""" + calls = mutmut_calls() + result = runner.invoke(app, ["mutate", "--changed"]) + globs = [glob for path, name, cls in _changed() for glob in _mutmut_globs(path, name, cls)] + pytest_args = tomllib.loads((REPO_ROOT / "pyproject.toml").read_text(encoding="utf-8")) + assert (result.exit_code, calls[0], calls[1]) == ( + 0, + [*UV_RUN, "mutmut", "run", *globs], + [*UV_RUN, "mutmut", "results", "--all", "true"], + ) + assert pytest_args["tool"]["mutmut"]["pytest_add_cli_args"] == ["-n", "0"] + + +def test_mutate_reports_each_survivor_and_the_counts_without_a_score( + mutmut_calls: Callable[..., list[list[str]]], +) -> None: + """Survivors of the selected functions are shown with their diff; siblings sharing a + prefix and unselected functions are not, and no percentage is printed.""" + calls = mutmut_calls() + result = runner.invoke(app, ["mutate", "--changed"]) + shown = [call[-1] for call in calls if "show" in call] + assert (result.exit_code, shown) == ( + 0, + ["devops_cli.pkg.mod.x_changed__mutmut_2", "devops_cli.pkg.mod.xǁRecordǁdoubled__mutmut_1"], + ) + expected = (f"{MODULE_PATH}:4 changed", f"{MODULE_PATH}:34 Record.doubled", SHOW, COUNTS) + assert ([text for text in expected if text not in result.output], "%" in result.output) == ( + [], + False, + ) + + +def test_mutate_never_calls_mutmut_when_only_a_decorated_function_changed( + mutation_repo: Path, + git: Callable[..., None], + mutmut_calls: Callable[..., list[list[str]]], +) -> None: + """mutmut skips a decorated function, so changing only one leaves nothing to mutate.""" + git(mutation_repo, "switch", "--quiet", "main") + _write(mutation_repo, MODULE_PATH, BASE_MODULE.replace("a + 1", "a + 3")) + calls = mutmut_calls() + result = runner.invoke(app, ["mutate", "--changed"]) + assert (result.exit_code, calls) == (0, []) + + +def test_mutate_needs_paths_or_changed(mutmut_calls: Callable[..., list[list[str]]]) -> None: + """Without PATHS or --changed there is nothing to choose from: a usage error.""" + calls = mutmut_calls() + result = runner.invoke(app, ["mutate"]) + assert (result.exit_code, calls) == (2, []) + + +def test_mutate_dry_run_plans_the_mutmut_requests_and_starts_none( + mutmut_calls: Callable[..., list[list[str]]], +) -> None: + """--dry-run reads git but starts no mutmut process, and names the run argv.""" + calls = mutmut_calls() + result = runner.invoke(app, ["mutate", "--changed", "--dry-run"]) + globs = [glob for path, name, cls in _changed() for glob in _mutmut_globs(path, name, cls)] + planned = ( + shlex.join([*UV_RUN, "mutmut", "run", *globs]), + shlex.join([*UV_RUN, "mutmut", "results", "--all", "true"]), + shlex.join([*UV_RUN, "mutmut", "show", ""]), + ) + assert (result.exit_code, calls, [text for text in planned if text not in result.output]) == ( + 0, + [], + [], + ) + + +@pytest.mark.parametrize( + ("codes", "calls_made"), + [ + pytest.param({"run_code": 1}, 1, id="run-fails"), + pytest.param({"results_code": 1}, 2, id="results-fail"), + ], +) +def test_mutate_exits_1_when_mutmut_fails( + mutmut_calls: Callable[..., list[list[str]]], codes: dict[str, int], calls_made: int +) -> None: + """A failing mutmut run or results call is the command's failure; nothing is reported.""" + calls = mutmut_calls(**codes) + result = runner.invoke(app, ["mutate", "--changed"]) + assert (result.exit_code, len(calls)) == (1, calls_made) + + +@pytest.mark.parametrize( + ("base", "error"), + [ + pytest.param("--output=x", "Refusing to diff against '--output=x'", id="option"), + pytest.param("no-such-ref", "Cannot diff against 'no-such-ref'", id="no-commit"), + ], +) +def test_mutate_fails_on_a_base_that_names_no_commit( + mutmut_calls: Callable[..., list[list[str]]], base: str, error: str +) -> None: + """A base git would read as an option is refused, and one naming no commit is an error + rather than an empty selection; mutmut never runs.""" + calls = mutmut_calls() + result = runner.invoke(app, ["mutate", "--changed", f"--base={base}"]) + assert (result.exit_code, calls, error in result.output) == (1, [], True) + + +def test_tally_counts_only_the_selected_functions_mutants() -> None: + """The mutant pattern keeps a sibling sharing the function's prefix out of the counts.""" + target = MutationTarget(path=MODULE_PATH, line=4, class_name=None, name="changed") + report = tally(RESULTS, [target]) + assert (report.counts, [name for name, _ in report.survivors]) == ( + {"killed": 1, "survived": 1, "timeout": 0, "no tests": 0}, + ["devops_cli.pkg.mod.x_changed__mutmut_2"], + ) + + +def test_mutate_is_no_gate_step() -> None: + """Neither the `devops ci` stage list nor ci.yml runs mutation testing.""" + workflow = yaml.safe_load((REPO_ROOT / ".github/workflows/ci.yml").read_text("utf-8")) + runs = [ + str(step.get("run", "")) + for job in workflow["jobs"].values() + for step in job.get("steps", []) + ] + mutating = [run for run in runs if "mutmut" in run or "ci mutate" in run] + assert ("mutate" in {spec.name for spec in get_check_specs()}, mutating) == (False, []) + + +def test_gitignore_keeps_mutants_out_of_the_tree() -> None: + """mutmut's copy of the tree is ignored, so neither git nor the CI cache sees it.""" + lines = (REPO_ROOT / ".gitignore").read_text(encoding="utf-8").splitlines() + ignored = pathspec.PathSpec.from_lines(CONST_GITIGNORE_PATTERN_STYLE, lines) + assert ignored.match_file("mutants/x") + + +def _changed() -> list[tuple[str, str, str | None]]: + return [ + *((PACKAGE_PATH, name, cls) for name, cls in CHANGED_IN_PACKAGE), + *((MODULE_PATH, name, cls) for name, cls in CHANGED_IN_MODULE), + ] diff --git a/tests/test_ssh.py b/tests/test_ssh.py index 1e5dea2ae9..3e740f3a18 100755 --- a/tests/test_ssh.py +++ b/tests/test_ssh.py @@ -562,7 +562,9 @@ def test_crypto_ssh_keys_edge_cases(tmp_path: Path) -> None: assert parse_key_prefix(Path("my-prefix-id_ed25519-20260901")) == "my-prefix" -def test_crypto_ssh_keys_devcontainer_config_resolution(tmp_path: Path) -> None: +def test_crypto_ssh_keys_devcontainer_config_resolution( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: """Verify get_ssh_key_prefix resolves key_prefix from .devcontainer/config.yaml and ancestors.""" from devops_cli.config.settings import _find_project_config_path from devops_cli.crypto.ssh_keys import get_ssh_key_prefix @@ -588,6 +590,6 @@ def test_crypto_ssh_keys_devcontainer_config_resolution(tmp_path: Path) -> None: assert get_ssh_key_prefix(root_proj) == "custom-root-prefix" # 3. Verify _find_project_config_path detects .devcontainer/config.yaml - with patch("devops_cli.config.settings.os.environ.get", return_value=None): - found = _find_project_config_path(base_dir=sub_dir) - assert found == (dev_dir / "config.yaml").resolve() + monkeypatch.delenv("DEVOPS_CLI_CONFIG", raising=False) + found = _find_project_config_path(base_dir=sub_dir) + assert found == (dev_dir / "config.yaml").resolve() diff --git a/uv.lock b/uv.lock index 9772659075..ea22ec9b95 100644 --- a/uv.lock +++ b/uv.lock @@ -788,6 +788,7 @@ dev = [ { name = "diff-cover" }, { name = "h11" }, { name = "hypothesis" }, + { name = "mutmut" }, { name = "mypy" }, { name = "pre-commit" }, { name = "pytest" }, @@ -872,6 +873,7 @@ dev = [ { name = "diff-cover", specifier = "==10.6.0" }, { name = "h11", specifier = "==0.16.0" }, { name = "hypothesis", specifier = "==6.168.3" }, + { name = "mutmut", specifier = "==3.8.0" }, { name = "mypy", specifier = "==2.3.1" }, { name = "pre-commit", specifier = "==4.6.2" }, { name = "pytest", specifier = "==9.1.1" }, @@ -1719,6 +1721,45 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/82/3d/14ce75ef66813643812f3093ab17e46d3a206942ce7376d31ec2d36229e7/lark-1.3.1-py3-none-any.whl", hash = "sha256:c629b661023a014c37da873b4ff58a817398d12635d3bbb2c5a03be7fe5d1e12", size = 113151, upload-time = "2025-10-27T18:25:54.882Z" }, ] +[[package]] +name = "libcst" +version = "1.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/02/c0/098e5c91ff1537f00c85a6438b6cb1863d17144680cc91f47c87f104a200/libcst-1.9.0.tar.gz", hash = "sha256:087b58a9afe076bb08e2d726478e1f16cb928d67ffa9092817e033c335de522a", size = 914739, upload-time = "2026-07-29T21:28:43.153Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/65/2a/4943c71d90975bc59034a057dea346b365c276f308c1d31f5cf2bd85492d/libcst-1.9.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:eccf4c57d273cdd3fe1c67b72cf9bb1bbd4547aa011824e96ccf5b7136057aa4", size = 2044529, upload-time = "2026-07-29T19:25:11.04Z" }, + { url = "https://files.pythonhosted.org/packages/be/ed/1168b98c2a0f338be3a44753647baab051feaf6167cc887bf4447f8fd920/libcst-1.9.0-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:32395244edfe6538e0ea2bf82051d60103d3f54861274805c4fb3745efb70a85", size = 2203519, upload-time = "2026-07-29T19:25:12.543Z" }, + { url = "https://files.pythonhosted.org/packages/25/7d/2eaa697a80f899bcf2245680bbfcc1e478eb3b3328c21d4b2880bdf00dac/libcst-1.9.0-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:444e84c76cd035cd2fe136838c1a524d34b08216521f6f5093df8a6f6cfa5799", size = 2255879, upload-time = "2026-07-29T19:25:14.137Z" }, + { url = "https://files.pythonhosted.org/packages/90/03/793b9fd96dd52d202f5f2b88d7e54f05ebed767d1bb3b32395a1817bf6ab/libcst-1.9.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:bb5d0946f2b4c6711b5d69fe4f833b364f9e7a1a2b08f88b98619dc18975099a", size = 2269807, upload-time = "2026-07-29T19:25:15.647Z" }, + { url = "https://files.pythonhosted.org/packages/a3/f4/1bc7aaea03971c45e8a885fed9fc1c73176dbbd00b0296a3cde9529bafd6/libcst-1.9.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:45808c03528b3ad40b14095348a918e08d98c47b4a125d631cb78e817c0a5b16", size = 2378171, upload-time = "2026-07-29T19:25:17.289Z" }, + { url = "https://files.pythonhosted.org/packages/8e/f7/bc49e367d2bc8817213594dd52cf6b2da2dbbda90b5382d60653999274ac/libcst-1.9.0-cp314-cp314-win_amd64.whl", hash = "sha256:568288cdbfe3b4ca3ae4852cb0a439ff053dd54c841bc4995bf2b71238b5de40", size = 2177847, upload-time = "2026-07-29T19:25:19.35Z" }, + { url = "https://files.pythonhosted.org/packages/87/80/4d81577a22e6d535d1a3409f3a1c6903e09036f0e17fc47f92169dbc3501/libcst-1.9.0-cp314-cp314-win_arm64.whl", hash = "sha256:107593af46945593e7825821793393262bc4fa1d3ea24c3ed487b61269bbbdf8", size = 2058134, upload-time = "2026-07-29T19:25:20.769Z" }, + { url = "https://files.pythonhosted.org/packages/d1/7f/c3f3a0e7a1a2adaa76e815e82a7814d6bfe7d49432276bba652248c68d0b/libcst-1.9.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f6248cb07444ab9a6733a855737a9febed8b9adca51347019348b09a3ac7dfe9", size = 2036102, upload-time = "2026-07-29T19:25:22.212Z" }, + { url = "https://files.pythonhosted.org/packages/4e/af/2f5543255b2c7d749b966adeccc6bfb1652cf8b425afb913d0f3f025a865/libcst-1.9.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:496c24e0d3240bc7da45dae543aff3f5b6509978c39262d6b84ed2fb999dded2", size = 2194806, upload-time = "2026-07-29T19:25:24.017Z" }, + { url = "https://files.pythonhosted.org/packages/cb/5b/03f4cddce426d005e208b39ea7b2d456e667cdee0f1891360f0fc8430f20/libcst-1.9.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:ea490fa8540503db5f321f0268becab46eb50f710e8cec8041e241fd66f6874f", size = 2246762, upload-time = "2026-07-29T19:25:25.365Z" }, + { url = "https://files.pythonhosted.org/packages/d8/31/9d5fe1e43dc3dbcc74f70f3e0e73fcdd8d84effc1059d8b45974f0d0d2eb/libcst-1.9.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:50ab94bb2524b419056d4003032b8c67102ac800f8d85b3c4260a01746d94dbb", size = 2259633, upload-time = "2026-07-29T19:25:26.928Z" }, + { url = "https://files.pythonhosted.org/packages/a8/2b/6752b28d88c3a19b3bc0b9e1838443b6760d5c862b4f4b37955402659e24/libcst-1.9.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:a2faaf92500d0226358125630f5aab4758e8aad3f2d70a10892ec3c700781a54", size = 2368043, upload-time = "2026-07-29T19:25:28.344Z" }, + { url = "https://files.pythonhosted.org/packages/e2/94/775825b2637f8ab05694b6a4b3802ae6783b4e799f9b58d2400c7e2d4369/libcst-1.9.0-cp314-cp314t-win_amd64.whl", hash = "sha256:0c7b548512db25af9c2997a95fa731bd6b6928ecbad6c0915d7482d8bb42d34f", size = 2176432, upload-time = "2026-07-29T19:25:29.921Z" }, + { url = "https://files.pythonhosted.org/packages/fb/3d/88ad67427c6fd9db929e087912b0a540e5140e5cb77e7ca4170edaac8531/libcst-1.9.0-cp314-cp314t-win_arm64.whl", hash = "sha256:497d5329345f1f5df84e41b0bbd00204b64a2fd30dfe3cfaeaebca633a31e877", size = 2052931, upload-time = "2026-07-29T19:25:31.397Z" }, + { url = "https://files.pythonhosted.org/packages/39/e4/ad790b043a38b10cea13166c8dd716654ad8b227c20f12eebf6326191cd9/libcst-1.9.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:a5068bf6114f6f4d79af7a6c80a28d1deb50441150ea1db13b5458ab34bec159", size = 2043987, upload-time = "2026-08-11T05:54:02.122Z" }, + { url = "https://files.pythonhosted.org/packages/15/6b/d3cd8275cc54ffc9817ade91442b3e6e9edd1a4518bd4e6dda13e3152dbe/libcst-1.9.0-cp315-cp315-manylinux_2_28_aarch64.whl", hash = "sha256:7acfd18adcdd32dcf41ce676cf121002afcbe9ad2c72dc0c18d78465beedc228", size = 2204003, upload-time = "2026-08-11T05:54:04.031Z" }, + { url = "https://files.pythonhosted.org/packages/da/62/87eddccb11d5d221d50ac4fff4b6e9b8d48c547028d01f7d0fbc5c8a1d75/libcst-1.9.0-cp315-cp315-manylinux_2_28_x86_64.whl", hash = "sha256:86361e2b426bd1b403e52375703c8b764e226e571adcb30442510710681edbf0", size = 2256053, upload-time = "2026-08-11T05:54:06.228Z" }, + { url = "https://files.pythonhosted.org/packages/18/53/a44126aeb9fca8b4e342e0cc803ea00ca8f6cd5712619a7897b3eba13797/libcst-1.9.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:8c14abe844bec8b021111b3985474e49f5af799c020e8e40dedcac87c97a40c5", size = 2270576, upload-time = "2026-08-11T05:54:08.01Z" }, + { url = "https://files.pythonhosted.org/packages/bb/51/3af3dd44b117d66486e0ed61e43a16b7fc8cc5c372e1dd4ca0e70b888d46/libcst-1.9.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:8930971d2299b7006bb5d10c10038f44efb6da89d5bca2823595e31a9cdb96af", size = 2378573, upload-time = "2026-08-11T05:54:10.093Z" }, + { url = "https://files.pythonhosted.org/packages/fc/e8/e545087d298dbf6494e84a8092f0f5dbd62eedacabd4ecd6b364367b4804/libcst-1.9.0-cp315-cp315-win_amd64.whl", hash = "sha256:5891ce9cff815077614f509e3a23888c5ddb8081d6188e8ba1172c0ccc369022", size = 2177937, upload-time = "2026-08-11T05:54:12.168Z" }, + { url = "https://files.pythonhosted.org/packages/84/17/93a00a8e03494a84db102dd0e3d35b8876b1084ca2c194b331a168d86eb1/libcst-1.9.0-cp315-cp315-win_arm64.whl", hash = "sha256:1260b5d070a3324447a53a00387225a55472a62077ce01922d30a2a78cc4b138", size = 2058633, upload-time = "2026-08-11T05:54:13.817Z" }, + { url = "https://files.pythonhosted.org/packages/d7/00/c3751b12eb81822ea0b6131d374a98bc6c024c4b9ec5f6ea8f53dc23e967/libcst-1.9.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:02ee2dbdb5c218116f16a021350fc267a14be205b50d81c33f5d73857ab6fbf7", size = 2036178, upload-time = "2026-08-11T05:54:15.545Z" }, + { url = "https://files.pythonhosted.org/packages/2f/12/48ff486eb5adc593f4818569e8896b74b672414ab4722a74b17e4c4cf31e/libcst-1.9.0-cp315-cp315t-manylinux_2_28_aarch64.whl", hash = "sha256:3e5b684191a0462b2d40a73261ea7f4da6a49e7a030b7e0fceca46bebb51dfe5", size = 2195496, upload-time = "2026-08-11T05:54:17.625Z" }, + { url = "https://files.pythonhosted.org/packages/51/18/b13a4669864d41a4801fed7b86ede1049dc9a1e1dde250a7ee1f9c3b1285/libcst-1.9.0-cp315-cp315t-manylinux_2_28_x86_64.whl", hash = "sha256:2b150c4f298fe54eb0fe73abf71f57db74d070796140a8c206c9615b6861f01e", size = 2245769, upload-time = "2026-08-11T05:54:19.343Z" }, + { url = "https://files.pythonhosted.org/packages/c8/c7/cf2d46744825e84afbd7228fdeeea8d23cf6c4b2074253c27efb7705c653/libcst-1.9.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:50b913e37187f00a6fb88962009364e1cf1b1284aa1762304f34b52b972f2218", size = 2260576, upload-time = "2026-08-11T05:54:21.444Z" }, + { url = "https://files.pythonhosted.org/packages/d1/4d/5433d3d62250b2e4325938db101766bcab2a006819684713bcccb6259a88/libcst-1.9.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:9f92c75283030fd58fb7d6e560168a00381e0e3368ec8a026a3ec8a828a05f93", size = 2368709, upload-time = "2026-08-11T05:54:23.276Z" }, + { url = "https://files.pythonhosted.org/packages/87/39/9f0e1690727623f99489895db0e42048a3e1e8cea0627517c593e437fd83/libcst-1.9.0-cp315-cp315t-win_amd64.whl", hash = "sha256:4adf97bb1aff8039b0bd4991e2f838be6e4fad552821b26b71a5d1a653c2582f", size = 2177866, upload-time = "2026-08-11T05:54:25.144Z" }, + { url = "https://files.pythonhosted.org/packages/cd/79/9dc7811883e67ea771057e8937bc536eb3e77f3635fc5a93cd85b6fe1ea8/libcst-1.9.0-cp315-cp315t-win_arm64.whl", hash = "sha256:8f0dd08a5773d7051e105250b2a2c73d8065ea9b2d68e7e1bdc5244660e75f93", size = 2052908, upload-time = "2026-08-11T05:54:26.835Z" }, +] + [[package]] name = "librt" version = "0.15.0" @@ -2053,6 +2094,23 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/be/59/e26cb779be4c591d1a910f59d29aca9fba4de70349840a833beba2652371/multidict-6.9.1-py3-none-any.whl", hash = "sha256:7bf6478188f4e47bf5686e8a33da4ae28bf43b1b2528d9ee144d28492bfac60b", size = 19176, upload-time = "2026-09-21T17:59:03.501Z" }, ] +[[package]] +name = "mutmut" +version = "3.8.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "coverage" }, + { name = "libcst" }, + { name = "pytest" }, + { name = "setproctitle" }, + { name = "textual" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/78/30/b334a22184026d92a7549c8a76ad1d397ea65a6f8534ef486556ab861c70/mutmut-3.8.0.tar.gz", hash = "sha256:bc670276518f893ab356f1d28826c49b7e606e7cf89c300e3888c0b52fc1d2ed", size = 83631, upload-time = "2026-09-12T16:53:58.138Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/66/2a/a9904a45804c1de50c0c3baad1512b78d5b66d2befd841104b8a62bf0f35/mutmut-3.8.0-py3-none-any.whl", hash = "sha256:4c0abcef6b8d1116f2adfaad19df12e1c621e4a402d4367ef15bf8cba497b91d", size = 81469, upload-time = "2026-09-12T16:53:56.906Z" }, +] + [[package]] name = "mypy" version = "2.3.1" @@ -3405,6 +3463,62 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b7/46/f5af3402b579fd5e11573ce652019a67074317e18c1935cc0b4ba9b35552/secretstorage-3.5.0-py3-none-any.whl", hash = "sha256:0ce65888c0725fcb2c5bc0fdb8e5438eece02c523557ea40ce0703c266248137", size = 15554, upload-time = "2025-11-23T19:02:51.545Z" }, ] +[[package]] +name = "setproctitle" +version = "1.3.8" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/49/b0/6b8a516c5a9e9630bd5293db78314ac012f690305fe93beadea388626efb/setproctitle-1.3.8.tar.gz", hash = "sha256:cafe209d064a6efb88cb45a03e97981ff8832802b2b5d009dde0197a3b7b41c8", size = 27214, upload-time = "2026-10-01T21:09:27.121Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/1b/15043f8886aecfb31759c4a7c2cda9f85971242a10723049fc0fea34629f/setproctitle-1.3.8-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:f5f1d7e0d57cd75febd70c6fc26c2ea06024ab2006011abb3094b9fea54801ee", size = 18104, upload-time = "2026-10-01T20:59:57.014Z" }, + { url = "https://files.pythonhosted.org/packages/0d/be/c2a6880394bef30aafe274d00ca0c7dac34fff1fb867f6c51abf876a640f/setproctitle-1.3.8-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:b8954fc72fdd49588c8b8d615eabc27dfd8eb6d0cffe987fc5df02934816fb19", size = 13124, upload-time = "2026-10-01T20:59:58.611Z" }, + { url = "https://files.pythonhosted.org/packages/a7/96/6b3818e7f63a30f13bbe97b1ea0a51509a20b5b2d48c95e526c3054343d5/setproctitle-1.3.8-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:4d6a0245679b74e0fda974edb672cd1f2351b0d762279b6776ca3a065c9322a4", size = 33180, upload-time = "2026-10-01T21:04:02.137Z" }, + { url = "https://files.pythonhosted.org/packages/4f/43/fd3220b4bb2169d8723b3561ae7f8e1ee6f2e13e2da38b3a7a150004d2aa/setproctitle-1.3.8-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:394aca04e9f11c469f4f29d25a40a79eb4b8c9a72f438ba6390b776590f89757", size = 34071, upload-time = "2026-10-01T21:07:16.281Z" }, + { url = "https://files.pythonhosted.org/packages/34/58/ee9eeebeb74125723b60eada6e6b2def747815228193327ce470da088f2b/setproctitle-1.3.8-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f92f6ded50c0ae7b0fed612be77c5345ed4a4578f99b98c7f8258d0e599eff16", size = 35923, upload-time = "2026-10-01T21:07:19.054Z" }, + { url = "https://files.pythonhosted.org/packages/f6/fe/b339602e96d73b29fd123c8b9c886e8f9a5afa12a18218eece56bd99c668/setproctitle-1.3.8-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c09f15930910dd895ac113b16c0b3ac2051dcbd44b0f017f94cb51349ba11583", size = 32116, upload-time = "2026-10-01T21:07:25.121Z" }, + { url = "https://files.pythonhosted.org/packages/b2/5e/8d46d34648d8dfdc3f3e941c149ae316b6c6f417391018e279a1bb733c42/setproctitle-1.3.8-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:4756a96435917494ec2f27f0da46bc05eecaa1a7e072d57220ecb2d46ea8a3d3", size = 32980, upload-time = "2026-10-01T21:07:27.826Z" }, + { url = "https://files.pythonhosted.org/packages/dd/6a/10720d27d5f4a47c9af51652b49dd22313be20b9d542e72f80b4b363702b/setproctitle-1.3.8-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:65279b2df2951b64878da5382363e730d242486179c440c8653fe39aa3cc9e62", size = 34307, upload-time = "2026-10-01T21:07:30.62Z" }, + { url = "https://files.pythonhosted.org/packages/6e/65/95dd7b0245fdb7d2f6633613c559ecd9f0b2afeb6e3d962c218b6a1722d4/setproctitle-1.3.8-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:3d2ced815b940c88097e07182c57cbfe1a0156839d1edc9be2bc0e4c74ab4eed", size = 31126, upload-time = "2026-10-01T21:07:33.59Z" }, + { url = "https://files.pythonhosted.org/packages/fd/96/4d62c4ba70cf8fa305f1dcbe35e93449819bb27b451fcb473556acf92650/setproctitle-1.3.8-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:37a91697c3b96bac58b6936b3bf0366af96a2a6cef963fdd9aaf0593a4bd1ff2", size = 32468, upload-time = "2026-10-01T21:07:36.312Z" }, + { url = "https://files.pythonhosted.org/packages/0a/4a/1ec517435d4b572f6c468795331c7b376ec310eca5b1321504c6647b85a9/setproctitle-1.3.8-cp314-cp314-win32.whl", hash = "sha256:7cdd3d6e5e8abcee233157615d88dbb80527a5a4eccb95a93fbf92e6d2c8f9dd", size = 12255, upload-time = "2026-10-01T21:08:12.203Z" }, + { url = "https://files.pythonhosted.org/packages/7c/13/e74a4fa864a0a694104ff74fcb3bef523be94321bac1a8ece64ad04ef233/setproctitle-1.3.8-cp314-cp314-win_amd64.whl", hash = "sha256:5cff3bdbe6be556cc19bd072ff1ed9b5a8f4cbf356cd19b1ca94506b3e2b29f6", size = 13159, upload-time = "2026-10-01T21:08:14.231Z" }, + { url = "https://files.pythonhosted.org/packages/38/d8/019116e7defcd5d2c9264da4a82d369de6806a9161adf73e5f73e63fb715/setproctitle-1.3.8-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:84320e61f3906cc550b900ab1ba02ec53edd2d2e1e917f0873cba16592801c89", size = 18105, upload-time = "2026-10-01T21:07:38.655Z" }, + { url = "https://files.pythonhosted.org/packages/a7/f5/bfa9d6b5574903c17e02caba0e25815bb1c7e7b895d594475676baaa35b4/setproctitle-1.3.8-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:8086259943fc75eb07e11c1d08600709b9ce4fb2ec9bbd2490556c47d3ead135", size = 13125, upload-time = "2026-10-01T21:07:40.774Z" }, + { url = "https://files.pythonhosted.org/packages/d3/29/c7febeedee66b929c335d7b8ce83b1c4baccc65c94a4112fd8c1ea32b57d/setproctitle-1.3.8-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:8879d303d4e3559efdba033ff198c6869010f7958412ec2047674881859fdd7f", size = 34818, upload-time = "2026-10-01T21:07:47.999Z" }, + { url = "https://files.pythonhosted.org/packages/36/b9/90fea18bcb74f19d411df7e9e2d981c4d3e99817870acb0b5cac6540629f/setproctitle-1.3.8-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f7de4da27fa4481e8a7a4ef58c908ffd2b996847c3d7fbf27b5c53ce0984c408", size = 35622, upload-time = "2026-10-01T21:07:51.03Z" }, + { url = "https://files.pythonhosted.org/packages/8f/e9/5899eab6e0b4a127e98a268a157b6bdba4f8ad18d0ed90fdf3e081c20a3b/setproctitle-1.3.8-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:741b1ae7e1cd68745b8b677daba73685dab2d1b8bb12500e6537f3482a91150f", size = 37762, upload-time = "2026-10-01T21:07:53.758Z" }, + { url = "https://files.pythonhosted.org/packages/fd/cd/190748a1f68afe6154b62517d2288b7d4c2092b0efa6e61d044c0f99d17b/setproctitle-1.3.8-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c85ff5b000eef8a280333ca158483a76f86bd374816add5c016a9f4294471289", size = 33548, upload-time = "2026-10-01T21:07:56.148Z" }, + { url = "https://files.pythonhosted.org/packages/26/db/889062b0970f04bc76d8eed03165dc17de8df282399ad931cb10a23b33a3/setproctitle-1.3.8-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:656ffe282ec0ca18308eebb100898c79b4f5698a93228d50d2f2a4a09474d7e0", size = 34298, upload-time = "2026-10-01T21:07:58.898Z" }, + { url = "https://files.pythonhosted.org/packages/6d/bc/adedb2c18eb7bb152b6bc59187f46fc328e7bb729bf28a7e4e43521c4c7a/setproctitle-1.3.8-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:ae87e7b3e6414b3dd887adb72d2c4ea9f210c5f48efafd295ade4a58c760d29d", size = 35897, upload-time = "2026-10-01T21:08:01.561Z" }, + { url = "https://files.pythonhosted.org/packages/38/8e/f1769dcd1eb668b01ad251eb6780b030752d18dabc1b82789b255189772e/setproctitle-1.3.8-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:09cb645c6ae440286391e256203fc03522b3b0f55fda8219f698abb5c447cce7", size = 32435, upload-time = "2026-10-01T21:08:04.112Z" }, + { url = "https://files.pythonhosted.org/packages/79/e5/68be1eed21bba3ce27c6907ddcf0559cb99e4de3aa3ee000a38994371b73/setproctitle-1.3.8-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:84003eeaf2d7460390bbff1dbd7bee5b1213e7ae47a489f0fb7aad6acd2b045c", size = 34024, upload-time = "2026-10-01T21:08:06.514Z" }, + { url = "https://files.pythonhosted.org/packages/40/7e/f275783d6915fac997dbfa3729330552c4f2ddcd4f1bba7ff522f5f05c28/setproctitle-1.3.8-cp314-cp314t-win32.whl", hash = "sha256:ac4e037d276ce27069cad0083c4611b45232278bd2fbac33f06ef9438c171a1e", size = 12259, upload-time = "2026-10-01T21:08:08.432Z" }, + { url = "https://files.pythonhosted.org/packages/86/59/3347f13aa38c81d78f5c93bc55e4355c43550f47348e5de48c5080f3a1b2/setproctitle-1.3.8-cp314-cp314t-win_amd64.whl", hash = "sha256:c284642b229ba7b7b927fb044aba03694b880ab572db3f07a10adc786db1ff7b", size = 13163, upload-time = "2026-10-01T21:08:10.087Z" }, + { url = "https://files.pythonhosted.org/packages/92/e4/e9866831fd0cff677c67488059fab3786a843ff0bd86f4b3c44bea8dd763/setproctitle-1.3.8-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:63348d86ae60b071a898e4241b41da1346d8c36f1a60bf3b698ae5eb35b79865", size = 18107, upload-time = "2026-10-01T21:08:16.029Z" }, + { url = "https://files.pythonhosted.org/packages/ff/79/5c11a8c8cf3b91e54fdf4c93d1c79d99a491e04d77d34c80a90552fe6b46/setproctitle-1.3.8-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:59239b6e5007b1bec79ef444a390b3bcd59cbcb2686c9910da5a42f1e99f738c", size = 13132, upload-time = "2026-10-01T21:08:17.756Z" }, + { url = "https://files.pythonhosted.org/packages/9c/6d/47dea0a33ec67a2813e40bd92deea74c3732fd598bd71b636a92897eaf17/setproctitle-1.3.8-cp315-cp315-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:38310d9cf94959e39d22fdc0154c66c8bdbadfa790c524b04cb36da6333c7507", size = 33509, upload-time = "2026-10-01T21:08:20.254Z" }, + { url = "https://files.pythonhosted.org/packages/f1/7c/5d6945012077e6c393d59432df42d281d213f508bcf6d83a1287ab2eb9ae/setproctitle-1.3.8-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a279b136ed97407209d2dc9c30d1e65405d1a4a06ab162cedd9c4159b51f8f20", size = 34405, upload-time = "2026-10-01T21:08:22.796Z" }, + { url = "https://files.pythonhosted.org/packages/9f/d9/543a4470bfd01529dc35f0014dc68c70665db8b790e3647b41d155203b87/setproctitle-1.3.8-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:26997a85aa70bb088e86f0b7899fb0c909be824d22fc025e87b0005afbe59261", size = 36167, upload-time = "2026-10-01T21:08:25.35Z" }, + { url = "https://files.pythonhosted.org/packages/44/c7/fc55041b162833c4bbbbfe78ed417bcab7b22f9fa72aff1722ff6af46fae/setproctitle-1.3.8-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:35fc5e10fcba6df25d676ef908b44a36c17e7f167738ed016561185e24f4d274", size = 32623, upload-time = "2026-10-01T21:08:27.778Z" }, + { url = "https://files.pythonhosted.org/packages/a5/e2/8c73c990c338b9ca5bf4fc6167ac864a80a53a10e71fd2755ba146f1fce6/setproctitle-1.3.8-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:f5df0503093ec8c3c7e1da53920e79c62ab653b51b136c4736caa252552a8732", size = 33510, upload-time = "2026-10-01T21:08:30.431Z" }, + { url = "https://files.pythonhosted.org/packages/cd/61/8e10270d3a7326dc4e8a1408c631e6ae912625b91f38adaf04794a19e07b/setproctitle-1.3.8-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:0a582308ba43afa7233d28243d9d1212e11c81d3c187a43929ec0cb70c4781c5", size = 34528, upload-time = "2026-10-01T21:08:37.161Z" }, + { url = "https://files.pythonhosted.org/packages/77/d4/00773ca8c876123348e65edfd9eec47464bbfa1a31067c6e1cd382356a0f/setproctitle-1.3.8-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:ce48dbf74e8ec618d74cbaffe1159a4c32a4428de598f0ccdb0782bae618a72a", size = 31681, upload-time = "2026-10-01T21:08:39.874Z" }, + { url = "https://files.pythonhosted.org/packages/d5/42/19c6b634cca492575f9d99868bc35134528fb390d683d6a0396f61df0b8d/setproctitle-1.3.8-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:dd3a8fcee7d8a23e44781144830dee97b53ca4e0380bdd2a0e05b13913ce5725", size = 32999, upload-time = "2026-10-01T21:08:42.36Z" }, + { url = "https://files.pythonhosted.org/packages/94/34/09f653f687e4a1a6f515642519cc65f0e6bcf34631386380924fc9785b44/setproctitle-1.3.8-cp315-cp315-win32.whl", hash = "sha256:50beee618377ce6fd35767a9327f2da594b36778eb10b503ee2dc9b7c801f433", size = 12251, upload-time = "2026-10-01T21:09:17.504Z" }, + { url = "https://files.pythonhosted.org/packages/89/69/ab9afe8c198594533ad5eed6dcea647e1743ac8196a6c6dea974724b72e6/setproctitle-1.3.8-cp315-cp315-win_amd64.whl", hash = "sha256:f5916010de8b6045d7c63d98bb3f7a1e13f8c9c1046e859f2fd8de79c4e2d865", size = 13161, upload-time = "2026-10-01T21:09:19.295Z" }, + { url = "https://files.pythonhosted.org/packages/78/90/da93e1ae012f2515473a45fb33f5ba2ddbbfcce1381c5e41005b31ab3230/setproctitle-1.3.8-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:e9f643bd97374aeb7e4274e5c361277bf1428e8e55246cee6823fa3525dc2c04", size = 18119, upload-time = "2026-10-01T21:08:44.296Z" }, + { url = "https://files.pythonhosted.org/packages/af/35/41b28fa8eb8f1bee9c5516b99262a5df413937bf186e9d50ec3ef812fc61/setproctitle-1.3.8-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:fbd9ceb8c091c125e5892757e4d16af06674dc96edd7b5bf1e627b1ae7650c66", size = 13140, upload-time = "2026-10-01T21:08:46.797Z" }, + { url = "https://files.pythonhosted.org/packages/0c/19/089c878e6b8a3a391ceb03e1653ad6f33f27a5f7e204cf4a54b6a053b83d/setproctitle-1.3.8-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:322b4643f98c824b17dbf2ddb07ea7a37def8cc9e18adee320befce4bdffa271", size = 35122, upload-time = "2026-10-01T21:08:49.921Z" }, + { url = "https://files.pythonhosted.org/packages/88/a7/f419b87fcb6202ef0a94f7cd6bdecb23c2d01f2f07b38f92d3f0c5dfb518/setproctitle-1.3.8-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9e36ee7300584a53fd7ac5f3853323411bde1cf6c081921bd3754a73b4071245", size = 35944, upload-time = "2026-10-01T21:08:52.612Z" }, + { url = "https://files.pythonhosted.org/packages/1e/16/fb181112f3c09a8c8962bd110f538c8a9d287a0c6a8bfd5b4dc39d54e0df/setproctitle-1.3.8-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5c05aff52e6eb9c4d2ea86cf0d0a60b1487ed570263a1b13bb30d9f96aa8ba97", size = 37981, upload-time = "2026-10-01T21:08:55.136Z" }, + { url = "https://files.pythonhosted.org/packages/d8/8f/934846cf63b5ae2e9a88dcac6ddc3ec813e6b9e0919994684f7674155b8a/setproctitle-1.3.8-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:df807e7f036c19235320b6b5137291891d660f10ccb0b50dc46bc8385be18379", size = 34229, upload-time = "2026-10-01T21:08:57.703Z" }, + { url = "https://files.pythonhosted.org/packages/c9/04/c11f73d8aa0ebe5d63866130ad14ca3789a4dfb9fc617c3a612af9c177f9/setproctitle-1.3.8-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:bef8c5f8820c70e8761171409052056ffd247023b001a6254287a0694c3d8b1c", size = 34743, upload-time = "2026-10-01T21:09:04.088Z" }, + { url = "https://files.pythonhosted.org/packages/38/50/8c780488db26e8f51af91465bda6ee224522248dc5220b282791dacbbe5e/setproctitle-1.3.8-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:7855290194637a3c5a2e37c423efbf5813fde97a6b63ab99feade5e05d73dc6c", size = 36094, upload-time = "2026-10-01T21:09:06.67Z" }, + { url = "https://files.pythonhosted.org/packages/b1/e6/13d541653607b3b7232dc9f8baae05b24112ac9a3756c3653903c624c4a9/setproctitle-1.3.8-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:8c0a7753f5ddaf0ecd1fc8df3e2106611d4290f0508e643e723cb5000b7d6c2f", size = 33148, upload-time = "2026-10-01T21:09:09.064Z" }, + { url = "https://files.pythonhosted.org/packages/42/94/f3e16c3a7949fa28a777aa30830bf89098026e13669144b0ec1b147f17f4/setproctitle-1.3.8-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:97b35b15f81363a314baca76674c19027dce19eed1590abd51c2d285830efd50", size = 34488, upload-time = "2026-10-01T21:09:11.756Z" }, + { url = "https://files.pythonhosted.org/packages/4c/e7/9baa826fc44c6f607a39ad35d419da7f51dec2df31ef169e7a4a34e1cc75/setproctitle-1.3.8-cp315-cp315t-win32.whl", hash = "sha256:ecf44731e351c6100885120cecf53a0f43a1bb975a92480de1f9e022ab542bc1", size = 12260, upload-time = "2026-10-01T21:09:13.6Z" }, + { url = "https://files.pythonhosted.org/packages/71/fb/08f55fab7294d18a6b1bc6d13340706c998b4641bd5f99ed9c7a626fcbf0/setproctitle-1.3.8-cp315-cp315t-win_amd64.whl", hash = "sha256:61aac898128dade36438da9387fea570f00cd519ad5231d3b268913afc2fc329", size = 13170, upload-time = "2026-10-01T21:09:15.351Z" }, +] + [[package]] name = "shellingham" version = "1.5.4" From 198a2734ef36c38bc1d6629fe32e70f47276dd10 Mon Sep 17 00:00:00 2001 From: dan-petty-bot Date: Fri, 9 Oct 2026 18:32:11 +0000 Subject: [PATCH 14/15] feat(release): v0.2.32 --- docs/ROADMAP.md | 82 +++++++++++++++++++++++-------------------------- pyproject.toml | 2 +- uv.lock | 2 +- 3 files changed, 41 insertions(+), 45 deletions(-) diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index ed610bb123..78464a2374 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -2,35 +2,21 @@ # Roadmap — dan-petty/devops-cli -## Current release: v0.2.31 +## Current release: v0.2.32 -- [x] #1109 fix(security): URL credential masking uses urllib and httpx2, so passwords containing '@' and non-http schemes are masked and IPv6 hosts stay intact — Status: Done · Priority: P1-High · Value: High · Effort: Medium -- [x] #1141 fix(security): each finding keeps its own fingerprint across unrelated edits, and deduplication and correlation give one result in every input order, in devops scan and in reviews — Status: Done · Priority: P1-High · Value: High · Effort: Medium -- [x] #855 test(security): pin the finding fingerprint and run-store digest to literal values — Status: Done · Priority: P2-Medium · Value: Medium · Effort: Low -- [x] #1036 fix(ai): the durable-run store resolves under the data directory, so tests never write .data/durable_runs.db into the checkout — Status: Done · Priority: P2-Medium · Value: Medium · Effort: Low -- [x] #1041 fix(ci): tests render CLI help at the same width locally and in github ci, so the gate catches width-dependent failures — Status: Done · Priority: P2-Medium · Value: Medium · Effort: Low -- [x] #1108 fix(docker): the Docker endpoint check covers the endpoint the SDK dials, including contexts and the TUI, and pushes accept registry ports — Status: Done · Priority: P2-Medium · Value: High · Effort: Medium -- [x] #1120 fix(deps): pyproject.toml declares every package src imports, and a deptry step in devops ci keeps it that way — Status: Done · Priority: P2-Medium · Value: Medium · Effort: Medium -- [x] #1122 fix(security): the devcontainer no longer starts the git daemon stub meant for argo cd, which served every clone under repos/ without authentication on port 9418 — Status: Done · Priority: P2-Medium · Value: Medium · Effort: Low -- [x] #1311 fix(ci): tests touch no state outside their temporary directories — Status: Done · Priority: P2-Medium · Value: — · Effort: — -- [x] #1338 perf(ci): the gate's test workers start at least 15% faster, and the full test run keeps at least half of that saving — Status: Done · Priority: P2-Medium · Value: Medium · Effort: Medium -- [x] #1371 fix(k8s): the argocd and otel perimeters admit 0.0.0.0/0 ingress and deploy-stack applies neither — Status: Done · Priority: P2-Medium · Value: Medium · Effort: Medium -- [x] #1383 fix(cli): docker sandbox and test sandbox dry runs check the workspace as the real run does — Status: Done · Priority: P2-Medium · Value: Medium · Effort: Low -- [x] #1485 feat(k8s): argo cd image updater keeps the devops application on the digest of service:latest — Status: Done · Priority: P2-Medium · Value: Medium · Effort: Medium - -## Planned release: v0.2.32 - -- [ ] #850 feat(ci): changed-line coverage on pull requests (diff-cover) — Status: Ready · Priority: P2-Medium · Value: Medium · Effort: Medium -- [ ] #852 feat(ci): shuffled repeat runs of a pull request's changed test files — Status: Ready · Priority: P2-Medium · Value: Medium · Effort: Medium -- [ ] #965 fix(ci): review workflow tests start the logfire SDK's credential check, which the network guard blocks — Status: Ready · Priority: P2-Medium · Value: Medium · Effort: Low -- [ ] #1060 fix(k8s): the ollama tier DaemonSets drop privilege escalation and capabilities, use RuntimeDefault seccomp and a read-only root filesystem, and run as non-root where the model directory allows — Status: Ready · Priority: P2-Medium · Value: Medium · Effort: Medium -- [ ] #1111 fix(k8s): service URLs bracket IPv6 hosts, k8s:// addresses reach only their Service, and https probe targets are probed over https — Status: Ready · Priority: P2-Medium · Value: Medium · Effort: Medium -- [ ] #1112 fix(security): URL and host:port reads use the sending client's parser, so key trust, crawls, probes and settings act on the host actually dialled — Status: Ready · Priority: P2-Medium · Value: Medium · Effort: Medium -- [ ] #1114 fix(git): GitHub clones trust GitHub's published host keys through OpenSSH, so junk known_hosts lines and a failed key scan no longer skip pinning — Status: Ready · Priority: P2-Medium · Value: Medium · Effort: Medium -- [ ] #1486 refactor(release): the release no longer pins, bumps or pre-publishes the service image tag; image updater rolls service:latest — Status: Ready · Priority: P2-Medium · Value: High · Effort: High -- [ ] #798 fix(security): the host sandbox declares a noexec /tmp it never applies — Status: Ready · Priority: P3-Low · Value: Low · Effort: Low -- [ ] #853 feat(ci): on-demand mutation testing of changed functions (`devops ci mutate`) — Status: Ready · Priority: P3-Low · Value: Low · Effort: Medium -- [ ] #884 fix(ci): coverage index treats module-level and import-time changes as unindexed — Status: Ready · Priority: P3-Low · Value: Medium · Effort: Medium +- [x] #1129 fix(k8s): k8s-monitoring collectors run in the chart's preset shapes, and node-exporter keeps the series the node dashboards read — Status: Done · Priority: P1-High · Value: High · Effort: Low +- [x] #850 feat(ci): changed-line coverage on pull requests (diff-cover) — Status: Done · Priority: P2-Medium · Value: Medium · Effort: Medium +- [x] #852 feat(ci): shuffled repeat runs of a pull request's changed test files — Status: Done · Priority: P2-Medium · Value: Medium · Effort: Medium +- [x] #965 fix(ci): review workflow tests start the logfire SDK's credential check, which the network guard blocks — Status: Done · Priority: P2-Medium · Value: Medium · Effort: Low +- [x] #1060 fix(k8s): the ollama tier DaemonSets drop privilege escalation and capabilities, use RuntimeDefault seccomp and a read-only root filesystem, and run as non-root where the model directory allows — Status: Done · Priority: P2-Medium · Value: Medium · Effort: Medium +- [x] #1111 fix(k8s): service URLs bracket IPv6 hosts, k8s:// addresses reach only their Service, and https probe targets are probed over https — Status: Done · Priority: P2-Medium · Value: Medium · Effort: Medium +- [x] #1112 fix(security): URL and host:port reads use the sending client's parser, so key trust, crawls, probes and settings act on the host actually dialled — Status: Done · Priority: P2-Medium · Value: Medium · Effort: Medium +- [x] #1114 fix(git): GitHub clones trust GitHub's published host keys through OpenSSH, so junk known_hosts lines and a failed key scan no longer skip pinning — Status: Done · Priority: P2-Medium · Value: Medium · Effort: Medium +- [x] #1486 refactor(release): the release no longer pins, bumps or pre-publishes the service image tag; image updater rolls service:latest — Status: Done · Priority: P2-Medium · Value: High · Effort: High +- [x] #1494 fix(ci): ci jobs run on a named ubuntu-24.04 runner and always use uv's managed python, never the runner's own python — Status: Done · Priority: P2-Medium · Value: High · Effort: Low +- [x] #1499 fix(ci): ci's trivy scans run the trivy version tools.lock pins, so ci and local scans agree — Status: Done · Priority: P2-Medium · Value: Medium · Effort: Low +- [x] #798 fix(security): the host sandbox declares a noexec /tmp it never applies — Status: Done · Priority: P3-Low · Value: Low · Effort: Low +- [x] #853 feat(ci): on-demand mutation testing of changed functions (`devops ci mutate`) — Status: Done · Priority: P3-Low · Value: Low · Effort: Medium ## Planned release: v0.2.33 @@ -41,8 +27,9 @@ - [ ] #277 feat(ai): cross-domain analogical pattern retriever (`devops ai research analogies`) — Status: Ready · Priority: P1-High · Value: High · Effort: High - [ ] #278 feat(ai): living mental model synthesizer & causal graph distiller (`devops ai research model`) — Status: Ready · Priority: P1-High · Value: High · Effort: High - [ ] #412 feat(cli): reachable `--dry-run` previews for delegated commands — Status: Ready · Priority: P1-High · Value: Medium · Effort: High -- [ ] #419 feat(review): publish scanner findings to code scanning — Status: New · Priority: P1-High · Value: — · Effort: — -- [ ] #438 feat(cli): oci container image packaging, standardized metadata & ghcr package integration — Status: New · Priority: P1-High · Value: — · Effort: — +- [ ] #419 feat(review): publish scanner findings to code scanning — Status: Ready · Priority: P1-High · Value: — · Effort: — +- [ ] #438 feat(cli): oci container image packaging, standardized metadata & ghcr package integration — Status: Ready · Priority: P1-High · Value: — · Effort: — +- [ ] #873 feat(review): ruff and mypy run as review evidence with the project's settings, advisory rules report only on changed lines, and changed functions show complexity before and after — Status: Ready · Priority: P1-High · Value: Medium · Effort: Medium ## Planned release: v0.2.34 @@ -54,23 +41,32 @@ - [ ] #793 fix(ai): a partial pricing snapshot replaces the whole catalog and never expires — Status: Ready · Priority: P1-High · Value: Medium · Effort: Medium - [ ] #794 fix(k8s): tunnel sync and url setup still overwrite settings they should keep — Status: New · Priority: P1-High · Value: High · Effort: Medium - [ ] #820 chore(ai): remove the code, config and policies left over from the removed vLLM deployments — Status: Ready · Priority: P1-High · Value: Medium · Effort: High +- [ ] #1013 fix(review): the response cache stores and serves only replies the review can use, and a schema echo no longer reads as a clean file — Status: Blocked · Priority: P1-High · Value: High · Effort: Medium +- [ ] #1021 fix(review): a correct refutation stands when the guard's evidence is a path token, a citation inside the finding's own lines, or generic scanner wording — Status: Blocked · Priority: P1-High · Value: High · Effort: Medium + +## Planned release: v0.2.35 + +- [ ] #410 feat(cli): local-path provisioner volume reclaim failures — Status: New · Priority: P2-Medium · Value: Medium · Effort: Medium +- [ ] #411 feat(cli): output format adoption across the command surface — Status: New · Priority: P2-Medium · Value: Medium · Effort: High +- [ ] #416 feat(cli): structured fuzzing of parsers and schema boundaries — Status: New · Priority: P2-Medium · Value: Medium · Effort: Medium +- [ ] #417 feat(ai): synthetic prompt adversaries for injection resistance — Status: New · Priority: P2-Medium · Value: Medium · Effort: Medium +- [ ] #423 feat(cli): blind exception handling policy — Status: New · Priority: P2-Medium · Value: Medium · Effort: High +- [ ] #425 feat(cli): outward-facing capability & upstream maturity survey — Status: New · Priority: P2-Medium · Value: — · Effort: — +- [ ] #478 feat(ai): llm gateway tuning render and apply configuration with rollback — Status: New · Priority: P2-Medium · Value: Medium · Effort: High ## Backlog +- [ ] #1496 chore(github): copilot reviews each pull request into main once and ai scan for pull requests is off, so the copilot allowance lasts the month — Status: New · Priority: P0-Critical · Value: Medium · Effort: Low - [ ] #772 feat(review): review tools run through one injectable executor in a network-less sandbox with CPU, memory and time limits — Status: Ready · Priority: P1-High · Value: High · Effort: High - [ ] #844 feat(ci): fail-to-pass check proves a fix's tests fail on its base (`devops ci fail-to-pass`) — Status: Ready · Priority: P1-High · Value: Medium · Effort: High - [ ] #857 feat(mcp): mcp tools declare ToolAnnotations, and mutating tools require approval in devops-cli's own agent loop — Status: New · Priority: P1-High · Value: High · Effort: High - [ ] #861 fix(github): supply-chain claims made true — live Dependabot, zizmor and workflow invocation contracts — Status: New · Priority: P1-High · Value: High · Effort: High -- [ ] #873 feat(review): ruff and mypy run as review evidence with the project's settings, advisory rules report only on changed lines, and changed functions show complexity before and after — Status: Ready · Priority: P1-High · Value: Medium · Effort: Medium - [ ] #983 refactor(github): the github session owns transport, ledger, error classes and link pagination — Status: New · Priority: P1-High · Value: — · Effort: — -- [ ] #1013 fix(review): the response cache stores and serves only replies the review can use, and a schema echo no longer reads as a clean file — Status: Blocked · Priority: P1-High · Value: High · Effort: Medium -- [ ] #1021 fix(review): a correct refutation stands when the guard's evidence is a path token, a citation inside the finding's own lines, or generic scanner wording — Status: Blocked · Priority: P1-High · Value: High · Effort: Medium - [ ] #1066 fix(ai): a rag collection records its embedding model, a mismatch fails instead of wiping the collection, and ranking keeps the cosine score — Status: Ready · Priority: P1-High · Value: Medium · Effort: Medium - [ ] #1103 refactor(docs): no documentation-only pull requests: release artifacts are made as the release merges, and every kept doc changes with its code or is deleted — Status: New · Priority: P1-High · Value: High · Effort: Medium - [ ] #1104 fix(k8s): the pyroscope Service alias collides with the pyroscope Helm release's own Service, so a fresh deploy-stack can't install Pyroscope — Status: Ready · Priority: P1-High · Value: Medium · Effort: Low - [ ] #1107 feat(ci): hand-rolled URL and address parsing fails `devops ci`, AGENTS.md makes the library the rule, and reviews stop discarding the findings — Status: New · Priority: P1-High · Value: High · Effort: High - [ ] #1128 refactor(k8s): the monitoring stack runs on k8s-monitoring and chart features, with no duplicate collection, dead defaults or leftovers — Status: New · Priority: P1-High · Value: High · Effort: High -- [ ] #1129 fix(k8s): k8s-monitoring collectors run in the chart's preset shapes, and node-exporter keeps the series the node dashboards read — Status: Ready · Priority: P1-High · Value: High · Effort: Low - [ ] #1130 fix(k8s): the prometheus server scrapes only itself and the otel collector, and k8s-monitoring discovers every other target — Status: Ready · Priority: P1-High · Value: High · Effort: Medium - [ ] #1137 feat(review): evidence-first code review — tools find, version-pinned facts ground, models explain and plan, fixes are re-checked — Status: New · Priority: P1-High · Value: High · Effort: High - [ ] #1139 fix(ai): the knowledge base is re-indexed whenever the installed knowledge base differs from what its collection holds, and rag status and drift read Qdrant instead of the local cache — Status: Ready · Priority: P1-High · Value: High · Effort: Medium @@ -95,14 +91,7 @@ - [ ] #1432 fix(k8s): k8s:// service requests authenticate with the Kubernetes client's own auth settings, and the pod informer watches through the typed list call — Status: New · Priority: P1-High · Value: High · Effort: Medium - [ ] #1435 fix(security): the agent scan tools run the scanner adapters and report a missing or failed scan as such, not as clean — Status: New · Priority: P1-High · Value: High · Effort: Medium - [ ] #1450 fix(release): the Service's cut commit collects the changelog fragments into the version's CHANGELOG.md section — Status: New · Priority: P1-High · Value: High · Effort: Medium -- [ ] #410 feat(cli): local-path provisioner volume reclaim failures — Status: New · Priority: P2-Medium · Value: Medium · Effort: Medium -- [ ] #411 feat(cli): output format adoption across the command surface — Status: New · Priority: P2-Medium · Value: Medium · Effort: High - [ ] #414 feat(cli): generator-side rule pruning measured against verifier overlap — Status: New · Priority: P2-Medium · Value: Medium · Effort: Medium -- [ ] #416 feat(cli): structured fuzzing of parsers and schema boundaries — Status: New · Priority: P2-Medium · Value: Medium · Effort: Medium -- [ ] #417 feat(ai): synthetic prompt adversaries for injection resistance — Status: New · Priority: P2-Medium · Value: Medium · Effort: Medium -- [ ] #423 feat(cli): blind exception handling policy — Status: New · Priority: P2-Medium · Value: Medium · Effort: High -- [ ] #425 feat(cli): outward-facing capability & upstream maturity survey — Status: New · Priority: P2-Medium · Value: — · Effort: — -- [ ] #478 feat(ai): llm gateway tuning render and apply configuration with rollback — Status: New · Priority: P2-Medium · Value: Medium · Effort: High - [ ] #480 feat(review): review page size against quality and speed — Status: New · Priority: P2-Medium · Value: Medium · Effort: Low - [ ] #482 feat(ai): llm cache effectiveness during reviews response cache and prefix cache — Status: New · Priority: P2-Medium · Value: Medium · Effort: Medium - [ ] #539 AST support for YAML, Dockerfiles and Helm templates — Status: New · Priority: P2-Medium · Value: Medium · Effort: Medium @@ -148,7 +137,7 @@ - [ ] #877 feat(review): feedback export counts each review subject once and keeps every human verdict — Status: Ready · Priority: P2-Medium · Value: Medium · Effort: Medium - [ ] #879 docs(agents): task files carry no status, milestone or priority and are written only by the delivering pr — Status: Ready · Priority: P2-Medium · Value: Medium · Effort: Medium - [ ] #880 refactor(github): the board's priority field is the only priority source, and stray type labels merge into type/bug — Status: Ready · Priority: P2-Medium · Value: Medium · Effort: Medium -- [ ] #882 feat(github): reprioritization re-ranks the planned releases and the backlog — Status: Ready · Priority: P2-Medium · Value: Medium · Effort: High +- [ ] #882 feat(roadmap): every open p0 and p1 item sits in an open release, placed by intake as it arrives and by reprioritize from the backlog — Status: Ready · Priority: P2-Medium · Value: Medium · Effort: High - [ ] #883 feat(review): verified findings about merged code enter the roadmap through intake — Status: Ready · Priority: P2-Medium · Value: Medium · Effort: Medium - [ ] #887 fix(security): local names come from the public suffix list, and domains match on DNS labels, not string suffixes — Status: Ready · Priority: P2-Medium · Value: Medium · Effort: Medium - [ ] #888 fix(ai): reasoning request parameters follow the model's declared capability, not its name — Status: Ready · Priority: P2-Medium · Value: Medium · Effort: Medium @@ -191,7 +180,7 @@ - [ ] #1116 fix(cli): `devops docker prune` removes stopped containers, unused networks and dangling images instead of failing on every engine — Status: Ready · Priority: P2-Medium · Value: Medium · Effort: Low - [ ] #1117 feat(docker): container commands find a Podman engine before Docker's default socket, and rootless sandboxes run as the host user — Status: Ready · Priority: P2-Medium · Value: High · Effort: Medium - [ ] #1118 fix(github): gh calls no longer stall silently for up to a minute behind a fixed 60-call window, and the unmaintained `ratelimit` package is removed — Status: New · Priority: P2-Medium · Value: Medium · Effort: Low -- [ ] #1119 chore(deps): actionlint comes from the actionlint project's own digest-pinned image, not a third-party PyPI repackaging — Status: New · Priority: P2-Medium · Value: Medium · Effort: Medium +- [ ] #1119 chore(deps): the workflow linter comes from a maintained source that knows current runner labels, replacing the stalled actionlint — Status: New · Priority: P2-Medium · Value: Medium · Effort: Medium - [ ] #1123 fix(github): the release-start trim and the cap descope pass over an item that a staying item depends on, so the job never keeps an item whose dependency it moved — Status: Ready · Priority: P2-Medium · Value: High · Effort: Medium - [ ] #1126 feat(roadmap): the roadmap job tallies each release's joins, descopes and trims by reason, and reports them in its plan and as gauges — Status: Ready · Priority: P2-Medium · Value: High · Effort: Medium - [ ] #1127 feat(roadmap): a consolidation job proposes one task for open items that share a root cause or change surface, and a person applies it (`devops roadmap consolidate`) — Status: New · Priority: P2-Medium · Value: Medium · Effort: High @@ -289,6 +278,10 @@ - [ ] #1468 fix(config): a config file that does not parse never prints its line from any command that loads settings — Status: New · Priority: P2-Medium · Value: High · Effort: Low - [ ] #1469 fix(config): devops config audit-keys exits 1 when it finds a plaintext secret — Status: New · Priority: P2-Medium · Value: High · Effort: Low - [ ] #1470 fix(roadmap): refine writes its section's end marker, so a re-refined item keeps one design section instead of two — Status: New · Priority: P2-Medium · Value: Medium · Effort: Low +- [ ] #1492 fix(security): the service image ships a gh built with go 1.27.2 or later, and the two go stdlib ignores are dropped — Status: New · Priority: P2-Medium · Value: Medium · Effort: Low +- [ ] #1498 fix(ai): agent tools taken from the mcp server stop offering the model fastmcp's ctx parameter — Status: New · Priority: P2-Medium · Value: Medium · Effort: Low +- [ ] #1514 feat(roadmap): a release keeps 4 slots above its cap of 12, so a start still fills to 12 and nothing is trimmed or descoped until it holds more than 16 — Status: New · Priority: P2-Medium · Value: Medium · Effort: Low +- [ ] #1515 feat(roadmap): refine runs every hour and readies the new items of every planned release, nearest first, before that release starts — Status: New · Priority: P2-Medium · Value: High · Effort: Medium - [ ] #409 feat(telemetry): startup dependency ordering for the telemetry stack — Status: New · Priority: P3-Low · Value: Low · Effort: Low - [ ] #477 feat(ai): llm gateway tuning cost from real traffic and no-load capacity estimates — Status: New · Priority: P3-Low · Value: Low · Effort: Medium - [ ] #479 feat(ai): reasoning budget tuning for the review pool — Status: New · Priority: P3-Low · Value: Low · Effort: Medium @@ -334,3 +327,6 @@ - [ ] #1302 fix(review): a dependency advisory that admission rejects is not reported — Status: New · Priority: P3-Low · Value: Low · Effort: Low - [ ] #1303 docs(agent): pending-a-person steps name only manifests that exist in the repository — Status: New · Priority: P3-Low · Value: — · Effort: — - [ ] #1350 fix(github): the commit-status read fails closed when the runner raises, and check_verdict no longer swallows StopIteration from under-scripted test mocks — Status: New · Priority: P3-Low · Value: Medium · Effort: Low +- [ ] #1495 fix(ci): the toolchain action's cache steps run on node 24, and only one job per push saves the setup-uv cache — Status: New · Priority: P3-Low · Value: Low · Effort: Low +- [ ] #1497 fix(ci): the test run stops warning about unclosed test databases, pydantic's deprecated Extra and starlette's BlockingPortal alias — Status: New · Priority: P3-Low · Value: Medium · Effort: Medium +- [ ] #1501 fix(ci): ci jobs move from ubuntu-24.04 to ubuntu-26.04 once the workflow linter accepts the label — Status: New · Priority: P3-Low · Value: Medium · Effort: Low diff --git a/pyproject.toml b/pyproject.toml index 44da68741b..1de256f231 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "devops-cli" -version = "0.2.31" +version = "0.2.32" description = "DevOps CLI for managing repos, SSH keys, Kubernetes, and more" requires-python = ">=3.14" diff --git a/uv.lock b/uv.lock index ea22ec9b95..f400e7869c 100644 --- a/uv.lock +++ b/uv.lock @@ -715,7 +715,7 @@ wheels = [ [[package]] name = "devops-cli" -version = "0.2.31" +version = "0.2.32" source = { editable = "." } dependencies = [ { name = "aiolimiter" }, From f61cd53e73550c4b38dbf56f53bfbdaa2fa5e2cc Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 9 Oct 2026 12:39:10 -0600 Subject: [PATCH 15/15] chore(release): collect the v0.2.32 changelog fragments (#1517) The Service's cut (198a273) bumped v0.2.32 without collecting the 13 fragments (#1450), so CHANGELOG.md's newest section was 0.2.31. This moves them into the [0.2.32] section before release PR #1516 merges. --- CHANGELOG.md | 51 +++++++++++++++++++++++++++++++++++++++++++++ changelog.d/1060.md | 2 -- changelog.d/1111.md | 6 ------ changelog.d/1112.md | 12 ----------- changelog.d/1114.md | 9 -------- changelog.d/1129.md | 5 ----- changelog.d/1486.md | 8 ------- changelog.d/1494.md | 2 -- changelog.d/1499.md | 2 -- changelog.d/798.md | 3 --- changelog.d/850.md | 2 -- changelog.d/852.md | 5 ----- changelog.d/853.md | 3 --- changelog.d/965.md | 2 -- 14 files changed, 51 insertions(+), 61 deletions(-) delete mode 100644 changelog.d/1060.md delete mode 100644 changelog.d/1111.md delete mode 100644 changelog.d/1112.md delete mode 100644 changelog.d/1114.md delete mode 100644 changelog.d/1129.md delete mode 100644 changelog.d/1486.md delete mode 100644 changelog.d/1494.md delete mode 100644 changelog.d/1499.md delete mode 100644 changelog.d/798.md delete mode 100644 changelog.d/850.md delete mode 100644 changelog.d/852.md delete mode 100644 changelog.d/853.md delete mode 100644 changelog.d/965.md diff --git a/CHANGELOG.md b/CHANGELOG.md index ad29867cd9..bdee531bf0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,57 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.2.32] - 2026-10-09 + +### Added +- Pull requests show changed-line coverage against their base branch (diff-cover), plus any added `pragma: no cover` lines, in the Tests & Coverage job summary. The report is advisory and sets no coverage threshold (#850). +- pytest-randomly 5.0.0 joins the dev dependency group. `addopts` blocks it with `-p no:randomly`, so `pytest`, `devops ci` and every other run keep file order, and `uv run pytest --co -q` collects the same order as before (#852). +- `devops ci test --repeat N --seed S` runs the selected test files N times, one run after another on one process (`-n 0`), each shuffled by pytest-randomly with seeds S to S+N-1. S defaults to a seed derived from HEAD's commit hash. The first failing run stops the command and prints its seed with the command that reproduces it. `--repeat` refuses a run that no test file narrows, since shuffling the whole suite waits for thread-leak isolation (#852). +- The advisory **Changed-Test Independence** pull-request job in `ci.yml` runs `devops ci test --repeat 3` over the pull request's added or modified test files, and skips its toolchain and test steps when no test file changed (#852). +- `devops ci mutate [PATHS] [--changed] [--base REF]` mutation-tests functions with mutmut 3.8 on demand (#853). With `--changed` it maps the functions the working tree changed since its merge base with `--base` (default `main`), untracked files git does not ignore included, to mutmut's names, and a `--base` naming no commit is an error; PATHS alone select every function in those files. mutmut runs the tests covering each function in its own process, with xdist off, and the command shows each mutant no test killed, with its diff, then the killed, survived, timeout and no-tests counts. It prints no score, exits 0 whatever survives, and is neither a `devops ci` stage nor a `ci.yml` step. The first run mutates the whole source tree into the git-ignored `mutants/` and runs the test suite once, serially; later runs reuse it, and `rm -rf mutants` resets it. +- An architectural invariant fails on any `# pragma: no mutate` under `src`, so no line exempts itself from mutation (#853). + +### Changed +- The settings parser refuses scheme-less URLs for `argocd.url`, `grafana.url`, `ai.ollama_urls`, and `OLLAMA_BASE_URL` with a prescriptive `ConfigurationError` instead of prefixing `http://`. +- The network probe refuses targets lacking a host name or carrying invalid ports with a `ValidationError`. +- The embedding benchmark refuses unrecognised endpoints under a gateway provider, requiring `--provider` to benchmark external endpoints. +- Sandbox whitelist parsing refuses entries containing empty port suffixes (`example.com:`, `example.com:/path`). +- Failed repository clones wrap `gitlib.GitCommandError` into `GitOperationError` and report masked stderr from git and OpenSSH without exposing credentials. +- Pinned GitHub host keys are seeded across all clone operations, including HTTPS clones. +- The release no longer pins, bumps or pre-publishes the Service image's tag; Argo CD Image Updater rolls the Service onto `service:latest` (#1486). A release pull request's CI now builds, smoke-tests and scans the Service image without pushing it. On the merge to `main`, `release.yml` builds the image, scans it, pushes it by digest and attests its provenance, then tags it `vX.Y.Z` and `latest`, and Image Updater moves Application `devops` onto the new digest within one poll, with no git commit. + +### Removed +- In-process `known_hosts` parser and runtime `ssh-keyscan` invocation, delegating host key validation to OpenSSH. +- The release cut's bump of the Service image's `newTag` and its rewrite of the Argo CD git sources' `targetRevision` (#1486). +- `devops release check`'s checks of the Service image pin and of the Argo CD `targetRevision`s (#1486). +- The `images:` pin in `k8s/devops/kustomization.yaml` (#1486). +- Service image publishing from `release/vX.Y.Z` in `release.yml`, with its publication plan and the step that pointed `latest` at an image the release branch published (#1486). + +### Fixed +- The `devops review` command tests no longer start the Logfire SDK's token-check thread, which printed the "Logfire API is unreachable" warning on every run and made the dry-run socket-recorder test flaky. The tests read the per-test config instead of a `MagicMock` settings object, and a background thread that dies with an exception now fails the test run (#965). +- The ollama tier DaemonSets no longer run ollama as root: every tier runs it as UID and GID 10001 with RuntimeDefault seccomp, no privilege escalation, all capabilities dropped and a read-only root filesystem, with `/tmp` on an emptyDir (#1060). `HOME` is `/home/ollama`, so the key and models stay on the hostPath `/var/lib/ollama` and nothing is downloaded again. A root initContainer, `own-model-directory`, holding `CAP_CHOWN` alone, gives that directory to UID 10001 at every start, because `fsGroup` does not apply to hostPath volumes; it is the one `run-as-non-root` exception kube-linter reports, recorded in the manifest and `k8s/README.md`. `test_every_ollama_tier_runs_unprivileged` pins these settings for all 9 tiers. +- Kubernetes service, node, LoadBalancer, and telemetry collector URL builders bracket IPv6 host addresses using `httpx2.URL`, preventing URL parser failures. +- `configure-urls` handles IPv6 cluster endpoints and falls back safely to loopback when endpoints are unreachable, including port-80 LoadBalancers. +- Kubernetes Service proxy addressing validates namespace, service, and port identifiers and refuses dot segments (`..`, `.`, `%2e%2e`), preventing path traversal and credential leakage beyond the Service boundary. +- Target resolution for Kubernetes API proxies preserves server path prefixes, raw URI encodings, and cleanly separates connection base URLs and path prefixes. +- Sandbox network probe targets using `https://` are probed over HTTPS with paths appended via `append_path`, preserving path queries and IPv6 bracketing. +- URL, endpoint, and authority reads across benchmark runners, docs ingester, telemetry exporters, vulnerability lookups, and pricing now use sending client parsers (`httpx2.URL` and `read_url_or_authority`), preventing scheme sniffing and port mismatch bugs. +- Benchmark key trust boundaries compare canonical URL origins through `httpx2.Origin`, preventing trust boundary leaks and ensuring consistent host evaluation. +- The documentation crawler normalizes link resolution and origin checks using `httpx2.URL.origin`, preventing scheme downgrades and SSRF boundary escapes. +- OTLP telemetry client preserves explicit collector schemes and endpoints, preventing invalid gRPC port conversions and TLS configuration errors. +- Vault broker URI parsing respects scheme case-insensitivity and preserves fragment separation. +- Prometheus keeps every series node-exporter serves (no allow list; its collector flags decide what is collected), so Node Exporter Full and the Kubernetes node dashboard show data again (#1129). +- The `alloy-singleton` collector runs as one Deployment pod through the chart's `singleton` preset instead of a DaemonSet per node, so Kubernetes events are watched and shipped once (#1129). +- Alloy writes the cluster name to Prometheus once, as `cluster`, without the duplicate `k8s_cluster_name` label (#1129). +- `kube_hpa_labels` is removed from the kube-state-metrics allow list, since kube-state-metrics v2 never serves it (#1129). +- CI jobs name their runner image, `ubuntu-24.04`, instead of `ubuntu-latest`, and uv in `ci.yml` and `release.yml` uses only its own CPython builds (`UV_MANAGED_PYTHON`). GitHub moves `ubuntu-latest` to Ubuntu 26.04 from 2026-10-19, where uv would have used the image's own Python 3.14 instead of the 3.14.7 that `.python-version` pins. The move to `ubuntu-26.04` waits for the workflow linter to accept the label (#1501) (#1494). +- CI's and the release's Service image scans run Trivy 0.75.0, the version `tools.lock` pins for `devops install-tools`, instead of 0.70.0, and a workflow contract test fails whenever an `aquasecurity/trivy-action` step's `version` differs from the lock (#1499). + +### Security +- The host sandbox no longer declares a noexec `/tmp` that bubblewrap never applied (#798). Bubblewrap has no noexec option for a tmpfs, so the host policy now declares only the 64 MiB size, and the container sandboxes keep their `size=64m,noexec` policy. A host sandbox whose policy declares a tmpfs option bubblewrap cannot apply, such as `noexec` or `size=50%`, now fails at construction with an error naming the option, instead of dropping it. SECURITY.md now says that the host sandbox's `/tmp` allows execution. +- The output-cap test now runs a writer that ignores SIGPIPE and checks that the sandbox kills it at the cap within 1 s, well before its timeout (#798). +- GitHub clones append GitHub's published host keys directly to `~/.ssh/known_hosts`, ensuring junk known_hosts lines no longer skip pinning and failed keyscans no longer skip host-key verification silently. + ## [0.2.31] - 2026-10-09 ### Added diff --git a/changelog.d/1060.md b/changelog.d/1060.md deleted file mode 100644 index 2053eef944..0000000000 --- a/changelog.d/1060.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- The ollama tier DaemonSets no longer run ollama as root: every tier runs it as UID and GID 10001 with RuntimeDefault seccomp, no privilege escalation, all capabilities dropped and a read-only root filesystem, with `/tmp` on an emptyDir (#1060). `HOME` is `/home/ollama`, so the key and models stay on the hostPath `/var/lib/ollama` and nothing is downloaded again. A root initContainer, `own-model-directory`, holding `CAP_CHOWN` alone, gives that directory to UID 10001 at every start, because `fsGroup` does not apply to hostPath volumes; it is the one `run-as-non-root` exception kube-linter reports, recorded in the manifest and `k8s/README.md`. `test_every_ollama_tier_runs_unprivileged` pins these settings for all 9 tiers. diff --git a/changelog.d/1111.md b/changelog.d/1111.md deleted file mode 100644 index b9f58aae1e..0000000000 --- a/changelog.d/1111.md +++ /dev/null @@ -1,6 +0,0 @@ -### Fixed -- Kubernetes service, node, LoadBalancer, and telemetry collector URL builders bracket IPv6 host addresses using `httpx2.URL`, preventing URL parser failures. -- `configure-urls` handles IPv6 cluster endpoints and falls back safely to loopback when endpoints are unreachable, including port-80 LoadBalancers. -- Kubernetes Service proxy addressing validates namespace, service, and port identifiers and refuses dot segments (`..`, `.`, `%2e%2e`), preventing path traversal and credential leakage beyond the Service boundary. -- Target resolution for Kubernetes API proxies preserves server path prefixes, raw URI encodings, and cleanly separates connection base URLs and path prefixes. -- Sandbox network probe targets using `https://` are probed over HTTPS with paths appended via `append_path`, preserving path queries and IPv6 bracketing. diff --git a/changelog.d/1112.md b/changelog.d/1112.md deleted file mode 100644 index 78117ad3d0..0000000000 --- a/changelog.d/1112.md +++ /dev/null @@ -1,12 +0,0 @@ -### Changed -- The settings parser refuses scheme-less URLs for `argocd.url`, `grafana.url`, `ai.ollama_urls`, and `OLLAMA_BASE_URL` with a prescriptive `ConfigurationError` instead of prefixing `http://`. -- The network probe refuses targets lacking a host name or carrying invalid ports with a `ValidationError`. -- The embedding benchmark refuses unrecognised endpoints under a gateway provider, requiring `--provider` to benchmark external endpoints. -- Sandbox whitelist parsing refuses entries containing empty port suffixes (`example.com:`, `example.com:/path`). - -### Fixed -- URL, endpoint, and authority reads across benchmark runners, docs ingester, telemetry exporters, vulnerability lookups, and pricing now use sending client parsers (`httpx2.URL` and `read_url_or_authority`), preventing scheme sniffing and port mismatch bugs. -- Benchmark key trust boundaries compare canonical URL origins through `httpx2.Origin`, preventing trust boundary leaks and ensuring consistent host evaluation. -- The documentation crawler normalizes link resolution and origin checks using `httpx2.URL.origin`, preventing scheme downgrades and SSRF boundary escapes. -- OTLP telemetry client preserves explicit collector schemes and endpoints, preventing invalid gRPC port conversions and TLS configuration errors. -- Vault broker URI parsing respects scheme case-insensitivity and preserves fragment separation. diff --git a/changelog.d/1114.md b/changelog.d/1114.md deleted file mode 100644 index 7dea4f9048..0000000000 --- a/changelog.d/1114.md +++ /dev/null @@ -1,9 +0,0 @@ -### Security -- GitHub clones append GitHub's published host keys directly to `~/.ssh/known_hosts`, ensuring junk known_hosts lines no longer skip pinning and failed keyscans no longer skip host-key verification silently. - -### Changed -- Failed repository clones wrap `gitlib.GitCommandError` into `GitOperationError` and report masked stderr from git and OpenSSH without exposing credentials. -- Pinned GitHub host keys are seeded across all clone operations, including HTTPS clones. - -### Removed -- In-process `known_hosts` parser and runtime `ssh-keyscan` invocation, delegating host key validation to OpenSSH. diff --git a/changelog.d/1129.md b/changelog.d/1129.md deleted file mode 100644 index ab1434a99a..0000000000 --- a/changelog.d/1129.md +++ /dev/null @@ -1,5 +0,0 @@ -### Fixed -- Prometheus keeps every series node-exporter serves (no allow list; its collector flags decide what is collected), so Node Exporter Full and the Kubernetes node dashboard show data again (#1129). -- The `alloy-singleton` collector runs as one Deployment pod through the chart's `singleton` preset instead of a DaemonSet per node, so Kubernetes events are watched and shipped once (#1129). -- Alloy writes the cluster name to Prometheus once, as `cluster`, without the duplicate `k8s_cluster_name` label (#1129). -- `kube_hpa_labels` is removed from the kube-state-metrics allow list, since kube-state-metrics v2 never serves it (#1129). diff --git a/changelog.d/1486.md b/changelog.d/1486.md deleted file mode 100644 index 479b3903fc..0000000000 --- a/changelog.d/1486.md +++ /dev/null @@ -1,8 +0,0 @@ -### Changed -- The release no longer pins, bumps or pre-publishes the Service image's tag; Argo CD Image Updater rolls the Service onto `service:latest` (#1486). A release pull request's CI now builds, smoke-tests and scans the Service image without pushing it. On the merge to `main`, `release.yml` builds the image, scans it, pushes it by digest and attests its provenance, then tags it `vX.Y.Z` and `latest`, and Image Updater moves Application `devops` onto the new digest within one poll, with no git commit. - -### Removed -- The release cut's bump of the Service image's `newTag` and its rewrite of the Argo CD git sources' `targetRevision` (#1486). -- `devops release check`'s checks of the Service image pin and of the Argo CD `targetRevision`s (#1486). -- The `images:` pin in `k8s/devops/kustomization.yaml` (#1486). -- Service image publishing from `release/vX.Y.Z` in `release.yml`, with its publication plan and the step that pointed `latest` at an image the release branch published (#1486). diff --git a/changelog.d/1494.md b/changelog.d/1494.md deleted file mode 100644 index dd65fabb9a..0000000000 --- a/changelog.d/1494.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- CI jobs name their runner image, `ubuntu-24.04`, instead of `ubuntu-latest`, and uv in `ci.yml` and `release.yml` uses only its own CPython builds (`UV_MANAGED_PYTHON`). GitHub moves `ubuntu-latest` to Ubuntu 26.04 from 2026-10-19, where uv would have used the image's own Python 3.14 instead of the 3.14.7 that `.python-version` pins. The move to `ubuntu-26.04` waits for the workflow linter to accept the label (#1501) (#1494). diff --git a/changelog.d/1499.md b/changelog.d/1499.md deleted file mode 100644 index a90f18faea..0000000000 --- a/changelog.d/1499.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- CI's and the release's Service image scans run Trivy 0.75.0, the version `tools.lock` pins for `devops install-tools`, instead of 0.70.0, and a workflow contract test fails whenever an `aquasecurity/trivy-action` step's `version` differs from the lock (#1499). diff --git a/changelog.d/798.md b/changelog.d/798.md deleted file mode 100644 index 955263f79f..0000000000 --- a/changelog.d/798.md +++ /dev/null @@ -1,3 +0,0 @@ -### Security -- The host sandbox no longer declares a noexec `/tmp` that bubblewrap never applied (#798). Bubblewrap has no noexec option for a tmpfs, so the host policy now declares only the 64 MiB size, and the container sandboxes keep their `size=64m,noexec` policy. A host sandbox whose policy declares a tmpfs option bubblewrap cannot apply, such as `noexec` or `size=50%`, now fails at construction with an error naming the option, instead of dropping it. SECURITY.md now says that the host sandbox's `/tmp` allows execution. -- The output-cap test now runs a writer that ignores SIGPIPE and checks that the sandbox kills it at the cap within 1 s, well before its timeout (#798). diff --git a/changelog.d/850.md b/changelog.d/850.md deleted file mode 100644 index 8e0c161516..0000000000 --- a/changelog.d/850.md +++ /dev/null @@ -1,2 +0,0 @@ -### Added -- Pull requests show changed-line coverage against their base branch (diff-cover), plus any added `pragma: no cover` lines, in the Tests & Coverage job summary. The report is advisory and sets no coverage threshold (#850). diff --git a/changelog.d/852.md b/changelog.d/852.md deleted file mode 100644 index 0832023887..0000000000 --- a/changelog.d/852.md +++ /dev/null @@ -1,5 +0,0 @@ -### Added - -- pytest-randomly 5.0.0 joins the dev dependency group. `addopts` blocks it with `-p no:randomly`, so `pytest`, `devops ci` and every other run keep file order, and `uv run pytest --co -q` collects the same order as before (#852). -- `devops ci test --repeat N --seed S` runs the selected test files N times, one run after another on one process (`-n 0`), each shuffled by pytest-randomly with seeds S to S+N-1. S defaults to a seed derived from HEAD's commit hash. The first failing run stops the command and prints its seed with the command that reproduces it. `--repeat` refuses a run that no test file narrows, since shuffling the whole suite waits for thread-leak isolation (#852). -- The advisory **Changed-Test Independence** pull-request job in `ci.yml` runs `devops ci test --repeat 3` over the pull request's added or modified test files, and skips its toolchain and test steps when no test file changed (#852). diff --git a/changelog.d/853.md b/changelog.d/853.md deleted file mode 100644 index 75778785be..0000000000 --- a/changelog.d/853.md +++ /dev/null @@ -1,3 +0,0 @@ -### Added -- `devops ci mutate [PATHS] [--changed] [--base REF]` mutation-tests functions with mutmut 3.8 on demand (#853). With `--changed` it maps the functions the working tree changed since its merge base with `--base` (default `main`), untracked files git does not ignore included, to mutmut's names, and a `--base` naming no commit is an error; PATHS alone select every function in those files. mutmut runs the tests covering each function in its own process, with xdist off, and the command shows each mutant no test killed, with its diff, then the killed, survived, timeout and no-tests counts. It prints no score, exits 0 whatever survives, and is neither a `devops ci` stage nor a `ci.yml` step. The first run mutates the whole source tree into the git-ignored `mutants/` and runs the test suite once, serially; later runs reuse it, and `rm -rf mutants` resets it. -- An architectural invariant fails on any `# pragma: no mutate` under `src`, so no line exempts itself from mutation (#853). diff --git a/changelog.d/965.md b/changelog.d/965.md deleted file mode 100644 index f3915ca463..0000000000 --- a/changelog.d/965.md +++ /dev/null @@ -1,2 +0,0 @@ -### Fixed -- The `devops review` command tests no longer start the Logfire SDK's token-check thread, which printed the "Logfire API is unreachable" warning on every run and made the dry-run socket-recorder test flaky. The tests read the per-test config instead of a `MagicMock` settings object, and a background thread that dies with an exception now fails the test run (#965).