tidaldb/tests/e2e/features/02-public-endpoint.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

153 lines
5.7 KiB
TypeScript

/**
* Runbook section 2 — the public endpoint and its TLS identity.
*
* CAP-003 public DNS resolves to every node
* CAP-004 TLS identity is correct and not near expiry
*
* The certificate is inspected through a real validated handshake rather than
* by reading the cert-manager Certificate object. A Certificate resource can
* report Ready while Traefik serves a stale or default certificate — the only
* claim that matters is what an external client is actually handed.
*/
import { resolve4 } from 'node:dns/promises';
import { connect, type PeerCertificate } from 'node:tls';
import { expect, test } from '@playwright/test';
import { recordJson } from '../support/evidence';
import { EXPECTED_NODE_IPS, PUBLIC_BASE_URL, PUBLIC_HOST } from '../support/env';
/** Minimum remaining certificate validity before this is a finding. */
const MIN_CERT_DAYS = 30;
type CertificateFacts = {
subjectCN: string;
issuer: string;
validTo: string;
daysRemaining: number;
subjectAltName?: string;
authorized: boolean;
protocol: string | null;
};
/**
* Complete a validated TLS handshake against one node IP with SNI set, and
* report what the peer presented.
*
* Connecting by IP with an explicit servername is deliberate: it proves the
* certificate is correct on *that specific node* rather than on whichever node
* DNS happened to return, which is how a partially-deployed certificate hides.
*/
async function inspectCertificate(host: string): Promise<CertificateFacts> {
const { promise, resolve, reject } = Promise.withResolvers<CertificateFacts>();
const socket = connect({
host,
port: 443,
servername: PUBLIC_HOST,
rejectUnauthorized: true,
timeout: 15_000,
});
socket.once('secureConnect', () => {
const certificate: PeerCertificate = socket.getPeerCertificate();
const validTo = new Date(certificate.valid_to);
// X.509 RDNs can legitimately repeat, so Node types these as
// `string | string[]`. Take the first value rather than stringifying an
// array into the assertion message.
const first = (value: string | string[] | undefined): string =>
Array.isArray(value) ? (value[0] ?? '') : (value ?? '');
resolve({
subjectCN: first(certificate.subject?.CN),
issuer: [first(certificate.issuer?.O), first(certificate.issuer?.CN)]
.filter(Boolean)
.join(' '),
validTo: validTo.toISOString(),
daysRemaining: Math.floor((validTo.getTime() - Date.now()) / 86_400_000),
subjectAltName: certificate.subjectaltname,
authorized: socket.authorized,
protocol: socket.getProtocol(),
});
socket.end();
});
socket.once('timeout', () => {
socket.destroy();
reject(new Error(`TLS handshake to ${host} timed out`));
});
socket.once('error', (error) => reject(error));
return promise;
}
test.describe('section 2 — public endpoint and TLS', () => {
test('the public hostname resolves to every node IP', async ({}, testInfo) => {
const addresses = await resolve4(PUBLIC_HOST);
await recordJson(testInfo, 'dns-a-records', {
host: PUBLIC_HOST,
resolved: [...addresses].sort(),
expected: [...EXPECTED_NODE_IPS].sort(),
});
// A missing record silently concentrates traffic; an extra record points
// somewhere undocumented. Assert the exact set.
expect([...addresses].sort(), 'A records must match the known node set').toEqual(
[...EXPECTED_NODE_IPS].sort(),
);
});
test('every node presents a valid, correctly-named, unexpired certificate', async ({}, testInfo) => {
const facts: Record<string, CertificateFacts> = {};
for (const ip of EXPECTED_NODE_IPS) {
facts[ip] = await test.step(`TLS handshake to ${ip}`, () => inspectCertificate(ip));
}
await recordJson(testInfo, 'tls-certificates', facts);
for (const [ip, certificate] of Object.entries(facts)) {
// rejectUnauthorized was true, so reaching here already proves the chain
// validated. Assert it explicitly so the intent survives a refactor.
expect(certificate.authorized, `${ip} chain must validate`).toBe(true);
expect(certificate.subjectCN, `${ip} certificate CN`).toBe(PUBLIC_HOST);
expect(certificate.issuer, `${ip} issuer should be Let's Encrypt`).toContain(
"Let's Encrypt",
);
expect(certificate.subjectAltName, `${ip} SAN must cover the hostname`).toContain(
PUBLIC_HOST,
);
expect(
certificate.daysRemaining,
`${ip} certificate expires in ${certificate.daysRemaining}d — renewal is overdue`,
).toBeGreaterThan(MIN_CERT_DAYS);
expect(certificate.protocol, `${ip} should negotiate modern TLS`).toMatch(
/TLSv1\.[23]/,
);
}
// All three nodes are fronted by the same Traefik and must present the same
// certificate. A divergence means one node did not pick up a renewal.
const distinctExpiries = [
...new Set(Object.values(facts).map((certificate) => certificate.validTo)),
];
expect(
distinctExpiries,
'every node must serve the same certificate generation',
).toHaveLength(1);
});
test('health is publicly reachable without a credential', async ({
playwright,
}, testInfo) => {
const context = await playwright.request.newContext({ ignoreHTTPSErrors: false });
try {
const response = await context.get(`${PUBLIC_BASE_URL}/health`);
const body = await response.text();
await recordJson(testInfo, 'health', { status: response.status(), body: body.slice(0, 300) });
// /health is intentionally open — it is what the probes and the uptime
// monitor call. It must not require the bearer.
expect(response.status(), '/health must be open and 200').toBe(200);
} finally {
await context.dispose();
}
});
});