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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changelog.d/1100.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### Security
- **Loki Admits Only the OpenTelemetry Collector from `otel` (`k8s/logging/networkpolicy.yaml`)**: Loki's 3100 ingress from `otel` named the whole namespace, and Loki runs without authentication, so Jaeger or any later `otel` workload could push and query logs. The peer now combines the namespace with the collector release's pod labels; the shape was checked live under the cluster's kube-router, which enforces it with `ports` on ingress (#1100).
- **The Loki Peer Is Tied to the Collector Release It Names**: a test checks the policy's `app.kubernetes.io/instance` and `app.kubernetes.io/name` against the `otel-collector` release `devops k8s` installs and its chart, so renaming the release or overriding the chart name fails the tests instead of cutting the collector off from Loki (#1100).

### Fixed
- **Review Personas Are Shown Only the Target's Judged Claims (`devops review path`, `branch`, `pr`)**: the persona loop built its system prompt without the review's target, so a review run from another checkout was shown the working directory's disproved claims, which could suppress a valid finding. Every layer from `_execute_review_workflow` and `ReviewPipelineOrchestrator` down to `render_negative_exemplars` now requires the target, so no caller can fall back to the working directory (#1100).
- **A Review of Another Checkout Reads That Checkout's Analysis Metadata**: `--summary` and the persona loop loaded file analysis metadata from the working directory's repository; they now load it from the target's (#1100).
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Task: Loki Admits Only the Collector from `otel`, and Persona Exemplars Come from the Review's Target (#1100)

**Issue**: [#1100](https://github.com/dan-petty/devops-cli/issues/1100)
**Status**: Done
**Milestone**: v0.2.25
**Priority**: priority/p0-critical
**Scope**: scope/security

## Description
The Copilot review of release PR #1089 left two threads, and the release cannot merge with either unresolved.

- **Loki ingress** (`k8s/logging/networkpolicy.yaml`). The 3100 rule's `otel` peer was namespace-only, and Loki runs with `auth_enabled: false`, so Jaeger, or any workload later deployed to `otel`, could push and query logs. The `otel` namespace's own egress rule admits every pod to `logging:3100`, so this ingress rule is the only gate. The peer now combines `namespaceSelector` (`kubernetes.io/metadata.name: otel`) with `podSelector` on the collector release's labels (`app.kubernetes.io/name: opentelemetry-collector`, `app.kubernetes.io/instance: otel-collector`), with `ports` in the same rule. `k8s/cloudflared/networkpolicy.yaml` records that kube-router refused a combined peer with `ports` on egress, so the shape was proven live on ingress before the change (Measurements), and a comment in the policy says so.
- **Exemplar target** (`ai/review/classification.py`, `ai/review/common_hallucinations.py`, `ai/review/runner.py`, `ai/review/pipeline.py`). `_persona_system_prompt(persona, agents_md, target)` and `render_negative_exemplars(target, ...)` take the target as a required argument and no longer fall back to the working directory. `_execute_review_workflow`, `ReviewPipelineOrchestrator`, `_run_persona_loop` and `_run_review` take a required keyword-only `target_dir`, and `run_pre_analysis_refresh` a required one, so a new caller that leaves the target out fails to type-check rather than showing the working directory's judged claims. `_execute_review_workflow` passes its `target_dir` to the persona loop, the fallback path when the analysis client is not an `LLMClient`.
- **Analysis metadata target** (`ai/review/runner.py`). `--summary` and the persona loop (`_load_shared_metadata_for_pages`, `_prepare_review_metadata`, `_execute_findings_validation`) found the repository to load file analysis metadata from with `find_repo_root(Path.cwd())`; they now use the review's `target_dir`.

## Acceptance Criteria
- [x] **Loki admits only the collector from `otel` on 3100.** `test_loki_ingress_from_otel_admits_only_the_collector` (`tests/test_k8s_network_policies.py`) pins the rule's peers and port (red: the `otel` peer had no pod selector). The shape was proven in throwaway namespaces, which were deleted (Measurements).
- [x] **The applied policy matches the file.** After a server dry run and `kubectl diff`, the file was applied; `kubectl diff -f k8s/logging/networkpolicy.yaml` then exited 0. The collector still delivers OTLP logs to Loki, and an unlabelled pod in `otel` is refused on `loki.logging:3100` (Measurements).
- [x] **Exemplars come from the review's target only.** `test_a_review_outside_the_working_directory_is_shown_only_its_targets_judged_claims` (`tests/test_review_judged_claims.py`) records a judged claim in a target outside the working directory and one in the working directory, runs `_execute_review_workflow` down the persona-loop path, and reads the system prompt each persona is given. On the old code it showed the working directory's claim and not the target's; it now shows only the target's. Every caller of the two functions passes the target (`git grep`), and the existing tests pass one.
- [x] **No layer falls back to the working directory.** `test_no_review_layer_falls_back_to_the_working_directory_for_its_target` (`tests/test_review_judged_claims.py`) checks that the four layers take `target_dir` keyword-only with no default and that `run_pre_analysis_refresh` has none (red: three had `DEFAULT_CURRENT_PATH`). `test_a_review_outside_the_working_directory_reads_its_targets_analysis_metadata` runs `_execute_review_workflow` with and without `--summary` from a working directory that is not the target, and records the repository every metadata load reads (red: the working directory's, on both paths).
- [x] **The policy's pod labels follow the collector release.** `test_loki_otel_peer_names_the_collector_release_the_stack_installs` (`tests/test_k8s_network_policies.py`) checks the peer's `app.kubernetes.io/instance` against the `otel-collector` release in `stack_lifecycle.py`, and its `app.kubernetes.io/name` against the chart name with no `nameOverride` in `k8s/otel/values.yaml`.
- Pending a person: once this merges into `release/v0.2.25`, answer and resolve both Copilot threads on #1089:
- `uv run devops pr threads reply PRRT_kwDOThbRVc6oq3os "Fixed in #1100: Loki's 3100 peer from otel now combines the namespace with the collector release's pod labels, proven live under kube-router."`
- `uv run devops pr threads reply PRRT_kwDOThbRVc6oq3oy "Fixed in #1100: every review layer requires the target, so personas are shown only the target project's judged claims."`
- `uv run devops pr threads resolve PRRT_kwDOThbRVc6oq3os PRRT_kwDOThbRVc6oq3oy`
- Pending a person: `changelog.d/1100.md` lands after the v0.2.25 cut, so collect it before #1089 merges into `main`, the way #1099 collected #1097's: `git switch -c chore/cut-v0.2.25-1100 origin/release/v0.2.25`, `uv run devops release prepare 0.2.25 --no-sync-docs`, commit `CHANGELOG.md` and the deleted fragment, then `uv run devops pr create` into `release/v0.2.25`. After it merges, `uv run devops pr wait 1089`.

## Measurements
- **Probe.** Two throwaway namespaces labelled `app.kubernetes.io/part-of=np-probe`: a busybox `httpd` on 8080 in the destination, on the node Loki runs on, and four clients in the source, one labelled `app.kubernetes.io/name=probe-allowed` and one unlabelled on that node, and the same pair on another node. Without a policy all four connected. With a default-deny ingress policy none did. With the candidate added (`podSelector: {}`, an intra-namespace rule, and a rule whose peer combines `namespaceSelector` on the source namespace with `podSelector` on `probe-allowed`, `ports: [8080/TCP]`), both labelled clients connected and both unlabelled clients were refused, on either node. A second listener on 8081 refused the labelled clients, so the port restriction is enforced too. The namespaces were deleted.
- **Live check.** Before the apply, an unlabelled throwaway pod in `otel` reached `loki.logging:3100/ready`. After it, that pod was refused, and an OTLP log record sent to the collector's 4318 arrived in Loki under its `service_name`, as one sent before the apply had. The pod was deleted. The two marker records (`service_name="np-probe-1100"`) stay in Loki until retention removes them.
11 changes: 10 additions & 1 deletion k8s/logging/networkpolicy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,23 @@ spec:
# 1. Intra-namespace communications (Fluent Bit -> Loki)
- from:
- podSelector: {}
# 2. Allow Grafana/Alloy in monitoring and OTel collector in otel namespace to push/query Loki (3100)
# 2. Allow Grafana/Alloy in monitoring and the OTel collector release in otel to push/query
# Loki (3100). The otel peer names the collector's pods: Loki has auth disabled, so a
# namespace-only peer would admit Jaeger and any other otel workload. Unlike the egress
# caveat in k8s/cloudflared/networkpolicy.yaml, this cluster's kube-router enforces an
# ingress peer that combines namespaceSelector and podSelector with `ports` in the same
# rule (checked live, #1100).
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: monitoring
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: otel
podSelector:
matchLabels:
app.kubernetes.io/name: opentelemetry-collector
app.kubernetes.io/instance: otel-collector
ports:
- protocol: TCP
port: 3100
Expand Down
11 changes: 5 additions & 6 deletions src/devops_cli/ai/review/classification.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,13 @@
)


def _persona_system_prompt(
persona: PersonaDefinition, agents_md: str, target: Path | None = None
) -> str:
def _persona_system_prompt(persona: PersonaDefinition, agents_md: str, target: Path) -> str:
"""Compose the per-file/segment system prompt for this persona.

The false positives a person disproved in reviews of `target` (the working directory by
default) are appended, so a persona sees what it has already got wrong against this
codebase before a model is paid to produce it again (#950).
The false positives a person disproved in reviews of `target`, the directory the review
reads, are appended, so a persona sees what it has already got wrong against that codebase
before a model is paid to produce it again (#950). The working directory is never assumed:
a review of another checkout must not be shown claims judged against this one (#1100).
"""
from devops_cli.ai.review.common_hallucinations import render_negative_exemplars

Expand Down
15 changes: 7 additions & 8 deletions src/devops_cli/ai/review/common_hallucinations.py
Original file line number Diff line number Diff line change
Expand Up @@ -1030,24 +1030,23 @@ def remove(learned: list[CommonHallucinationEntry]) -> list[CommonHallucinationE


def render_negative_exemplars(
target: Path | None = None,
target: Path,
limit: int = DEFAULT_HALLUCINATION_EXEMPLAR_COUNT,
max_chars: int = DEFAULT_HALLUCINATION_EXEMPLAR_CHARS,
) -> str:
"""Render the false positives a persona is told not to raise again, as a prompt block.

These are the claims people disproved in reviews of the target, the repository `target` (the
working directory by default) belongs to, the most often judged first: recurrence a person
confirmed is what a reviewer should stop repeating. Until a person has judged one there, the
curated builtin entries are shown instead, under a heading that does not claim they were
reported against this codebase. Another repository's judged claims are never shown: they
describe code this review cannot see.
These are the claims people disproved in reviews of the target, the repository `target`
belongs to, the most often judged first: recurrence a person confirmed is what a reviewer
should stop repeating. Until a person has judged one there, the curated builtin entries are
shown instead, under a heading that does not claim they were reported against this codebase.
Another repository's judged claims are never shown: they describe code this review cannot see.

Showing a persona what has been disproved costs a few hundred tokens once per segment;
re-deriving those findings costs a generation and a verification each. Only the head of the
distribution is shown, because recurrence is concentrated there.
"""
project = project_of(target or Path.cwd())
project = project_of(target)
judged = sorted(
(
e
Expand Down
11 changes: 6 additions & 5 deletions src/devops_cli/ai/review/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
>>> from devops_cli.ai.client import LLMClient
>>> from devops_cli.ai.review import ReviewPipelineOrchestrator
>>>
>>> orchestrator = ReviewPipelineOrchestrator(session_id="session-001")
>>> metadata = orchestrator.run_pre_analysis_refresh()
>>> from pathlib import Path
>>> orchestrator = ReviewPipelineOrchestrator(session_id="session-001", target_dir=Path("."))
>>> metadata = orchestrator.run_pre_analysis_refresh(Path("."))
>>> payloads = orchestrator.init_per_file_payloads(["src/main.py"], metadata)
>>> orchestrator.execute_multi_persona_review(payloads, {"src/main.py": "def main(): pass"})
>>> orchestrator.execute_finding_verification(payloads)
Expand Down Expand Up @@ -120,7 +121,6 @@
CONST_VERIFICATION_UNAVAILABLE,
)
from devops_cli.config.defaults import (
DEFAULT_CURRENT_PATH,
DEFAULT_LOCATION_CONTEXT_LINES,
DEFAULT_REVIEW_CONVENTIONS_MAX_CHARS,
DEFAULT_REVIEW_PERSONA_REPLY_MAX_TOKENS,
Expand Down Expand Up @@ -1805,7 +1805,8 @@ def __init__(
self,
session_id: str | None = None,
llm_client: LLMClient | None = None,
target_dir: Path = DEFAULT_CURRENT_PATH,
*,
target_dir: Path,
session_dir: Path | None = None,
concurrency: int | None = None,
parallel: bool = True,
Expand Down Expand Up @@ -1915,7 +1916,7 @@ def _load_pre_analysis_cache(repo: Path, force_refresh: bool) -> dict[str, FileA

def run_pre_analysis_refresh(
self,
target_dir: Path = DEFAULT_CURRENT_PATH,
target_dir: Path,
target_type: Literal["branch", "pr", "path"] = "path",
target_ref: str = ".",
force_refresh: bool = False,
Expand Down
Loading
Loading