tidaldb/tests/e2e/features/04-network-isolation.spec.ts
jordan 15f6b11187 test(e2e): Playwright evidence harness for the deploy-verification runbook
Turns docs/runbooks/deploy-verification.md from prose into 32 executable checks
against the live orchard9-k3sf cluster, and it found real defects on its first
run — including in the runbook it verifies.

WHY PLAYWRIGHT, HONESTLY
tidalDB serves zero HTML (no text/html, no Html(), 10 JSON routes), so this uses
Playwright in three distinct roles rather than pretending there is a UI:
  * request fixture as a real HTTP client for DNS/TLS/auth/quorum/404;
  * a browser for the only genuine screens in the chain, Grafana;
  * a test harness for cluster-plane checks with no HTTP surface, shelling out
    to kubectl and attaching the real transcript as evidence.

WHAT IT CAUGHT
  * The runbook asserted the operator/data credential split was "not active yet
    - requires an image roll". globalSetup read the live image and the live
    secret; a probe returned data->403, admin->200. It had been enforcing the
    whole time. Section 9 rewritten. (BUG-001)
  * docs/ops/grafana-tidaldb.json shipped datasource uid ${DS_PROMETHEUS} - a
    Grafana export-for-sharing placeholder with no __inputs block to resolve it.
    Under ConfigMap provisioning every panel queried a datasource that did not
    exist, so the whole board was blank. The API said "loaded" and I had only
    ever checked the API. 41 refs fixed here, 58 across the fleet ConfigMap,
    which was also blanking the postgres and redis dashboards. (BUG-007)
  * Stat panels used calcs "lastNonNull". Grafana's reducer is "lastNotNull", so
    no value was ever computed and Cluster health / Reseed pending / Indexed
    vectors rendered as empty boxes. I chased panel width and then panel height
    before comparing against a working stat panel elsewhere in the same Grafana.
    A spelling error wearing a layout bug's clothes. (BUG-009)
  * The namespace variable defaulted to All, so cluster panels silently included
    tidaldb-586b544c8-vpkmw from the superseded standalone deployment. Latency
    legends read "p50 p50 p50" with no way to tell the nodes apart. Both fixed.
  * "5xx ratio" rendered "No data" as large green text - at a glance a healthy
    value. And Fleet state gave three fields one shared green threshold, so
    reseed_required=1 would have shown GREEN during the exact incident the panel
    exists to surface. Split into three panels with per-field mappings.
  * tidalctl cluster-status exits 2 on a FULLY CONVERGED cluster, because the
    aggregated endpoint reports healthy peers as region=null applied=0
    reachable=false. The runbook claimed `cluster-status && deploy` was a safe
    gate; that claim came from an exit code masked by a shell pipeline. The gate
    can never pass here. Documented, test pins it, engine defect recorded.
    (BUG-005)
  * The deployed image writes ANSI colour into container logs, which the
    collector stores verbatim. Already fixed in logging.rs, not yet rolled;
    pinned as a tripwire. (BUG-006)
  * The runbook's own backup command sorted ALL backups by timestamp and
    selected a restore-canary run: 20 items, one volume, a meaningless pass.
    Now filters on the schedule label the freshness alert actually watches.

DEFECTS FOUND BY LOOKING AT THE SCREENS
Six of the first eight captures were slop and were fixed, not promoted:
230-350px of dead space; a verdict that rendered "exit code 2" in green; the
1600x1800 dashboard scaled into 16:9 until illegible (now clipped to the
evidence band using real element bounds); the dream beat whose caption described
a contradiction the image did not show (now a purpose-built capture holding the
committed doc text, the running image, and the live 403/200 side by side); and a
one-frame blink to bare background at every scene boundary, because Remotion
Sequences do not overlap and both scenes sat at opacity 0 on the boundary frame.

TRIPWIRES IN THE HONEST DIRECTION
Three tests assert what is ABSENT - zero tidaldb_http_* families, JSON_LOGS
unset, plain-text logs - and each carries the message "good news, roll the
runbook section from pending to live". The metric-absence test also asserts the
baseline family count, so "absent" cannot pass for "the scrape failed". That is
the drift that made section 9 stale in the first place.

Regression config uses workers:1 and retries:0 deliberately: a live-cluster
check that only passes on the second attempt has told you something true.

Verified: 32 passed (46.8s); 9 demo captures each asserting before photographing;
tsc clean; render 82.05s 1920x1080 h264, 0 empty frames across 10 boundaries;
every promoted image inspected individually and judged perfect; walk-the-render
ledger complete with no fails.
2026-08-23 14:03:29 -06:00

171 lines
6.0 KiB
TypeScript

/**
* Runbook section 4 — NetworkPolicy enforcement.
*
* CAP-008 the metrics port is not reachable from arbitrary pods
* CAP-009 metrics reach the platform with the labels the dashboard queries
*
* A NetworkPolicy that blocks everything is an observability outage and one
* that blocks nothing is theatre, so both directions are proven in the same
* test: the foreign pod is refused AND the scraper still collects.
*/
import { expect, test } from '@playwright/test';
import { kubectl, withPortForward } from '../support/cluster';
import { observed, recordJson } from '../support/evidence';
import {
FOREIGN_NAMESPACE,
FOREIGN_POD,
NAMESPACE,
OBS_NAMESPACE,
PORT_METRICS,
} from '../support/env';
/**
* Generous, because a 6-second client timeout truncates this scrape on a loaded
* node and returns zero lines — indistinguishable from "this pod exports
* nothing". That false negative briefly looked like a pod had stopped
* exporting entirely (BUG-002).
*/
const SCRAPE_TIMEOUT_SECONDS = 15;
/** Minimum series a healthy node exports, well below the observed ~330. */
const MIN_EXPECTED_SERIES = 100;
async function podIp(pod: string): Promise<string> {
const result = await kubectl([
'-n',
NAMESPACE,
'get',
'pod',
pod,
'-o',
'jsonpath={.status.podIP}',
]);
expect(result.code, `could not read ${pod} IP: ${result.stderr}`).toBe(0);
expect(result.stdout.trim(), `${pod} should have an IP`).toMatch(/^\d+\.\d+\.\d+\.\d+$/);
return result.stdout.trim();
}
test.describe('section 4 — network isolation', () => {
test('the NetworkPolicy exists and selects the cluster pods', async ({}, testInfo) => {
const result = await observed(testInfo, 'get networkpolicy', () =>
kubectl(['-n', NAMESPACE, 'get', 'networkpolicy', 'tidaldb', '-o', 'json']),
);
expect(result.code, result.stderr).toBe(0);
const policy = JSON.parse(result.stdout) as {
spec: { podSelector: { matchLabels: Record<string, string> }; ingress: unknown[] };
};
await recordJson(testInfo, 'policy-selector', policy.spec.podSelector);
expect(
policy.spec.podSelector.matchLabels['app.kubernetes.io/name'],
'the policy must select the tidaldb pods',
).toBe('tidaldb');
expect(
policy.spec.ingress.length,
'the policy must declare at least one ingress allowance',
).toBeGreaterThan(0);
});
test('a pod in an unrelated namespace is refused on the metrics port', async ({}, testInfo) => {
const target = await podIp('tidaldb-0');
const result = await observed(testInfo, 'foreign pod probes metrics port', () =>
kubectl([
'-n',
FOREIGN_NAMESPACE,
'exec',
FOREIGN_POD,
'--',
'sh',
'-c',
`wget -qO- --timeout=5 http://${target}:${PORT_METRICS}/metrics 2>&1 | head -3`,
]),
);
const output = `${result.stdout}${result.stderr}`;
await recordJson(testInfo, 'foreign-probe', {
from: `${FOREIGN_NAMESPACE}/${FOREIGN_POD}`,
to: `${target}:${PORT_METRICS}`,
exitCode: result.code,
output: output.trim().slice(0, 400),
});
// Before the policy existed this returned '# HELP tidaldb_uptime_seconds…'
// from any pod in the cluster. The refusal is the whole point.
expect(
output,
'a foreign pod must NOT receive metrics — this is the exposure the policy closes',
).not.toContain('tidaldb_');
expect(output.toLowerCase()).toMatch(/refused|timed out|no route|unreachable/);
});
test('the scraper still collects metrics through the policy', async ({}, testInfo) => {
const target = await podIp('tidaldb-0');
const result = await observed(testInfo, 'scraper collects metrics', () =>
kubectl(
[
'-n',
OBS_NAMESPACE,
'exec',
'deploy/vmagent',
'--',
'sh',
'-c',
`wget -qO- --timeout=${SCRAPE_TIMEOUT_SECONDS} http://${target}:${PORT_METRICS}/metrics | grep -c '^tidaldb_'`,
],
{ timeoutMs: 45_000 },
),
);
expect(result.code, `scrape failed: ${result.stderr}`).toBe(0);
const seriesCount = Number.parseInt(result.stdout.trim(), 10);
await recordJson(testInfo, 'scrape-series-count', { target, seriesCount });
// A policy that blocked the scraper too would be an observability outage
// dressed as a security win.
expect(
seriesCount,
'the scraper must still reach the metrics port through the policy',
).toBeGreaterThan(MIN_EXPECTED_SERIES);
});
test('metrics carry the labels the dashboard templates depend on', async ({
playwright,
}, testInfo) => {
await withPortForward(OBS_NAMESPACE, 'svc/vmsingle', 8428, async (forward) => {
const context = await playwright.request.newContext();
try {
const response = await context.get(
`http://127.0.0.1:${forward.localPort}/api/v1/series`,
{ params: { 'match[]': 'tidaldb_health_ok' } },
);
expect(response.status(), 'vmsingle series query').toBe(200);
const payload = (await response.json()) as { data: Record<string, string>[] };
const labelSets = payload.data ?? [];
await recordJson(testInfo, 'series-labels', {
seriesCount: labelSets.length,
labels: labelSets.length > 0 ? Object.keys(labelSets[0]).sort() : [],
});
expect(labelSets.length, 'tidaldb_health_ok must exist in the store').toBeGreaterThan(0);
// The dashboard's $namespace / $pod template variables resolve against
// these exact label names. A rename leaves every panel blank while the
// series still exists — a monitoring outage that looks like an outage.
for (const label of ['namespace', 'pod', 'container', 'partition_id']) {
expect(
Object.keys(labelSets[0]),
`series must carry the '${label}' label the dashboard queries`,
).toContain(label);
}
} finally {
await context.dispose();
}
});
});
});