Files
web-terminal/relay-auth/test/mtls.test.ts
Yaojia Wang 2af57e6686 feat(relay): rendezvous-relay service — 7 packages + plans (contracts/transport/agent/control-plane/e2e/auth/web)
Multi-tenant reverse-tunnel service ("ngrok for Claude Code" with E2E): a
host-agent dials OUT to an operator-run relay; external devices reach the host
THROUGH the relay, routed by per-tenant subdomain, forwarding ciphertext only
(the relay never sees plaintext). Lets a customer reach their own self-hosted
web-terminal from anywhere with zero networking setup.

Packages — all tsc-strict + vitest green (656 tests), cross-package integration verified:
- relay-contracts: frozen shared contracts (mux frame codec, data model,
  capability token, E2E envelope, pairing) — the src/types.ts analog
- term-relay:   native WS mux + stateless data plane (subdomain routing, ciphertext forward)
- agent:        host-agent (pairing, per-host Ed25519 + mTLS dial-out, forwards to 127.0.0.1:3000)
- control-plane: accounts/hosts registry, pairing-code flow, routing table, provisioning
- relay-e2e:    browser<->agent E2E (X25519 ECDH through relay, AEAD, anti-replay, recoverable replay key)
- relay-auth:   Passkey/WebAuthn, capability tokens, per-host certs, deny-by-default tenant isolation
- relay-web:    browser login + Web Crypto E2E + client-side preview rendering

Security invariants INV1-15 enforced; cross-tenant isolation CI tripwire live
(.github/workflows/relay-tripwire.yml). Design + implementation-level plans in
docs/PLAN_RELAY_*.md and docs/EXPLORE_RELAY_SERVICE.md.

NOTE: generated autonomously per the reviewed plans. The security-critical
packages (relay-e2e, relay-auth) REQUIRE expert security audit before any real
deployment — passing tests prove self-consistency, not resistance to attackers.
Base app (src/, public/) unchanged; concurrent desktop work left uncommitted.
2026-07-02 06:10:16 +02:00

149 lines
6.5 KiB
TypeScript

import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
import { describe, it, expect } from 'vitest'
import { spiffeIdFor, parseSpiffeId, SpiffeError } from '../src/agent/spiffe.js'
import {
verifyAgentCert,
defaultParseX509,
splitPemBundle,
type ParsedCert,
} from '../src/agent/verify-mtls.js'
import { shouldRotate, DEFAULT_ROTATION_PLAN } from '../src/agent/rotate.js'
import { fakeHostRegistry, makeHost } from './_helpers.js'
const FIXTURES = join(dirname(fileURLToPath(import.meta.url)), 'fixtures', 'mtls')
const readFixture = (name: string): string => readFileSync(join(FIXTURES, name), 'utf8')
const NOW = 1_700_000_000
const DOMAIN = 'example.com'
function certParser(cert: ParsedCert) {
return () => cert
}
describe('SPIFFE-ID scheme (T9)', () => {
it('formats and round-trips account/host', () => {
const id = spiffeIdFor('acct-A', 'host-1', DOMAIN)
expect(id).toBe('spiffe://relay.example.com/account/acct-A/host/host-1')
expect(parseSpiffeId(id)).toEqual({ accountId: 'acct-A', hostId: 'host-1' })
})
it('rejects a path-traversal / wildcard SPIFFE-ID', () => {
expect(() => parseSpiffeId('spiffe://relay.example.com/account/../host/x')).toThrow()
expect(() => parseSpiffeId('spiffe://relay.example.com/account/*/host/x')).toThrow(SpiffeError)
})
})
describe('agent cert verification (INV4/INV14)', () => {
const enrolled = spiffeIdFor('acct-A', 'host-1', DOMAIN)
const hosts = fakeHostRegistry([makeHost('acct-A', 'host-1')])
const validCert: ParsedCert = {
spiffeUri: enrolled,
notBefore: NOW - 10,
notAfter: NOW + 3600,
chainValid: true,
}
it('accepts an enrolled, in-date, chain-valid cert', async () => {
const r = await verifyAgentCert('leaf', 'ca', NOW, hosts, certParser(validCert))
expect(r).toMatchObject({ ok: true, hostId: 'host-1', accountId: 'acct-A' })
})
it('refuses a SPIFFE-ID whose host is not in the registry (INV4)', async () => {
const cert = { ...validCert, spiffeUri: spiffeIdFor('acct-A', 'host-unknown', DOMAIN) }
const r = await verifyAgentCert('leaf', 'ca', NOW, hosts, certParser(cert))
expect(r).toMatchObject({ ok: false, reason: 'host_not_enrolled' })
})
it('refuses an expired leaf', async () => {
const cert = { ...validCert, notAfter: NOW - 1 }
const r = await verifyAgentCert('leaf', 'ca', NOW, hosts, certParser(cert))
expect(r).toMatchObject({ ok: false, reason: 'expired' })
})
it('refuses a SPIFFE-ID account mismatch (cert account ≠ registry account)', async () => {
const cert = { ...validCert, spiffeUri: spiffeIdFor('acct-B', 'host-1', DOMAIN) }
const r = await verifyAgentCert('leaf', 'ca', NOW, hosts, certParser(cert))
expect(r).toMatchObject({ ok: false, reason: 'spiffe_account_mismatch' })
})
it('refuses a chain that does not verify against the CA', async () => {
const cert = { ...validCert, chainValid: false }
const r = await verifyAgentCert('leaf', 'ca', NOW, hosts, certParser(cert))
expect(r).toMatchObject({ ok: false, reason: 'chain_invalid' })
})
})
describe('defaultParseX509 real X.509 path validation (INV4/INV14)', () => {
const leafPem = readFixture('leaf.pem')
const caChainPem = readFixture('ca-chain.pem') // intermediate + root
const rootPem = readFixture('root.pem')
const intermediatePem = readFixture('intermediate.pem')
const foreignLeafPem = readFixture('foreign-leaf.pem')
it('splits a multi-cert PEM bundle into every certificate', () => {
expect(splitPemBundle(caChainPem)).toHaveLength(2)
expect(splitPemBundle(rootPem)).toHaveLength(1)
expect(splitPemBundle('')).toHaveLength(0)
})
it('parses the SPIFFE SAN, validity window, and validates the full chain', () => {
const parsed = defaultParseX509(leafPem, caChainPem)
expect(parsed.spiffeUri).toBe(spiffeIdFor('acct-A', 'host-1', DOMAIN))
expect(parsed.chainValid).toBe(true)
expect(parsed.notAfter).toBeGreaterThan(parsed.notBefore)
})
it('refuses when the intermediate is missing (root-only anchor is not a single hop)', () => {
// Real path validation: leaf is signed by the intermediate, not the root directly.
// A single-hop check against the first bundle cert would wrongly pass; chain walking refuses.
expect(defaultParseX509(leafPem, rootPem).chainValid).toBe(false)
})
it('refuses when no trusted self-signed root terminates the path (intermediate only)', () => {
expect(defaultParseX509(leafPem, intermediatePem).chainValid).toBe(false)
})
it('refuses a leaf signed by a foreign CA not in the trusted bundle', () => {
expect(defaultParseX509(foreignLeafPem, caChainPem).chainValid).toBe(false)
})
it('refuses when the CA bundle is empty', () => {
expect(defaultParseX509(leafPem, '').chainValid).toBe(false)
})
it('end-to-end: verifyAgentCert accepts the real enrolled leaf with the production parser', async () => {
const hosts = fakeHostRegistry([makeHost('acct-A', 'host-1')])
const parsed = defaultParseX509(leafPem, caChainPem)
const now = parsed.notBefore + 60 // fixtures are long-lived; sample inside the validity window
const r = await verifyAgentCert(leafPem, caChainPem, now, hosts, defaultParseX509)
expect(r).toMatchObject({ ok: true, hostId: 'host-1', accountId: 'acct-A' })
})
it('end-to-end: verifyAgentCert refuses the real foreign leaf (chain_invalid) with the production parser', async () => {
const hosts = fakeHostRegistry([makeHost('acct-A', 'host-1')])
const parsed = defaultParseX509(foreignLeafPem, caChainPem)
const now = parsed.notBefore + 60
const r = await verifyAgentCert(foreignLeafPem, caChainPem, now, hosts, defaultParseX509)
expect(r).toMatchObject({ ok: false, reason: 'chain_invalid' })
})
it('reports unparseable_cert when the leaf PEM is garbage', async () => {
const hosts = fakeHostRegistry([makeHost('acct-A', 'host-1')])
const r = await verifyAgentCert('not-a-cert', caChainPem, NOW, hosts, defaultParseX509)
expect(r).toMatchObject({ ok: false, reason: 'unparseable_cert' })
})
})
describe('rotation policy (T9)', () => {
it('false when fresh, true at ~50% TTL, true after expiry', () => {
const ttl = DEFAULT_ROTATION_PLAN.certTtlSeconds
const issuedAt = NOW
const notAfter = issuedAt + ttl
expect(shouldRotate(notAfter, issuedAt + 1, DEFAULT_ROTATION_PLAN)).toBe(false)
expect(shouldRotate(notAfter, issuedAt + ttl / 2, DEFAULT_ROTATION_PLAN)).toBe(true)
expect(shouldRotate(notAfter, notAfter + 100, DEFAULT_ROTATION_PLAN)).toBe(true)
})
})