diff --git a/.github/workflows/intercept-e2e.yml b/.github/workflows/intercept-e2e.yml index fc8ef07..ac6517d 100644 --- a/.github/workflows/intercept-e2e.yml +++ b/.github/workflows/intercept-e2e.yml @@ -1,5 +1,5 @@ # Weekly (and path-filtered) product-path evidence: trigger → StackRun → -# operator → PR PipelineRun → intercept (Telepresence or mirrord) → tests. +# operator → PR PipelineRun → mirrord intercept → routing proof → tests. # Not the everyday PR gate — local-regression.yml is. Path filters still # start Kind when Helm/tasks/operator/orchestrator/pipeline/stacks or the # listed scripts change. @@ -38,7 +38,7 @@ on: workflow_dispatch: schedule: # Weekly product-path evidence on the default branch (Monday). - # Changing this workflow file on a PR runs the same telepresence + mirrord jobs as the cron. + # Changing this workflow file on a PR runs the same mirrord job as the cron. - cron: "43 7 * * 1" permissions: @@ -56,7 +56,8 @@ jobs: strategy: fail-fast: false matrix: - backend: [telepresence, mirrord] + # mirrord is the only in-cluster intercept backend (see docs/intercept-backends.md). + backend: [mirrord] env: E2E_ARTIFACT_DIR: ${{ github.workspace }}/artifacts/${{ matrix.backend }} E2E_GIT_SSH_PRIVATE_KEY: ${{ secrets.E2E_GIT_SSH_PRIVATE_KEY }} @@ -123,10 +124,6 @@ jobs: set -o pipefail bash build-images/build-and-push.sh localhost:5000 latest 2>&1 | tee build-images.log - - name: Install Telepresence traffic manager - if: matrix.backend == 'telepresence' - run: ./scripts/install-telepresence-traffic-manager.sh - - name: Run authenticated product path env: PR_NUMBER: ${{ github.run_number }} diff --git a/.gitignore b/.gitignore index 924c0ea..2451b88 100644 --- a/.gitignore +++ b/.gitignore @@ -75,3 +75,4 @@ sample-repos/*/venv/ sample-repos/*/output/ sample-repos/*/.mvn/wrapper/maven-wrapper.jar docs/demos/media/ +artifacts/ diff --git a/AGENTS.md b/AGENTS.md index 13527a1..f6d4989 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,6 +15,33 @@ Do **not** stop after a single partial test run. Follow **[docs/AGENT-REGRESSION - Run **`bash scripts/run-regression-agent.sh`** (or **`run-regression-agent-full.sh`** if Results + DB must pass). - **Loop**: fix failures → re-run until **`regression exit code: 0`** and done criteria in the doc are met. +## Local kind first — CI is confirmation, not the debugger + +`intercept-e2e.yml` costs ~20 min per cycle (runner queue + `kind create` + image build + pipeline) and only hands back log zips after the cluster is gone. On 2026-09-27 four consecutive mirrord-intercept fixes were debugged that way; each was a two-minute `kubectl logs` question on a live cluster. + +When changing `tasks/**`, `pipeline/**`, `scripts/run-product-intercept-e2e.sh`, `scripts/run-e2e-with-intercepts.sh`, `operator/`, or `orchestrator/`: + +1. Bring up (or reuse) the persistent local cluster once — check `MemAvailable` in `/proc/meminfo` is above 8 GiB first: + + ```bash + bash scripts/run-cluster-ci.sh --skip-isolation # kind "tekton-stack" + registry + Tekton + kubectl create namespace staging --dry-run=client -o yaml | kubectl apply -f - + kubectl label namespace staging pod-security.kubernetes.io/enforce=privileged \ + pod-security.kubernetes.io/audit=privileged pod-security.kubernetes.io/warn=privileged --overwrite + kubectl create secret generic ssh-key-secret -n tekton-pipelines --dry-run=client -o yaml | kubectl apply -f - + bash build-images/build-and-push.sh localhost:5000 latest + ``` + +2. Iterate against it. Re-apply only what changed (`kubectl apply -f tasks/`, `kubectl apply -f pipeline/`, rebuild one tool image) and rerun + `bash scripts/run-product-intercept-e2e.sh --intercept-backend mirrord --pr 2>&1 | tee /tmp/intercept-local.log`. + Watch live: `kubectl get pods -n staging -w`, `kubectl logs -n staging `, `kubectl logs -n staging -l app=mirrord --tail=-1`. + +3. Do **not** `kind delete cluster --name tekton-stack` between iterations. Delete only when the cluster itself is suspect. Never touch other kind clusters on the machine. + +4. Push to CI when the local run is green. CI then confirms on a clean VM. + +Log-grep gates in tasks match **specific fatal messages**, never a generic `ERROR ` (mirrord emits a non-fatal telemetry `ERROR` line). See [docs/intercept-backends.md](docs/intercept-backends.md). + ## Quick commands | Intent | Command | diff --git a/PR-TELEPRESENCE-INTERCEPT-CONFIRMATION.md b/PR-TELEPRESENCE-INTERCEPT-CONFIRMATION.md deleted file mode 100644 index a0350fa..0000000 --- a/PR-TELEPRESENCE-INTERCEPT-CONFIRMATION.md +++ /dev/null @@ -1,174 +0,0 @@ -# PR / Telepresence Intercept — Setup Confirmation - -**Date:** 2026-03-04 -**Repository:** tekton-dag -**Pipeline:** `stack-pr-test` (`pipeline/stack-pr-pipeline.yaml`) - ---- - -## 1. PR Code Runs Alongside Original Services — Not Replacing Them - -The PR pipeline deploys a **separate Pod** for the changed app. The original -Deployment and Service remain running and continue to serve all normal traffic. - -### How it works - -| Component | Behavior during PR test | -|-----------|------------------------| -| **Original service** | Untouched. Continues running and serving non-PR traffic. | -| **PR pod** | Created as a standalone Pod with labels `app: pr-test`, `component: `, `managed-by: tekton-job-standardization`. | -| **Telepresence intercept** | Routes **only** requests carrying the PR header (e.g. `x-dev-session:pr-42`) to the PR pod. All other traffic goes to the original service. | -| **After tests** | PR pod is removed by the `cleanup-stack-pods` finally task. Original service is never modified. | - -### Concrete example - -For a stack **A → B → C → D** where **C** changed in the PR: - -- **A, B, D** — normal deployed services, untouched -- **C** — Telepresence intercepts the existing C service so that requests - carrying the PR's baggage header get routed to the PR pod running the new C build -- The e2e test enters through **A** with the header; **B** forwards it to **C** - (intercepted → PR pod); **C** forwards to **D** normally -- All other traffic to **C** (without the header) continues to the original C deployment - -### Key configuration - -- **Intercept header:** `x-dev-session:pr-` (configurable via stack `propagation.header-name`) -- **Intercept command:** `telepresence intercept --namespace --port : --http-match
` -- **PR pod naming:** `pr--` -- **Telepresence image:** `ghcr.io/telepresenceio/tel2:2.20.0` - -### Source references - -| File | What it confirms | -|------|------------------| -| `tasks/deploy-intercept.yaml` (lines 9–23) | PR pods are additive; original services are untouched | -| `pipeline/stack-pr-pipeline.yaml` (lines 9–13) | Pipeline uses currently running apps; only changed app is built | -| `tasks/deploy-intercept.yaml` (lines 193–227) | PR pod spec with distinct labels, separate from original Deployment | -| `tasks/cleanup-stack.yaml` | PR pods are removed in `finally` block | - ---- - -## 2. Valid Tests Exist for the Telepresence Intercept - -The pipeline executes three layers of testing after intercepts are deployed. - -### Layer 1 — Propagation Validation - -**Task:** `validate-stack-propagation` (`tasks/validate-propagation.yaml`) - -Sends a request through the entry app with the intercept header and verifies -hop-by-hop that the header reaches the intercepted app(s). Confirms the -Telepresence routing is active and the baggage chain is intact. - -- Validates header propagation from entry point **up to** the intercepted app -- Understands propagation roles: originator sets, forwarder passes through, terminal receives -- Accounts for multi-intercept scenarios (header must continue past forwarders when another intercept is downstream) - -### Layer 2 — End-to-End Through Entry Point - -**Task:** `run-stack-tests` (`tasks/run-stack-tests.yaml`) — Phase 1 - -Sends requests through the stack's entry app (frontend) with the intercept -header attached. This exercises the **full chain** including the PR build. - -- Request enters at A, flows through the chain, hits the PR build via Telepresence -- Proves the PR app works correctly in the context of the full stack -- Uses Artillery load test template with intercept headers pre-configured - -### Layer 3 — Per-App Test Suites - -**Task:** `run-stack-tests` (`tasks/run-stack-tests.yaml`) — Phase 2 - -Runs each app's configured test suites with the intercept header: - -| Test type | Tool | Purpose | -|-----------|------|---------| -| API tests | Postman / Newman | Functional API validation | -| UI tests | Playwright | Browser-based UI testing | -| Load tests | Artillery | Performance under load | - -- For **intercepted apps**: validates the PR build directly -- For **non-intercepted apps**: validates they still work correctly with the header present - -### Test execution order in pipeline - -``` -deploy-intercepts - │ - ▼ -validate-propagation ← Header reaches intercepted app(s)? - │ - ▼ -run-tests ← E2E + per-app suites with intercept header - │ - ▼ -finally: - ├── cleanup ← Remove PR pods - └── post-pr-comment ← Report results on GitHub PR -``` - -### Source references - -| File | What it confirms | -|------|------------------| -| `tasks/validate-propagation.yaml` | Propagation validation logic and scenarios | -| `tasks/run-stack-tests.yaml` | Two-phase test execution (E2E + per-app) | -| `tests/artillery/entry-e2e.yml` | Artillery template with `x-dev-session` and `baggage` headers | -| `pipeline/stack-pr-pipeline.yaml` (lines 306–341) | Pipeline wiring: validate → test → cleanup | - ---- - -## 3. Summary - -| Requirement | Status | Evidence | -|-------------|--------|----------| -| PR code does **not** replace the original service | **Confirmed** | Separate Pod with distinct labels; Telepresence header-based routing; original Deployment untouched | -| PR code runs **alongside** the original service | **Confirmed** | Both original Deployment and PR Pod serve traffic simultaneously; header determines routing | -| Original service continues serving non-PR traffic | **Confirmed** | Only requests with `x-dev-session:pr-` route to PR pod | -| Valid tests exist for the intercept | **Confirmed** | Three-layer testing: propagation validation, E2E through entry, per-app suites | -| Tests use the intercept header | **Confirmed** | All test phases inject `x-dev-session` and `baggage` headers | -| PR pods are cleaned up after tests | **Confirmed** | `cleanup-stack-pods` runs in pipeline `finally` block | - ---- - -## 4. Milestone 5: Original Traffic Validation and MetalBear Evaluation - -Milestone 5 ([milestones/milestone-5.md](milestones/milestone-5.md)) adds two areas of work: - -### 4.1 Original traffic validation (implemented) - -A new pipeline task `validate-original-traffic` sends requests to every service -**without any intercept headers** while Telepresence intercepts are active. This -explicitly proves that the original deployments continue to serve normal traffic -during the PR test window. - -Three validation phases: - -| Phase | What it does | -|-------|-------------| -| Direct health check | `curl` each service without headers — must get HTTP 2xx/3xx | -| Entry-point passthrough | Request through the full chain without headers — must reach all original deployments | -| Artillery load burst | 10-second burst at 5 req/s without headers — must maintain < 10% error rate | - -The task runs **in parallel** with `validate-propagation` (no additional pipeline -duration) and both must pass before `run-tests` begins. - -| File | Purpose | -|------|---------| -| `tasks/validate-original-traffic.yaml` | Tekton task with 3-phase validation | -| `tests/artillery/original-traffic-e2e.yml` | Standalone Artillery config for local testing | -| `pipeline/stack-pr-pipeline.yaml` | Pipeline wiring (parallel validation) | - -### 4.2 MetalBear (mirrord) evaluation (planned) - -Evaluate [mirrord](https://mirrord.dev/) as an alternative to Telepresence for -header-based traffic interception in the PR pipeline. Key evaluation areas: - -- Header-based intercept parity with `--http-header-filter` -- In-cluster execution feasibility (Tekton pod → mirrord → target service) -- Reduced cluster footprint (no persistent Traffic Manager) -- Traffic mirroring capability for shadow/comparison testing - -See [milestones/milestone-5.md](milestones/milestone-5.md) for full PoC tasks -and decision criteria. diff --git a/README.md b/README.md index 7a667e7..84c9885 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ Each row links to the **in-browser player** on Pages (`#seg-…`) and to the **c | [M4.1](milestones/milestone-4.1.md) | **Completed** | Standalone baggage libraries (Spring Boot, Node, Flask, PHP) | | [M5](milestones/milestone-5.md) | **Completed** | Original traffic validation + mirrord evaluation | | [M6](milestones/milestone-6.md) | **Completed** | Full MetalBear testing (all intercept scenarios) | -| [M7](milestones/milestone-7.md) | **Completed** | Dual intercept backend: Telepresence or mirrord via `intercept-backend` param | +| [M7](milestones/milestone-7.md) | **Completed** | Dual intercept backend via `intercept-backend` param. Superseded 2026-09-27: in-cluster Telepresence removed, mirrord only ([why](docs/intercept-backends.md)) | | [M7.1](milestones/milestone-7-1.md) | **Completed** | Pipeline speed: parallel containerize, Kaniko cache, parallel clone | | [M8](milestones/milestone-8.md) | **Partial** | Demo assets: Manim + TTS + composed segments + [GitHub Pages](https://jmjava.github.io/tekton-dag/); VHS terminal recordings, Slidev PDF, full concat still open | | [M9](milestones/milestone-9.md) | **Completed** | Test-trace regression graph + minimal test selection (Neo4j, mock Datadog). 10 Newman requests, 36 assertions. Test filtering in PR pipeline. | @@ -148,7 +148,7 @@ flowchart LR Promote[stack-promote] end subgraph runtime [Runtime] - Intercept[Intercept: Telepresence or mirrord] + Intercept[Intercept: mirrord header steal] Validate[Validate propagation + original traffic] Test[Run tests: Newman / Playwright / Artillery] end @@ -171,7 +171,7 @@ flowchart LR | **Merge** (`stack-merge-release`) | Promote RC to release, build, tag release images, push next dev cycle version commit. | | **Promote** (`stack-promote`) | Copy release-tagged images to a target registry/environment (`registries.yaml` or API overrides); optional approval gate. | -**Intercept backends:** Telepresence (default) or mirrord, selected via pipeline param `intercept-backend`. Both are implemented. Weekly/manual CI is [`.github/workflows/intercept-e2e.yml`](.github/workflows/intercept-e2e.yml) (`scripts/run-product-intercept-e2e.sh`). Treat only a recent successful matrix job and its retained traffic artifact as verification ([M17.3](milestones/milestone-17.md)). +**Intercept backend:** mirrord (header steal, routing proven from the PR pod access log). The in-cluster Telepresence backend was removed on 2026-09-27; Telepresence remains a laptop tool only. See [docs/intercept-backends.md](docs/intercept-backends.md). Weekly/manual CI is [`.github/workflows/intercept-e2e.yml`](.github/workflows/intercept-e2e.yml) (`scripts/run-product-intercept-e2e.sh`). Treat only a recent successful matrix job and its retained traffic artifact as verification ([M17.3](milestones/milestone-17.md)). **Orchestration service** (M10): In-cluster Flask service that receives GitHub webhooks, resolves repo-to-stack dynamically, and creates **StackRun** CRs. The Go operator reconciles each StackRun into a Tekton PipelineRun. Packaged via Helm (`operator.enabled` defaults **true**) with an ArgoCD ApplicationSet for multi-team provisioning. Mutation APIs require a bearer token. See [docs/m10-multi-team-architecture.md](docs/m10-multi-team-architecture.md) and [orchestrator/README.md](orchestrator/README.md). @@ -196,8 +196,8 @@ flowchart LR kubectl apply -f tasks/ kubectl apply -f pipeline/ -# 5. Optional: Telepresence Traffic Manager (for PR pipeline intercepts) -./scripts/install-telepresence-traffic-manager.sh +# 5. mirrord intercept proxy identity (ServiceAccount + Role in staging) +./scripts/install-mirrord-intercept-rbac.sh # 6. Optional: Postgres + Tekton Results (persist run history) ./scripts/install-postgres-kind.sh @@ -230,11 +230,10 @@ kubectl port-forward svc/el-stack-event-listener 8080:8080 -n tekton-pipelines & ```bash # Product path against a cluster that already has the control plane -./scripts/run-product-intercept-e2e.sh --intercept-backend telepresence ./scripts/run-product-intercept-e2e.sh --intercept-backend mirrord # Full local helper (bootstrap + PR pipeline) -./scripts/run-e2e-with-intercepts.sh --intercept-backend telepresence +./scripts/run-e2e-with-intercepts.sh --intercept-backend mirrord ./scripts/run-e2e-with-intercepts.sh --intercept-backend mirrord --skip-bootstrap ``` diff --git a/docs/CUSTOMIZATION.md b/docs/CUSTOMIZATION.md index 8e9576f..aaee874 100644 --- a/docs/CUSTOMIZATION.md +++ b/docs/CUSTOMIZATION.md @@ -20,7 +20,7 @@ namespace: tekton-pipelines cluster: prod-us-east imageRegistry: registry.internal/squad-b cacheRepo: registry.internal/squad-b/kaniko-cache -interceptBackend: telepresence +interceptBackend: mirrord maxConcurrentRuns: 5 maxParallelBuilds: 8 stacks: @@ -34,7 +34,7 @@ teamName: "squad-b" namespace: "tekton-pipelines" imageRegistry: "registry.internal/squad-b" cacheRepo: "registry.internal/squad-b/kaniko-cache" -interceptBackend: "telepresence" +interceptBackend: "mirrord" maxParallelBuilds: 8 stackFile: "stacks/squad-b-core.yaml" gitUrl: "https://github.com/myorg/platform.git" @@ -235,13 +235,13 @@ Ensure a **compile image** exists that matches that toolchain (build and push wi ## 8. Add intercept backend support -**Goal:** Use **mirrord** instead of **Telepresence** (or switch per environment). +**Goal:** Understand the intercept backend setting. mirrord is the only implemented backend; the in-cluster Telepresence task was removed (see [intercept-backends.md](intercept-backends.md)). -1. **Cluster** — install the components your chosen backend needs (e.g. Telepresence Traffic Manager or mirrord operator per vendor docs). +1. **Cluster** — run `./scripts/install-mirrord-intercept-rbac.sh` once per target namespace (ServiceAccount + Role for the proxy pod). -2. **Helm** — set `interceptBackend: "mirrord"` in values; the orchestrator sets `INTERCEPT_BACKEND` for webhook-created runs. +2. **Helm** — `interceptBackend` is `"mirrord"`; the orchestrator sets `INTERCEPT_BACKEND` for webhook-created runs. -3. **Pipeline param** — `stack-pr-test` already exposes `intercept-backend` (`telepresence` | `mirrord`). `generate-run.sh` supports: +3. **Pipeline param** — `stack-pr-test` exposes `intercept-backend` (`mirrord`; kept for API compatibility). `generate-run.sh` supports: ```bash ./scripts/generate-run.sh --mode pr --repo demo-fe --pr 1 --intercept-backend mirrord --apply diff --git a/docs/README-FULL.md b/docs/README-FULL.md index 13f2d7d..b427082 100644 --- a/docs/README-FULL.md +++ b/docs/README-FULL.md @@ -74,7 +74,7 @@ So: **one stack file → one DAG → one resolved JSON → same pipeline for all ### Intercepts for debugging (PR flow) -On PRs, the pipeline builds images, then **deploys one pod per built app** and configures **Telepresence intercepts** so that traffic carrying the PR’s header is routed to those PR pods instead of the normal staging deployment. That gives you “this PR’s code path” end-to-end for debugging. +On PRs, the pipeline builds images, then **deploys one pod per built app** and configures **mirrord intercepts** (header steal; see [intercept-backends.md](intercept-backends.md)) so that traffic carrying the PR’s header is routed to those PR pods instead of the normal staging deployment. That gives you “this PR’s code path” end-to-end for debugging. **How it works** @@ -82,10 +82,9 @@ On PRs, the pipeline builds images, then **deploys one pod per built app** and c `resolve-stack` sets `intercept-header-value` (e.g. `x-dev-session:pr-42`) from the stack’s `propagation.header-name` and the PR number. The same value is used for intercepts and for validation/tests. 2. **Per-app PR pods** - The **deploy-stack-intercepts** task, for each app in `build-apps`: + The **deploy-intercept-mirrord** task, for each app in `build-apps`: - Reads from `stack-json` and `built-images`: image, namespace, container port, service port. - - Creates a **Pod** with (1) the built image (PR build) and (2) a Telepresence sidecar. - - The sidecar runs `telepresence intercept --namespace --port : --http-match `. + - Creates a **Pod** running the built image (PR build) and a mirrord proxy pod that runs `mirrord exec` with an `http_filter.header_filter` steal on the live deployment, relaying matched requests to the PR pod. - So any request that matches the header (e.g. `x-dev-session: pr-42`) to the **existing** Kubernetes Service for that app is intercepted and sent to this PR pod instead of the normal deployment. 3. **Arbitrary config support** @@ -97,7 +96,7 @@ On PRs, the pipeline builds images, then **deploys one pod per built app** and c **End-to-end for a developer** - Open the app (e.g. frontend) with a header `x-dev-session: pr-`. -- That request hits the entry service; Telepresence sends it to the PR pod for the entry app. +- That request hits the entry service; the intercept sends it to the PR pod for the entry app. - The entry app calls its downstreams (from the DAG); those requests carry the same header, so they are intercepted to the corresponding PR pods. - So the entire path from entry through the DAG runs the PR build, enabling debugging of the full stack for that PR. @@ -105,7 +104,7 @@ On PRs, the pipeline builds images, then **deploys one pod per built app** and c - **DAG**: One stack YAML defines nodes (apps) and edges (`downstream`). Resolve computes topo order, entry, and propagation chain. - **Arbitrary config**: All behavior is driven by stack-json and params; pipelines stay generic. -- **Intercepts**: One PR pod per built app, Telepresence sidecar, header-based routing so “this PR” traffic hits PR pods end-to-end for debugging. +- **Intercepts**: One PR pod per built app, mirrord header steal, header-based routing so “this PR” traffic hits PR pods end-to-end for debugging. ### Stack Graph — Arbitrary DAG (examples) @@ -285,20 +284,20 @@ Browser → demo-fe (originator: SETS baggage=dev-session=pr-42, x-dev-session=p → demo-api (terminal: ACCEPTS header, end of chain) ``` -**The header only needs to propagate up to the intercepted app.** Beyond the intercept, downstream calls are normal -- there's no Telepresence intercept on those services, so the header doesn't need to be there. +**The header only needs to propagate up to the intercepted app.** Beyond the intercept, downstream calls are normal -- there's no intercept on those services, so the header doesn't need to be there. **Intercepted originator** (FE PR): the PR build must set headers on outgoing requests. If there are other intercepted apps downstream, they need the header to route correctly. If the FE is the only intercepted app, the header still needs to reach it (but that's handled by the test harness sending it in). -**Intercepted forwarder** (middleware PR): Telepresence routes matching traffic to the PR pod of B. B's downstream calls to C and D go to their normal deployments — no intercept to match on, so **B does not need to forward the header**. Exception: if both B and C are intercepted in the same PR, B must forward so C's intercept catches it. +**Intercepted forwarder** (middleware PR): the intercept routes matching traffic to the PR pod of B. B's downstream calls to C and D go to their normal deployments — no intercept to match on, so **B does not need to forward the header**. Exception: if both B and C are intercepted in the same PR, B must forward so C's intercept catches it. -**Intercepted terminal** (API PR): the header reached it via Telepresence, end of the line. No forwarding needed. +**Intercepted terminal** (API PR): the header reached it via the intercept, end of the line. No forwarding needed. ``` A(originator) → B(forwarder) → C(terminal) → D(terminal) If B is intercepted: - header: test → A → B(PR) ✓ (Telepresence routes to PR B) + header: test → A → B(PR) ✓ (intercept routes to PR B) B → C: normal call (C has no intercept, header not needed) B → D: normal call (D has no intercept, header not needed) @@ -375,8 +374,8 @@ tekton-job-standardization/ ├── tasks/ │ ├── resolve-stack.yaml # Parse graph, topo sort, resolve versions │ ├── build-app.yaml # Compile (npm/maven/gradle/composer/pip) + Kaniko -│ ├── deploy-intercept.yaml # PR pods with Telepresence intercepts -│ ├── validate-propagation.yaml # Header flow validation +│ ├── deploy-intercept-mirrord.yaml # PR pods + mirrord header-steal intercepts +│ ├── validate-propagation.yaml # Header flow validation + PR-pod routing proof │ ├── run-stack-tests.yaml # Postman / Playwright / Artillery per app │ ├── version-bump.yaml # RC bump (PR) or release promote (merge) │ ├── tag-release-images.yaml # crane re-tag with clean semver @@ -393,7 +392,7 @@ tekton-job-standardization/ ├── verify-dag-phase2.sh # Phase 2 DAG verification (Tekton resolve vs CLI) ├── kind-with-registry.sh # Create kind cluster + local registry (localhost:5000) ├── install-tekton.sh # Install Tekton Pipelines + git-clone + stack tasks/pipelines - └── install-telepresence-traffic-manager.sh # Install Traffic Manager for PR intercepts + └── install-mirrord-intercept-rbac.sh # ServiceAccount + Role for the mirrord proxy pod ``` ## Pipeline Flows @@ -409,7 +408,7 @@ tekton-job-standardization/ │ build-apps ← compile per toolchain, Kaniko pushes v0.1.0-rc.4 │ - deploy-intercepts ← PR pods + Telepresence for each built app + deploy-intercepts ← PR pods + mirrord intercept for each built app │ validate-propagation ← verifies header flows through all hops │ @@ -466,7 +465,7 @@ You can run **both** the build pipelines and the **full PR pipeline** (deploy in **Standalone local repo:** To work in a new git repo with no AWS and paths at repo root (easier for local runs and Phase 2 clone), run `./scripts/extract-standalone-repo.sh [OUTPUT_DIR]`. This copies the milestone into a new tree with `stacks/`, `tasks/`, etc. at root and a README + SHARING-BACK.md for contributing back when it works. See the script for next steps (`git init`, remote, push). -- **Full PR pipeline** (`stack-pr-test`): clone → resolve → bump RC → build apps → deploy PR pods + Telepresence intercepts → validate header propagation → run tests (Postman/Playwright/Artillery) → push version → cleanup. Use this for full local testing. +- **Full PR pipeline** (`stack-pr-test`): clone → resolve → bump RC → build apps → deploy PR pods + mirrord intercepts → validate header propagation + routing proof → run tests (Postman/Playwright/Artillery) → push version → cleanup. Use this for full local testing. - **Merge pipeline** (`stack-merge-release`): clone → resolve → release version → build apps → tag and push images. Use this for build-only validation or release simulation. **1. Kind cluster + local registry (recommended for local builds)** @@ -487,17 +486,17 @@ Then install Tekton and this repo’s tasks/pipelines: ./scripts/install-tekton.sh ``` -Install the **Telepresence Traffic Manager** so the full PR pipeline (deploy intercepts, validate propagation, run tests) can route traffic to PR pods: +mirrord needs no cluster-side install beyond the proxy pod identity, once per namespace: ```bash -./scripts/install-telepresence-traffic-manager.sh +./scripts/install-mirrord-intercept-rbac.sh ``` (Optional: `--version 2.20.0` to match the sidecar image in `deploy-intercept`; default is 2.20.0.) **1b. Other local clusters (minikube, k3d)** -Create a cluster with [minikube](https://minikube.sigs.k8s.io/) or [k3d](https://k3d.io/). Install Tekton Pipelines and the **Telepresence Traffic Manager** (so the full PR pipeline can run intercepts). Apply this repo’s tasks and pipelines (and the git-clone task from the Tekton catalog if needed): +Create a cluster with [minikube](https://minikube.sigs.k8s.io/) or [k3d](https://k3d.io/). Install Tekton Pipelines and run `./scripts/install-mirrord-intercept-rbac.sh`. Apply this repo’s tasks and pipelines (and the git-clone task from the Tekton catalog if needed): ```bash kubectl apply -f tasks/ diff --git a/docs/README.md b/docs/README.md index 8b3285b..5a9a187 100644 --- a/docs/README.md +++ b/docs/README.md @@ -10,6 +10,7 @@ This folder contains design, operations, and verification docs for the tekton-da | **Milestones (historical)** | [../milestones/completed/](../milestones/completed/) — M2, M3 | | **Archive (not maintained)** | [archive/](archive/) — obsolete session plans and similar | | **Customization & ops** | [CUSTOMIZATION.md](CUSTOMIZATION.md), [MAINTENANCE.md](MAINTENANCE.md) | +| **Intercept backends** | [intercept-backends.md](intercept-backends.md) — mirrord with PR-pod routing proof; why the in-cluster Telepresence backend was removed | | **Teams: stacks + baggage libs** | [BAGGAGE-CONTRACT.md](BAGGAGE-CONTRACT.md) — original override header hop-to-hop; [TEAM-ONBOARDING-STACKS-AND-BAGGAGE.md](TEAM-ONBOARDING-STACKS-AND-BAGGAGE.md) — libraries + new stack checklist | | **Demo toolchain (M8)** | [demos/](demos/) — [demos/README.md](demos/README.md) (`docgen` CLI; `generate-all.sh` is a thin wrapper); [milestones/milestone-8.md](../milestones/milestone-8.md) | | **GitHub Actions** | [REGRESSION.md](REGRESSION.md) — which workflows run on every PR vs schedule/path filters | diff --git a/docs/REGRESSION.md b/docs/REGRESSION.md index 2bf6165..2065152 100644 --- a/docs/REGRESSION.md +++ b/docs/REGRESSION.md @@ -117,7 +117,7 @@ chmod +x scripts/run-regression.sh # once, if needed ./scripts/run-regression.sh --local-only --kind-e2e # On an already prepared cluster: trigger -> StackRun -> operator -> PR PipelineRun -./scripts/run-product-intercept-e2e.sh --intercept-backend telepresence +./scripts/run-product-intercept-e2e.sh --intercept-backend mirrord ``` Environment: @@ -132,7 +132,7 @@ Environment: 1. **Often (fast, no cluster):** `./scripts/run-regression.sh --local-only` — Phase 1 + pytest + vitest; good for frequent pushes; safe to wire into lightweight CI. 2. **System bar (cluster):** **`./scripts/run-regression.sh --cluster --require-dag-verify`** when you need a real **Succeeded** `stack-dag-verify` and orchestrator Newman — treat as **integration / system** work: before releases, after big platform changes, on a schedule, or when agents/docs require proof — **not** as “must pass on every GitHub PR” unless you explicitly configure that. 3. **With Tekton Results:** `results-regression.yml` installs pinned Results/Postgres weekly and runs the strict agent entrypoint; locally use `--with-results-verify` or rely on **auto** when the API exists. -4. **Intercept E2E:** the weekly matrix exercises Telepresence and mirrord independently and retains StackRun, PipelineRun, TaskRun, pod-log, and test-traffic evidence for 30 days. +4. **Intercept E2E:** the weekly job exercises the mirrord backend with a PR-pod routing proof (in-cluster Telepresence was removed on 2026-09-27; see [intercept-backends.md](intercept-backends.md)) and retains StackRun, PipelineRun, TaskRun, pod-log, and test-traffic evidence for 30 days. After the tiers you care about are green, update [milestones/milestone-8.md](../milestones/milestone-8.md) and related testing docs. diff --git a/docs/SCRIPTS.md b/docs/SCRIPTS.md index f2527f6..06975c7 100644 --- a/docs/SCRIPTS.md +++ b/docs/SCRIPTS.md @@ -83,17 +83,17 @@ Shared helpers live in [`scripts/common.sh`](../scripts/common.sh) (sourced by m | [`merge-pr.sh`](../scripts/merge-pr.sh) | Merge helper for test PRs. | | [`rerun-pr-from.sh`](../scripts/rerun-pr-from.sh) | Create a StackRun with `spec.continueFrom` to re-run `stack-pr-continue` from a failed PR. | | [`configure-github-webhooks.sh`](../scripts/configure-github-webhooks.sh) | Wire GitHub webhooks to EventListener. | -| [`run-e2e-with-intercepts.sh`](../scripts/run-e2e-with-intercepts.sh) | Local Kind helper: bootstrap (optional) + PR pipeline with **telepresence** or **mirrord**. | +| [`run-e2e-with-intercepts.sh`](../scripts/run-e2e-with-intercepts.sh) | Local Kind helper: bootstrap (optional) + PR pipeline with **mirrord** intercepts. | | [`run-product-intercept-e2e.sh`](../scripts/run-product-intercept-e2e.sh) | Authenticated trigger → StackRun → operator → PR PipelineRun → intercept traffic. Used by [intercept-e2e.yml](../.github/workflows/intercept-e2e.yml). | | [`run-all-setup-and-test.sh`](../scripts/run-all-setup-and-test.sh) | Broad setup + test orchestration (legacy-style “do a lot”). | --- -## Intercept tooling (Telepresence, mirrord) +## Intercept tooling (mirrord) | Script | Purpose | |--------|---------| -| [`install-telepresence-traffic-manager.sh`](../scripts/install-telepresence-traffic-manager.sh) | Install Telepresence traffic manager in cluster. | +| [`install-mirrord-intercept-rbac.sh`](../scripts/install-mirrord-intercept-rbac.sh) | ServiceAccount + Role the in-cluster mirrord proxy pod runs as (once per namespace). | | [`install-mirrord.sh`](../scripts/install-mirrord.sh) | Install mirrord CLI / related setup. | | [`run-mirrord-poc.sh`](../scripts/run-mirrord-poc.sh) | Early mirrord PoC scenarios. | | [`run-mirrord-m6-scenarios.sh`](../scripts/run-mirrord-m6-scenarios.sh) | M6 mirrord test scenario driver. | diff --git a/docs/intercept-backends.md b/docs/intercept-backends.md new file mode 100644 index 0000000..84d9a3d --- /dev/null +++ b/docs/intercept-backends.md @@ -0,0 +1,171 @@ +# Intercept backend: mirrord (in-cluster Telepresence removed) + +**Status (2026-09-27):** mirrord is the only intercept backend. The in-cluster +Telepresence task, its image, its traffic-manager install script and its +pipeline branch were **removed** (approved 2026-09-27). Until this change +neither backend had ever routed a header request to a PR pod in CI; section 4 +explains how mirrord's green was a race and what now proves routing. +Telepresence is not part of this repository any more; developers may still use +it from a laptop with their own install, exactly as they would use `mirrord +exec` locally. + +This page records why, with the evidence, so the decision can be revisited +with facts rather than memory. + +## 1. What the PR pipeline has to prove + +The product contract for a PR run is: + +1. A request carrying the PR's session header (for example + `x-dev-session: pr-42`) that hits an intercepted app's Kubernetes Service is + served by that app's **PR pod**. +2. A request without the header is served by the **live baseline**, untouched. +3. The header (and `baggage`) is copied hop-to-hop through the stack. + +Three tasks check this: `validate-stack-propagation` (3 and, since this change, +1 and 2), `validate-original-traffic` (2), and `run-tests`. + +## 2. The Telepresence in-cluster path never worked + +Runs of `intercept-e2e.yml` on `main` were green for the `telepresence` matrix +leg from 2026-09-16 to 2026-09-21 and the session notes from February and March +2026 say "E2E with Telepresence intercepts passing". Reading the artifacts and +the task as it existed on `main` shows the pass was vacuous: + +| Fact | Evidence | +| --- | --- | +| The PR pod never ran the app. | `tasks/deploy-intercept.yaml` on `main` started the built image with `sh -c 'while true; do echo "PR build for ${APP}"; sleep 30; done'`. It could not answer an HTTP request. | +| The sidecar had no Telepresence CLI. | The sidecar image was `ghcr.io/telepresenceio/tel2:2.20.0`, the traffic-agent image. It ships one binary, `traffic`; `telepresence` is not present (`docker run --rm --entrypoint sh ghcr.io/telepresenceio/tel2:2.20.0 -c 'command -v telepresence'` prints nothing). `telepresence helm install` failed with *not found* and the container exited after its initial `sleep 10`, during which the pod was briefly `Ready`, so `kubectl wait` passed. | +| Validation was warn-only. | `validate-stack-propagation` printed `HOP 1 demo-fe (originator) [INTERCEPTED]: NOT CONFIRMED (header required at this hop)` and then `Propagation validation complete.` with exit 0. Artifact: run `35612789828`, `artifacts/telepresence/pr-pod-logs.txt`. | +| Green turned red the day the check became honest. | `d07635f` / `5ef46c7` (2026-09-26) made hop validation fail-closed. The next `main` run (`0c75b06`, 2026-09-27) failed. Nothing in Telepresence changed. | + +So "Telepresence used to work" is true for the laptop workflow, where a +developer runs `telepresence intercept` against the cluster and traffic lands +on a local process. It was never true for the in-cluster sidecar variant the +pipeline used; that variant reported success without doing anything. + +## 3. What was tried on PR #109 to make the in-cluster path real + +Commits on `fix/post-deploy-checks`, in order, each verified by a full CI run +(about 15 minutes each): + +| Attempt | Result | +| --- | --- | +| Real CLI image (`build-images/Dockerfile.telepresence`, Telepresence 2.32.1), sidecar in the PR pod. | `connector.CreateIntercept: grpc: the client connection is closing`. 2.32.1 could not create intercepts from inside this cluster at all. | +| Separate privileged client pod (own ServiceAccount, tun device, `HOME=/tmp`), still 2.32.1. | Same gRPC error. | +| Downgrade to 2.25.0 (matching the traffic manager). | Intercept created. Header-matched request to the Service hung (`HTTP 000`); unmatched request passed. | +| `--never-proxy /32` and a local `socat` relay to the PR pod. | Same hang. | +| Whole-port TCP intercept (`--mechanism tcp`) with a header router in front. | Steals *all* traffic to the port, which violates contract item 2, and Telepresence reported `container port 80 is already intercepted`. Rejected. | +| `--plaintext` (HTTP intercepts default to TLS toward the handler; the PR pod is plaintext nginx). | Intercept `ACTIVE`, filter `HTTP requests with header 'X-Dev-Session: pr-95'`. Smoke probe: headered request `HTTP 000` then `502`, unmatched `200`. Root cause visible only once log collection stopped truncating to 10 lines (`368b117`): `connector/session : root session exited with error: exec: "iptables": executable file not found in $PATH`. The client image (`bitnami/kubectl`) has no `iptables`, so the client's root session (the tunnel that carries intercepted requests back to the handler) never started. | + +Other costs of the in-cluster sidecar design that mirrord does not have: + +- Injecting the traffic-agent restarts the live baseline Deployment. +- The client needs `NET_ADMIN`, a tun device, root, and a privileged namespace. +- Client and traffic-manager versions must match closely; 2.32 vs 2.25 was + enough to break intercept creation. + +At that point the choice was: keep iterating on a design the project had never +had working, or ship the backend that already met the contract. We chose the +latter. + +## 4. Why mirrord is trusted + +`tasks/deploy-intercept-mirrord.yaml` runs the built image as the real app in +the PR pod and uses `mirrord exec` with `http_filter.header_filter` in steal +mode, relaying matched requests through `socat` to the PR pod IP. + +Its green runs were audited too, and they were **also false positives** until +this change. The proxy pod ran as the namespace `default` ServiceAccount, and +`mirrord exec` died within a second on +`deployments.apps "demo-fe" is forbidden: User "system:serviceaccount:staging:default"`. +The deploy step only checked `kubectl wait --for=condition=Ready`; a container +with no readiness probe is Ready the instant it runs, so the wait usually +caught that one-second window and printed `Intercept active`. Run +`36367430488` lost the race (`Restart Count: 4`) and exposed it. Downstream, +`/propagation` is served identically by the baseline and the PR pod and simply +echoes the header it received, so `PASS — REACHED session=pr-N` alone never +proved which pod answered. + +So as of 2026-09-27 **neither backend had ever routed a header request to a +PR pod in CI**. mirrord is the one worth finishing because its failure is a +plain RBAC gap and it needs no privileged client, no restart of the live +Deployment, and no version coupling. Fixes in this PR: + +- The proxy pod runs as `mirrord-intercept` (ServiceAccount + namespace Role: + read pods/deployments/replicasets, create the agent Job, **`get`/`create` + on `pods/portforward`**), created by + `scripts/install-mirrord-intercept-rbac.sh`, which the runners call. + mirrord OSS reaches its agent through the Kubernetes port-forward API as a + WebSocket upgrade; without that verb the agent starts and the proxy dies + ~17 s later with `failed to switch protocol: 403 Forbidden`. Found on the + local kind cluster in two minutes, after a CI round-trip had missed it. +- The deploy step fails closed with a positive marker: `RUST_LOG=mirrord=info` + makes the proxy log `Created agent pod ... pod_name: "mirrord-agent-…"`; the + step requires that agent pod and the proxy to be Running, with zero + restarts and no fatal log line (`Failed to create/connect to the created + mirrord-agent`, `Forbidden`, `Error:`), still true 40 s after the agent + appeared. `restartPolicy: Never`. The proxy's own IP:port is not probed — + under the mirrord layer socat's listener is virtual. mirrord's + `ERROR mirrord::connection: failed to obtain machine ID` is non-fatal + telemetry noise and is ignored on purpose. +- `validate-stack-propagation` adds a **routing proof**, fail-closed, per + intercepted app: + +1. `GET /propagation?probehit` **with** the header. The id must + appear in the PR pod's access log (nginx logs every request line to stdout; + the log is read through the Kubernetes API with the task's ServiceAccount, + which already has `pods/log`). +2. `GET /propagation?probemiss` **without** the header. The id + must **not** appear in the PR pod's log. + +If the intercept silently does nothing, step 1 fails. If it steals everything, +step 2 fails. The pipeline passes `deployed-pods` (app → PR pod name) from +`deploy-intercepts-result` to the validator for this purpose. + +## 5. What changed in the repository + +- `.github/workflows/intercept-e2e.yml`: matrix is `[mirrord]`; the + Telepresence traffic-manager step is gone. +- **Removed:** `tasks/deploy-intercept.yaml` (`deploy-stack-intercepts`), + `build-images/Dockerfile.telepresence` (and the `telepresence` entry in + `build-images/build-and-push.sh`), `scripts/install-telepresence-traffic-manager.sh`, + `PR-TELEPRESENCE-INTERCEPT-CONFIRMATION.md`, the `deploy-intercepts-telepresence` + branch in `pipeline/stack-pr-pipeline.yaml` and + `pipeline/stack-pr-continue-pipeline.yaml` (`deploy-intercepts-mirrord` now + runs unconditionally), and the Telepresence ServiceAccount block in + `scripts/run-product-intercept-e2e.sh`. +- `intercept-backend` / `INTERCEPT_BACKEND` / Helm `interceptBackend` are kept + for API compatibility; the only accepted value is `mirrord`. +- `tasks/deploy-intercept-mirrord.yaml`: proxy pod runs as `mirrord-intercept` + (`scripts/install-mirrord-intercept-rbac.sh`, called by both runner scripts), + `restartPolicy: Never`, fail-closed serving gate. +- `tasks/validate-propagation.yaml`: new `deployed-pods` param and the routing + proof above. +- `scripts/run-product-intercept-e2e.sh`: `--tail=-1` on log collection so + artifacts carry full step output. + +## 6. Telepresence on a laptop (outside this repository) + +If a developer prefers Telepresence to `mirrord exec` for local debugging, they +install it themselves per the Telepresence docs (traffic manager via the +`telepresence-oss` Helm chart) and run: + +```bash +telepresence connect --namespace staging +telepresence intercept demo-fe --port 8080:80 --http-header x-dev-session=pr-42 +# run demo-fe locally on :8080, attach a debugger, send a request with +# x-dev-session: pr-42 through the cluster entry point +telepresence leave demo-fe && telepresence quit +``` + +Nothing in the pipeline depends on it. + +## 7. If anyone wants in-cluster Telepresence back + +The history is in git (`git log -- tasks/deploy-intercept.yaml +build-images/Dockerfile.telepresence`). The last known blocker was small: the +client image lacked `iptables`, so the Telepresence root session exited at +connect time (section 3, last row). Any revival must run as its own +ServiceAccount, fail closed at deploy, and pass the routing proof in section 4 +for both matched and unmatched traffic before a matrix entry is added. diff --git a/docs/research/contributions.md b/docs/research/contributions.md index e0b74c0..1514456 100644 --- a/docs/research/contributions.md +++ b/docs/research/contributions.md @@ -26,7 +26,7 @@ These are the **only** claims the workshop/tool **paper** is allowed to make unt ### C3 — Header-matched intercepts with original-traffic safety -**Claim.** On a PR, only `changed-app`(s) are built and intercepted. Matching is the same session header used for propagation. Two backends are implemented and E2E-exercised: Telepresence (`--http-match`) and mirrord (`header_filter`). A separate **validate-original-traffic** path checks that requests *without* the header still hit baseline pods. +**Claim.** On a PR, only `changed-app`(s) are built and intercepted. Matching is the same session header used for propagation. The implemented backend is mirrord (`header_filter`), E2E-exercised with a fail-closed routing proof read from the PR pod access log; an in-cluster Telepresence variant was removed after it was shown never to have routed (`docs/intercept-backends.md`). A separate **validate-original-traffic** path checks that requests *without* the header still hit baseline pods. **Not claimed.** That Telepresence or mirrord are novel. The contribution is *CI-orchestrated, graph-aware placement* of intercepts plus an explicit safety check, not the intercept dataplane. diff --git a/docs/research/evaluation.md b/docs/research/evaluation.md index 2f084b0..3d63ef3 100644 --- a/docs/research/evaluation.md +++ b/docs/research/evaluation.md @@ -35,7 +35,7 @@ On 2026-09-07, `bash scripts/run-regression-stream.sh --local-only --require-lan |----------|------| | `local-regression.yml` | Every PR / `main` push: `--local-only --require-lang-tests` | | `cluster-regression.yml` | Nightly + tags + Helm/cluster-script PRs | -| `intercept-e2e.yml` | Weekly Telepresence + mirrord product path | +| `intercept-e2e.yml` | Weekly mirrord product path with PR-pod routing proof (in-cluster Telepresence removed 2026-09-27, see `docs/intercept-backends.md`) | | `results-regression.yml` | Weekly Results/Postgres + `run-regression-agent-full.sh` | | `operator.yml` | `operator/**` PRs: unit/envtest + Kind domain E2E | @@ -70,13 +70,12 @@ C2 (polyglot baggage **unit** tests) is PR-gated for Python, Node, Java, and PHP | No `x-dev-session` header (5 rounds) | baseline `tekton-dag-spring-boot` | 5/5 | | `x-dev-session: pr-test` (5 rounds) | intercept / local PR process | 5/5 | -Same header-filter idea is documented as parity with Telepresence `--http-match`. E2E scripts exist for **both** backends: +mirrord `header_filter` is the implemented backend; the in-cluster Telepresence task was removed (`docs/intercept-backends.md`): ```bash -./scripts/run-product-intercept-e2e.sh --intercept-backend telepresence ./scripts/run-product-intercept-e2e.sh --intercept-backend mirrord # local Kind helper: -./scripts/run-e2e-with-intercepts.sh --intercept-backend telepresence --skip-bootstrap +./scripts/run-e2e-with-intercepts.sh --intercept-backend mirrord --skip-bootstrap ``` **How to report:** “In a controlled Kind deployment of the three-app exemplar, unmatched requests remained on the baseline replica; matched requests were stolen (5/5 each).” Cite [`docs/mirrord-poc-results.md`](../mirrord-poc-results.md) for that smoke, and `run-isolation-eval.sh --cluster` for dummy-stack probes (this Cloud Agent: 6/6 `isolation_ok`). Neither is a site measurement (S21). diff --git a/helm/tekton-dag/README.md b/helm/tekton-dag/README.md index afc5497..834ad85 100644 --- a/helm/tekton-dag/README.md +++ b/helm/tekton-dag/README.md @@ -1,6 +1,6 @@ # tekton-dag Helm chart -Tekton-based CI/CD for multi-app stacks: stack resolution, Kaniko builds, PR intercept testing (Telepresence or mirrord), and an optional in-cluster orchestration service (GitHub webhooks, manual runs). +Tekton-based CI/CD for multi-app stacks: stack resolution, Kaniko builds, PR intercept testing (mirrord), and an optional in-cluster orchestration service (GitHub webhooks, manual runs). ## Prerequisites @@ -61,7 +61,7 @@ Packaged content under `raw/` is **not** committed by default; `package.sh` copi | `imageRegistry` | string | `"localhost:5000"` | Container registry base for runtime images; passed to orchestrator as `IMAGE_REGISTRY` | | `buildImageTag` | string | `"latest"` | Tag convention for build images (document alongside `compileImages`) | | `cacheRepo` | string | `"localhost:5000/kaniko-cache"` | Kaniko cache repository; passed to orchestrator as `CACHE_REPO` | -| `interceptBackend` | string | `"telepresence"` | Default intercept backend: `telepresence` or `mirrord` (`INTERCEPT_BACKEND` env) | +| `interceptBackend` | string | `"mirrord"` | Intercept backend (`INTERCEPT_BACKEND` env). Only `mirrord` is implemented. | | `maxParallelBuilds` | int | `5` | Max concurrent Kaniko-style builds for bootstrap-style runs (`MAX_PARALLEL_BUILDS` env) | | `compileImages.npm` | string | see `values.yaml` | Default compile image for npm | | `compileImages.maven` | string | … | Default compile image for Maven | diff --git a/helm/tekton-dag/values.yaml b/helm/tekton-dag/values.yaml index a4ea018..35f6eaa 100644 --- a/helm/tekton-dag/values.yaml +++ b/helm/tekton-dag/values.yaml @@ -4,7 +4,7 @@ namespace: "tekton-pipelines" imageRegistry: "localhost:5000" buildImageTag: "latest" cacheRepo: "localhost:5000/kaniko-cache" -interceptBackend: "telepresence" +interceptBackend: "mirrord" maxParallelBuilds: 5 # Default compile images (used when stack YAML does not specify a version). diff --git a/libs/tekton-dag-common/tests/fixtures/pipelineruns/pr.json b/libs/tekton-dag-common/tests/fixtures/pipelineruns/pr.json index 0663128..4245afd 100644 --- a/libs/tekton-dag-common/tests/fixtures/pipelineruns/pr.json +++ b/libs/tekton-dag-common/tests/fixtures/pipelineruns/pr.json @@ -45,7 +45,7 @@ }, { "name": "intercept-backend", - "value": "telepresence" + "value": "mirrord" }, { "name": "dashboard-url", diff --git a/libs/tekton-dag-common/tests/test_m13_manifests.py b/libs/tekton-dag-common/tests/test_m13_manifests.py index dd943e5..6b7b46b 100644 --- a/libs/tekton-dag-common/tests/test_m13_manifests.py +++ b/libs/tekton-dag-common/tests/test_m13_manifests.py @@ -93,13 +93,51 @@ def test_deploy_full_stack_has_validate_secrets_param(): def test_intercept_tasks_inject_baggage_env(): - for rel in ("tasks/deploy-intercept.yaml", "tasks/deploy-intercept-mirrord.yaml"): + for rel in ("tasks/deploy-intercept-mirrord.yaml",): script = _load(rel)["spec"]["steps"][0]["script"] assert "BAGGAGE_ENABLED" in script, rel assert "BAGGAGE_ROLE" in script, rel assert "APP_NAME" in script, rel +def test_mirrord_proxy_runs_as_own_service_account_and_fails_closed(): + """2026-09-27: the proxy ran as staging:default (403 on the target + Deployment) and the deploy step only waited for a Ready flicker.""" + task = _load("tasks/deploy-intercept-mirrord.yaml") + params = {p["name"]: p for p in task["spec"]["params"]} + assert params["proxy-service-account"]["default"] == "mirrord-intercept" + script = task["spec"]["steps"][0]["script"] + assert "serviceAccountName: ${PROXY_SA}" in script + assert "restartPolicy: Never" in script + assert "Failed to create mirrord-agent|Failed to connect to the created mirrord-agent|Forbidden" in script + assert "kubectl wait --for=condition=Ready \"pod/${PROXY_NAME}\"" not in script + # Positive marker: the agent pod named in the proxy log must be Running + # 40 s later. A generic 'ERROR mirrord' must NOT be treated as fatal + # (mirrord prints a non-fatal machine-ID telemetry ERROR). + assert "Created agent pod" in script + assert "-ge 40" in script + assert "grep -Eq 'ERROR mirrord" not in script + rbac = (ROOT / "scripts/install-mirrord-intercept-rbac.sh").read_text() + assert '"pods/portforward"' in rbac, "mirrord OSS connects to its agent via port-forward" + + +def test_validate_propagation_proves_routing_from_pr_pod_log(): + """/propagation echoes the header on baseline and PR pod alike, so the + validator must read the PR pod's own access log (fail-closed).""" + task = _load("tasks/validate-propagation.yaml") + params = {p["name"]: p for p in task["spec"]["params"]} + assert "deployed-pods" in params + script = task["spec"]["steps"][0]["script"] + assert "Routing proof (fail-closed)" in script + assert "probehit" in script and "probemiss" in script + assert "/pods/$2/log" in script + assert "intercept steals all traffic" in script + for rel in ("pipeline/stack-pr-pipeline.yaml", "pipeline/stack-pr-continue-pipeline.yaml"): + pipeline = (ROOT / rel).read_text() + assert "value: $(tasks.deploy-intercepts-result.results.deployed-pods)" in pipeline, rel + assert "deploy-intercepts-telepresence" not in pipeline, rel + + def test_resolve_stack_installs_jq_and_yq_without_swallowing_errors(): """Kind cluster CI failed when mikefarah/yq:4 had no jq and apk was `|| true`.""" task = _load("tasks/resolve-stack.yaml") diff --git a/libs/tekton-dag-common/tests/test_m17_intercept_automation.py b/libs/tekton-dag-common/tests/test_m17_intercept_automation.py index b780b53..f0f9036 100644 --- a/libs/tekton-dag-common/tests/test_m17_intercept_automation.py +++ b/libs/tekton-dag-common/tests/test_m17_intercept_automation.py @@ -21,7 +21,9 @@ def test_intercept_workflow_has_explicit_backend_cadence_and_evidence(): assert '"scripts/bootstrap-namespace.sh"' in workflow assert "workflow_dispatch:" in workflow assert "schedule:" in workflow - assert "backend: [telepresence, mirrord]" in workflow + # 2026-09-27: in-cluster Telepresence removed; mirrord is the only backend. + assert "backend: [mirrord]" in workflow + assert "telepresence" not in workflow.lower() assert "E2E_GIT_SSH_PRIVATE_KEY" in workflow assert "Require E2E SSH credential" not in workflow assert "public application repositories will use HTTPS" in workflow diff --git a/milestones/milestone-7.md b/milestones/milestone-7.md index 96ef95e..d42f85f 100644 --- a/milestones/milestone-7.md +++ b/milestones/milestone-7.md @@ -1,6 +1,8 @@ # Milestone 7: Prototype `deploy-intercept-mirrord` Tekton task (run either backend) -> **Active milestone.** Follows [milestone 6](milestone-6.md) (mirrord validated for all PR pipeline scenarios). **Delayed migration:** do not replace Telepresence yet; add mirrord as an option and support **running either** via a pipeline parameter. Default remains Telepresence so existing behavior is unchanged until you opt in to mirrord. +> **Status 2026-09-27 — superseded in part.** The "run either backend" plan below is historical. In-cluster Telepresence was removed (it had never routed a header request to a PR pod in CI; see [docs/intercept-backends.md](../docs/intercept-backends.md) for the evidence) and **mirrord is the only backend**. `intercept-backend` defaults to `mirrord` and is kept for API compatibility. The routing proof in `validate-stack-propagation` (PR-pod access log, matched + unmatched probes) is now the exit criterion for 7.1/7.2 and passes on kind. +> +> Original framing: Follows [milestone 6](milestone-6.md) (mirrord validated for all PR pipeline scenarios). **Delayed migration:** do not replace Telepresence yet; add mirrord as an option and support **running either** via a pipeline parameter. Default remains Telepresence so existing behavior is unchanged until you opt in to mirrord. ## Goal @@ -120,6 +122,7 @@ Add to `scripts/publish-build-images.sh`. ## References - [Milestone 6](milestone-6.md) — mirrord validation results (all scenarios pass) -- [tasks/deploy-intercept.yaml](../tasks/deploy-intercept.yaml) — current Telepresence-based task (to be replaced) +- `tasks/deploy-intercept.yaml` — former Telepresence-based task, removed 2026-09-27 (git history; see [docs/intercept-backends.md](../docs/intercept-backends.md)) +- [tasks/deploy-intercept-mirrord.yaml](../tasks/deploy-intercept-mirrord.yaml) — the mirrord task, now the only backend - [docs/mirrord-poc-results.md](../docs/mirrord-poc-results.md) — M5 PoC, config format, security notes - [docs/mirrord-m6-test-scenarios.md](../docs/mirrord-m6-test-scenarios.md) — validated test scenarios diff --git a/operator/internal/pipeline/builder.go b/operator/internal/pipeline/builder.go index f0f61a9..e3a0209 100644 --- a/operator/internal/pipeline/builder.go +++ b/operator/internal/pipeline/builder.go @@ -191,7 +191,7 @@ func BuildPR(opt Options) (*unstructured.Unstructured, error) { } intercept := opt.InterceptBackend if intercept == "" { - intercept = "telepresence" + intercept = "mirrord" } params := []any{ param("git-url", opt.GitURL), @@ -392,7 +392,7 @@ func BuildPRContinue(opt Options) (*unstructured.Unstructured, error) { } intercept := opt.InterceptBackend if intercept == "" { - intercept = "telepresence" + intercept = "mirrord" } params := []any{ param("stack-json", opt.ContinueStackJSON), diff --git a/operator/internal/pipeline/builder_test.go b/operator/internal/pipeline/builder_test.go index 6aed73f..b95b5bd 100644 --- a/operator/internal/pipeline/builder_test.go +++ b/operator/internal/pipeline/builder_test.go @@ -30,7 +30,7 @@ func TestBuildersMatchGolden(t *testing.T) { prOpt.ChangedApp = "demo-fe" prOpt.PRNumber = 42 prOpt.AppRevisions = `{"demo-fe":"abc123"}` - prOpt.InterceptBackend = "telepresence" + prOpt.InterceptBackend = "mirrord" mergeOpt := optBase mergeOpt.ChangedApp = "demo-fe" diff --git a/operator/internal/pipeline/testdata/golden/pr.json b/operator/internal/pipeline/testdata/golden/pr.json index 0663128..4245afd 100644 --- a/operator/internal/pipeline/testdata/golden/pr.json +++ b/operator/internal/pipeline/testdata/golden/pr.json @@ -45,7 +45,7 @@ }, { "name": "intercept-backend", - "value": "telepresence" + "value": "mirrord" }, { "name": "dashboard-url", diff --git a/orchestrator/README.md b/orchestrator/README.md index 5c1e465..7f54cfd 100644 --- a/orchestrator/README.md +++ b/orchestrator/README.md @@ -35,7 +35,7 @@ Defined in `app.py` (with defaults). Common ones: | `TEAM_NAME` | Team identifier (logging / config context). | | `IMAGE_REGISTRY` | Container registry base passed into runs. | | `CACHE_REPO` | Kaniko cache repository. | -| `INTERCEPT_BACKEND` | `telepresence` or `mirrord` (default `telepresence`). | +| `INTERCEPT_BACKEND` | `mirrord` (only implemented backend). | | `MAX_PARALLEL_BUILDS` | Parallelism hint (default `5`). | | `GIT_URL` | Platform repo URL. | | `GIT_REVISION` | Default branch/tag/SHA. | diff --git a/orchestrator/app.py b/orchestrator/app.py index 3690367..c6f370e 100644 --- a/orchestrator/app.py +++ b/orchestrator/app.py @@ -30,7 +30,7 @@ def create_app(): TEAM_NAME=os.environ.get("TEAM_NAME", "default"), IMAGE_REGISTRY=os.environ.get("IMAGE_REGISTRY", "localhost:5000"), CACHE_REPO=os.environ.get("CACHE_REPO", "localhost:5000/kaniko-cache"), - INTERCEPT_BACKEND=os.environ.get("INTERCEPT_BACKEND", "telepresence"), + INTERCEPT_BACKEND=os.environ.get("INTERCEPT_BACKEND", "mirrord"), MAX_PARALLEL_BUILDS=int(os.environ.get("MAX_PARALLEL_BUILDS", "5")), GIT_URL=os.environ.get("GIT_URL", "https://github.com/jmjava/tekton-dag.git"), GIT_REVISION=os.environ.get("GIT_REVISION", "main"), diff --git a/orchestrator/k8s-deployment.yaml b/orchestrator/k8s-deployment.yaml index 33e1de3..b86384c 100644 --- a/orchestrator/k8s-deployment.yaml +++ b/orchestrator/k8s-deployment.yaml @@ -33,7 +33,7 @@ spec: - name: CACHE_REPO value: "" - name: INTERCEPT_BACKEND - value: telepresence + value: mirrord - name: MAX_PARALLEL_BUILDS value: "5" - name: GIT_URL diff --git a/orchestrator/pipelinerun_builder.py b/orchestrator/pipelinerun_builder.py index 5f4b02a..31c16d7 100644 --- a/orchestrator/pipelinerun_builder.py +++ b/orchestrator/pipelinerun_builder.py @@ -46,7 +46,7 @@ def build_pr_pipelinerun( git_revision, image_registry, cache_repo="", - intercept_backend="telepresence", + intercept_backend="mirrord", app_revisions=None, namespace="tekton-pipelines", compile_images=None, diff --git a/orchestrator/tests/conftest.py b/orchestrator/tests/conftest.py index aab68e8..9121a88 100644 --- a/orchestrator/tests/conftest.py +++ b/orchestrator/tests/conftest.py @@ -31,7 +31,7 @@ def flask_app(): TEAM_NAME="alpha", IMAGE_REGISTRY="registry.example.com:5000", CACHE_REPO="registry.example.com:5000/kaniko-cache", - INTERCEPT_BACKEND="telepresence", + INTERCEPT_BACKEND="mirrord", MAX_PARALLEL_BUILDS=5, GIT_URL="https://github.com/org/tekton-dag.git", GIT_REVISION="main", diff --git a/orchestrator/tests/test_pipelinerun_goldens.py b/orchestrator/tests/test_pipelinerun_goldens.py index 0714abe..3a715b7 100644 --- a/orchestrator/tests/test_pipelinerun_goldens.py +++ b/orchestrator/tests/test_pipelinerun_goldens.py @@ -32,7 +32,7 @@ def test_pr_golden(monkeypatch): image_registry="localhost:5000", cache_repo="localhost:5000/kaniko-cache", app_revisions='{"demo-fe":"abc123"}', - intercept_backend="telepresence", + intercept_backend="mirrord", namespace="tekton-pipelines", timeout="2h", max_retries=2, diff --git a/pipeline/stack-pr-continue-pipeline.yaml b/pipeline/stack-pr-continue-pipeline.yaml index 04fde50..7b41846 100644 --- a/pipeline/stack-pr-continue-pipeline.yaml +++ b/pipeline/stack-pr-continue-pipeline.yaml @@ -36,8 +36,8 @@ spec: description: "JSON map of app → image URI (from build-apps result)" - name: intercept-backend type: string - description: "Which intercept backend was used: telepresence or mirrord" - default: "telepresence" + description: "Intercept backend used (mirrord)" + default: "mirrord" - name: bumped-versions type: string description: "JSON map of app → version (from bump-rc-version result)" @@ -63,33 +63,7 @@ spec: value: $(tasks.run-tests.results.test-summary) tasks: - - name: deploy-intercepts-telepresence - when: - - input: $(params.intercept-backend) - operator: in - values: ["telepresence"] - taskRef: - name: deploy-stack-intercepts - params: - - name: stack-json - value: $(params.stack-json) - - name: build-apps - value: $(params.build-apps) - - name: propagation-chain - value: $(params.propagation-chain) - - name: built-images - value: $(params.built-images) - - name: intercept-header-value - value: $(params.intercept-header-value) - workspaces: - - name: shared-workspace - workspace: shared-workspace - - name: deploy-intercepts-mirrord - when: - - input: $(params.intercept-backend) - operator: in - values: ["mirrord"] taskRef: name: deploy-intercept-mirrord params: @@ -114,7 +88,6 @@ spec: - name: shared-workspace workspace: shared-workspace runAfter: - - deploy-intercepts-telepresence - deploy-intercepts-mirrord - name: validate-propagation @@ -129,6 +102,8 @@ spec: value: $(params.build-apps) - name: intercept-header-value value: $(params.intercept-header-value) + - name: deployed-pods + value: $(tasks.deploy-intercepts-result.results.deployed-pods) runAfter: - deploy-intercepts-result diff --git a/pipeline/stack-pr-pipeline.yaml b/pipeline/stack-pr-pipeline.yaml index 824a29d..e120257 100644 --- a/pipeline/stack-pr-pipeline.yaml +++ b/pipeline/stack-pr-pipeline.yaml @@ -9,7 +9,7 @@ spec: description: > PR testing pipeline. Uses the currently running apps in the cluster and only builds/replaces the one app being tested (changed-app). Other apps are left - as-is; Telepresence intercepts route PR traffic only to the new build. + as-is; mirrord intercepts route PR traffic only to the new build. Tests one app at a time (changed-app is required when invoking this pipeline). 1. Clones platform repo and resolves the stack graph 2. Clones and builds ONLY the changed app (snapshot tag) — no build of other apps @@ -59,8 +59,8 @@ spec: description: "Pre-built image for mirrord proxy pods (M7)" default: "localhost:5000/tekton-dag-build-mirrord:latest" - name: intercept-backend - description: "Which intercept backend to use: telepresence (default) or mirrord" - default: "telepresence" + description: "Intercept backend. Only mirrord is implemented; the param is kept for API compatibility." + default: "mirrord" - name: dashboard-url description: "Base URL of Tekton Dashboard; PR comment will include link to this run (optional)" default: "" @@ -387,35 +387,7 @@ spec: runAfter: - build-containerize - - name: deploy-intercepts-telepresence - when: - - input: $(params.intercept-backend) - operator: in - values: ["telepresence"] - taskRef: - name: deploy-stack-intercepts - params: - - name: stack-json - value: $(tasks.resolve-stack.results.stack-json) - - name: build-apps - value: $(tasks.resolve-stack.results.build-apps) - - name: propagation-chain - value: $(tasks.resolve-stack.results.propagation-chain) - - name: built-images - value: $(tasks.build-containerize.results.built-images) - - name: intercept-header-value - value: $(tasks.resolve-stack.results.intercept-header-value) - workspaces: - - name: shared-workspace - workspace: shared-workspace - runAfter: - - build-containerize - - name: deploy-intercepts-mirrord - when: - - input: $(params.intercept-backend) - operator: in - values: ["mirrord"] taskRef: name: deploy-intercept-mirrord params: @@ -444,7 +416,6 @@ spec: - name: shared-workspace workspace: shared-workspace runAfter: - - deploy-intercepts-telepresence - deploy-intercepts-mirrord - name: validate-propagation @@ -459,6 +430,8 @@ spec: value: $(tasks.resolve-stack.results.build-apps) - name: intercept-header-value value: $(tasks.resolve-stack.results.intercept-header-value) + - name: deployed-pods + value: $(tasks.deploy-intercepts-result.results.deployed-pods) runAfter: - deploy-intercepts-result diff --git a/sample-repos/conversion/tekton-dag-vue-fe/Dockerfile b/sample-repos/conversion/tekton-dag-vue-fe/Dockerfile index 566e9a7..3f90766 100644 --- a/sample-repos/conversion/tekton-dag-vue-fe/Dockerfile +++ b/sample-repos/conversion/tekton-dag-vue-fe/Dockerfile @@ -14,12 +14,20 @@ RUN npm ci COPY . . RUN npm run build -# Serve with nginx. /propagation is proxied to the BFF so curl validation -# (and the SPA) see the original override header hop-to-hop. +# Serve with nginx. /propagation is answered on localhost by +# propagation_proxy.py, which copies the incoming override into the hop +# report and nests the BFF response. FROM nginx:alpine ENV BFF_UPSTREAM=http://release-lifecycle-demo -ENV NGINX_ENVSUBST_FILTER=BFF_UPSTREAM -COPY nginx.conf.template /etc/nginx/templates/default.conf.template +ENV APP_NAME=demo-fe +ENV BAGGAGE_HEADER_NAME=x-dev-session +ENV BAGGAGE_KEY=dev-session +RUN apk add --no-cache python3 +COPY propagation_proxy.py /usr/local/bin/propagation_proxy.py +COPY nginx.conf.template /etc/nginx/conf.d/default.conf +COPY docker-entrypoint-wrap.sh /docker-entrypoint-wrap.sh +RUN chmod +x /docker-entrypoint-wrap.sh COPY --from=build /app/dist /usr/share/nginx/html EXPOSE 80 +ENTRYPOINT ["/docker-entrypoint-wrap.sh"] CMD ["nginx", "-g", "daemon off;"] diff --git a/sample-repos/conversion/tekton-dag-vue-fe/docker-entrypoint-wrap.sh b/sample-repos/conversion/tekton-dag-vue-fe/docker-entrypoint-wrap.sh new file mode 100644 index 0000000..07d7a54 --- /dev/null +++ b/sample-repos/conversion/tekton-dag-vue-fe/docker-entrypoint-wrap.sh @@ -0,0 +1,3 @@ +#!/bin/sh +python3 /usr/local/bin/propagation_proxy.py & +exec /docker-entrypoint.sh "$@" diff --git a/sample-repos/conversion/tekton-dag-vue-fe/nginx.conf.template b/sample-repos/conversion/tekton-dag-vue-fe/nginx.conf.template index 4347ec8..0b04943 100644 --- a/sample-repos/conversion/tekton-dag-vue-fe/nginx.conf.template +++ b/sample-repos/conversion/tekton-dag-vue-fe/nginx.conf.template @@ -12,12 +12,10 @@ server { add_header Set-Cookie $dev_session_cookie always; location /propagation { - proxy_pass ${BFF_UPSTREAM}; + proxy_pass http://127.0.0.1:8081; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; - proxy_set_header x-dev-session $http_x_dev_session; - proxy_set_header baggage $http_baggage; proxy_pass_request_headers on; } diff --git a/sample-repos/conversion/tekton-dag-vue-fe/propagation_proxy.py b/sample-repos/conversion/tekton-dag-vue-fe/propagation_proxy.py new file mode 100644 index 0000000..7d005da --- /dev/null +++ b/sample-repos/conversion/tekton-dag-vue-fe/propagation_proxy.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Echo the original override on GET /propagation and nest the BFF hop.""" + +from __future__ import annotations + +import json +import os +import urllib.error +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + +def _env(name: str, default: str = "") -> str: + return os.environ.get(name, default).strip() + + +APP_NAME = _env("APP_NAME", "demo-fe") +HEADER_NAME = _env("BAGGAGE_HEADER_NAME", "x-dev-session") +BAGGAGE_KEY = _env("BAGGAGE_KEY", "dev-session") +BFF_UPSTREAM = _env("BFF_UPSTREAM").rstrip("/") + + +def downstream_hop(session: str) -> list: + if not BFF_UPSTREAM or not session: + return [] + url = BFF_UPSTREAM + "/propagation" + headers = { + HEADER_NAME: session, + "baggage": f"{BAGGAGE_KEY}={session}", + } + req = urllib.request.Request(url, headers=headers) + try: + with urllib.request.urlopen(req, timeout=20) as resp: + payload = resp.read().decode("utf-8", "replace") + return [json.loads(payload)] + except (urllib.error.URLError, TimeoutError, json.JSONDecodeError, ValueError) as exc: + return [{"error": str(exc)}] + + +class Handler(BaseHTTPRequestHandler): + def do_GET(self) -> None: # noqa: N802 + session = self.headers.get(HEADER_NAME, "") or "" + body = json.dumps( + {"app": APP_NAME, "session": session, "hops": downstream_hop(session)} + ).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, fmt: str, *args: object) -> None: + return + + +def main() -> None: + ThreadingHTTPServer(("127.0.0.1", 8081), Handler).serve_forever() + + +if __name__ == "__main__": + main() diff --git a/scripts/extract-standalone-repo.sh b/scripts/extract-standalone-repo.sh index 085526c..746be4d 100755 --- a/scripts/extract-standalone-repo.sh +++ b/scripts/extract-standalone-repo.sh @@ -56,8 +56,8 @@ Standalone Tekton pipeline system for **local development and proof-of-concept** # 2. Tekton + stack tasks/pipelines (labels namespace for Pod Security) ./scripts/install-tekton.sh -# 3. Optional: Telepresence Traffic Manager (for full PR pipeline with intercepts) -./scripts/install-telepresence-traffic-manager.sh +# 3. mirrord intercept proxy identity (for the full PR pipeline with intercepts) +./scripts/install-mirrord-intercept-rbac.sh # 4. Prove the DAG ./scripts/verify-dag-phase1.sh @@ -73,7 +73,7 @@ For manual pipeline runs, use `--registry localhost:5000 --storage-class ""`. Se - **stacks/** — Stack YAML (DAG), registry, versions - **tasks/** — Tekton tasks (resolve, build, deploy-intercept, validate, test, version, cleanup) - **pipeline/** — stack-pr-test, stack-merge-release, stack-dag-verify -- **scripts/** — kind-with-registry, install-tekton, install-telepresence-traffic-manager, verify-dag-phase1/2, generate-run, stack-graph +- **scripts/** — kind-with-registry, install-tekton, install-mirrord-intercept-rbac, verify-dag-phase1/2, generate-run, stack-graph - **docs/** — C4 diagrams, local DAG verification plan ## Sharing back to reference-architecture diff --git a/scripts/generate-run.sh b/scripts/generate-run.sh index cc92213..f5df987 100755 --- a/scripts/generate-run.sh +++ b/scripts/generate-run.sh @@ -27,7 +27,7 @@ source "$SCRIPT_DIR/common.sh" # --no-build-images Use bare ubuntu:22.04 # --namespace Target namespace (default: tekton-pipelines) # --storage-class PVC storage class -# --intercept-backend telepresence (default) | mirrord (M7) +# --intercept-backend mirrord (only implemented backend) # --apply kubectl create the StackRun # --dry-run Print the YAML without applying @@ -48,7 +48,7 @@ VERSION_OVERRIDES="{}" APPLY=false BUILD_IMAGES="${BUILD_IMAGES:-true}" BUILD_IMAGE_TAG="${BUILD_IMAGE_TAG:-latest}" -INTERCEPT_BACKEND="${INTERCEPT_BACKEND:-telepresence}" +INTERCEPT_BACKEND="${INTERCEPT_BACKEND:-mirrord}" if [[ "${GENERATE_PIPELINE_RUN:-false}" == "true" ]]; then die "--pipeline-run / GENERATE_PIPELINE_RUN was removed in M16; emit a StackRun (default) instead" diff --git a/scripts/install-mirrord-intercept-rbac.sh b/scripts/install-mirrord-intercept-rbac.sh new file mode 100755 index 0000000..9c3915b --- /dev/null +++ b/scripts/install-mirrord-intercept-rbac.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +# Create the ServiceAccount + Role the in-cluster mirrord proxy pod runs as. +# +# `mirrord exec` inside the proxy pod must resolve its target Deployment and +# create the mirrord-agent Job in the same namespace. The pipeline SA cannot +# create ServiceAccounts, so a cluster admin runs this once per namespace +# (run-cluster-ci.sh / run-product-intercept-e2e.sh do it for CI). +# +# Usage: ./scripts/install-mirrord-intercept-rbac.sh [--namespace staging] [--name mirrord-intercept] +set -euo pipefail + +NAMESPACE="${MIRRORD_INTERCEPT_NAMESPACE:-staging}" +SA_NAME="${MIRRORD_INTERCEPT_SA:-mirrord-intercept}" + +while [[ $# -gt 0 ]]; do + case "$1" in + --namespace) NAMESPACE="$2"; shift 2 ;; + --name) SA_NAME="$2"; shift 2 ;; + -h|--help) sed -n '2,10p' "$0"; exit 0 ;; + *) echo "unknown arg: $1" >&2; exit 64 ;; + esac +done + +kubectl create namespace "$NAMESPACE" --dry-run=client -o yaml | kubectl apply -f - + +cat < replicaset -> pod) and agent placement. + - apiGroups: [""] + resources: ["pods", "pods/log", "services", "endpoints"] + verbs: ["get", "list", "watch"] + # mirrord OSS reaches its agent through the Kubernetes port-forward API + # (WebSocket upgrade on pods/portforward; the apiserver authorizes a + # WebSocket GET as verb "get", SPDY POST as "create"). Without this the + # agent starts and the proxy dies with "failed to switch protocol: 403". + - apiGroups: [""] + resources: ["pods/portforward"] + verbs: ["get", "create"] + - apiGroups: ["apps"] + resources: ["deployments", "replicasets", "statefulsets"] + verbs: ["get", "list", "watch"] + # The mirrord-agent runs as a Job in the target namespace. + - apiGroups: ["batch"] + resources: ["jobs"] + verbs: ["get", "list", "watch", "create", "delete"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: ${SA_NAME} + namespace: ${NAMESPACE} + labels: + app.kubernetes.io/part-of: tekton-job-standardization +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: ${SA_NAME} +subjects: + - kind: ServiceAccount + name: ${SA_NAME} + namespace: ${NAMESPACE} +EOF + +echo "OK: ServiceAccount ${NAMESPACE}/${SA_NAME} ready for the mirrord intercept proxy" diff --git a/scripts/install-tekton.sh b/scripts/install-tekton.sh index 45be660..6020e0a 100755 --- a/scripts/install-tekton.sh +++ b/scripts/install-tekton.sh @@ -88,8 +88,8 @@ apply_with_retry -f "$MILESTONE_DIR/tasks/" -n "$NAMESPACE" apply_with_retry -f "$MILESTONE_DIR/pipeline/" -n "$NAMESPACE" echo "" -echo " Done. For full PR pipeline (intercepts), also install the Traffic Manager:" -echo " ./scripts/install-telepresence-traffic-manager.sh" +echo " Done. For the full PR pipeline (mirrord intercepts), also create the proxy identity:" +echo " ./scripts/install-mirrord-intercept-rbac.sh" echo " Then you can run:" echo " ./scripts/verify-dag-phase2.sh # DAG verification (resolve vs CLI)" echo " ./scripts/generate-run.sh --mode merge --repo demo-fe --registry localhost:5000 --storage-class \"\" | kubectl create -f -" diff --git a/scripts/install-telepresence-traffic-manager.sh b/scripts/install-telepresence-traffic-manager.sh deleted file mode 100755 index c56cb9f..0000000 --- a/scripts/install-telepresence-traffic-manager.sh +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env bash -# Install Telepresence Traffic Manager in the cluster so PR pipeline intercepts can work. -# Run after the cluster is up (e.g. after kind-with-registry.sh). Requires helm and kubectl. -# Usage: ./install-telepresence-traffic-manager.sh [--version VERSION] -# Example: ./install-telepresence-traffic-manager.sh --version 2.20.0 -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -TELEPRESENCE_VERSION="${TELEPRESENCE_VERSION:-2.20.0}" -NAMESPACE="${TELEPRESENCE_NAMESPACE:-ambassador}" -CHART_OCI="oci://ghcr.io/telepresenceio/telepresence-oss" - -while [[ $# -gt 0 ]]; do - case "$1" in - --version) TELEPRESENCE_VERSION="$2"; shift 2 ;; - --namespace) NAMESPACE="$2"; shift 2 ;; - *) echo "Unknown option: $1" >&2; exit 1 ;; - esac -done - -need() { command -v "$1" >/dev/null 2>&1 || { echo "Required: $1" >&2; exit 1; }; } -need helm -need kubectl - -# Use writable dirs for Helm cache/config so helm template can pull the chart without touching /root -HELM_RUN_DIR="${TMPDIR:-/tmp}/helm-telepresence-$$" -mkdir -p "$HELM_RUN_DIR" -export HELM_CACHE_HOME="${HELM_RUN_DIR}/cache" -export HELM_CONFIG_HOME="${HELM_RUN_DIR}/config" -export XDG_CACHE_HOME="${HELM_RUN_DIR}/xdg-cache" -export XDG_CONFIG_HOME="${HELM_RUN_DIR}/xdg-config" -trap "rm -rf '$HELM_RUN_DIR'" EXIT - -echo "==============================================" -echo " Install Telepresence Traffic Manager" -echo " Version: $TELEPRESENCE_VERSION" -echo " Namespace: $NAMESPACE" -echo "==============================================" - -# Install or upgrade (idempotent). If helm is snap-installed, it may fail in restricted -# environments with "mkdir /root/snap: permission denied"; then run this script with -# full permissions or install helm without snap (e.g. get.helm.sh). -kubectl create namespace "$NAMESPACE" --dry-run=client -o yaml | kubectl apply -f - -if helm status traffic-manager -n "$NAMESPACE" >/dev/null 2>&1; then - echo " Upgrading existing traffic-manager..." - helm upgrade --namespace "$NAMESPACE" --reuse-values \ - --version "$TELEPRESENCE_VERSION" \ - traffic-manager "$CHART_OCI" -else - echo " Installing traffic-manager..." - helm install --create-namespace --namespace "$NAMESPACE" \ - --version "$TELEPRESENCE_VERSION" \ - traffic-manager "$CHART_OCI" -fi - -echo " Waiting for Traffic Manager to be ready..." -kubectl wait --for=condition=Available deployment/traffic-manager -n "$NAMESPACE" --timeout=120s 2>/dev/null || true - -echo "" -echo " Done. Traffic Manager is in namespace '$NAMESPACE'." -echo " PR pipeline deploy-intercept pods will use it for intercepts." -echo " (Sidecar image in deploy-intercept task should match; default tel2:2.20.0)" -echo "" diff --git a/scripts/isolation_eval/cluster.py b/scripts/isolation_eval/cluster.py index 67c7109..4b3840a 100644 --- a/scripts/isolation_eval/cluster.py +++ b/scripts/isolation_eval/cluster.py @@ -267,25 +267,51 @@ def _free_port() -> int: return port +def _start_port_forward(ns: str) -> tuple[subprocess.Popen, str]: + port = _free_port() + proc = subprocess.Popen( + ["kubectl", "-n", ns, "port-forward", "svc/entry", f"{port}:80"], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + ) + return proc, f"http://127.0.0.1:{port}/" + + +def _port_forward_output(proc: subprocess.Popen) -> str: + if proc.stdout is None: + return "" + try: + return proc.stdout.read() or "" + except Exception: + return "" + + def curl_entry(ns: str, header: bool) -> str: """Hit svc/entry via kubectl port-forward. Nested Kind (Cloud Agent Docker-in-Docker) often cannot program ClusterIP iptables (missing xt_statistic). Port-forward goes through the API server to the pod and still exercises the intercept router on that pod. + + kubectl exits on the first refused connection (the router container can + be Ready before Python binds 8080). Restart the forward until the deadline + instead of recording that first refusal as the cell result. """ - port = _free_port() - pf = subprocess.Popen( - ["kubectl", "-n", ns, "port-forward", "svc/entry", f"{port}:80"], - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - text=True, - ) - url = f"http://127.0.0.1:{port}/" + deadline = time.time() + 20 last_err = "port-forward never accepted a connection" + saw_dead_forward = False + pf: subprocess.Popen | None = None + url = "" try: - deadline = time.time() + 20 while time.time() < deadline: + if pf is None or pf.poll() is not None: + if pf is not None: + saw_dead_forward = True + out = _port_forward_output(pf) + if out.strip(): + last_err = out + pf, url = _start_port_forward(ns) try: req = urllib.request.Request(url) if header: @@ -295,13 +321,17 @@ def curl_entry(ns: str, header: bool) -> str: except Exception as exc: last_err = str(exc) if pf.poll() is not None: - out = pf.stdout.read() if pf.stdout else "" - return f"probe-error:port-forward:{out or last_err}" + saw_dead_forward = True + out = _port_forward_output(pf) + if out.strip(): + last_err = out time.sleep(0.2) - return f"probe-error:{last_err}" + prefix = "probe-error:port-forward:" if saw_dead_forward else "probe-error:" + return f"{prefix}{last_err}" finally: - pf.terminate() - try: - pf.wait(timeout=5) - except Exception: - pf.kill() + if pf is not None and pf.poll() is None: + pf.terminate() + try: + pf.wait(timeout=5) + except Exception: + pf.kill() diff --git a/scripts/isolation_eval/test_cluster.py b/scripts/isolation_eval/test_cluster.py index d9d2bc5..a1dfe4b 100644 --- a/scripts/isolation_eval/test_cluster.py +++ b/scripts/isolation_eval/test_cluster.py @@ -41,6 +41,7 @@ def test_port_forward_exit_is_probe_error(self) -> None: proc = MagicMock() proc.poll.return_value = 1 proc.stdout = io.StringIO("forward failed\n") + clock = iter([0, 0, 100]) with ( patch("cluster.subprocess.Popen", return_value=proc), @@ -49,10 +50,45 @@ def test_port_forward_exit_is_probe_error(self) -> None: "cluster.urllib.request.urlopen", side_effect=OSError("connection refused"), ), + patch("cluster.time.time", side_effect=lambda: next(clock)), + patch("cluster.time.sleep"), ): out = curl_entry("demo-ns", False) self.assertTrue(out.startswith("probe-error:port-forward:")) - proc.terminate.assert_called() + self.assertIn("forward failed", out) + + def test_port_forward_restarts_after_refused_connection(self) -> None: + dead = MagicMock() + dead.poll.return_value = 1 + dead.stdout = io.StringIO("lost connection to pod\n") + live = MagicMock() + live.poll.return_value = None + live.stdout = io.StringIO("") + + class FakeResp: + def read(self) -> bytes: + return b"pr/inventory-api/app-0\n" + + def __enter__(self) -> "FakeResp": + return self + + def __exit__(self, *args: object) -> None: + return None + + with ( + patch("cluster.subprocess.Popen", side_effect=[dead, live]) as popen, + patch("cluster._free_port", side_effect=[18081, 18082]), + patch( + "cluster.urllib.request.urlopen", + side_effect=[OSError("connection refused"), FakeResp()], + ), + patch("cluster.time.time", return_value=0), + patch("cluster.time.sleep"), + ): + out = curl_entry("demo-ns", False) + self.assertEqual(out, "pr/inventory-api/app-0") + self.assertEqual(popen.call_count, 2) + live.terminate.assert_called() class WaitReadyTests(unittest.TestCase): diff --git a/scripts/run-all-setup-and-test.sh b/scripts/run-all-setup-and-test.sh index 9765c93..669f24c 100755 --- a/scripts/run-all-setup-and-test.sh +++ b/scripts/run-all-setup-and-test.sh @@ -75,10 +75,10 @@ else echo ">>> 4. Tekton Results (skipped --skip-results)" fi -# 5. Telepresence Traffic Manager (required for intercept E2E) +# 5. mirrord intercept proxy RBAC (required for intercept E2E) echo "" -echo ">>> 5. Telepresence Traffic Manager" -run_step "5. Telepresence Traffic Manager" ./scripts/install-telepresence-traffic-manager.sh +echo ">>> 5. mirrord intercept proxy RBAC" +run_step "5. mirrord intercept proxy RBAC" ./scripts/install-mirrord-intercept-rbac.sh # 6. Git SSH key secret (required for clone-app-repos SSH pull; created from ~/.ssh if missing) echo "" diff --git a/scripts/run-e2e-with-intercepts.sh b/scripts/run-e2e-with-intercepts.sh index 49b1fbd..952f95c 100755 --- a/scripts/run-e2e-with-intercepts.sh +++ b/scripts/run-e2e-with-intercepts.sh @@ -1,16 +1,16 @@ #!/usr/bin/env bash -# Run full E2E with live Telepresence intercepts: bootstrap (build + deploy full stack), +# Run full E2E with live mirrord intercepts: bootstrap (build + deploy full stack), # then PR pipeline (build changed-app, deploy intercepts, run E2E through entry). # NOTE: This script uses a PR number (e.g. --pr 1) with default git-revision (main). # That is a pipeline sanity check only — it does NOT test the PR feature (no real PR). # For the valid PR test, use create-test-pr.sh → generate-run pr → merge-pr.sh → generate-run merge. # See docs/PR-TEST-FLOW.md. -# Prerequisites: Kind, Tekton, Postgres, Results, Telepresence Traffic Manager. +# Prerequisites: Kind, Tekton, Postgres, Results (mirrord proxy RBAC is created by this script). # Required: Kubernetes secret with SSH key for cloning app repos, e.g.: # kubectl create secret generic git-ssh-key --from-file=id_ed25519=$HOME/.ssh/id_ed25519 -n $NAMESPACE # Override name with GIT_SSH_SECRET_NAME. # -# Usage: ./run-e2e-with-intercepts.sh [--stack STACK] [--changed-app APP] [--pr N] [--registry URL] [--namespace NS] [--intercept-backend telepresence|mirrord] [--skip-bootstrap] [--skip-install-check] [--no-verify-db] +# Usage: ./run-e2e-with-intercepts.sh [--stack STACK] [--changed-app APP] [--pr N] [--registry URL] [--namespace NS] [--intercept-backend mirrord] [--skip-bootstrap] [--skip-install-check] [--no-verify-db] # Require bash (script uses [[ ]], etc.); re-exec if run with sh if [ -z "${BASH_VERSION:-}" ]; then exec bash "$0" "$@" @@ -24,7 +24,7 @@ STACK_FILE="stack-one.yaml" STACK_PATH="stacks/$STACK_FILE" CHANGED_APP="demo-fe" PR_NUMBER="1" -INTERCEPT_BACKEND="${INTERCEPT_BACKEND:-telepresence}" +INTERCEPT_BACKEND="${INTERCEPT_BACKEND:-mirrord}" GIT_URL="${GIT_URL:-https://github.com/jmjava/tekton-dag.git}" GIT_REV="${GIT_REV:-main}" GIT_SSH_SECRET_NAME="${GIT_SSH_SECRET_NAME:-git-ssh-key}" @@ -57,9 +57,6 @@ need jq if [[ "$SKIP_INSTALL_CHECK" != "true" ]]; then kubectl cluster-info &>/dev/null || { echo "No cluster. Run kind-with-registry.sh and install-tekton.sh." >&2; exit 1; } kubectl get deployment tekton-results-api -n "$NAMESPACE" &>/dev/null || { echo "Tekton Results not found. Run install-postgres-kind.sh and install-tekton-results.sh." >&2; exit 1; } - if [[ "$INTERCEPT_BACKEND" == "telepresence" ]]; then - kubectl get deployment traffic-manager -n ambassador &>/dev/null || { echo "Telepresence Traffic Manager not found. Run install-telepresence-traffic-manager.sh." >&2; exit 1; } - fi kubectl get secret "$GIT_SSH_SECRET_NAME" -n "$NAMESPACE" &>/dev/null || { echo "Secret $GIT_SSH_SECRET_NAME not found. Create it with: kubectl create secret generic $GIT_SSH_SECRET_NAME --from-file=id_ed25519=\$HOME/.ssh/id_ed25519 -n $NAMESPACE" >&2; exit 1; } fi @@ -68,9 +65,11 @@ fi # Ensure SA and RBAC for pipeline (deploy in staging, etc.) kubectl create serviceaccount tekton-pr-sa -n "$NAMESPACE" 2>/dev/null || true kubectl create clusterrolebinding tekton-pr-sa-admin --clusterrole=cluster-admin --serviceaccount="$NAMESPACE":tekton-pr-sa 2>/dev/null || true +# Identity for the in-cluster mirrord proxy pod (reads the target Deployment, creates the agent Job) +"$SCRIPT_DIR/install-mirrord-intercept-rbac.sh" --namespace staging echo "==============================================" -echo " E2E with live Telepresence intercepts" +echo " E2E with live mirrord intercepts" echo " Stack: $STACK_FILE changed-app: $CHANGED_APP pr: $PR_NUMBER intercept-backend: $INTERCEPT_BACKEND" echo " Registry: $IMAGE_REGISTRY" echo "==============================================" diff --git a/scripts/run-product-intercept-e2e.sh b/scripts/run-product-intercept-e2e.sh index c3e967b..c086bb4 100755 --- a/scripts/run-product-intercept-e2e.sh +++ b/scripts/run-product-intercept-e2e.sh @@ -11,7 +11,7 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # shellcheck source=common.sh source "$SCRIPT_DIR/common.sh" -INTERCEPT_BACKEND="${INTERCEPT_BACKEND:-telepresence}" +INTERCEPT_BACKEND="${INTERCEPT_BACKEND:-mirrord}" STACK_FILE="${STACK_FILE:-stack-one.yaml}" CHANGED_APP="${CHANGED_APP:-demo-fe}" PR_NUMBER="${PR_NUMBER:-900001}" @@ -40,8 +40,8 @@ while [[ $# -gt 0 ]]; do esac done -[[ "$INTERCEPT_BACKEND" == "telepresence" || "$INTERCEPT_BACKEND" == "mirrord" ]] \ - || die "--intercept-backend must be telepresence or mirrord" +[[ "$INTERCEPT_BACKEND" == "mirrord" ]] \ + || die "--intercept-backend must be mirrord (Telepresence in-cluster was removed; see docs/intercept-backends.md)" [[ "$PR_NUMBER" =~ ^[0-9]+$ ]] || die "--pr must be numeric" need kubectl @@ -99,8 +99,10 @@ collect_run_evidence() { }' >"$ARTIFACT_DIR/$prefix-pipeline-results.json" || true kubectl get taskrun -n "$NAMESPACE" -l "tekton.dev/pipelineRun=$pipeline_run" -o yaml \ >"$ARTIFACT_DIR/$prefix-taskruns.yaml" 2>&1 || true + # --tail=-1: with a label selector kubectl defaults to the last 10 lines + # per container, which hides every step's diagnostics. kubectl logs -n "$NAMESPACE" -l "tekton.dev/pipelineRun=$pipeline_run" \ - --all-containers=true --prefix=true \ + --all-containers=true --prefix=true --tail=-1 \ >"$ARTIFACT_DIR/$prefix-pod-logs.txt" 2>&1 || true } @@ -192,7 +194,7 @@ verify_pr_evidence() { || die "PR PipelineRun run-tests TaskRun did not succeed" kubectl logs -n "$NAMESPACE" -l \ "tekton.dev/pipelineRun=$pipeline_run,tekton.dev/pipelineTask=run-tests" \ - --all-containers=true --prefix=true \ + --all-containers=true --prefix=true --tail=-1 \ >"$ARTIFACT_DIR/pr-traffic-evidence.log" [[ -s "$ARTIFACT_DIR/pr-traffic-evidence.log" ]] \ || die "run-tests traffic evidence log is empty" @@ -201,6 +203,10 @@ verify_pr_evidence() { resolve_api_token start_port_forward +# The pipeline SA cannot create ServiceAccounts. The mirrord proxy pod needs +# an API identity the runner creates here. +"$(dirname "$0")/install-mirrord-intercept-rbac.sh" --namespace staging + echo ">>> Trigger bootstrap through authenticated orchestrator API" bootstrap_payload="$(jq -nc --arg stack "stacks/$STACK_FILE" \ '{mode:"bootstrap", stack_file:$stack, git_revision:"main"}')" diff --git a/scripts/run-stack-tests-runners.sh b/scripts/run-stack-tests-runners.sh index 203c661..319328d 100755 --- a/scripts/run-stack-tests-runners.sh +++ b/scripts/run-stack-tests-runners.sh @@ -278,7 +278,7 @@ for APP in $APP_LIST; do [ "$BA" = "$APP" ] && IS_INTERCEPTED=true done if [ "$IS_INTERCEPTED" = "true" ]; then - echo " (INTERCEPTED — hitting PR build via Telepresence)" + echo " (INTERCEPTED — hitting PR build via mirrord)" else echo " (normal cluster deployment)" fi diff --git a/tasks/clone-app-repos.yaml b/tasks/clone-app-repos.yaml index 424ece2..6c7f3e0 100644 --- a/tasks/clone-app-repos.yaml +++ b/tasks/clone-app-repos.yaml @@ -78,7 +78,12 @@ spec: local APP="$1" REPO="$2" REVISION="$3" URL="$4" echo " Cloning $APP from $URL (revision: $REVISION) -> $WORKSPACE/$APP" git clone --depth 1 "$URL" "$WORKSPACE/$APP" 2>&1 | sed "s/^/ [$APP] /" - (cd "$WORKSPACE/$APP" && git fetch --depth 1 origin "$REVISION" 2>/dev/null && git checkout "$REVISION" 2>/dev/null || true) + if ! git -C "$WORKSPACE/$APP" fetch --depth 1 origin "$REVISION"; then + echo "ERROR: could not fetch $REVISION for $APP" >&2 + exit 1 + fi + git -C "$WORKSPACE/$APP" checkout --detach FETCH_HEAD + echo " [$APP] at $(git -C "$WORKSPACE/$APP" rev-parse --short HEAD) ($REVISION)" echo " Done: $APP" } diff --git a/tasks/deploy-intercept-mirrord.yaml b/tasks/deploy-intercept-mirrord.yaml index 777d087..a9eb581 100644 --- a/tasks/deploy-intercept-mirrord.yaml +++ b/tasks/deploy-intercept-mirrord.yaml @@ -37,6 +37,13 @@ spec: type: string default: "localhost:5000/tekton-dag-build-mirrord:latest" description: "Image for mirrord proxy pods (mirrord CLI + socat)" + - name: proxy-service-account + type: string + default: "mirrord-intercept" + description: | + ServiceAccount the proxy pod runs as. mirrord exec must read the target + Deployment and create the mirrord-agent Job; the default SA cannot. + Create it with scripts/install-mirrord-intercept-rbac.sh. workspaces: - name: shared-workspace description: "Workspace to write deployed-pods.json for pass-through result" @@ -57,6 +64,7 @@ spec: INTERCEPT="$(params.intercept-header-value)" DEFAULT_NS="$(params.default-namespace)" MIRRORD_IMAGE="$(params.mirrord-image)" + PROXY_SA="$(params.proxy-service-account)" DEPLOYED_PODS_FILE="$(workspaces.shared-workspace.path)/deployed-pods.json" echo "=============================================" @@ -116,8 +124,6 @@ spec: containers: - name: pr-component image: ${IMAGE} - command: ["/bin/sh"] - args: ["-c", "while true; do echo 'PR build for ${APP}'; sleep 30; done"] ports: - containerPort: ${CPORT} env: @@ -141,9 +147,20 @@ spec: PR_POD_IP=$(kubectl get pod "$POD_NAME" -n "$NS" -o jsonpath='{.status.podIP}') echo " PR pod ready: $POD_NAME (IP: $PR_POD_IP)" - # mirrord config: steal traffic matching header, target the deployment (original app) - HEADER_FILTER="${INTERCEPT}" - [ -z "$HEADER_FILTER" ] && HEADER_FILTER=".*" + # mirrord config: steal traffic matching header, target the deployment (original app). + # mirrord evaluates http_filter.header_filter as a regex against the + # string ": " (colon + space). The param is "name:value" + # with no space, so passing it verbatim never matched (2026-09-27, + # found on local kind). Build an anchored, case-insensitive filter. + if [ -n "$INTERCEPT" ]; then + HDR_NAME="${INTERCEPT%%:*}" + HDR_VAL="${INTERCEPT#*:}" + HDR_VAL="${HDR_VAL# }" + HEADER_FILTER="(?i)^${HDR_NAME}: ${HDR_VAL}\$" + else + HEADER_FILTER=".*" + fi + echo " mirrord header_filter: ${HEADER_FILTER}" MIRRORD_CONFIG=$(jq -n \ --arg path "deployment/${APP}" \ --arg ns "$NS" \ @@ -174,7 +191,9 @@ spec: component: ${APP} managed-by: tekton-job-standardization spec: + serviceAccountName: ${PROXY_SA} hostPID: true + restartPolicy: Never containers: - name: mirrord-proxy image: ${MIRRORD_IMAGE} @@ -183,9 +202,22 @@ spec: - -c - | set -e + export HOME=/tmp echo "Starting mirrord proxy for ${APP} -> ${PR_POD_IP}:${CPORT}" - exec mirrord exec -f /config/config.json -- socat TCP-LISTEN:${CPORT},fork TCP:${PR_POD_IP}:${CPORT} + exec /usr/local/bin/mirrord exec -f /config/config.json -- socat TCP-LISTEN:${CPORT},fork TCP:${PR_POD_IP}:${CPORT} env: + - name: HOME + value: /tmp + - name: MIRRORD_TELEMETRY + value: "false" + - name: MIRRORD_PROGRESS_MODE + value: "off" + # INFO gives the gate below its positive marker: + # 'Created agent pod ... pod_name: "mirrord-agent-..."'. + # (mirrord still prints a non-fatal + # 'ERROR mirrord::connection: failed to obtain machine ID'.) + - name: RUST_LOG + value: "mirrord=info" - name: PR_POD_IP value: "${PR_POD_IP}" - name: CPORT @@ -195,6 +227,8 @@ spec: mountPath: /config readOnly: true securityContext: + runAsUser: 0 + privileged: true capabilities: add: [SYS_ADMIN, SYS_PTRACE, NET_ADMIN] volumes: @@ -203,7 +237,62 @@ spec: name: ${CM_NAME} PROXYPOD - kubectl wait --for=condition=Ready "pod/${PROXY_NAME}" --namespace "$NS" --timeout=120s || true + # Fail closed, with a positive marker. A Ready flicker is not proof: + # with no readiness probe a container is Ready the instant it runs, + # and mirrord exec can fail seconds later. Observed on kind: the + # proxy logs 'Created agent pod' at ~1s; without pods/portforward + # RBAC the WebSocket upgrade 403s at ~+17s and the agent gives up at + # ~+30s. So require: proxy Running, zero restarts, no fatal log + # line, the agent pod named in the proxy log Running, and all of + # that still true 40s after the agent pod was first seen. The + # proxy's own IP:port is NOT probed - under the mirrord layer socat's + # listener is virtual; routing is proven in validate-propagation. + PROXY_OK=false + AGENT_POD="" + AGENT_SEEN=0 + DEADLINE=$(( $(date +%s) + 180 )) + while [ "$(date +%s)" -lt "$DEADLINE" ]; do + PHASE=$(kubectl get "pod/${PROXY_NAME}" -n "$NS" -o jsonpath='{.status.phase}' 2>/dev/null || echo "") + RESTARTS=$(kubectl get "pod/${PROXY_NAME}" -n "$NS" -o jsonpath='{.status.containerStatuses[0].restartCount}' 2>/dev/null || echo "0") + PROXY_LOG=$(kubectl logs "pod/${PROXY_NAME}" -n "$NS" 2>/dev/null || true) + # Fatal log lines only. A generic "ERROR mirrord::..." is not + # fatal (the machine-ID telemetry lookup); a real crash ends the + # process and, with restartPolicy Never, moves the pod to Failed. + if [ "$PHASE" = "Failed" ] || [ "$PHASE" = "Succeeded" ] || [ "${RESTARTS:-0}" != "0" ] \ + || printf '%s' "$PROXY_LOG" | grep -Eq 'Failed to create mirrord-agent|Failed to connect to the created mirrord-agent|Forbidden|^Error:|agent (connection|creation) (failed|timed out)'; then + break + fi + if [ -z "$AGENT_POD" ]; then + AGENT_POD=$(printf '%s' "$PROXY_LOG" | sed -n 's/.*Created agent pod.*pod_name: "\([^"]*\)".*/\1/p' | head -n 1) + [ -z "$AGENT_POD" ] || AGENT_SEEN=$(date +%s) + fi + if [ "$PHASE" = "Running" ] && [ -n "$AGENT_POD" ]; then + AGENT_PHASE=$(kubectl get "pod/${AGENT_POD}" -n "$NS" -o jsonpath='{.status.phase}' 2>/dev/null || echo "") + if [ "$AGENT_PHASE" = "Failed" ] || [ "$AGENT_PHASE" = "Succeeded" ]; then + break + fi + if [ "$AGENT_PHASE" = "Running" ] && [ $(( $(date +%s) - AGENT_SEEN )) -ge 40 ]; then + PROXY_OK=true + break + fi + fi + sleep 3 + done + if ! $PROXY_OK; then + echo "ERROR: mirrord proxy ${PROXY_NAME} did not establish an agent connection (proxy phase=${PHASE:-?} restarts=${RESTARTS:-?} agent=${AGENT_POD:-none} agent phase=${AGENT_PHASE:-?})" >&2 + echo "--- proxy pod log ---" >&2 + kubectl logs "pod/${PROXY_NAME}" -n "$NS" 2>&1 | tail -n 60 >&2 || true + echo "--- proxy pod describe ---" >&2 + kubectl describe "pod/${PROXY_NAME}" -n "$NS" 2>&1 | tail -n 40 >&2 || true + echo "--- mirrord agent jobs/pods in $NS ---" >&2 + kubectl get jobs,pods -n "$NS" -l app=mirrord 2>&1 >&2 || true + if [ -n "$AGENT_POD" ]; then + echo "--- mirrord agent log (${AGENT_POD}) ---" >&2 + kubectl logs "pod/${AGENT_POD}" -n "$NS" --tail=-1 2>&1 | tail -n 60 >&2 || true + fi + exit 1 + fi + echo " Proxy ${PROXY_NAME} connected to agent ${AGENT_POD}; both Running 40s, 0 restarts (routing is proven in validate-propagation)" echo " Intercept active for $APP (traffic with header -> PR pod $POD_NAME)" echo "" diff --git a/tasks/deploy-intercept.yaml b/tasks/deploy-intercept.yaml deleted file mode 100644 index c46cbc0..0000000 --- a/tasks/deploy-intercept.yaml +++ /dev/null @@ -1,283 +0,0 @@ -apiVersion: tekton.dev/v1 -kind: Task -metadata: - name: deploy-stack-intercepts - labels: - app.kubernetes.io/part-of: tekton-job-standardization - app.kubernetes.io/version: "1.0.0" -spec: - description: > - Deploys PR pods with Telepresence intercepts ONLY for the app(s) - that changed. The rest of the stack runs as-is in the cluster. - - For a stack A→B→C→D where C changed: - - A, B, D: normal deployed services (untouched) - - C: Telepresence intercepts the existing C service so that - requests carrying the PR's baggage header get routed - to the PR pod running the new C build - - The e2e test enters through A with the header; B forwards - it to C (intercepted → PR pod); C forwards to D normally. - - The intercept-header-value (e.g. x-dev-session:pr-42) is what - Telepresence matches on. Only traffic with that header hits the - PR pod — all other traffic continues to the normal C deployment. - params: - - name: stack-json - type: string - description: "Full stack graph JSON (used to resolve ports, namespaces, topology)" - - name: build-apps - type: string - description: "Space-separated list of apps that were built (ONLY these get intercepts)" - - name: propagation-chain - type: string - default: "" - description: "Full ordered chain from entry to leaf (for logging context)" - - name: built-images - type: string - description: "JSON map of app → image URI" - - name: intercept-header-value - type: string - description: "Header match expression for Telepresence (e.g. x-dev-session:pr-42)" - - name: default-namespace - type: string - default: "staging" - - name: telepresence-image - type: string - default: "ghcr.io/telepresenceio/tel2:2.20.0" - workspaces: - - name: shared-workspace - optional: true - description: "Workspace to write deployed-pods.json for pass-through result (M7)" - results: - - name: deployed-pods - description: "JSON map of app → pod name" - steps: - - name: deploy - image: bitnami/kubectl:latest - script: | - #!/bin/bash - set -e - - STACK_JSON='$(params.stack-json)' - BUILD_APPS="$(params.build-apps)" - CHAIN="$(params.propagation-chain)" - BUILT='$(params.built-images)' - INTERCEPT="$(params.intercept-header-value)" - DEFAULT_NS="$(params.default-namespace)" - - # Compute the full app list from the graph for context - ALL_APPS=$(echo "$STACK_JSON" | jq -r '.apps[].name' | tr '\n' ' ') - - echo "=============================================" - echo " Intercept Deployment Plan" - echo "=============================================" - echo " Full stack apps: $ALL_APPS" - echo " Propagation chain: ${CHAIN:-}" - echo " Intercepted apps: $BUILD_APPS" - echo " Intercept header: $INTERCEPT" - echo "" - echo " Apps NOT intercepted run their normal cluster deployments." - echo " Only traffic matching the header routes to PR pods." - echo "" - - # Show each intercepted app's propagation role and chain position - for APP in $BUILD_APPS; do - PROP_ROLE=$(echo "$STACK_JSON" | jq -r --arg a "$APP" \ - '.apps[]|select(.name==$a)|."propagation-role" // "unknown"') - - echo " $APP:" - echo " propagation-role: $PROP_ROLE" - - # Check if there are other intercepted apps downstream of this one - HAS_DOWNSTREAM_INTERCEPT=false - FOUND_SELF=false - for C in $CHAIN; do - if [ "$C" = "$APP" ]; then - FOUND_SELF=true - continue - fi - if $FOUND_SELF; then - for BA in $BUILD_APPS; do - [ "$BA" = "$C" ] && HAS_DOWNSTREAM_INTERCEPT=true - done - fi - done - - case "$PROP_ROLE" in - originator) - echo " behavior: STARTS the baggage chain" - if $HAS_DOWNSTREAM_INTERCEPT; then - echo " app code: must set headers on outgoing requests (intercepted app downstream)" - else - echo " app code: must set headers on outgoing requests" - echo " note: no other intercepted apps downstream — header only needed to reach THIS app" - fi - ;; - forwarder) - if $HAS_DOWNSTREAM_INTERCEPT; then - echo " behavior: ACCEPTS incoming baggage and MUST FORWARD (intercepted app downstream)" - echo " app code: must parse incoming header, store in context, propagate on all outgoing calls" - else - echo " behavior: ACCEPTS incoming baggage, downstream calls are NORMAL" - echo " app code: header got traffic here via Telepresence — downstream calls go to" - echo " normal deployments, no forwarding needed for intercept routing" - fi - ;; - terminal) - echo " behavior: ACCEPTS incoming baggage, never forwards" - echo " app code: header got traffic here — end of the line" - ;; - esac - - # Chain position context - if [ -n "$CHAIN" ]; then - POSITION=0 - TOTAL=0 - for C in $CHAIN; do - TOTAL=$((TOTAL + 1)) - if [ "$C" = "$APP" ]; then - POSITION=$TOTAL - fi - done - if [ $POSITION -gt 0 ]; then - echo " chain position: $POSITION of $TOTAL" - UPSTREAM="" - DOWNSTREAM="" - FOUND=false - for C in $CHAIN; do - if [ "$C" = "$APP" ]; then - FOUND=true - continue - fi - if $FOUND; then - DOWNSTREAM="$DOWNSTREAM $C" - else - UPSTREAM="$UPSTREAM $C" - fi - done - [ -n "$UPSTREAM" ] && echo " upstream (normal): $UPSTREAM" - [ -n "$DOWNSTREAM" ] && echo " downstream (normal): $DOWNSTREAM" - else - echo " chain position: leaf (fan-out target)" - fi - fi - echo "" - done - - echo '{}' > /tmp/pods.json - - for APP in $BUILD_APPS; do - echo "=========================================" - echo " Deploying intercept: $APP" - echo "=========================================" - - IMAGE=$(echo "$BUILT" | jq -r --arg a "$APP" '.[$a]') - NS=$(echo "$STACK_JSON" | jq -r --arg a "$APP" --arg d "$DEFAULT_NS" \ - '(.defaults.namespace // $d) as $dn | .apps[]|select(.name==$a)|.namespace // $dn') - CPORT=$(echo "$STACK_JSON" | jq -r --arg a "$APP" \ - '(.defaults."container-port" // "8080") as $dp | .apps[]|select(.name==$a)|."container-port" // $dp') - SPORT=$(echo "$STACK_JSON" | jq -r --arg a "$APP" \ - '(.defaults."service-port" // "80") as $dp | .apps[]|select(.name==$a)|."service-port" // $dp') - - POD_NAME="pr-${APP}-$(date +%s)" - - BAGGAGE_ROLE=$(echo "$STACK_JSON" | jq -r --arg a "$APP" ' - (.apps[] | select(.name==$a)) as $app | - ($app.downstream // []) as $down | - $app."propagation-role" // ( - if ($down|length)==0 then "terminal" - elif (($app.role // "")|ascii_downcase)=="frontend" then "originator" - else "forwarder" end) - ') - HEADER_NAME=$(echo "$STACK_JSON" | jq -r '.propagation."header-name" // "x-dev-session"') - BAGGAGE_KEY=$(echo "$STACK_JSON" | jq -r '.propagation."baggage-key" // "dev-session"') - DOWNSTREAM_URL=$(echo "$STACK_JSON" | jq -r --arg a "$APP" ' - (.apps[] | select(.name==$a) | .downstream // []) as $down | - if ($down|length)>0 then "http://" + ($down[0]|tostring) else empty end - ') - - echo " Image: $IMAGE" - echo " Namespace: $NS" - echo " Ports: container=$CPORT service=$SPORT" - echo " Intercept: $INTERCEPT" - echo " Pod: $POD_NAME" - echo " Baggage: role=$BAGGAGE_ROLE header=$HEADER_NAME" - - INTERCEPT_ARGS="" - if [ -n "$INTERCEPT" ]; then - INTERCEPT_ARGS="telepresence intercept ${APP} --namespace ${NS} --port ${CPORT}:${SPORT} --http-match ${INTERCEPT}" - else - INTERCEPT_ARGS="telepresence intercept ${APP} --namespace ${NS} --port ${CPORT}:${SPORT}" - fi - - cat < /tmp/pods-tmp.json - mv /tmp/pods-tmp.json /tmp/pods.json - done - - # Write to result and optionally to workspace for deploy-intercepts-result pass-through (M7) - cat /tmp/pods.json | tee $(results.deployed-pods.path) - WS_PATH="$(workspaces.shared-workspace.path)" - if [ -n "${WS_PATH}" ]; then - DEPLOYED_PODS_FILE="${WS_PATH}/deployed-pods.json" - mkdir -p "$(dirname "${DEPLOYED_PODS_FILE}")" - cp /tmp/pods.json "${DEPLOYED_PODS_FILE}" - fi \ No newline at end of file diff --git a/tasks/validate-original-traffic.yaml b/tasks/validate-original-traffic.yaml index 4217b26..bd6d72e 100644 --- a/tasks/validate-original-traffic.yaml +++ b/tasks/validate-original-traffic.yaml @@ -148,7 +148,7 @@ spec: echo "" echo " This request should flow through ALL original deployments." echo " Even intercepted apps should respond from their original pods" - echo " because no header matches the Telepresence intercept rule." + echo " because no header matches the mirrord intercept filter." echo "" PASSTHROUGH_RESULT=$(curl -s \ diff --git a/tasks/validate-propagation.yaml b/tasks/validate-propagation.yaml index 0d185f1..12d4fad 100644 --- a/tasks/validate-propagation.yaml +++ b/tasks/validate-propagation.yaml @@ -45,6 +45,14 @@ spec: - name: default-namespace type: string default: "staging" + - name: deployed-pods + type: string + default: "" + description: | + JSON map app -> PR pod name from deploy-intercepts. When non-empty the + task also proves routing: a header-matched request must be served by + that PR pod and an unmatched request must not be (read from the pod's + access log through the Kubernetes API). steps: - name: validate image: alpine:3.19 @@ -186,12 +194,17 @@ spec: TRACEPARENT="00-$(cat /dev/urandom | tr -dc 'a-f0-9' | head -c 32)-$(cat /dev/urandom | tr -dc 'a-f0-9' | head -c 16)-01" fetch_originator() { - curl -s \ + body_file=$(mktemp) + http_code=$(curl -s -o "$body_file" -w "%{http_code}" \ -H "${HEADER_NAME}: ${HEADER_VAL}" \ -H "baggage: ${BAGGAGE_KEY}=${HEADER_VAL}" \ -H "traceparent: ${TRACEPARENT}" \ --connect-timeout 10 --max-time 60 \ - "$1" 2>/dev/null || echo '{"error":"unreachable"}' + "$1" 2>/dev/null || true) + [ -n "$http_code" ] || http_code="000" + printf '%s' "$http_code" > /tmp/originator-http-code + cat "$body_file" + rm -f "$body_file" } URL="${BASE}/propagation" @@ -200,10 +213,11 @@ spec: echo "" RESULT=$(fetch_originator "$URL") - if echo "$RESULT" | grep -Eq '"error"[[:space:]]*:[[:space:]]*"unreachable"' \ - || echo "$RESULT" | grep -qi '404'; then + HTTP_CODE=$(cat /tmp/originator-http-code 2>/dev/null || echo "000") + if [ "$HTTP_CODE" = "404" ] || [ "$HTTP_CODE" = "000" ] \ + || echo "$RESULT" | grep -Eq '"error"[[:space:]]*:[[:space:]]*"unreachable"'; then URL="${BASE}/" - echo " /propagation unavailable — retrying $URL" + echo " /propagation unavailable (HTTP $HTTP_CODE) — retrying $URL" RESULT=$(fetch_originator "$URL") fi @@ -306,4 +320,90 @@ spec: echo "PASS: hop-to-hop verification complete" fi echo "" + + # ------------------------------------------------------------------ + # Routing proof (fail-closed). The /propagation echo above is served + # identically by the baseline and the PR pod, so it cannot tell which + # pod answered. Prove it from the PR pod's own access log: a request + # tagged with a unique query string and carrying the header must show + # up there; an untagged-header request with a different tag must not. + # ------------------------------------------------------------------ + DEPLOYED_PODS='$(params.deployed-pods)' + if [ -n "$HEADER_VAL" ] && [ -n "$BUILD_APPS" ] \ + && [ -n "$DEPLOYED_PODS" ] && [ "$DEPLOYED_PODS" != "{}" ]; then + echo "Routing proof (fail-closed): PR pod must serve matched traffic only" + SA_DIR=/var/run/secrets/kubernetes.io/serviceaccount + API="https://kubernetes.default.svc" + pod_log() { + # $1 namespace, $2 pod. Prefer the app container; fall back to the + # pod default if that container name does not exist. + out=$(curl -s --cacert "$SA_DIR/ca.crt" \ + -H "Authorization: Bearer $(cat "$SA_DIR/token")" \ + "$API/api/v1/namespaces/$1/pods/$2/log?container=pr-component&sinceSeconds=600" || true) + if printf '%s' "$out" | grep -q '"kind":"Status"'; then + out=$(curl -s --cacert "$SA_DIR/ca.crt" \ + -H "Authorization: Bearer $(cat "$SA_DIR/token")" \ + "$API/api/v1/namespaces/$1/pods/$2/log?sinceSeconds=600" || true) + fi + printf '%s' "$out" + } + for APP in $BUILD_APPS; do + POD=$(echo "$DEPLOYED_PODS" | jq -r --arg a "$APP" '.[$a] // empty') + if [ -z "$POD" ]; then + echo " $APP: FAIL — no PR pod recorded in deployed-pods" + FAILED=1 + continue + fi + NS=$(echo "$STACK_JSON" | jq -r --arg a "$APP" --arg d "$DEFAULT_NS" \ + '(.defaults.namespace // $d) as $dn | .apps[]|select(.name==$a)|.namespace // $dn') + SPORT=$(echo "$STACK_JSON" | jq -r --arg a "$APP" \ + '(.defaults."service-port" // "80") as $dp | .apps[]|select(.name==$a)|."service-port" // $dp') + SVC="http://${APP}.${NS}.svc.cluster.local:${SPORT}" + TAG=$(cat /dev/urandom | tr -dc 'a-z0-9' | head -c 12) + HIT="probehit${TAG}" + MISS="probemiss${TAG}" + + HIT_CODE=$(curl -s -o /dev/null -w "%{http_code}" \ + -H "${HEADER_NAME}: ${HEADER_VAL}" \ + -H "baggage: ${BAGGAGE_KEY}=${HEADER_VAL}" \ + --connect-timeout 10 --max-time 30 \ + "${SVC}/propagation?${HIT}" 2>/dev/null || echo "000") + MISS_CODE=$(curl -s -o /dev/null -w "%{http_code}" \ + --connect-timeout 10 --max-time 30 \ + "${SVC}/propagation?${MISS}" 2>/dev/null || echo "000") + echo " $APP -> $POD: matched request HTTP $HIT_CODE, unmatched request HTTP $MISS_CODE" + + LOG="" + ATTEMPT=0 + while [ $ATTEMPT -lt 10 ]; do + ATTEMPT=$((ATTEMPT + 1)) + LOG=$(pod_log "$NS" "$POD") + if printf '%s' "$LOG" | grep -q "$HIT"; then break; fi + sleep 2 + done + + if ! printf '%s' "$LOG" | grep -q "$HIT"; then + echo " $APP: FAIL — header-matched request never reached PR pod $POD (intercept is not routing)" + echo " --- last 20 log lines of $POD ---" + printf '%s\n' "$LOG" | tail -n 20 | sed 's/^/ /' + FAILED=1 + elif printf '%s' "$LOG" | grep -q "$MISS"; then + echo " $APP: FAIL — unmatched request also reached PR pod $POD (intercept steals all traffic)" + FAILED=1 + else + echo " $APP: PASS — PR pod $POD served the matched request and not the unmatched one" + fi + done + echo "" + if [ "$FAILED" -ne 0 ]; then + echo "FAIL: intercept routing not proven" + exit 1 + fi + echo "PASS: intercept routing proven from PR pod access logs" + echo "" + elif [ -n "$BUILD_APPS" ]; then + echo "Routing proof skipped: deployed-pods not provided" + echo "" + fi + echo "Propagation validation complete."