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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion engine/adapters/hs/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
58 changes: 58 additions & 0 deletions engine/adapters/hs/adapter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand All @@ -340,13 +343,36 @@ 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 {
t.Errorf("policy without tests must not carry a test report")
}
}

// 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": ["*:*"] } ] }`,
Expand Down Expand Up @@ -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)
}
}
87 changes: 74 additions & 13 deletions engine/adapters/hs/tests.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ package hs

import (
"encoding/json"
"fmt"
"regexp"
"strings"

hspolicy "github.com/juanfont/headscale/hscontrol/policy"
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
Expand All @@ -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
Expand All @@ -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)
Expand All @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion web/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
File renamed without changes.
30 changes: 27 additions & 3 deletions web/src/impact/AnalysisStrip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -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
Expand Down Expand Up @@ -53,15 +55,19 @@ 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) ||
(overlays && !!result.externalShare) ||
!!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) => {
Expand Down Expand Up @@ -112,6 +118,24 @@ export function AnalysisStrip({
) : focusedActor != null && onCloseDevice ? (
<DeviceInspector result={result} deviceId={focusedActor} onClose={onCloseDevice} />
) : null}
{ result.tests && (
<Panel
{...collapse("an-tests", tests.failing === 0)}
title="Policy tests"
badge={
tests.failing > 0 ? (
<span className="tests-failing">{tests.failing} failing</span>
) : (
`${tests.passed} / ${tests.total} passing`
)
}
>
{/* don't show the pane in tutorial mode */}
{!learnVisible && (
<TestsPanel report={result.tests} />
)}
</Panel>
)}

{result.posture &&
overlayPanel(
Expand Down
46 changes: 46 additions & 0 deletions web/src/matrix/TestsPanel.test.tsx
Original file line number Diff line number Diff line change
@@ -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<void>) | 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(<TestsPanel report={failing} />);
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(
<TestsPanel report={{ acl: { passed: true, cases: [{ label: "a → b", expect: "reachable", pass: true }] } }} />,
);
expect(document.body.textContent).not.toContain("rejects");
});
Loading
Loading