From 46ee68b863e5f8be9d9d3e72b0255334040adbde Mon Sep 17 00:00:00 2001 From: frozenprocess <54559947+frozenprocess@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:37:55 +0000 Subject: [PATCH] UI tests: Engine runs every tests but it doesn't show the results to users. this change represent the test errors to users in both the editor and as a seperate pane. The pane only is visiable if user is not in learn mode. --- engine/adapters/hs/adapter.go | 2 +- engine/adapters/hs/adapter_test.go | 58 +++++++++++++ engine/adapters/hs/tests.go | 87 ++++++++++++++++--- web/src/App.tsx | 2 +- web/src/app/{Share.tsx => ShareUI.tsx} | 0 web/src/impact/AnalysisStrip.tsx | 30 ++++++- web/src/matrix/TestsPanel.test.tsx | 46 ++++++++++ web/src/matrix/TestsPanel.tsx | 79 +++++++++++++++++ web/src/snapshot/ImportTailnet.test.tsx | 2 +- ...ortTailnet.tsx => ImportTailnetButton.tsx} | 0 web/src/snapshot/SnapshotPanel.tsx | 2 +- web/src/styles/tutorials.css | 13 +++ web/src/tutorials/GradingChecklist.tsx | 35 ++------ 13 files changed, 306 insertions(+), 50 deletions(-) rename web/src/app/{Share.tsx => ShareUI.tsx} (100%) create mode 100644 web/src/matrix/TestsPanel.test.tsx create mode 100644 web/src/matrix/TestsPanel.tsx rename web/src/snapshot/{ImportTailnet.tsx => ImportTailnetButton.tsx} (100%) diff --git a/engine/adapters/hs/adapter.go b/engine/adapters/hs/adapter.go index bacac32..5373212 100644 --- a/engine/adapters/hs/adapter.go +++ b/engine/adapters/hs/adapter.go @@ -133,7 +133,7 @@ func (e *Evaluator) evaluate(req eval.Request) eval.Result { c.services(req.Snapshot.Services) c.externalShare(extPeers, pf.ExternalShare) c.ssh(req.SSHUsers) - evalTests(pm, pf.Policy, &res) + evalTests(pm, pf.Policy, req.Policy, &res) return res } diff --git a/engine/adapters/hs/adapter_test.go b/engine/adapters/hs/adapter_test.go index c706605..c3d749a 100644 --- a/engine/adapters/hs/adapter_test.go +++ b/engine/adapters/hs/adapter_test.go @@ -320,6 +320,9 @@ func TestEvaluate_TestsGrading(t *testing.T) { t.Errorf("case %q should pass", c.Label) } } + if ds := testFailureDiags(pass); len(ds) != 0 { + t.Errorf("passing tests must not raise diagnostics, got %+v", ds) + } // Wrong port — the accept assertion fails, the deny still holds. fail := New().Evaluate(eval.Request{ @@ -340,6 +343,17 @@ func TestEvaluate_TestsGrading(t *testing.T) { t.Errorf("db:5432 deny should still pass, got %+v", c) } + // The failing assertion surfaces as a policy error at its accept entry + // (line 5 of the policy text), not as a fatal one. + ds := testFailureDiags(fail) + if len(ds) != 1 { + t.Fatalf("want 1 test-failure diagnostic, got %+v", ds) + } + if d := ds[0]; d.Severity != "error" || !strings.HasPrefix(d.Pointer, "5:") || + !strings.Contains(d.Message, "tag:web:443 should be reachable") { + t.Errorf("diagnostic = %+v, want an error at line 5 naming tag:web:443", d) + } + // No tests block — no report. none := New().Evaluate(eval.Request{Snapshot: snap, Policy: `{}`}) if none.Tests != nil { @@ -347,6 +361,18 @@ func TestEvaluate_TestsGrading(t *testing.T) { } } +// testFailureDiags returns res's diagnostics raised by a failing tests or +// sshTests block. +func testFailureDiags(res eval.Result) []eval.Diagnostic { + var out []eval.Diagnostic + for _, d := range res.Diagnostics { + if d.Code == "policy" && (strings.HasPrefix(d.Message, "tests: ") || strings.HasPrefix(d.Message, "sshTests: ")) { + out = append(out, d) + } + } + return out +} + func TestEvaluate_NoPostureNoReport(t *testing.T) { res := New().Evaluate(eval.Request{ Policy: `{ "acls": [ { "action": "accept", "src": ["*"], "dst": ["*:*"] } ] }`, @@ -533,3 +559,35 @@ func TestEvaluate_UndefinedPostureWarns(t *testing.T) { t.Errorf("warnings =\n%s\nwant\n%s", got, strings.Join(want, "\n")) } } + +func TestEvaluate_SSHTestsFailureDiagnostic(t *testing.T) { + snap := eval.Snapshot{ + Users: []eval.User{{ID: 1, Email: "alice@example.com"}}, + Devices: []eval.Device{ + {ID: 1, Name: "alice-laptop", User: "alice@example.com", IPv4: "100.64.0.1"}, + {ID: 2, Name: "web-1", Tags: []string{"tag:web"}, IPv4: "100.64.0.2"}, + }, + } + // The ssh rule admits the login, but no ACL opens tcp/22, so the sshTests + // accept assertion can't hold. + res := New().Evaluate(eval.Request{ + Snapshot: snap, + SSHUsers: []string{"root"}, + Policy: `{ + "tagOwners": { "tag:web": ["alice@example.com"] }, + "acls": [ { "action": "accept", "src": ["alice@example.com"], "dst": ["tag:web:443"] } ], + "ssh": [ { "action": "accept", "src": ["alice@example.com"], "dst": ["tag:web"], "users": ["root"] } ], + "sshTests": [ { "src": "alice@example.com", "dst": ["tag:web"], "accept": ["root"] } ] + }`, + }) + if res.Tests == nil || res.Tests.SSH == nil || res.Tests.SSH.Passed { + t.Fatalf("want a failing SSH test group, got %+v", res.Tests) + } + ds := testFailureDiags(res) + if len(ds) != 1 { + t.Fatalf("want 1 sshTests diagnostic, got %+v", ds) + } + if d := ds[0]; !strings.HasPrefix(d.Message, "sshTests: ") || !strings.HasPrefix(d.Pointer, "5:") { + t.Errorf("diagnostic = %+v, want an sshTests error at line 5", d) + } +} diff --git a/engine/adapters/hs/tests.go b/engine/adapters/hs/tests.go index 8009606..8a65018 100644 --- a/engine/adapters/hs/tests.go +++ b/engine/adapters/hs/tests.go @@ -2,6 +2,7 @@ package hs import ( "encoding/json" + "fmt" "regexp" "strings" @@ -9,6 +10,7 @@ import ( policyv2 "github.com/juanfont/headscale/hscontrol/policy/v2" "github.com/frozenprocess/tailground/engine/eval" + "github.com/frozenprocess/tailground/engine/preflight" ) // policyTests mirrors the `tests` / `sshTests` blocks well enough to enumerate @@ -31,7 +33,10 @@ type policyTests struct { // evalTests runs the policy's own `tests` / `sshTests` blocks (D6) and records a // per-assertion pass/fail report. It only runs when the policy declares tests. -func evalTests(pm hspolicy.PolicyManager, cleanedPolicy string, res *eval.Result) { +// Each failing assertion also becomes a "policy" error diagnostic located in +// rawPolicy (the user's text), because Tailscale rejects a policy whose tests +// fail. cleanedPolicy is the preflight output the assertions are read from. +func evalTests(pm hspolicy.PolicyManager, cleanedPolicy, rawPolicy string, res *eval.Result) { var pt policyTests if err := json.Unmarshal([]byte(cleanedPolicy), &pt); err != nil { return @@ -50,40 +55,46 @@ func evalTests(pm hspolicy.PolicyManager, cleanedPolicy string, res *eval.Result if len(pt.Tests) > 0 { testErr := v2pm.RunTests() g := &eval.TestGroup{Passed: testErr == nil} - for _, t := range pt.Tests { - for _, dst := range t.Accept { + var ptrs []string // JSON pointer of each case, parallel to g.Cases + for i, t := range pt.Tests { + for j, dst := range t.Accept { g.Cases = append(g.Cases, eval.TestCase{ - Label: t.Src + " → " + dst, Expect: "reachable", Pass: true, + Label: t.Src + " → " + dst, Expect: expectReachable, Pass: true, }) + ptrs = append(ptrs, fmt.Sprintf("/%s/%d/accept/%d", testsKey, i, j)) } - for _, dst := range t.Deny { + for j, dst := range t.Deny { g.Cases = append(g.Cases, eval.TestCase{ - Label: t.Src + " → " + dst, Expect: "blocked", Pass: true, + Label: t.Src + " → " + dst, Expect: expectBlocked, Pass: true, }) + ptrs = append(ptrs, fmt.Sprintf("/%s/%d/deny/%d", testsKey, i, j)) } } if !g.Passed { attributeACLFailures(testErr, g) } report.ACL = g + res.Diagnostics = append(res.Diagnostics, testDiags(rawPolicy, testsKey, g, ptrs)...) } if len(pt.SSHTests) > 0 { sshErr := v2pm.RunSSHTests() g := &eval.TestGroup{Passed: sshErr == nil} - for _, t := range pt.SSHTests { + var ptrs []string // JSON pointer of each case, parallel to g.Cases + for i, t := range pt.SSHTests { dstLabel := strings.Join(t.Dst, ", ") - add := func(users []string, expect string) { - for _, u := range users { + add := func(field string, users []string, expect string) { + for j, u := range users { g.Cases = append(g.Cases, eval.TestCase{ Label: t.Src + " → " + dstLabel + " as " + displayUser(u), Expect: expect, Pass: true, }) + ptrs = append(ptrs, fmt.Sprintf("/%s/%d/%s/%d", sshTestsKey, i, field, j)) } } - add(t.Accept, "reachable") - add(t.Deny, "blocked") - add(t.Check, "via check") + add("accept", t.Accept, expectReachable) + add("deny", t.Deny, expectBlocked) + add("check", t.Check, expectViaCheck) } if !g.Passed { attributeSSHFailures(sshErr, g) @@ -96,18 +107,68 @@ func evalTests(pm hspolicy.PolicyManager, cleanedPolicy string, res *eval.Result if g.Passed && sshMatrixAllDeny(res.SSH) { g.Passed = false for i := range g.Cases { - if g.Cases[i].Expect != "blocked" { + if g.Cases[i].Expect != expectBlocked { g.Cases[i].Pass = false g.Cases[i].Detail = "no rule opens tcp/22 to this destination — Tailscale SSH still needs an L4 grant for port 22" } } } report.SSH = g + res.Diagnostics = append(res.Diagnostics, testDiags(rawPolicy, sshTestsKey, g, ptrs)...) } res.Tests = report } +// Policy keys of the self-check blocks, as they appear in JSON pointers. +const ( + testsKey = "tests" + sshTestsKey = "sshTests" +) + +// TestCase.Expect values. +const ( + expectReachable = "reachable" + expectBlocked = "blocked" + expectViaCheck = "via check" +) + +// testDiags returns one "policy" error diagnostic per failing case in g, located +// at the case's entry in rawPolicy via ptrs (parallel to g.Cases), and one per +// unattributed failure line, located at the block named by key. A failed group +// with nothing to attribute still yields a single diagnostic, so a rejected +// policy never looks clean. +func testDiags(rawPolicy, key string, g *eval.TestGroup, ptrs []string) []eval.Diagnostic { + if g.Passed { + return nil + } + var out []eval.Diagnostic + for i, c := range g.Cases { + if c.Pass { + continue + } + msg := fmt.Sprintf("%s: %s should be %s", key, c.Label, c.Expect) + if c.Detail != "" { + msg += " (" + c.Detail + ")" + } + d := diag("error", "policy", "%s", msg) + d.Pointer = preflight.LocatePointer(rawPolicy, ptrs[i]) + out = append(out, d) + } + blockPtr := preflight.LocatePointer(rawPolicy, "/"+key) + for _, ln := range g.RawFailures { + d := diag("error", "policy", "%s: %s", key, ln) + d.Pointer = blockPtr + out = append(out, d) + } + if len(out) == 0 { + d := diag("error", "policy", "%s: the policy's tests fail; Tailscale rejects this policy", key) + d.Pointer = blockPtr + out = append(out, d) + } + return out +} + // sshMatrixAllDeny reports whether the gated SSH matrix has at least one entry // and every one of them is "deny" — i.e. the L4 tcp/22 gate (or the ssh[] block // itself) blocked every probed login. diff --git a/web/src/App.tsx b/web/src/App.tsx index f365c5f..bef39ff 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -10,7 +10,7 @@ import { useMediaQuery, MOBILE_QUERY } from "./app/useMediaQuery"; import { useHashRoute } from "./app/useHashRoute"; import { useShareHydration } from "./app/useShareHydration"; import { TourNote } from "./tutorials/TourNote"; -import { ShareBanner, ShareButton, ShareConsent } from "./app/Share"; +import { ShareBanner, ShareButton, ShareConsent } from "./app/ShareUI"; import { ThemeToggle } from "./app/ThemeToggle"; import { AboutButton } from "./app/AboutButton"; import { GitHubButton } from "./app/GitHubButton"; diff --git a/web/src/app/Share.tsx b/web/src/app/ShareUI.tsx similarity index 100% rename from web/src/app/Share.tsx rename to web/src/app/ShareUI.tsx diff --git a/web/src/impact/AnalysisStrip.tsx b/web/src/impact/AnalysisStrip.tsx index 6bca7f5..bf37600 100644 --- a/web/src/impact/AnalysisStrip.tsx +++ b/web/src/impact/AnalysisStrip.tsx @@ -7,6 +7,7 @@ import { PosturePanel, postureCount } from "../matrix/PosturePanel"; import { RoutePanel } from "../matrix/RoutePanel"; import { ServicePanel } from "../matrix/ServicePanel"; import { ExternalSharePanel, externalShareCount } from "../matrix/ExternalSharePanel"; +import { TestsPanel, testCounts } from "../matrix/TestsPanel"; import { PairDetail } from "../matrix/PairDetail"; import { DeviceInspector } from "../inspector/DeviceInspector"; @@ -15,9 +16,10 @@ const clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n /** * The analysis strip that sits *below* the matrix grid / graph canvas (L-C). - * Everything here is derived from the same `Result`: the four Tailground overlay - * layers (posture / routes / services / node-sharing) as collapsible panels with - * a count badge, plus the transient PairDetail / DeviceInspector cards. + * Everything here is derived from the same `Result`: the policy's own tests, the + * four Tailground overlay layers (posture / routes / services / node-sharing) as + * collapsible panels with a count badge, plus the transient PairDetail / + * DeviceInspector cards. * * L-D: the strip's height is a drag-persisted fraction of the impact pane * (`layout.strip`), and each sub-panel's collapse state persists in @@ -53,8 +55,10 @@ export function AnalysisStrip({ const overlays = !sshMode; const denials = result.posture ? postureCount(result.posture) : 0; + const tests = testCounts(result.tests); const hasContent = + !!result.tests || !!result.posture || (overlays && !!result.routes) || (overlays && !!result.services) || @@ -62,6 +66,8 @@ export function AnalysisStrip({ !!selectedPair || (focusedActor != null && !!onCloseDevice); + // const learnVisible = useStore((s) => s.leftTab === "learn" && (s.mobilePane === "learn") || !isMobile), + const learnVisible = useStore((s) => s.leftTab === "learn"); if (!hasContent) return null; const onDragMove = (e: PointerEvent) => { @@ -112,6 +118,24 @@ export function AnalysisStrip({ ) : focusedActor != null && onCloseDevice ? ( ) : null} + { result.tests && ( + 0 ? ( + {tests.failing} failing + ) : ( + `${tests.passed} / ${tests.total} passing` + ) + } + > + {/* don't show the pane in tutorial mode */} + {!learnVisible && ( + + )} + + )} {result.posture && overlayPanel( diff --git a/web/src/matrix/TestsPanel.test.tsx b/web/src/matrix/TestsPanel.test.tsx new file mode 100644 index 0000000..cc9539c --- /dev/null +++ b/web/src/matrix/TestsPanel.test.tsx @@ -0,0 +1,46 @@ +// @vitest-environment jsdom +import { afterEach, expect, it } from "vitest"; +import type { TestReport } from "../engine/types"; +import { render } from "../test/render"; +import { TestsPanel, testCounts } from "./TestsPanel"; + +const failing: TestReport = { + acl: { + passed: false, + cases: [ + { label: "alice → tag:web:443", expect: "reachable", pass: false, detail: "expected allowed, got denied" }, + { label: "alice → tag:db:5432", expect: "blocked", pass: true }, + ], + }, + ssh: { passed: false, cases: [], rawFailures: ["unparsed failure"] }, +}; + +let unmount: (() => Promise) | undefined; +afterEach(async () => { + await unmount?.(); + unmount = undefined; +}); + +it("counts failures, treating an engine-failed group as at least one", () => { + expect(testCounts(failing)).toEqual({ total: 2, passed: 1, failing: 2 }); + expect(testCounts({ acl: { passed: false, cases: [{ label: "x", expect: "blocked", pass: true }] } }).failing).toBe(1); + expect(testCounts({ acl: { passed: true, cases: [{ label: "x", expect: "blocked", pass: true }] } }).failing).toBe(0); + expect(testCounts(undefined)).toEqual({ total: 0, passed: 0, failing: 0 }); +}); + +it("renders each assertion and warns that the policy would be rejected", async () => { + unmount = await render(); + const text = document.body.textContent ?? ""; + expect(text).toContain("Tailscale rejects a policy whose tests fail"); + expect(document.querySelectorAll("li.fail")).toHaveLength(1); + expect(document.querySelectorAll("li.ok")).toHaveLength(1); + expect(text).toContain("expected allowed, got denied"); + expect(text).toContain("unparsed failure"); +}); + +it("omits the rejection warning when everything passes", async () => { + unmount = await render( + , + ); + expect(document.body.textContent).not.toContain("rejects"); +}); diff --git a/web/src/matrix/TestsPanel.tsx b/web/src/matrix/TestsPanel.tsx new file mode 100644 index 0000000..173a94e --- /dev/null +++ b/web/src/matrix/TestsPanel.tsx @@ -0,0 +1,79 @@ +import type { TestGroup, TestReport } from "../engine/types"; + +/** The report's groups with display names, in a fixed order. */ +export function testGroups(report: TestReport | undefined): [string, TestGroup][] { + const groups: [string, TestGroup][] = []; + if (report?.acl) groups.push(["Reachability", report.acl]); + if (report?.ssh) groups.push(["SSH", report.ssh]); + return groups; +} + +/** + * Counts for a test report. `failing` is the number of failed assertions plus + * unattributed failure lines; it is at least 1 for any group the engine marked + * failed, since `passed` is authoritative and per-case marks are best-effort. + */ +export function testCounts(report: TestReport | undefined) { + let total = 0; + let passed = 0; + let failing = 0; + for (const [, g] of testGroups(report)) { + const ok = g.cases.filter((c) => c.pass).length; + total += g.cases.length; + passed += ok; + if (!g.passed) { + failing += Math.max(1, g.cases.length - ok + (g.rawFailures?.length ?? 0)); + } + } + return { total, passed, failing }; +} + +/** Pass/fail list of each assertion in `groups`, plus unattributed failures. */ +export function TestGroupList({ groups }: { groups: [string, TestGroup][] }) { + return ( + <> + {groups.map(([name, g]) => ( +
+ {groups.length > 1 &&
{name}
} +
    + {g.cases.map((c, i) => ( +
  • + {c.pass ? "✓" : "✗"} + + {c.label} — {c.expect} + + {c.detail && {c.detail}} +
  • + ))} +
+ {g.rawFailures?.map((f, i) => ( +
+ {f} +
+ ))} +
+ ))} + + ); +} + +/** + * Body of the policy-tests panel: the outcome of the policy's own `tests` / + * `sshTests` blocks. Wrapped by `AnalysisStrip` in a collapsible ``; + * rendered wherever the matrix or graph is shown, when the policy declares + * tests. Failing assertions are also flagged in the editor. + */ +export function TestsPanel({ report }: { report: TestReport }) { + const { failing } = testCounts(report); + return ( +
+ {failing > 0 && ( +

+ Tailscale rejects a policy whose tests fail. Fix the policy or the + assertion flagged in the editor. +

+ )} + +
+ ); +} diff --git a/web/src/snapshot/ImportTailnet.test.tsx b/web/src/snapshot/ImportTailnet.test.tsx index c436503..e0e808d 100644 --- a/web/src/snapshot/ImportTailnet.test.tsx +++ b/web/src/snapshot/ImportTailnet.test.tsx @@ -4,7 +4,7 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { parse as parseJsonc } from "jsonc-parser"; import { render } from "../test/render"; import { useStore } from "../state/store"; -import { ImportTailnetButton } from "./ImportTailnet"; +import { ImportTailnetButton } from "./ImportTailnetButton"; const apiOutput = JSON.stringify({ devices: [ diff --git a/web/src/snapshot/ImportTailnet.tsx b/web/src/snapshot/ImportTailnetButton.tsx similarity index 100% rename from web/src/snapshot/ImportTailnet.tsx rename to web/src/snapshot/ImportTailnetButton.tsx diff --git a/web/src/snapshot/SnapshotPanel.tsx b/web/src/snapshot/SnapshotPanel.tsx index d842908..86fe96e 100644 --- a/web/src/snapshot/SnapshotPanel.tsx +++ b/web/src/snapshot/SnapshotPanel.tsx @@ -7,7 +7,7 @@ import { usePaneMax } from "../app/usePaneMax"; import { usePanelCollapse } from "../app/usePanelCollapse"; import { LeftTabs } from "../app/LeftTabs"; import { SnapshotJson } from "./SnapshotJson"; -import { ImportTailnetButton } from "./ImportTailnet"; +import { ImportTailnetButton } from "./ImportTailnetButton"; import { DevicesSection, ExternalSection, ServicesSection, UsersSection } from "./Sections"; import { GroupsHostsEditor } from "./GroupsHostsEditor"; diff --git a/web/src/styles/tutorials.css b/web/src/styles/tutorials.css index 07e1684..5c15a60 100644 --- a/web/src/styles/tutorials.css +++ b/web/src/styles/tutorials.css @@ -329,3 +329,16 @@ th.rowhead.clickable:hover { .tour-note { bottom: 76px; } .tour-note span { display: none; } } + +/* Policy-tests panel in the analysis strip; reuses the .grading list. */ +.tests-panel { + padding: 6px 12px; +} +.tests-reject { + margin: 0 0 6px; + color: var(--danger); +} +.tests-failing { + color: var(--danger); + font-weight: 600; +} diff --git a/web/src/tutorials/GradingChecklist.tsx b/web/src/tutorials/GradingChecklist.tsx index 324a936..e8e5683 100644 --- a/web/src/tutorials/GradingChecklist.tsx +++ b/web/src/tutorials/GradingChecklist.tsx @@ -1,4 +1,5 @@ -import type { TestGroup, TestReport } from "../engine/types"; +import type { TestReport } from "../engine/types"; +import { TestGroupList, testCounts, testGroups } from "../matrix/TestsPanel"; /** Live pass/fail of the lesson's `tests` / `sshTests` assertions. */ export function GradingChecklist({ @@ -10,9 +11,7 @@ export function GradingChecklist({ complete: boolean; graded: boolean; }) { - const groups: [string, TestGroup][] = []; - if (report?.acl) groups.push(["Reachability", report.acl]); - if (report?.ssh) groups.push(["SSH", report.ssh]); + const groups = testGroups(report); if (groups.length === 0) { return ( @@ -24,11 +23,7 @@ export function GradingChecklist({ ); } - const total = groups.reduce((n, [, g]) => n + g.cases.length, 0); - const passed = groups.reduce( - (n, [, g]) => n + g.cases.filter((c) => c.pass).length, - 0, - ); + const { total, passed } = testCounts(report); return (
@@ -37,27 +32,7 @@ export function GradingChecklist({ {complete ? "✓ Lesson complete" : `${passed} / ${total} checks passing`}
- {groups.map(([name, g]) => ( -
- {groups.length > 1 &&
{name}
} -
    - {g.cases.map((c, i) => ( -
  • - {c.pass ? "✓" : "✗"} - - {c.label} — {c.expect} - - {c.detail && {c.detail}} -
  • - ))} -
- {g.rawFailures?.map((f, i) => ( -
- {f} -
- ))} -
- ))} + ); }