diff --git a/.agent/specs/SPEC-P5_TENANT_GUARDRAILS.md b/.agent/specs/SPEC-P5_TENANT_GUARDRAILS.md index a1e9785..f72238a 100644 --- a/.agent/specs/SPEC-P5_TENANT_GUARDRAILS.md +++ b/.agent/specs/SPEC-P5_TENANT_GUARDRAILS.md @@ -398,6 +398,27 @@ nothing about VPC CNI enforcement or IRSA. eks mode allows no skip. Probe Pods: `window.sh run_probe` adds the tenant label in tenant namespaces and the app requests and memory limit. Runbook `docs/runbooks/P5_ISOLATION_SUITE.md`.) + (24/11, after Codex review: admission records the policy that denied + (`deny:kyverno:`) and treats an unreachable webhook as an error; + `can-i` answers other than yes/no are errors; workload ServiceAccount + cases; T03 adds a foreign kind; network and T07 probes are Jobs; the P4 + wrapper needs exit 0 and the full case set of each probe, `platform` + included; evidence is scrubbed; an exit trap removes and checks every + suite object. After Codex re-review: probe results count only from a + `Complete` Job; enforced accepts only a fully passing control receipt of + `RUN_ID-control` for the same sandbox; RBAC by SubjectAccessReview + (`evaluationError` is an error); failed lists are errors, not "none"; + cleanup is a recorded case before RESULT. Third Codex pass: the log + read must succeed; cleanup also deletes and waits for the `window.sh` + probe Pods (`zdr-probe`); account IDs side by side are all scrubbed; + egress is keyed by the policy podSelector with integer ports. + Codex APPROVE at ae20196; its two should-fix items done: a policy + without policyTypes counts its egress (Kubernetes default), and + cleanup touches only this run's probes (`PROBE_RUN` label set by + `window.sh`). + Kind with Argo CD: 39 cases, + 33 PASS, 0 FAIL, 6 `SKIPPED_NEEDS_EKS`; one policy in `Audit` still + exits 1.) ### P5-T4.2 — L3 window on EKS (4 h) @@ -409,18 +430,37 @@ pre-inventory, the owner's explicit approval. **B. Build (1 h)** — bootstrap with the RAG platform and NetworkPolicy enabled; platform through Argo CD; both sandboxes Ready **before** any guardrail. +Pre-flight (Codex review 24/11): the planned `vpc_cidr` and DB subnets equal +the NetworkPolicy `ipBlock` values (`gitops/check.sh` checks this against +`infra/terraform/variables.tf`; recheck if the plan overrides `vpc_cidr`). **C. Control, then guardrails (1 h)** -- [ ] Control run: tenant-a reaches a listener in tenant-b (expected to succeed). -- [ ] Apply baseline and NetworkPolicies; Kyverno in `Audit`; reports clean; - switch to `Enforce`. +The apps `25-tenants` and `47-kyverno-policies` use automated sync with +`selfHeal`: a NetworkPolicy deleted by hand comes back within a reconcile, and +a policy edited in the cluster is reverted. So every step that removes or +changes a guardrail first suspends automated sync on the root app and on that +app, and re-enables it afterwards. Audit to Deny is a Git commit, not a +cluster edit. + +- [ ] Control run: suspend sync (root, `25-tenants`), delete the tenant + NetworkPolicies, `NET_PHASE=control`: the suite refuses to run if any + NetworkPolicy remains, and every path (own app, a→b, b→a, metadata) must + be open. Keep its JSON. +- [ ] Re-enable sync; NetworkPolicies back from Git; PolicyEndpoints present. + Kyverno in `Audit`; reports clean; commit `Deny`; Argo applies it. - [ ] Delete and re-create both sandboxes; both Ready; independent check passes. **D. Suite and failure case (1 h)** -- [ ] Full suite; observation limit 10 minutes per negative case, 900 s total. -- [ ] Kyverno outage case of §4 on EKS. +- [ ] Full suite, `NET_PHASE=enforced CONTROL=`: it checks the + control file, that every Git NetworkPolicy has a PolicyEndpoint, and runs + network and IAM probes as Jobs (the VPC CNI does not enforce NetworkPolicy + on a Pod without an owner). Only a timeout counts as a network deny; + `AccessDenied` is the only IAM deny. Observation limit 10 minutes per + negative case, 900 s total. +- [ ] Kyverno outage case of §4 on EKS, with sync of `45-kyverno` and + `47-kyverno-policies` suspended first (self-heal would scale Kyverno back). - [ ] Owner-typed micro-lab: one forbidden request per layer, typed by hand. **E. Teardown (0.5 h)** — requests and cleanup → policies → Kyverno → P4/P3 diff --git a/docs/runbooks/P5_ISOLATION_SUITE.md b/docs/runbooks/P5_ISOLATION_SUITE.md index 4cf9b2e..05c75f0 100644 --- a/docs/runbooks/P5_ISOLATION_SUITE.md +++ b/docs/runbooks/P5_ISOLATION_SUITE.md @@ -2,16 +2,17 @@ > **TL;DR** · Để làm gì: một lệnh thử mọi lớp chặn (RBAC, Pod Security, Kyverno, quota, NetworkPolicy, IAM/DB) > và ghi `acceptance.json` · -> Trạng thái: Claude chạy trên kind 24/11 (Kyverno `Deny`): 24 PASS, 0 FAIL, 7 SKIPPED_NEEDS_EKS · +> Trạng thái: Claude chạy trên kind 24/11 sau review Codex (Kyverno `Deny`, có Argo CD): 39 case, 33 PASS, 0 FAIL, +> 6 SKIPPED_NEEDS_EKS · > Liên quan: `tests/isolation/run.sh`, SPEC-P5 P5-T4.1, THREAT_MODEL §11 · > Mục lục: 0 Dựng kind · 1 Chạy · 2 Đọc kết quả · 3 Tự kiểm bộ test · 4 Dọn · 5 Trên EKS Ví von: mỗi case là một **người thử cửa**. Họ ghi lại cửa nào chặn mình (`deny:pod-security`, `deny:kyverno`…), không chỉ "bị chặn". Chặn đúng nhưng **sai cửa** cũng là FAIL: lớp mình tưởng đang canh thật ra không canh. -## 0. Dựng kind (không AWS, ~5 phút) +## 0. Dựng kind (không AWS, ~8 phút) -Giống mục 0 của `P5_L2_KIND_KYVERNO.md`, nhưng policy bật thẳng `Deny`: +Giống mục 0 của `P5_L2_KIND_KYVERNO.md`, nhưng policy bật thẳng `Deny`, thêm Argo CD cho hai case T03: ```bash cd /r/_Projects/Eurus_Workspace/Zero-D-Rift @@ -35,11 +36,17 @@ for f in gitops/platform/policies/*.yaml; do done # "Available" chưa chắc webhook đã nhận kết nối: thử lại tới khi Kyverno nhận policy until $K apply -f "$LAB/policies/"; do sleep 5; done +curl -fsSL -o "$LAB/argocd-install-v3.5.7.yaml" https://raw.githubusercontent.com/argoproj/argo-cd/v3.5.7/manifests/install.yaml +echo "09bfbb9041b4a8503c6e4fa22cf41c403fa62be17526de353648a4551f5beb77 $LAB/argocd-install-v3.5.7.yaml" | sha256sum -c +$K create namespace argocd +$K apply -n argocd --server-side -f "$LAB/argocd-install-v3.5.7.yaml" > /dev/null +$K -n argocd wait --for=condition=Available deploy --all --timeout=300s +$K apply -f gitops/platform/apps/85-project-requests.yaml sleep 30 ``` -**Phải thấy:** `OK`, ba Deployment `condition met`, ba `validatingpolicy … created` (có thể kèm một lần -`connection refused` trước đó, vòng `until` tự thử lại). +**Phải thấy:** hai dòng `OK` (sha256), các Deployment `condition met`, ba `validatingpolicy … created` (có thể kèm một lần +`connection refused` trước đó, vòng `until` tự thử lại), `appproject.argoproj.io/zdr-requests created`. ## 1. Chạy @@ -49,7 +56,9 @@ MODE=kind CTX=kind-zdr-p5-iso OUT="$LAB/acceptance.json" bash tests/isolation/ru **Dự đoán trước:** Pod `privileged` bị lớp nào chặn? Pod gắn nhãn `tenant-b` trong `tenant-a`? Pod xin 1Gi? -**Phải thấy:** `total 31, pass 24, fail 0, skipped 7`, `RESULT: PASS`, `exit=0`. +**Phải thấy:** `total 39, pass 33, fail 0, skipped 6`, dòng `PASS … cleanup … verified-empty`, `RESULT: PASS`, `exit=0`. +Không cài Argo CD thì hai case T03 thành SKIPPED: `total 39, pass 31, skipped 8`. Case `cleanup` chỉ PASS khi suite +**đọc được** danh sách và thấy trống; đọc lỗi thì là `unverified`, tính FAIL. ## 2. Đọc kết quả @@ -58,8 +67,9 @@ jq -r '.cases[] | "\(.result)\t\(.threat)\t\(.id)\t\(.observed)"' "$LAB/acceptan jq '.summary' "$LAB/acceptance.json" ``` -Cột `observed` cho biết **lớp nào** trả lời: `deny:rbac`, `deny:pod-security`, `deny:kyverno`, `deny:quota`, -`deny:limitrange`. `SKIPPED_NEEDS_EKS` = kind không có VPC CNI, IRSA, RDS, Argo CD; **không bao giờ** tính là PASS. +Cột `observed` cho biết **lớp nào** trả lời: `deny:rbac`, `deny:pod-security`, `deny:kyverno:`, `deny:quota`, +`deny:limitrange`, `deny:argocd`. Bắt đầu bằng `error:` (webhook không gọi được, SubjectAccessReview báo `evaluationError`, mạng `refused`, Job không `Complete`…) nghĩa là +**không ai quyết định cả**, nên tính FAIL chứ không tính là bị chặn. `SKIPPED_NEEDS_EKS` = kind không có VPC CNI, IRSA, RDS, Argo CD; **không bao giờ** tính là PASS. File không chứa tên context (trên EKS tên đó có account ID). ## 3. Tự kiểm bộ test: nó có biết FAIL không? @@ -79,6 +89,10 @@ $K patch validatingpolicy zdr-image-digest --type merge -p '{"spec":{"validation Bài học Claude gặp khi viết suite: `pod … | case_admit` chạy vế phải trong **subshell**, nên kết quả (kể cả FAIL) bị mất, suite vẫn báo PASS với 18/30 case. Sửa bằng `shopt -s lastpipe`. Bước 3 này là để bắt đúng loại lỗi đó. +Điều Claude phát hiện khi thử wrapper Job (24/11): kindnet của kind **cũng** thực thi NetworkPolicy. Một Job trong tenant-a +gọi `kubernetes.default.svc:443` bị TIMEOUT, vì sau DNAT API server nằm ở cổng 6443, mà policy chỉ mở 443. Suite vẫn để +case mạng SKIPPED trên kind, vì thứ cần chứng minh là VPC CNI trên EKS (PolicyEndpoint, standard mode), không phải kindnet. + ## 4. Dọn ```bash @@ -90,17 +104,41 @@ kind get clusters ## 5. Trên EKS (window L3, P5-T4.2; cần phê duyệt riêng) +Chạy **hai pha**. Ví von: muốn chứng minh cửa khóa được thì trước hết phải thấy cửa **mở** khi chưa khóa. +Nếu không, "bị chặn" có thể chỉ là do đường mạng hỏng. + +**Pha control** (chưa có NetworkPolicy): tạm dừng auto-sync của app root và `25-tenants`, xóa NetworkPolicy +của hai tenant, rồi chạy: + +```bash +MODE=eks CTX="$(kubectl config current-context)" NET_PHASE=control RUN_ID=P5-L3--01-control OUT=control.json bash tests/isolation/run.sh +``` + +Suite chỉ chạy 4 đường mạng: own-app, a→b, b→a, metadata. Cả 4 phải `allow`. Nếu còn NetworkPolicy, hoặc không đọc được +danh sách NetworkPolicy, suite dừng trước khi thử mạng. + +**Pha enforced**: bật lại sync. Argo trả NetworkPolicy từ Git. Kyverno `Audit` → báo cáo sạch → commit `Deny`. +Sau đó chạy: + ```bash -MODE=eks CTX="$(kubectl config current-context)" RUN_ID=P5-L3--01 OUT=acceptance.json bash tests/isolation/run.sh +MODE=eks CTX="$(kubectl config current-context)" NET_PHASE=enforced CONTROL=control.json RUN_ID=P5-L3--01 OUT=acceptance.json bash tests/isolation/run.sh ``` - Không in `CTX` ra màn hình (có account ID). Suite từ chối chạy nếu `CTX` khác context hiện tại, - vì `window.sh probe` dùng context hiện tại. -- Ở `eks`, **không case nào được SKIPPED**; thêm các case mạng (Pod Python thật, chờ 20 s cho khoảng hở - standard mode), T07 (ServiceAccount `zdr-iso-other` ngoài mẫu `rag-*`, phải `AccessDenied`) và probe P4 - (`sandbox` dương tính, `cross` âm tính cho cả hai tenant). -- Suite tự xoá Pod và ServiceAccount nó tạo. Kiểm sau khi chạy: - `kubectl get pods,sa -A -l app.kubernetes.io/name=zdr-isolation; kubectl -n tenant-a get sa zdr-iso-other`. + vì `window.sh probe` dùng context hiện tại. Mọi dòng ghi ra đều đã lọc tên context, ARN, account ID. +- Ở `eks`, **không case nào được SKIPPED**. Probe mạng và T07 chạy bằng **Job**, vì VPC CNI không áp + NetworkPolicy cho Pod không có owner. Mỗi Job chờ 20 s cho khoảng hở của standard mode. + - Mạng: chỉ `TIMEOUT` mới tính là NetworkPolicy chặn. `refused` hay lỗi DNS là FAIL. + - T07: chỉ `AccessDenied` mới tính là IAM chặn. +- Pha enforced chỉ nhận file control của **đúng** `RUN_ID-control`, cùng sandbox, và mọi case đều PASS (case `net-control-receipt`). +- Trước các case mạng, suite đợi mỗi NetworkPolicy trong Git có một PolicyEndpoint, tức node agent đã nạp. +- Kết quả của một Job chỉ được đọc khi Job đã `Complete`; Job thất bại thì là lỗi, kể cả khi log đã in `RESULT TIMEOUT`. +- Probe P4 (`platform`, `sandbox`, `cross` cho cả hai tenant) phải exit 0 và in **đủ** từng case. Thiếu case + hay có `SKIP` đều là FAIL. +- Suite tự xóa Job, Pod, ServiceAccount và Argo app nó tạo (nhãn `app.kubernetes.io/name=zdr-isolation`), + cùng Pod probe của `window.sh` **của chính lần chạy này** (nhãn `zdr-probe` và `rag.zero-drift.io/probe-run`, + do suite đặt qua biến `PROBE_RUN`), đợi chúng biến mất rồi kiểm lại. Probe của lần chạy khác không bị đụng tới. + Còn sót, hoặc không đọc được danh sách, thì exit 1. ## Bảng dự đoán (owner tự điền) diff --git a/gitops/check.sh b/gitops/check.sh index 30ea83c..e4ef094 100644 --- a/gitops/check.sh +++ b/gitops/check.sh @@ -6,6 +6,9 @@ set -euo pipefail here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" cd "$here" +# Terraform's vpc_cidr (rule 18 cross-check). The guard tests copy only gitops/, +# so they pass the real file in TF_VARIABLES. +export TF_VARIABLES="${TF_VARIABLES:-$here/../infra/terraform/variables.tf}" failed=0 pass() { echo "PASS $1"; } @@ -38,7 +41,7 @@ unpinned="$(grep -h -E '^\s*-?\s*(image|package):\s*\S' $files | grep -v '@sha25 # 4-7 need structure: read every document once. python -I - $files <<'EOF' || failed=1 -import sys, yaml, re +import sys, yaml, re, os, ipaddress, json docs = [] for f in sys.argv[1:]: for d in yaml.safe_load_all(open(f)): @@ -78,24 +81,32 @@ res(charts == {"crossplane": "2.4.3", "kro": "0.9.4", "kyverno": "3.10.0"}, f"He # Chart images: the values must carry a digest (Crossplane: repository@sha256 + # ignoreTag; kro and Kyverno: tag v...@sha256), otherwise the chart default tag # is used. Every "image" block in the values counts; Kyverno has eight. -def image_blocks(node): +# The digest must sit in the key the chart template reads (Codex PR #71 +# review): a digest moved to an unused key would leave the real image on a tag. +def image_blocks(node, path=()): if isinstance(node, dict): for k, v in node.items(): if k == "image" and isinstance(v, dict): - yield v - yield from image_blocks(v) + yield path, v + yield from image_blocks(v, path + (k,)) elif isinstance(node, list): for x in node: - yield from image_blocks(x) -NEED_IMAGES = {"crossplane": 1, "kro": 1, "kyverno": 8} + yield from image_blocks(x, path) +IMAGE_KEYS = { # chart -> {path of the image block: field the template reads} + "crossplane": {(): "repository"}, + "kro": {(): "tag"}, + "kyverno": {p: "tag" for p in [("admissionController", "initContainer"), ("admissionController", "container"), + ("backgroundController",), ("reportsController",), ("upgrade", "legacyPolicyCheck"), + ("crds", "migration"), ("webhooksCleanup",), ("test",)]}, +} for f, d in apps: s = d["spec"]["source"] if "chart" in s: - blocks = list(image_blocks(s.get("helm", {}).get("valuesObject", {}))) - refs = [b.get("repository", "") + ":" + str(b.get("tag", "")) for b in blocks] - res(len(refs) == NEED_IMAGES.get(s["chart"], -1) - and all(re.search(r"@sha256:[0-9a-f]{64}", r) for r in refs), - f"{d['metadata']['name']}: chart image pinned by digest ({len(refs)} image blocks)") + blocks = dict(image_blocks(s.get("helm", {}).get("valuesObject", {}))) + want = IMAGE_KEYS.get(s["chart"], {}) + res(want and set(blocks) == set(want) + and all(re.search(r"@sha256:[0-9a-f]{64}$", str(blocks[p].get(k, ""))) for p, k in want.items()), + f"{d['metadata']['name']}: chart image pinned by digest at the chart's keys ({len(blocks)} image blocks)") for f, d in apps: a = d["spec"].get("syncPolicy", {}).get("automated", {}) name = d["metadata"]["name"] @@ -300,6 +311,11 @@ for t in sorted(TENANTS): res(lab.get("rag.zero-drift.io/tenant") == t and all(lab.get(k) == v for k, v in PSS.items()), f"namespace {t}: tenant label = name; Pod Security enforce/audit/warn restricted v1.35") +others = [d["metadata"]["name"] for f, d in objs_of("Namespace") + if d["metadata"]["name"] not in TENANTS and "rag.zero-drift.io/tenant" in d["metadata"].get("labels", {})] +res(not others, "tenant label only on tenant namespaces (Kyverno and NetworkPolicy select it)" + + (f": {others}" if others else "")) + # 14. Tenant RBAC (D1): in each tenant namespace one Role tenant-viewer, read # verbs only, no Secrets, no wildcard, bound only to zdr::developers; # no ClusterRoleBinding names a tenant group, and no RBAC object of a tenant @@ -321,6 +337,10 @@ for t in sorted(TENANTS): crb = [f"{f}: {d['metadata']['name']}" for f, d in objs_of("ClusterRoleBinding") if any(str(s.get("name", "")).startswith("zdr:") for s in d.get("subjects", []) or [])] res(not crb, "no ClusterRoleBinding for a tenant group" + (f": {crb}" if crb else "")) +foreign = [f"{d['metadata'].get('namespace')}/{d['metadata']['name']}" for f, d in objs_of("RoleBinding") + for s in d.get("subjects", []) or [] if str(s.get("name", "")).startswith("zdr:") + and s.get("name") != f"zdr:{d['metadata'].get('namespace')}:developers"] +res(not foreign, "a tenant group is bound only in its own namespace" + (f": {foreign}" if foreign else "")) stray = [f for f, d in docs if d.get("kind") in ("Role", "RoleBinding") and d.get("metadata", {}).get("namespace") in TENANTS and not f.replace("\\", "/").startswith("platform/tenants/")] @@ -410,6 +430,68 @@ for f, d in objs_of("NetworkPolicy"): or not {"10.0.0.0/16", "169.254.0.0/16"} <= set(b.get("except", []))): wide.append(f"{d['metadata'].get('namespace')}/{d['metadata']['name']}") res(not wide, "no NetworkPolicy opens 0.0.0.0/0 on all ports or into the VPC/metadata" + (f": {wide}" if wide else "")) +# Every egress rule names its peers and its ports (an empty rule, a rule without +# "to" or without "ports" allows everything); a namespaceSelector peer is only +# the DNS path to kube-system on port 53. +DNS_NS = {"matchLabels": {"kubernetes.io/metadata.name": "kube-system"}} +loose = [] +for f, d in objs_of("NetworkPolicy"): + for r in d.get("spec", {}).get("egress", []) or []: + peers, ports = r.get("to") or [], r.get("ports") or [] + if (not peers or not ports or any(p == {} for p in peers) + or any("namespaceSelector" in p and (p["namespaceSelector"] != DNS_NS + or any(str(q.get("port")) != "53" for q in ports)) for p in peers)): + loose.append(f"{d['metadata'].get('namespace')}/{d['metadata']['name']}") +res(not loose, "every egress rule names peers and ports; other namespaces only for DNS" + (f": {loose}" if loose else "")) +# Each tenant's egress is exactly these four rules, each port with an explicit +# protocol and number (a port entry {} means every port). A rule that goes +# missing (no DB path for one tenant) fails here too, not only a wider one. +# A rule is keyed by the Pods it applies to (the policy podSelector) as well as +# its peers and ports; ports must be an integer with TCP or UDP. A policy whose +# policyTypes leave out Egress has no egress effect, so its rules do not count; +# with policyTypes omitted, Kubernetes adds Egress when the policy has egress rules. +def canon_rule(r, sel): + ports = r.get("ports") or [] + if any(set(q) != {"protocol", "port"} or type(q["port"]) is not int or q["protocol"] not in ("TCP", "UDP") + for q in ports): + return ("bad-port",) + return (json.dumps(sel, sort_keys=True), json.dumps(sorted(json.dumps(p, sort_keys=True) for p in r.get("to") or [])), + tuple(sorted((q["protocol"], str(q["port"])) for q in ports))) +def egress_on(spec): + pt = spec.get("policyTypes") + return "Egress" in pt if pt else bool(spec.get("egress")) +def want_egress(t, vpc_s, dbs_s): + sel = {"matchLabels": {"rag.zero-drift.io/tenant": t}} + return sorted([ + canon_rule({"to": [{"namespaceSelector": DNS_NS, "podSelector": {"matchLabels": {"k8s-app": "kube-dns"}}}], + "ports": [{"protocol": "UDP", "port": 53}, {"protocol": "TCP", "port": 53}]}, sel), + canon_rule({"to": [{"ipBlock": {"cidr": c}} for c in sorted(dbs_s)], "ports": [{"protocol": "TCP", "port": 5432}]}, sel), + canon_rule({"to": [{"ipBlock": {"cidr": "0.0.0.0/0", "except": [vpc_s, "169.254.0.0/16"]}}], + "ports": [{"protocol": "TCP", "port": 443}]}, sel), + canon_rule({"to": [{"podSelector": {"matchLabels": {"rag.zero-drift.io/tenant": t}}}], + "ports": [{"protocol": "TCP", "port": 8080}]}, sel)], key=str) +_tf = open(os.environ["TF_VARIABLES"], encoding="utf-8").read() if os.path.exists(os.environ["TF_VARIABLES"]) else "" +_m = re.search(r'variable "vpc_cidr"[^}]*?default\s*=\s*"([0-9./]+)"', _tf, re.S) +_vpc = ipaddress.ip_network(_m.group(1)) if _m else None +_dbs = [str(n) for n in list(_vpc.subnets(new_prefix=24))[10:12]] if _vpc else [] +for t in sorted(TENANTS): + got = sorted((canon_rule(r, d["spec"].get("podSelector")) for f, d in objs_of("NetworkPolicy", t) + if egress_on(d.get("spec", {})) + for r in d.get("spec", {}).get("egress", []) or []), key=str) + res(_vpc is not None and got == want_egress(t, str(_vpc), _dbs), + f"{t}: egress is exactly DNS 53, DB 5432, HTTPS 443 outside the VPC, app 8080 in-tenant") +# The DB and VPC addresses in the policies follow Terraform's vpc_cidr default +# (locals.tf: cidrsubnet(vpc_cidr, 8, 10 + i)); a VPC override must change both. +tf = open(os.environ["TF_VARIABLES"], encoding="utf-8").read() if os.path.exists(os.environ["TF_VARIABLES"]) else "" +m = re.search(r'variable "vpc_cidr"[^}]*?default\s*=\s*"([0-9./]+)"', tf, re.S) +vpc = ipaddress.ip_network(m.group(1)) if m else None +dbs = {str(n) for n in list(vpc.subnets(new_prefix=24))[10:12]} if vpc else set() +cidrs = {p["ipBlock"]["cidr"] for f, d in objs_of("NetworkPolicy") for r in d.get("spec", {}).get("egress", []) or [] + for p in r.get("to") or [] if "ipBlock" in p and p["ipBlock"]["cidr"] != "0.0.0.0/0"} +vexc = {e for f, d in objs_of("NetworkPolicy") for r in d.get("spec", {}).get("egress", []) or [] + for p in r.get("to") or [] for e in p.get("ipBlock", {}).get("except", []) if e != "169.254.0.0/16"} +res(vpc is not None and cidrs == dbs and vexc == {str(vpc)}, + f"NetworkPolicy DB subnets {sorted(cidrs)} and VPC except {sorted(vexc)} match Terraform vpc_cidr {vpc}") sys.exit(0 if ok else 1) EOF diff --git a/gitops/platform/tenants/networkpolicy.yaml b/gitops/platform/tenants/networkpolicy.yaml index 3f8ab93..82e827c 100644 --- a/gitops/platform/tenants/networkpolicy.yaml +++ b/gitops/platform/tenants/networkpolicy.yaml @@ -1,4 +1,4 @@ -# P5 (DRF-68, SPEC-P5 P5-T3 B, D5, threats T04, T06, T07). Enforced by the +# P5 (DRF-68, SPEC-P5 P5-T3 B, D5, threats T10, T06). Enforced by the # VPC CNI node agent in standard mode (infra/terraform, vpc-cni # configuration_values); on a cluster without it these objects do nothing. # Per tenant namespace: deny all, then allow only diff --git a/gitops/tests/check_guards.sh b/gitops/tests/check_guards.sh index 32ce060..15eadc9 100644 --- a/gitops/tests/check_guards.sh +++ b/gitops/tests/check_guards.sh @@ -8,6 +8,7 @@ set -euo pipefail src="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" tmp="$(mktemp -d)" trap 'rm -rf "$tmp"' EXIT +export TF_VARIABLES="$src/../infra/terraform/variables.tf" failed=0 n=0 @@ -153,6 +154,19 @@ case_ "default-deny with an allow rule" "tenant-a: one default-deny" "$NP" 'docs case_ "ingress from another namespace" "ingress only from Pods of the same namespace" "$NP" 'docs[4]["spec"]["ingress"][0]["from"].append({"namespaceSelector": {}})' case_ "443 rule without ports" "0.0.0.0/0 on all ports" "$NP" 'del docs[3]["spec"]["egress"][0]["ports"]' case_ "443 rule reaches metadata" "into the VPC/metadata" "$NP" 'docs[8]["spec"]["egress"][0]["to"][0]["ipBlock"]["except"] = ["10.0.0.0/16"]' +# Codex review of P5 code (340558c): four mutations that used to pass. +case_ "unrestricted egress rule" "every egress rule names peers and ports" "$NP" 'docs[1]["spec"]["egress"].append({})' +case_ "egress to every namespace" "every egress rule names peers and ports" "$NP" 'docs[4]["spec"]["egress"][0]["to"].append({"namespaceSelector": {}})' +case_ "DB subnet off the VPC" "match Terraform vpc_cidr" "$NP" 'docs[2]["spec"]["egress"][0]["to"][0]["ipBlock"]["cidr"] = "10.1.10.0/24"' +case_ "HTTPS rule with an empty port" "tenant-a: egress is exactly" "$NP" 'docs[3]["spec"]["egress"][0]["ports"] = [{}]' +case_ "tenant-b loses DB egress" "tenant-b: egress is exactly" "$NP" 'del docs[7]' +case_ "app egress to the other tenant" "tenant-a: egress is exactly" "$NP" 'docs[4]["spec"]["egress"][0]["to"] = [{"podSelector": {"matchLabels": {"rag.zero-drift.io/tenant": "tenant-b"}}}]' +case_ "tenant-b DB policy selects no Pod" "tenant-b: egress is exactly" "$NP" 'docs[7]["spec"]["podSelector"] = {"matchLabels": {"rag.zero-drift.io/tenant": "nobody"}}' +case_ "HTTPS port as a string" "tenant-a: egress is exactly" "$NP" 'docs[3]["spec"]["egress"][0]["ports"][0]["port"] = "443"' +case_ "extra egress policy without policyTypes" "tenant-a: egress is exactly" "$NP" 'import copy; x = copy.deepcopy(docs[3]); x["metadata"]["name"] = "extra"; del x["spec"]["policyTypes"]; x["spec"]["egress"][0]["ports"] = [{"protocol": "TCP", "port": 22}]; docs.append(x)' +case_ "tenant label on zdr-platform" "tenant label only on tenant namespaces" platform/tenants/namespaces.yaml 'next(d for d in docs if d["metadata"]["name"] == "zdr-platform")["metadata"].setdefault("labels", {})["rag.zero-drift.io/tenant"] = "zdr-platform"' +case_ "tenant group bound in zdr-platform" "bound only in its own namespace" platform/tenants/rbac.yaml 'docs.append({"apiVersion": "rbac.authorization.k8s.io/v1", "kind": "RoleBinding", "metadata": {"name": "x", "namespace": "zdr-platform"}, "roleRef": {"apiGroup": "rbac.authorization.k8s.io", "kind": "ClusterRole", "name": "view"}, "subjects": [{"kind": "Group", "apiGroup": "rbac.authorization.k8s.io", "name": "zdr:tenant-a:developers"}]})' +case_ "Kyverno digest in an unused key" "pinned by digest at the chart's keys" "$KY" 'v = '"$KV"'; b = v["backgroundController"]; b["unused"] = {"image": b.pop("image")}' echo if (( failed )); then echo "RESULT: FAIL"; exit 1; fi diff --git a/infra/p4-window/window.sh b/infra/p4-window/window.sh index 6c12f6d..46eb1af 100644 --- a/infra/p4-window/window.sh +++ b/infra/p4-window/window.sh @@ -96,12 +96,15 @@ run_probe() { # namespace serviceaccount extra-env-json args... # P5 (SPEC-P5 A2, D6): in a tenant namespace the probe carries the tenant label # and the app's requests and memory limit, so it passes Kyverno and the # NetworkPolicy allow rules like the app itself. The same image alone is not enough. + # PROBE_RUN (optional, set by tests/isolation/run.sh) marks the Pods of one + # suite run, so its cleanup never touches a probe that another run started. jq -n --arg ns "$ns" --arg pod "$pod" --arg sa "$sa" --arg img "$IMG" --arg code "$(cat "$HERE/probe.py")" \ - --arg pns "$PLATFORM_NS" \ + --arg pns "$PLATFORM_NS" --arg run "${PROBE_RUN:-}" \ --argjson env "$env" --argjson vol "$vol" --argjson podsc "$POD_SC" --argjson ctrsc "$CTR_SC" \ --args '{apiVersion:"v1",kind:"Pod", metadata:{name:$pod,namespace:$ns,labels:({"app.kubernetes.io/name":"zdr-probe"} - + (if $ns == $pns then {} else {"rag.zero-drift.io/tenant":$ns} end))}, + + (if $ns == $pns then {} else {"rag.zero-drift.io/tenant":$ns} end) + + (if $run == "" then {} else {"rag.zero-drift.io/probe-run":$run} end))}, spec:{restartPolicy:"Never",activeDeadlineSeconds:150,serviceAccountName:$sa, automountServiceAccountToken:false,securityContext:$podsc,volumes:$vol.volumes, containers:[{name:"probe",image:$img,command:["python","-c",$code],args:$ARGS.positional, diff --git a/tests/isolation/run.sh b/tests/isolation/run.sh index 7fadfbf..603c010 100755 --- a/tests/isolation/run.sh +++ b/tests/isolation/run.sh @@ -1,17 +1,29 @@ #!/usr/bin/env bash # P5 isolation suite (DRF-70, SPEC-P5 P5-T4.1). Runs every case, writes # acceptance.json (case, threat, expected layer and result, observed result, -# UTC time, evidence line) and exits 0 only when every case that ran matched. +# UTC time, sanitized evidence) and exits 0 only when every case that ran matched. # -# MODE=kind CTX=kind-zdr-p5-kyv tests/isolation/run.sh # dry run, no AWS -# MODE=eks CTX= RUN_ID=P5-L3-... tests/isolation/run.sh +# MODE=kind CTX=kind-zdr-p5-iso tests/isolation/run.sh # dry run, no AWS +# MODE=eks CTX= NET_PHASE=control RUN_ID=... OUT=control.json tests/isolation/run.sh +# MODE=eks CTX= NET_PHASE=enforced RUN_ID=... CONTROL=control.json tests/isolation/run.sh # # kind: cases that need EKS (VPC CNI NetworkPolicy, IMDS, IRSA, RDS, S3) are -# written as SKIPPED_NEEDS_EKS, never PASS. eks: nothing may be skipped; the -# P4 negatives run unchanged through infra/p4-window/window.sh probe, which -# uses the current kubectl context, so CTX must be the current context. -# Each Pod case is a server dry run, except the network cases (real Pods, -# deleted afterwards). The context name is never written to the output. +# written as SKIPPED_NEEDS_EKS, never PASS. eks: nothing may be skipped. +# eks NET_PHASE=control runs only the network paths, with no NetworkPolicy in +# the tenant namespaces: every path must be open, so a later deny is the policy's +# doing (a failed or non-empty NetworkPolicy list stops it). NET_PHASE=enforced +# runs everything; it needs the control file of RUN_ID-control for the same +# sandbox with every case PASS, the Git NetworkPolicies present and programmed +# (PolicyEndpoints), and Kyverno in Deny. A probe result counts only when its +# Job is Complete. +# The P4 negatives run through infra/p4-window/window.sh probe, which uses the +# current kubectl context, so CTX must be the current context. +# Admission cases are server dry runs. Network and IAM cases run as Jobs: the +# VPC CNI does not enforce NetworkPolicy on a Pod without an owner. Everything +# the suite creates carries app.kubernetes.io/name=zdr-isolation; it is removed +# and the removal verified (case "cleanup") before RESULT, and again from an +# exit trap on an abnormal exit. The context name, account IDs and ARNs are +# scrubbed from every line written. set -euo pipefail # "pod ... | case_admit" must record in this shell, not in a pipeline subshell, # or its result (and a FAIL) would be lost. @@ -20,26 +32,87 @@ cd "$(dirname "$0")/../.." MODE="${MODE:?MODE=kind|eks}"; CTX="${CTX:?CTX=}" OUT="${OUT:-acceptance.json}"; RUN_ID="${RUN_ID:-dry-run}"; SANDBOX="${SANDBOX:-docs-qa}" +NET_PHASE="${NET_PHASE:-}"; CONTROL="${CONTROL:-}" K="kubectl --context $CTX" +LBL=app.kubernetes.io/name=zdr-isolation IMG="$(grep -m1 -o 'ghcr.io/eurusdevsec/zero-d-rift/rag-sandbox@sha256:[0-9a-f]\{64\}' gitops/platform/rgd/rag-sandbox.yaml)" cases='[]'; bad=0 -# window.sh probe uses the current context: refuse to mix two clusters (no name printed). -if [[ "$MODE" == eks && "$(kubectl config current-context)" != "$CTX" ]]; then - echo "FAIL CTX is not the current kubectl context"; exit 1 +if [[ "$MODE" == eks ]]; then + # window.sh probe uses the current context: refuse to mix two clusters (no name printed). + [[ "$(kubectl config current-context)" == "$CTX" ]] || { echo "FAIL CTX is not the current kubectl context"; exit 1; } + [[ "$NET_PHASE" == control || "$NET_PHASE" == enforced ]] || { echo "FAIL eks needs NET_PHASE=control|enforced"; exit 1; } + [[ "$NET_PHASE" == control || -s "$CONTROL" ]] || { echo "FAIL NET_PHASE=enforced needs CONTROL="; exit 1; } fi -# record ID THREAT LAYER EXPECTED OBSERVED EVIDENCE +# Remove the context name, AWS account IDs, ARNs and EKS endpoints from a line. +scrub() { + local s="${1//"$CTX"/}" + # The account-ID rule loops (one match per pass) so IDs that share a + # separator (two 12-digit IDs joined by a comma) are all replaced. + sed -E -e 's/arn:aws[a-z-]*:[^ "]*//g' -e ':a' -e 's/(^|[^0-9])[0-9]{12}([^0-9]|$)/\1\2/' -e 'ta' \ + -e 's/[A-Za-z0-9.-]+\.eks\.amazonaws\.com//g' <<< "$s" | tr '\n' ' ' | sed 's/ $//' +} + +# record ID THREAT LAYER EXPECTED OBSERVED EVIDENCE. Observed and evidence are +# scrubbed before they are printed or written. record() { - local res + local res ev ob; ev="$(scrub "$6")"; ob="$(scrub "$5")" if [[ "$5" == SKIPPED_* ]]; then res="$5" elif [[ "$4" == "$5" ]]; then res=PASS else res=FAIL; bad=1; fi - printf '%-18s %-6s %-12s expected=%-22s observed=%-22s %s\n' "$res" "$2" "$1" "$4" "$5" "${6:0:110}" - cases="$(jq -c --arg id "$1" --arg t "$2" --arg l "$3" --arg e "$4" --arg o "$5" --arg r "$res" \ - --arg ev "${6:0:300}" --arg at "$(date -u +%FT%TZ)" \ + printf '%-18s %-6s %-26s expected=%-30s observed=%-30s %s\n' "$res" "$2" "$1" "$4" "$ob" "${ev:0:110}" + cases="$(jq -c --arg id "$1" --arg t "$2" --arg l "$3" --arg e "$4" --arg o "$ob" --arg r "$res" \ + --arg ev "${ev:0:300}" --arg at "$(date -u +%FT%TZ)" \ '. + [{id:$id, threat:$t, layer:$l, expected:$e, observed:$o, result:$r, utc:$at, evidence:$ev}]' <<< "$cases")" } +# count_list NS RESOURCES: number of suite objects, or "error" when the list +# itself fails (a Forbidden or unreachable API is not "none left"). +count_list() { # NS RESOURCES [SELECTOR] + local out; out="$($K -n "$1" get "$2" -l "${3:-$LBL}" -o name 2>/dev/null)" || { echo error; return; } + grep -c . <<< "$out" || true +} +# window.sh probe Pods (the P4 wrapper) carry their own label and are deleted +# with --wait=false: wait for them to be gone and count them too. Only this +# run's probes: window.sh adds rag.zero-drift.io/probe-run=$PROBE_RUN, so a +# probe that another run or a person started is never deleted here. +export PROBE_RUN="iso-$(date -u +%Y%m%d%H%M%S)-$$-$RANDOM" +PROBE_LBL="app.kubernetes.io/name=zdr-probe,rag.zero-drift.io/probe-run=$PROBE_RUN" +# Delete what the suite created, then prove it is gone. Sets CLEANUP_STATE to +# verified-empty, left: or unverified; returns 0 only for verified-empty. +CLEANUP_STATE=unverified; CLEANED="" +cleanup() { + local argo n c left=0 unread=0 + for ns in tenant-a tenant-b; do + $K -n "$ns" delete jobs,pods,serviceaccounts -l "$LBL" --wait=true --timeout=120s >/dev/null 2>&1 || true + done + argo="$($K get ns argocd --ignore-not-found -o name 2>/dev/null)" || argo=error + [[ "$argo" == namespace/argocd ]] && { $K -n argocd delete applications.argoproj.io -l "$LBL" --wait=true --timeout=60s >/dev/null 2>&1 || true; } + for n in tenant-a:jobs,pods,serviceaccounts tenant-b:jobs,pods,serviceaccounts ${argo:+argocd:applications.argoproj.io}; do + [[ "$n" == argocd:* && "$argo" != namespace/argocd ]] && { [[ "$argo" == error ]] && unread=1; continue; } + c="$(count_list "${n%%:*}" "${n#*:}")" + if [[ "$c" == error ]]; then unread=1; else left=$((left + c)); fi + done + for ns in tenant-a tenant-b zdr-platform; do + $K -n "$ns" delete pod -l "$PROBE_LBL" --wait=false >/dev/null 2>&1 || true + $K -n "$ns" wait --for=delete pod -l "$PROBE_LBL" --timeout=120s >/dev/null 2>&1 || true + c="$(count_list "$ns" pods "$PROBE_LBL")" + if [[ "$c" == error ]]; then unread=1; else left=$((left + c)); fi + done + if (( unread )); then CLEANUP_STATE=unverified + elif (( left )); then CLEANUP_STATE="left:$left" + else CLEANUP_STATE=verified-empty; fi + [[ "$CLEANUP_STATE" == verified-empty ]] +} +# Abnormal exit (set -e, a refusal): still clean up, and never exit 0 unverified. +on_exit() { + local rc=$? + [[ -n "$CLEANED" ]] && exit "$rc" + cleanup || { echo "FAIL cleanup: $CLEANUP_STATE (label $LBL)"; rc=1; } + exit "$rc" +} +trap on_exit EXIT + # A restricted-compliant Pod that passes every guardrail; patches change one thing. pod() { # NAME NS [CONTAINER_PATCH] [SPEC_PATCH] [LABEL_PATCH] local c="${3:-}" s="${4:-}" l="${5:-}" @@ -53,160 +126,329 @@ pod() { # NAME NS [CONTAINER_PATCH] [SPEC_PATCH] [LABEL_PATCH] resources:{requests:{cpu:"50m",memory:"96Mi"},limits:{memory:"192Mi"}}} * $c)]} * $s)}' } -# Which layer answered an admission attempt: allow, or deny:. +# job NS NAME PYTHON_CODE [SPEC_PATCH] [ARGS...] -> prints the last "RESULT ..." +# line, read only when the Job has condition Complete=True. A Job that failed, +# hit its deadline or was never created prints "RESULT ERROR job-", even +# if its Pod logged a RESULT line first. The Job owns its Pod. +job() { + local ns=$1 n=$2 code=$3 spec="${4:-}" state=timeout i cond line + shift 4 || shift $# + if ! pod "$n" "$ns" "$(jq -nc --arg c "$code" '{command:(["python","-c",$c] + $ARGS.positional)}' --args "$@")" "$spec" \ + | jq '{apiVersion:"batch/v1",kind:"Job",metadata:{name:.metadata.name,namespace:.metadata.namespace,labels:.metadata.labels}, + spec:{backoffLimit:0,activeDeadlineSeconds:150,template:{metadata:{labels:.metadata.labels},spec:.spec}}}' \ + | $K apply -f - >/dev/null 2>&1; then + echo "RESULT ERROR job-apply"; return + fi + for i in $(seq 1 85); do + cond=" $($K -n "$ns" get job "$n" -o jsonpath='{range .status.conditions[?(@.status=="True")]}{.type}{" "}{end}' 2>/dev/null || true) " + [[ "$cond" == *" Complete "* ]] && { state=complete; break; } + [[ "$cond" == *" Failed "* ]] && { state=failed; break; } + sleep 2 + done + # The log read itself must succeed: a partial read that failed is no result. + line=""; local logs + if [[ "$state" == complete ]]; then + if logs="$($K -n "$ns" logs "job/$n" 2>/dev/null)"; then + line="$(grep '^RESULT ' <<< "$logs" | tail -1 || true)" + else state=log-error; fi + fi + $K -n "$ns" delete job "$n" --cascade=foreground --wait=true --timeout=60s >/dev/null 2>&1 || true + if [[ "$state" != complete ]]; then echo "RESULT ERROR job-$state" + elif [[ -n "$line" ]]; then echo "$line" + else echo "RESULT ERROR no-output"; fi +} + +# Which layer answered an admission attempt. A webhook that could not be called +# is an error, not a policy decision. admit() { # manifest on stdin -> prints "OBSERVED|evidence" - local out + local out p if out="$($K create --dry-run=server -f - 2>&1)"; then echo "allow|$out"; return; fi case "$out" in - *PodSecurity*) echo "deny:pod-security|$out" ;; - *vpol.validate.kyverno*) echo "deny:kyverno|$out" ;; - *"maximum memory usage"*) echo "deny:limitrange|$out" ;; + *"failed calling webhook"*) echo "error:webhook|$out" ;; + *"violates PodSecurity"*) echo "deny:pod-security|$out" ;; + *'vpol.validate.kyverno.svc-fail" denied the request'*) + p="$(grep -o 'Policy zdr-[a-z-]* failed' <<< "$out" | head -1 | cut -d' ' -f2)" + echo "deny:kyverno:${p:-unknown}|$out" ;; + *"maximum memory usage per Container"*) echo "deny:limitrange|$out" ;; *"exceeded quota"*) echo "deny:quota|$out" ;; - *) echo "deny:other|$out" ;; + *) echo "error:other|$out" ;; esac } case_admit() { # ID THREAT EXPECTED (manifest on stdin) - local r; r="$(admit)"; record "$1" "$2" admission "$3" "${r%%|*}" "$(tr '\n' ' ' <<< "${r#*|}")" + local r; r="$(admit)"; record "$1" "$2" admission "$3" "${r%%|*}" "${r#*|}" +} +# A SubjectAccessReview, not "can-i": can-i prints "no" also when the +# authorizer reports an evaluation error. Here allowed=true is allow, +# allowed=false without evaluationError is deny:rbac, anything else (an error, +# no answer) is error:rbac. Groups mirror what impersonation (--as) would send. +case_rbac() { # ID THREAT EXPECTED VERB RESOURCE[.GROUP] NS-or-- USER [GROUP] + local res="${5%%.*}" grp="" ans + [[ "$5" == *.* ]] && grp="${5#*.}" + ans="$(jq -n --arg v "$4" --arg r "$res" --arg g "$grp" --arg ns "$6" --arg u "$7" --arg gr "${8:-}" ' + ($u | startswith("system:serviceaccount:")) as $sa | + {apiVersion:"authorization.k8s.io/v1", kind:"SubjectAccessReview", + spec:{user:$u, + groups:((if $gr != "" then [$gr] else [] end) + + (if $sa then ["system:serviceaccounts", "system:serviceaccounts:" + ($u | split(":")[2])] else [] end) + + ["system:authenticated"]), + resourceAttributes:({verb:$v, resource:$r, group:$g} + (if $ns != "-" then {namespace:$ns} else {} end))}}' \ + | $K create -f - -o json 2>/dev/null \ + | jq -r '.status | (if (.evaluationError // "") != "" then "error:rbac" elif .allowed == true then "allow" + elif .allowed == false then "deny:rbac" else "error:rbac" end) + "|" + (.reason // "")' 2>/dev/null || true)" + [[ -n "$ans" ]] || ans="error:rbac|no SubjectAccessReview answer" + record "$1" "$2" rbac "$3" "${ans%%|*}" "SubjectAccessReview $4 $5 ${6} as $7: ${ans#*|}" +} + +# finish PHASE: clean up and record the verified result as a case, then write +# the JSON, then print RESULT. PASS is printed only after cleanup is verified. +finish() { + cleanup || true; CLEANED=1 + record cleanup T15 harness verified-empty "$CLEANUP_STATE" "suite objects (label $LBL) after the run" + jq -n --arg run "$RUN_ID" --arg mode "$MODE" --arg ph "$1" --arg sb "$SANDBOX" --arg img "$IMG" --argjson c "$cases" \ + '{run_id:$run, mode:$mode, net_phase:$ph, sandbox:$sb, image:$img, cases:$c, + summary:{total:($c|length), pass:([$c[]|select(.result=="PASS")]|length), + fail:([$c[]|select(.result=="FAIL")]|length), + skipped:([$c[]|select(.result|startswith("SKIPPED"))]|length)}}' > "$OUT" + echo + jq -r '.summary | "total \(.total), pass \(.pass), fail \(.fail), skipped \(.skipped)"' "$OUT" + if (( bad )); then echo "RESULT: FAIL ($1, $OUT)"; exit 1; fi + if [[ "$MODE" == eks && "$(jq '.summary.skipped' "$OUT")" != 0 ]]; then echo "RESULT: FAIL (skipped cases in eks mode)"; exit 1; fi + echo "RESULT: PASS ($1, $OUT)"; exit 0 } -case_rbac() { # ID THREAT EXPECTED VERB RESOURCE NS-or-- AS GROUP - local ns=() ans; [[ "$6" != - ]] && ns=(-n "$6") - ans="$($K auth can-i "$4" "$5" "${ns[@]}" --as="$7" ${8:+--as-group="$8"} 2>/dev/null || true)" - record "$1" "$2" rbac "$3" "$([[ "$ans" == yes* ]] && echo allow || echo deny:rbac)" "can-i $4 $5 ${6} as $7: ${ans:-no}" + +echo "isolation suite mode=$MODE phase=${NET_PHASE:-n/a} run=$RUN_ID $(date -u +%FT%TZ)" + +# --- T10, T06: network paths (D5), needs VPC CNI NetworkPolicy ------------------ +# connect: a Job in TENANT opens TCP to HOST:PORT. Only a timeout counts as a +# NetworkPolicy deny (the node agent drops); refused, DNS and other errors fail. +NETCODE='import socket, sys, time +host, port = sys.argv[1], int(sys.argv[2]) +time.sleep(20) # standard mode: a new Pod is default-allow until its policies are programmed +try: + addr = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)[0][4] +except Exception as e: + print("RESULT ERROR dns", type(e).__name__); sys.exit(0) +s = socket.socket(); s.settimeout(5) +try: + s.connect(addr); print("RESULT OPEN") +except socket.timeout: + print("RESULT TIMEOUT") +except ConnectionRefusedError: + print("RESULT ERROR refused") +except Exception as e: + print("RESULT ERROR", type(e).__name__)' +net_case() { # ID THREAT EXPECTED TENANT HOST PORT + local r obs; r="$(job "$4" "zdr-iso-net-$RANDOM" "$NETCODE" '' "$5" "$6")" + case "$r" in + "RESULT OPEN") obs=allow ;; "RESULT TIMEOUT") obs=deny:network ;; + *) obs="error:$(cut -d' ' -f3 <<< "$r")" ;; + esac + record "$1" "$2" networkpolicy "$3" "$obs" "$4 -> $5:$6: ${r#RESULT }" } +# NetworkPolicies of TENANT in Git, by name. +git_np() { python -I -c 'import sys,yaml; print("\n".join(d["metadata"]["name"] for d in yaml.safe_load_all(open(sys.argv[1])) if d and d["metadata"]["namespace"] == sys.argv[2]))' gitops/platform/tenants/networkpolicy.yaml "$1" | LC_ALL=C sort -u; } +NETS=("T10-own-app T10 tenant-a rag-$SANDBOX.tenant-a.svc 8080" + "T10-a-to-b T10 tenant-a rag-$SANDBOX.tenant-b.svc 8080" + "T10-b-to-a T10 tenant-b rag-$SANDBOX.tenant-a.svc 8080" + "T06-metadata T06 tenant-a 169.254.169.254 80") +if [[ "$MODE" != eks ]]; then + for c in T10-own-app T10-a-to-b T10-b-to-a T06-metadata; do + record "$c" "${c%%-*}" networkpolicy see-eks SKIPPED_NEEDS_EKS "kind has no VPC CNI NetworkPolicy" + done +elif [[ "$NET_PHASE" == control ]]; then + # The list must succeed and be empty: a Forbidden list is not "no policy". + for t in tenant-a tenant-b; do + if nps="$($K -n "$t" get networkpolicies -o name 2>/dev/null)"; then + c="$(grep -c . <<< "$nps" || true)"; o="$([[ "$c" == 0 ]] && echo none || echo "present:$c")" + else o=error:list; fi + record "net-control-$t" T10 networkpolicy none "$o" "$t NetworkPolicies before the control run" + done + # A path probed with policies present (or unknown) proves nothing: stop here. + (( bad )) || for c in "${NETS[@]}"; do set -- $c; net_case "$1" "$2" allow "$3" "$4" "$5"; done +else + # The receipt: a control run of this window (RUN_ID-control) and this + # sandbox, with every case PASS. Only fixed codes reach the output. + o="$(jq -r --arg run "$RUN_ID-control" --arg sb "$SANDBOX" ' + if .mode != "eks" or .net_phase != "control" then "not-a-control-run" + elif .run_id != $run then "other-run" + elif .sandbox != $sb then "other-sandbox" + elif (.summary.fail != 0) or (.summary.pass != .summary.total) or ([.cases[] | select(.result != "PASS")] | length) != 0 then "control-not-passing" + else "ok" end' "$CONTROL" 2>/dev/null || echo unreadable)" + case "$o" in ok|not-a-control-run|other-run|other-sandbox|control-not-passing) ;; *) o=unreadable ;; esac + record net-control-receipt T10 networkpolicy ok "$o" "control run $RUN_ID-control, sandbox $SANDBOX" + # The control run opened the same paths before the policies existed. + for c in "${NETS[@]}"; do set -- $c + o="$(jq -r --arg id "$1" '[.cases[] | select(.id == $id)][0] | if . == null then "missing" + elif .result == "PASS" and .observed == "allow" then "allow" else "not-allow" end' "$CONTROL" 2>/dev/null || echo unreadable)" + case "$o" in allow|not-allow|missing) ;; *) o=unreadable ;; esac + record "$1-control" "$2" networkpolicy allow "$o" "same path in the control run" + done + # Every Git NetworkPolicy exists and the node agent has programmed it. + for t in tenant-a tenant-b; do + want="$(git_np "$t")"; got="" + for i in $(seq 1 24); do + got="$($K -n "$t" get policyendpoints.networking.k8s.aws -o jsonpath='{range .items[*]}{.spec.policyRef.name}{"\n"}{end}' 2>/dev/null | LC_ALL=C sort -u || true)" + [[ "$got" == "$want" ]] && break; sleep 5 + done + record "net-programmed-$t" T10 networkpolicy programmed "$([[ "$got" == "$want" ]] && echo programmed || echo missing)" \ + "$t PolicyEndpoints for: $(tr '\n' ' ' <<< "$want")" + done + net_case T10-own-app T10 allow tenant-a "rag-$SANDBOX.tenant-a.svc" 8080 + net_case T10-a-to-b T10 deny:network tenant-a "rag-$SANDBOX.tenant-b.svc" 8080 + net_case T10-b-to-a T10 deny:network tenant-b "rag-$SANDBOX.tenant-a.svc" 8080 + net_case T06-metadata T06 deny:network tenant-a 169.254.169.254 80 +fi -echo "isolation suite mode=$MODE run=$RUN_ID $(date -u +%FT%TZ)" +if [[ "$NET_PHASE" == control ]]; then finish control; fi -# --- T04: Kubernetes RBAC (D1, D2) -------------------------------------------- +# --- T04: Kubernetes RBAC (D1, D2) ---------------------------------------------- DEV=dev-a; GRP=zdr:tenant-a:developers; SA=system:serviceaccount:tenant-a:default -case_rbac T04-own-pods T04 allow get pods tenant-a "$DEV" "$GRP" -case_rbac T04-b-pods T04 deny:rbac list pods tenant-b "$DEV" "$GRP" -case_rbac T04-b-sandboxes T04 deny:rbac get ragsandboxes.kro.run tenant-b "$DEV" "$GRP" -case_rbac T04-own-services T04 allow get services tenant-a "$DEV" "$GRP" -case_rbac T04-b-services T04 deny:rbac get services tenant-b "$DEV" "$GRP" -case_rbac T04-own-secrets T04 deny:rbac get secrets tenant-a "$DEV" "$GRP" -case_rbac T04-b-secrets T04 deny:rbac get secrets tenant-b "$DEV" "$GRP" -case_rbac T04-cluster T04 deny:rbac list namespaces - "$DEV" "$GRP" -case_rbac T04-create T04 deny:rbac create pods tenant-a "$DEV" "$GRP" -case_rbac T04-sa-b-pods T04 deny:rbac list pods tenant-b "$SA" -case_rbac T04-sa-secrets T04 deny:rbac get secrets tenant-a "$SA" - -# --- T05: Pod Security restricted -------------------------------------------- +WSA=system:serviceaccount:tenant-a:rag-$SANDBOX # the sandbox workload identity +case_rbac T04-own-pods T04 allow get pods tenant-a "$DEV" "$GRP" +case_rbac T04-b-pods T04 deny:rbac list pods tenant-b "$DEV" "$GRP" +case_rbac T04-b-sandboxes T04 deny:rbac get ragsandboxes.kro.run tenant-b "$DEV" "$GRP" +case_rbac T04-b-sas T04 deny:rbac list serviceaccounts tenant-b "$DEV" "$GRP" +case_rbac T04-own-services T04 allow get services tenant-a "$DEV" "$GRP" +case_rbac T04-b-services T04 deny:rbac get services tenant-b "$DEV" "$GRP" +case_rbac T04-own-secrets T04 deny:rbac get secrets tenant-a "$DEV" "$GRP" +case_rbac T04-b-secrets T04 deny:rbac get secrets tenant-b "$DEV" "$GRP" +case_rbac T04-cluster T04 deny:rbac list namespaces - "$DEV" "$GRP" +case_rbac T04-create T04 deny:rbac create pods tenant-a "$DEV" "$GRP" +case_rbac T04-sa-b-pods T04 deny:rbac list pods tenant-b "$SA" +case_rbac T04-sa-secrets T04 deny:rbac get secrets tenant-a "$SA" +case_rbac T04-wsa-b-pods T04 deny:rbac list pods tenant-b "$WSA" +case_rbac T04-wsa-secrets T04 deny:rbac get secrets tenant-a "$WSA" +case_rbac T04-wsa-b-secrets T04 deny:rbac get secrets tenant-b "$WSA" +case_rbac T04-wsa-b-sandbox T04 deny:rbac get ragsandboxes.kro.run tenant-b "$WSA" +case_rbac T04-wsa-cluster T04 deny:rbac list namespaces - "$WSA" + +# --- T05: Pod Security restricted ----------------------------------------------- pod ok tenant-a | case_admit T05-compliant T05 allow pod priv tenant-a '{"securityContext":{"privileged":true,"allowPrivilegeEscalation":true}}' | case_admit T05-privileged T05 deny:pod-security pod hostnet tenant-a '{}' '{"hostNetwork":true}' | case_admit T05-hostnetwork T05 deny:pod-security pod hostpath tenant-a '{"volumeMounts":[{"name":"h","mountPath":"/h"}]}' '{"volumes":[{"name":"h","hostPath":{"path":"/"}}]}' | case_admit T05-hostpath T05 deny:pod-security pod root tenant-a '{}' '{"securityContext":{"runAsNonRoot":false,"runAsUser":0}}' | case_admit T05-root T05 deny:pod-security -# --- T14, T10 label, T15 health: Kyverno (D6, D8) ---------------------------- -pod tag tenant-b '{"image":"ghcr.io/eurusdevsec/zero-d-rift/rag-sandbox:latest"}' | case_admit T14-tag T14 deny:kyverno -pod reg tenant-b "{\"image\":\"docker.io/library/python@sha256:$(printf 'a%.0s' {1..64})\"}" | case_admit T14-registry T14 deny:kyverno -pod spoof tenant-a '{}' '{}' '{"rag.zero-drift.io/tenant":"tenant-b"}' | case_admit T10-label-spoof T10 deny:kyverno +# --- T14, T10 label, T15 health: Kyverno (D6, D8) ------------------------------- +pod tag tenant-b '{"image":"ghcr.io/eurusdevsec/zero-d-rift/rag-sandbox:latest"}' | case_admit T14-tag T14 deny:kyverno:zdr-image-digest +pod reg tenant-b "{\"image\":\"docker.io/library/python@sha256:$(printf 'a%.0s' {1..64})\"}" | case_admit T14-registry T14 deny:kyverno:zdr-image-digest +pod spoof tenant-a '{}' '{}' '{"rag.zero-drift.io/tenant":"tenant-b"}' | case_admit T10-label-spoof T10 deny:kyverno:zdr-tenant-label pod plat zdr-platform '{"image":"busybox:1.37"}' '{}' '{"rag.zero-drift.io/tenant":"x"}' | case_admit T15-platform-out-of-scope T15 allow health="$($K get validatingpolicies.policies.kyverno.io -o json 2>/dev/null \ | jq -r '[.items[] | select(.metadata.name | startswith("zdr-"))] | if length == 3 and all(.spec.validationActions == ["Deny"] and .spec.failurePolicy == "Fail" and (.status.conditionStatus.ready == true)) then "ready-deny" else "not-ready-or-audit" end' || echo missing)" record T15-policies-enforced T15 kyverno ready-deny "$health" "3 zdr- ValidatingPolicies: Deny, Fail, Ready" -# --- T11: quota and LimitRange (D3) ------------------------------------------ +# --- T11: quota and LimitRange (D3) --------------------------------------------- pod gpu tenant-a '{"resources":{"limits":{"memory":"192Mi","nvidia.com/gpu":"1"}}}' | case_admit T11-gpu T11 deny:quota pod big tenant-a '{"resources":{"limits":{"memory":"1Gi"}}}' | case_admit T11-big T11 deny:limitrange pod noreq tenant-a | jq 'del(.spec.containers[0].resources)' | case_admit T11-defaults T11 allow -# --- T03: request path (D4), needs Argo CD ----------------------------------- -if $K get ns argocd >/dev/null 2>&1; then - app="zdr-iso-badns-$RANDOM" - jq -n --arg n "$app" '{apiVersion:"argoproj.io/v1alpha1",kind:"Application",metadata:{name:$n,namespace:"argocd"}, - spec:{project:"zdr-requests",source:{repoURL:"https://github.com/EurusDevSec/Zero-D-Rift.git",targetRevision:"main",path:"gitops/requests"}, - destination:{server:"https://kubernetes.default.svc",namespace:"zdr-platform"}}}' | $K apply -f - >/dev/null - sleep 20 - msg="$($K -n argocd get app "$app" -o jsonpath='{range .status.conditions[*]}{.type}: {.message}{end}' 2>&1)" - $K -n argocd delete app "$app" --wait=false >/dev/null 2>&1 || true - record T03-foreign-namespace T03 argocd deny:argocd "$([[ "$msg" == *InvalidSpecError* ]] && echo deny:argocd || echo allow)" "$msg" -else - record T03-foreign-namespace T03 argocd deny:argocd SKIPPED_NEEDS_EKS "no argocd namespace in this cluster" -fi - -# --- T10, T06: network (D5), needs VPC CNI NetworkPolicy --------------------- -# connect TENANT HOST PORT -> OPEN or CLOSED, from a real Pod of TENANT. -connect() { - local n="zdr-iso-net-$RANDOM" code - # Standard mode leaves a new Pod default-allow until its policies are - # programmed (SPEC-P5 §10): wait first, so a deny is not tested in the gap. - code="import socket,sys,time -time.sleep(20) -s=socket.socket(); s.settimeout(5) -try: s.connect((sys.argv[1], int(sys.argv[2]))); print('OPEN') -except Exception as e: print('CLOSED', type(e).__name__)" - pod "$n" "$1" "$(jq -nc --arg c "$code" --arg h "$2" --arg p "$3" '{command:["python","-c",$c,$h,$p]}')" \ - | $K apply -f - >/dev/null - $K -n "$1" wait --for=jsonpath='{.status.phase}'=Succeeded pod "$n" --timeout=90s >/dev/null 2>&1 || true - $K -n "$1" logs "$n" 2>/dev/null | tail -1 - $K -n "$1" delete pod "$n" --wait=false >/dev/null 2>&1 || true +# --- T03: request path (D4), needs Argo CD -------------------------------------- +# app NAME PATH NAMESPACE: an Application in project zdr-requests, auto-synced. +app() { + jq -n --arg n "$1" --arg p "$2" --arg ns "$3" '{apiVersion:"argoproj.io/v1alpha1",kind:"Application", + metadata:{name:$n,namespace:"argocd",labels:{"app.kubernetes.io/name":"zdr-isolation"}}, + spec:{project:"zdr-requests",source:{repoURL:"https://github.com/EurusDevSec/Zero-D-Rift.git",targetRevision:"main",path:$p}, + destination:{server:"https://kubernetes.default.svc",namespace:$ns},syncPolicy:{automated:{}}}}' | $K apply -f - >/dev/null } -net_case() { # ID THREAT EXPECTED TENANT HOST PORT - local r; r="$(connect "$4" "$5" "$6")" - record "$1" "$2" networkpolicy "$3" "$([[ "$r" == OPEN* ]] && echo allow || echo deny:network)" "$4 -> $5:$6: ${r:-no output}" +# wait_msg APP TEXT: poll conditions and the operation message for TEXT (90 s). +wait_msg() { + local m="" i + for i in $(seq 1 18); do + m="$($K -n argocd get app "$1" -o jsonpath='{range .status.conditions[*]}{.type}: {.message} {end}{.status.operationState.message}' 2>&1 || true)" + [[ "$m" == *"$2"* ]] && break; sleep 5 + done + echo "$m" } -if [[ "$MODE" == eks ]]; then - net_case T10-own-app T10 allow tenant-a "rag-$SANDBOX.tenant-a.svc" 8080 - net_case T10-a-to-b T10 deny:network tenant-a "rag-$SANDBOX.tenant-b.svc" 8080 - net_case T10-b-to-a T10 deny:network tenant-b "rag-$SANDBOX.tenant-a.svc" 8080 - net_case T06-metadata T06 deny:network tenant-a 169.254.169.254 80 +argo="$($K get ns argocd --ignore-not-found -o name 2>/dev/null)" || argo=error +if [[ "$argo" == namespace/argocd ]]; then + a="zdr-iso-badns-$RANDOM"; app "$a" gitops/requests zdr-platform + want="do not match any of the allowed destinations in project 'zdr-requests'" + m="$(wait_msg "$a" "$want")" + record T03-foreign-namespace T03 argocd deny:argocd "$([[ "$m" == *"$want"* ]] && echo deny:argocd || echo other)" "$m" + a="zdr-iso-badkind-$RANDOM"; app "$a" gitops/lab tenant-a + want="resource apps:Deployment is not permitted in project zdr-requests" + m="$(wait_msg "$a" "$want")" + # The list must succeed: a failed list is not "no Deployment created". + if dl="$($K get deploy -A -o name 2>/dev/null)"; then made="$(grep -c zdr-lab-pause <<< "$dl" || true)"; else made=list-error; fi + record T03-foreign-kind T03 argocd deny:argocd "$([[ "$m" == *"$want"* && "$made" == 0 ]] && echo deny:argocd || echo "other:deployments=$made")" "$m" +elif [[ "$argo" == error ]]; then + record T03-foreign-namespace T03 argocd deny:argocd error:list "could not read namespace argocd" + record T03-foreign-kind T03 argocd deny:argocd error:list "could not read namespace argocd" else - for c in T10-own-app T10-a-to-b T10-b-to-a T06-metadata; do - record "$c" "${c%%-*}" networkpolicy see-eks SKIPPED_NEEDS_EKS "kind has no VPC CNI NetworkPolicy" - done + record T03-foreign-namespace T03 argocd deny:argocd SKIPPED_NEEDS_EKS "no argocd namespace in this cluster" + record T03-foreign-kind T03 argocd deny:argocd SKIPPED_NEEDS_EKS "no argocd namespace in this cluster" fi -# --- T07: a ServiceAccount outside the trust pattern rag-* (A10) --------------- -# It carries the tenant role annotation (copied, never printed); STS must refuse. +# --- T07: a ServiceAccount outside the trust pattern rag-* (A10) ----------------- +# It carries the tenant role annotation (copied, never printed). STS must answer +# AssumeRoleWithWebIdentity with AccessDenied; an empty annotation, a missing +# IRSA environment or an unreachable STS is an error, not a denial. +T07CODE='import os, sys, boto3, botocore +arn, tf = os.environ.get("AWS_ROLE_ARN"), os.environ.get("AWS_WEB_IDENTITY_TOKEN_FILE") +if not arn or not tf: + print("RESULT ERROR no-irsa-env"); sys.exit(0) +region = os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION") or "us-east-1" +try: + boto3.client("sts", region_name=region).assume_role_with_web_identity( + RoleArn=arn, RoleSessionName="zdr-iso-t07", WebIdentityToken=open(tf).read()) + print("RESULT ASSUMED") +except botocore.exceptions.ClientError as e: + c = e.response.get("Error", {}).get("Code", "unknown") + print("RESULT", "DENIED" if c == "AccessDenied" else "ERROR", c) +except Exception as e: + print("RESULT ERROR", type(e).__name__)' if [[ "$MODE" == eks ]]; then - role="$($K -n tenant-a get sa "rag-$SANDBOX" -o jsonpath='{.metadata.annotations.eks\.amazonaws\.com/role-arn}')" - $K -n tenant-a create serviceaccount zdr-iso-other --dry-run=client -o json \ - | jq --arg r "$role" '.metadata.annotations["eks.amazonaws.com/role-arn"] = $r | .automountServiceAccountToken = false' \ - | $K apply -f - >/dev/null - unset role - n="zdr-iso-t07-$RANDOM" - code="import boto3 -try: boto3.client('sts', region_name='us-east-1').get_caller_identity(); print('ASSUMED') -except Exception as e: print('DENIED', getattr(e, 'response', {}).get('Error', {}).get('Code', type(e).__name__))" - pod "$n" tenant-a "$(jq -nc --arg c "$code" '{command:["python","-c",$c]}')" '{"serviceAccountName":"zdr-iso-other"}' \ - | $K apply -f - >/dev/null - $K -n tenant-a wait --for=jsonpath='{.status.phase}'=Succeeded pod "$n" --timeout=120s >/dev/null 2>&1 || true - r="$($K -n tenant-a logs "$n" 2>/dev/null | tail -1)" - $K -n tenant-a delete pod "$n" --wait=true >/dev/null 2>&1 || true - $K -n tenant-a delete serviceaccount zdr-iso-other >/dev/null 2>&1 || true - record T07-other-sa T07 iam deny:iam "$([[ "$r" == DENIED* ]] && echo deny:iam || echo allow)" "zdr-iso-other assumes tenant-a role: ${r:-no output}" + role="$($K -n tenant-a get sa "rag-$SANDBOX" -o jsonpath='{.metadata.annotations.eks\.amazonaws\.com/role-arn}' 2>/dev/null || true)" + if [[ -z "$role" ]]; then + record T07-other-sa T07 iam deny:iam error:no-annotation "rag-$SANDBOX in tenant-a has no role annotation to copy" + else + # An apply error can echo the object (and the ARN): keep it off the output. + if $K -n tenant-a create serviceaccount zdr-iso-other --dry-run=client -o json 2>/dev/null \ + | jq --arg r "$role" '.metadata.annotations["eks.amazonaws.com/role-arn"] = $r + | .metadata.labels["app.kubernetes.io/name"] = "zdr-isolation" | .automountServiceAccountToken = false' \ + | $K apply -f - >/dev/null 2>&1; then + r="$(job tenant-a "zdr-iso-t07-$RANDOM" "$T07CODE" '{"serviceAccountName":"zdr-iso-other"}')" + else r="RESULT ERROR sa-apply"; fi + unset role + case "$r" in "RESULT DENIED AccessDenied") obs=deny:iam ;; "RESULT ASSUMED") obs=allow ;; *) obs="error:$(cut -d' ' -f3 <<< "$r")" ;; esac + record T07-other-sa T07 iam deny:iam "$obs" "zdr-iso-other AssumeRoleWithWebIdentity on the tenant-a role: ${r#RESULT }" + fi else record T07-other-sa T07 iam deny:iam SKIPPED_NEEDS_EKS "needs IRSA" fi -# --- T08, T13, T06: P4 probes unchanged (window.sh probe), positives included -- +# --- T08, T13, T06: P4 probes (window.sh probe), positives included ------------- +# Each probe must exit 0 and print exactly its expected case set; a missing +# case, a SKIP or an early stop is a FAIL. +p4() { # LABEL "case name"... -- window.sh probe args... + local label=$1 want=() seen=() out rc=0 line st what t c; shift + while [[ "$1" != -- ]]; do want+=("$1"); shift; done; shift + out="$(bash infra/p4-window/window.sh probe "$@" 2>&1)" || rc=$? + while IFS= read -r line; do + line="${line%$'\r'}" + [[ "$line" =~ ^(PASS|FAIL|SKIP)\ \ ([^:]*):(.*)$ ]] || continue + st="${BASH_REMATCH[1]}"; what="${BASH_REMATCH[2]}"; seen+=("$what") + case "$what" in *IMDS*) t=T06 ;; *schema*|*ROLE*|*rag_bootstrap*|*pgvector*|*TLS*) t=T13 ;; *) t=T08 ;; esac + record "P4 $label: $what" "$t" iam-or-db pass "${st,,}" "$what:${BASH_REMATCH[3]}" + done <<< "$out" + for c in "${want[@]}"; do + printf '%s\n' "${seen[@]}" | grep -qxF "$c" || record "P4 $label: $c" T08 iam-or-db pass missing "case not printed by window.sh probe $*" + done + record "P4 $label: exit" T08 iam-or-db exit-0 "exit-$rc" "window.sh probe $* exit status" +} if [[ "$MODE" == eks ]]; then - for args in "sandbox tenant-a $SANDBOX" "sandbox tenant-b $SANDBOX" \ - "cross tenant-a $SANDBOX tenant-b" "cross tenant-b $SANDBOX tenant-a"; do - set -- $args; got=0 - while IFS= read -r line; do - line="${line%$'\r'}" - [[ "$line" =~ ^(PASS|FAIL|SKIP)\ \ (.*)$ ]] || continue - st="${BASH_REMATCH[1]}"; what="${BASH_REMATCH[2]}"; got=$((got + 1)) - case "$what" in *IMDS*) t=T06 ;; *schema*|*ROLE*) t=T13 ;; *) t=T08 ;; esac - record "P4: ${what%%:*}" "$t" iam-or-db pass "$( [[ $st == PASS ]] && echo pass || echo "${st,,}")" "$what" - done < <(bash infra/p4-window/window.sh probe "$@" 2>&1 || true) - # A probe that printed no case at all is a failure, never a silent pass. - (( got )) || record "P4: probe $1 $2" T08 iam-or-db pass no-output "window.sh probe $* printed no PASS/FAIL line" + p4 platform "bootstrap secret readable" "TLS on the connection" "pgvector installed by db-init" \ + "rag_bootstrap attributes" "rag_bootstrap database grants" "bootstrap identity cannot read the master secret" -- platform + for t in tenant-a tenant-b; do + o=$([[ $t == tenant-a ]] && echo tenant-b || echo tenant-a) + p4 "sandbox $t" "own secret readable" "own schema queried" "vector query in own schema" \ + "own bucket reachable (HeadBucket)" "app /readyz through the Service" "app /query through the Service" -- sandbox "$t" "$SANDBOX" + p4 "cross $t" "$t reads $o's secret" "$t reads the bootstrap secret" "$t reaches $o's bucket" "$t reads $o's schema" \ + "$t sandbox role runs CREATE ROLE" "$t sandbox role creates a schema" "$t Pod gets an IMDS token" -- cross "$t" "$SANDBOX" "$o" done else record P4-probes T08 iam-or-db pass SKIPPED_NEEDS_EKS "needs RDS, Secrets Manager, S3 and IRSA" fi -jq -n --arg run "$RUN_ID" --arg mode "$MODE" --arg img "$IMG" --argjson c "$cases" \ - '{run_id:$run, mode:$mode, image:$img, cases:$c, - summary:{total:($c|length), pass:([$c[]|select(.result=="PASS")]|length), - fail:([$c[]|select(.result=="FAIL")]|length), - skipped:([$c[]|select(.result|startswith("SKIPPED"))]|length)}}' > "$OUT" -echo -jq -r '.summary | "total \(.total), pass \(.pass), fail \(.fail), skipped \(.skipped)"' "$OUT" -skipped="$(jq '.summary.skipped' "$OUT")" -if (( bad )); then echo "RESULT: FAIL ($OUT)"; exit 1; fi -if [[ "$MODE" == eks && "$skipped" != 0 ]]; then echo "RESULT: FAIL (skipped cases in eks mode)"; exit 1; fi -echo "RESULT: PASS ($OUT)" +finish "${NET_PHASE:-none}"