From 2a602d5289160d709d675f7cc77e65cf2d0cf091 Mon Sep 17 00:00:00 2001 From: Yaojia Wang Date: Wed, 29 Jul 2026 10:40:15 +0200 Subject: [PATCH] fix(tunnel): close the three leftovers from the renewal-deadlock fix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. `.gitignore` swallowed a source file. `agent/src/dist/buildBinary.ts` is the packaging config, not build output, but the blanket `dist/` rule meant it was never committed — a fresh clone could neither typecheck `agent/src/index.ts` nor import it from the committed `agent/test/buildBinary.test.ts`. Re-included the DIRECTORY first (git does not descend into an excluded one, so un-ignoring just the file would not have worked) and committed the file. Verified build output under `agent/dist/`, `dist/`, `public/build/` is still ignored. 2. Tunnel logs named no host. `pair` learned hostId/subdomain from the enroll response and threw them away, so the long-running `run` process logged `{"subdomain":null,"hostId":null}` — including all 6380 warnings during the 8-day outage, at exactly the moment you want to know which host. New `config/hostRecord.ts` persists them at enrol; `resolveHostIdentity` resolves config > record > the subdomain embedded in the leaf's SPIFFE SAN, so hosts enrolled before the record existed get an identifier back without re-pairing. 3. The phone track had no recovery path. Added `POST /device/:id/recover`, mirroring the host route: cert in the body, device-CA path validation, SPIFFE parse, `notBefore` never graced, and the full registry check (active + same account + `:id` matches the cert + same key) — only `notAfter` is relaxed. Verified: agent 300/300, control-plane 296/296, tsc clean on both. NOTE: the iOS/Android clients are not wired to call /device/:id/recover yet — the server capability exists, the client-side trigger does not. --- .gitignore | 7 ++ agent/src/certs/nativeRenew.ts | 6 +- agent/src/cli/deps.ts | 7 +- agent/src/config/hostRecord.ts | 97 ++++++++++++++++++ agent/src/dist/buildBinary.ts | 45 +++++++++ agent/test/hostRecord.test.ts | 126 +++++++++++++++++++++++ control-plane/src/api/renew.ts | 48 +++++++++ control-plane/test/renew.test.ts | 129 ++++++++++++++++++++++++ deploy/nginx/enroll-recover-location.md | 16 ++- 9 files changed, 478 insertions(+), 3 deletions(-) create mode 100644 agent/src/config/hostRecord.ts create mode 100644 agent/src/dist/buildBinary.ts create mode 100644 agent/test/hostRecord.test.ts diff --git a/.gitignore b/.gitignore index d0d37f2..747972f 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,13 @@ node_modules/ # build output dist/ +# EXCEPTION: `agent/src/dist/` holds SOURCE (the packaging config for the distributable binary), +# not build output. The blanket `dist/` above swallowed it, so it was never committed — a fresh +# clone was missing it and could neither typecheck `agent/src/index.ts` nor import it from the +# committed `agent/test/buildBinary.test.ts`. The directory must be re-included FIRST: git does not +# descend into an excluded directory, so un-ignoring only the file inside it would not work. +!agent/src/dist/ +!agent/src/dist/** public/build/ desktop/build/ desktop/dist-app/ diff --git a/agent/src/certs/nativeRenew.ts b/agent/src/certs/nativeRenew.ts index 03b91fa..77db0b3 100644 --- a/agent/src/certs/nativeRenew.ts +++ b/agent/src/certs/nativeRenew.ts @@ -18,6 +18,7 @@ */ import { request as httpsRequest } from 'node:https' import type { AgentConfig } from '../config/agentConfig.js' +import { resolveHostIdentity } from '../config/hostRecord.js' import type { Keystore } from '../keys/keystore.js' import type { Logger } from '../log/logger.js' import type { TimerLike } from '../transport/seams.js' @@ -265,5 +266,8 @@ export function startNativeAutoRenew( ? { retryBackoff: createBackoff({ baseMs: opts.retryBaseMs, jitter: false }) } : {}), }) - return wireAutoRenew(rotator, hooks, logger, { subdomain: cfg.subdomain, hostId: cfg.hostId }) + // Prefer the resolved identity (config > enrolment record > leaf SPIFFE SAN) so renewal warnings + // actually name the host — `cfg` alone is null on every install that predates the record. + const ids = resolveHostIdentity(cfg, () => ks.loadCert()?.certPem ?? null) + return wireAutoRenew(rotator, hooks, logger, ids) } diff --git a/agent/src/cli/deps.ts b/agent/src/cli/deps.ts index c2616c4..3aa402e 100644 --- a/agent/src/cli/deps.ts +++ b/agent/src/cli/deps.ts @@ -13,6 +13,7 @@ import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import type { CliDeps, NativeEnrollResult } from '../cli.js' import type { AgentConfig } from '../config/agentConfig.js' +import { resolveHostIdentity, saveHostRecord } from '../config/hostRecord.js' import { loadAgentConfig } from '../config/agentConfig.js' import { openKeystore } from '../keys/keystore.js' import { generateIdentity, generateP256Identity } from '../keys/identity.js' @@ -100,6 +101,9 @@ async function enrollNative( ks: Keystore, ): Promise { const enroll = await redeemPairingCode(cfg.enrollUrl, code, id, ks, { allowMissingContentSecret: true }) + // Write the identifiers down: the long-running `run` process has no other way to learn them, and + // without them every log line from the tunnel reads `{"subdomain":null,"hostId":null}`. + saveHostRecord(cfg.stateDir, { hostId: enroll.hostId, subdomain: enroll.subdomain }) return { hostId: enroll.hostId, subdomain: enroll.subdomain } } @@ -184,7 +188,8 @@ function superviseNative(cfg: AgentConfig, ks: Keystore): Promise { }), (report) => { // INV9: only non-secret identifiers (subdomain/host id/expiry date) + boolean flags are logged. - const ids = { subdomain: cfg.subdomain, hostId: cfg.hostId, certNotAfter: certNotAfter(ks) } + const host = resolveHostIdentity(cfg, () => ks.loadCert()?.certPem ?? null) + const ids = { ...host, certNotAfter: certNotAfter(ks) } for (const line of renderHealthStatus(ids, report)) logger.log('info', line) }, ) diff --git a/agent/src/config/hostRecord.ts b/agent/src/config/hostRecord.ts new file mode 100644 index 0000000..585fecf --- /dev/null +++ b/agent/src/config/hostRecord.ts @@ -0,0 +1,97 @@ +/** + * Enrolment identifiers (`hostId` / `subdomain`) persisted next to the keystore. + * + * WHY: `pair --install` learns both from the control-plane's enroll response, but nothing ever wrote + * them down — so the long-running `run` process had `cfg.subdomain === null` and `cfg.hostId === null` + * and every log line came out as `{"subdomain":null,"hostId":null}`. When the tunnel broke in + * production, 6380 warnings named no host at all, which is exactly the moment you want them to. + * + * They are NOT secrets (the subdomain is a public DNS label), so this is a plain JSON file — kept in + * `stateDir` only because that is the one directory the agent already owns on every platform. + * + * Legacy installs enrolled before this existed have no record. Their leaf still carries the + * subdomain in its SPIFFE URI SAN, so `resolveHostIdentity` recovers it from there rather than + * forcing a re-pair just to get an identifier back into the logs. + */ +import { X509Certificate } from 'node:crypto' +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import type { AgentConfig } from './agentConfig.js' + +const RECORD_FILE = 'host.json' +const DIR_MODE = 0o700 + +/** Non-secret identifiers assigned by the control-plane at enrolment. */ +export interface HostRecord { + readonly hostId: string | null + readonly subdomain: string | null +} + +/** A non-empty string, or null — anything else on disk is treated as absent (never trusted). */ +function stringOrNull(value: unknown): string | null { + return typeof value === 'string' && value.length > 0 ? value : null +} + +/** Persist the enrolment identifiers into `stateDir`. Overwrites any previous record. */ +export function saveHostRecord(stateDir: string, record: HostRecord): void { + if (!existsSync(stateDir)) mkdirSync(stateDir, { recursive: true, mode: DIR_MODE }) + writeFileSync(join(stateDir, RECORD_FILE), `${JSON.stringify(record, null, 2)}\n`) +} + +/** + * Read the persisted identifiers, or null if this host has none. A missing, unreadable, or + * malformed file is reported as "no record" — this feeds a logging path and must never throw into + * the run loop. + */ +export function loadHostRecord(stateDir: string): HostRecord | null { + const path = join(stateDir, RECORD_FILE) + if (!existsSync(path)) return null + try { + const parsed: unknown = JSON.parse(readFileSync(path, 'utf8')) + if (typeof parsed !== 'object' || parsed === null) return null + const rec = parsed as Record + return { hostId: stringOrNull(rec['hostId']), subdomain: stringOrNull(rec['subdomain']) } + } catch { + return null + } +} + +/** SPIFFE IDs issued for hosts end in `/host/` (see relay-auth `spiffeIdFor`). */ +const SPIFFE_HOST_RE = /URI:(spiffe:\/\/[^\s,]*\/host\/([^\s,/]+))/ + +/** + * Recover the subdomain from a leaf's SPIFFE URI SAN, or null if it carries none. Parse failures + * are null, never throws — a legacy install with a damaged cert must still start. + */ +export function subdomainFromCertPem(certPem: string): string | null { + try { + const san = new X509Certificate(certPem).subjectAltName ?? '' + const match = SPIFFE_HOST_RE.exec(san) + return match?.[2] ?? null + } catch { + return null + } +} + +/** + * Resolve the identifiers to log for this host, most authoritative first: + * 1. explicit config (argv/env `SUBDOMAIN` / `HOST_ID`) — an operator override always wins; + * 2. the enrolment record written by `pair`; + * 3. the subdomain embedded in the stored leaf (legacy installs; yields no hostId). + * + * `readCertPem` is injected so this stays a pure decision over a supplied cert. + */ +export function resolveHostIdentity( + cfg: AgentConfig, + readCertPem: () => string | null, +): HostRecord { + const record = loadHostRecord(cfg.stateDir) + const subdomain = + cfg.subdomain ?? + record?.subdomain ?? + ((): string | null => { + const pem = readCertPem() + return pem === null ? null : subdomainFromCertPem(pem) + })() + return { hostId: cfg.hostId ?? record?.hostId ?? null, subdomain } +} diff --git a/agent/src/dist/buildBinary.ts b/agent/src/dist/buildBinary.ts new file mode 100644 index 0000000..8230b9e --- /dev/null +++ b/agent/src/dist/buildBinary.ts @@ -0,0 +1,45 @@ +/** + * Static-binary build spec — PLAN_RELAY_AGENT T16 (EXPLORE §6 distribution rank 2). Produces a + * `bun --compile` spec for a one-`curl | sh` install. `npx web-terminal-agent` stays the MVP path + * (rank 1). The bundle EXCLUDES dev/test deps and any terminal parser (INV11 re-check at the + * package boundary — the agent is a byte-shuttle, never an ANSI interpreter). + */ +export type BinaryTarget = 'darwin-arm64' | 'darwin-x64' | 'linux-x64' | 'linux-arm64' + +export const BINARY_TARGETS: readonly BinaryTarget[] = [ + 'darwin-arm64', + 'darwin-x64', + 'linux-x64', + 'linux-arm64', +] + +export interface BuildSpec { + readonly tool: 'bun' + readonly entry: string + readonly target: BinaryTarget + readonly bunTarget: string // bun's --target triple + readonly outfile: string + readonly minify: true + /** Package-name substrings that must NOT appear in the bundle graph (INV11 tripwire). */ + readonly forbiddenDeps: readonly string[] +} + +const BUN_TRIPLE: Readonly> = { + 'darwin-arm64': 'bun-darwin-arm64', + 'darwin-x64': 'bun-darwin-x64', + 'linux-x64': 'bun-linux-x64', + 'linux-arm64': 'bun-linux-arm64', +} + +/** Build the `bun --compile` spec for a target triple. Entry is the CLI. */ +export function buildBinaryConfig(target: BinaryTarget): BuildSpec { + return { + tool: 'bun', + entry: 'src/cli.ts', + target, + bunTarget: BUN_TRIPLE[target], + outfile: `dist/web-terminal-agent-${target}`, + minify: true, + forbiddenDeps: ['xterm', 'ansi', 'vt100'], + } +} diff --git a/agent/test/hostRecord.test.ts b/agent/test/hostRecord.test.ts new file mode 100644 index 0000000..9cabd13 --- /dev/null +++ b/agent/test/hostRecord.test.ts @@ -0,0 +1,126 @@ +import { describe, expect, it } from 'vitest' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { AgentConfig } from '../src/config/agentConfig.js' +import { + loadHostRecord, + resolveHostIdentity, + saveHostRecord, + subdomainFromCertPem, +} from '../src/config/hostRecord.js' + +const CFG: AgentConfig = { + relayUrl: 'wss://relay/agent', + enrollUrl: 'https://enroll.terminal.example.com/enroll', + stateDir: '/tmp/x', + localTargetUrl: 'ws://127.0.0.1:3000', + subdomain: null, + hostId: null, +} + +function tmpState(): string { + return mkdtempSync(join(tmpdir(), 'wta-hr-')) +} + +/** A real frp-client leaf as issued by the control-plane (SPIFFE URI SAN carries the subdomain). */ +const LEAF_PEM = `-----BEGIN CERTIFICATE----- +MIIB1TCCAXygAwIBAgIUUj+CZ+6p29yI59VpyrekwSp9tAgwCgYIKoZIzj0EAwIw +EDEOMAwGA1UEAwwFaDdmZDgwHhcNMjYwNzI5MDgzNzIyWhcNMzYwNzI2MDgzNzIy +WjAQMQ4wDAYDVQQDDAVoN2ZkODBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABACg +xWQCQuxawnkkPZIgagEFtG0oBiuron4SSw3U1Q0FwCSH3BJep1MJtIuEQU3HfM4N +6Tk5kW4MWuIM8sNriiqjgbMwgbAwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMC +B4AwEwYDVR0lBAwwCgYIKwYBBQUHAwIwXAYDVR0RBFUwU4IaaDdmZDgudGVybWlu +YWwuZXhhbXBsZS5jb22GNXNwaWZmZTovL3JlbGF5LmV4YW1wbGUuY29tL2FjY291 +bnQvYWNjLTEyMy9ob3N0L2g3ZmQ4MB0GA1UdDgQWBBSy/SJwjH/lm8TaY5Yk/TF+ +wpg78TAKBggqhkjOPQQDAgNHADBEAiAjq1o5xpk+iF55uVfdyLP/a9OC09O0mN4P +YRk8x5MFaQIgYC3GTWqkwu0azrdffKl6jX0stbG+oM+0Cx2Cn7wy27c= +-----END CERTIFICATE-----` + +describe('host record persistence', () => { + it('round-trips the enrolment identifiers through stateDir', () => { + const dir = tmpState() + saveHostRecord(dir, { hostId: 'h-1', subdomain: 'h7fd8' }) + expect(loadHostRecord(dir)).toEqual({ hostId: 'h-1', subdomain: 'h7fd8' }) + rmSync(dir, { recursive: true, force: true }) + }) + + it('returns null when nothing was ever enrolled here', () => { + const dir = tmpState() + expect(loadHostRecord(dir)).toBeNull() + rmSync(dir, { recursive: true, force: true }) + }) + + it('treats a corrupt record as absent rather than throwing (never crashes the run loop)', () => { + const dir = tmpState() + writeFileSync(join(dir, 'host.json'), '{not json') + expect(loadHostRecord(dir)).toBeNull() + rmSync(dir, { recursive: true, force: true }) + }) + + it('ignores a record whose fields are the wrong shape', () => { + const dir = tmpState() + writeFileSync(join(dir, 'host.json'), JSON.stringify({ hostId: 42, subdomain: [] })) + expect(loadHostRecord(dir)).toEqual({ hostId: null, subdomain: null }) + rmSync(dir, { recursive: true, force: true }) + }) +}) + +describe('subdomainFromCertPem', () => { + it('reads the subdomain out of the leaf SPIFFE URI SAN', () => { + expect(subdomainFromCertPem(LEAF_PEM)).toBe('h7fd8') + }) + + it('returns null for a certificate with no SPIFFE SAN', () => { + expect(subdomainFromCertPem('-----BEGIN CERTIFICATE-----\nnope\n-----END CERTIFICATE-----')).toBeNull() + }) + + it('returns null for garbage instead of throwing', () => { + expect(subdomainFromCertPem('not a cert')).toBeNull() + }) +}) + +describe('resolveHostIdentity precedence', () => { + it('keeps explicit config (env/argv) over everything else', () => { + const dir = tmpState() + saveHostRecord(dir, { hostId: 'from-file', subdomain: 'from-file' }) + const out = resolveHostIdentity( + { ...CFG, stateDir: dir, subdomain: 'from-env', hostId: 'from-env' }, + () => LEAF_PEM, + ) + expect(out).toEqual({ hostId: 'from-env', subdomain: 'from-env' }) + rmSync(dir, { recursive: true, force: true }) + }) + + it('falls back to the persisted enrolment record', () => { + const dir = tmpState() + saveHostRecord(dir, { hostId: 'h-1', subdomain: 'h7fd8' }) + expect(resolveHostIdentity({ ...CFG, stateDir: dir }, () => null)).toEqual({ + hostId: 'h-1', + subdomain: 'h7fd8', + }) + rmSync(dir, { recursive: true, force: true }) + }) + + /** + * Hosts enrolled before the record existed have no `host.json`. Their leaf still carries the + * subdomain, so they get an identifier in the logs without needing a re-pair. + */ + it('falls back to the leaf SPIFFE SAN when there is no record (legacy installs)', () => { + const dir = tmpState() + expect(resolveHostIdentity({ ...CFG, stateDir: dir }, () => LEAF_PEM)).toEqual({ + hostId: null, + subdomain: 'h7fd8', + }) + rmSync(dir, { recursive: true, force: true }) + }) + + it('yields nulls when nothing is known (unenrolled host)', () => { + const dir = tmpState() + expect(resolveHostIdentity({ ...CFG, stateDir: dir }, () => null)).toEqual({ + hostId: null, + subdomain: null, + }) + rmSync(dir, { recursive: true, force: true }) + }) +}) diff --git a/control-plane/src/api/renew.ts b/control-plane/src/api/renew.ts index f868f75..b7164c2 100644 --- a/control-plane/src/api/renew.ts +++ b/control-plane/src/api/renew.ts @@ -433,6 +433,54 @@ export function buildRenewRouter(deps: RenewDeps): FastifyPluginAsync { } }) + /** + * Device counterpart of `/recover` (phone track). Same reason it exists, same shape: the lapsed + * cert arrives in the BODY because no terminator forwards an expired client certificate, so this + * route is the sole verifier — device-CA path validation, SPIFFE parse, `notBefore`, and the full + * registry consistency check (active + same account + `:id` matches the cert + same key). Only + * the `notAfter` bound is relaxed, by `expiredRenewGraceMs`. + */ + app.post('/device/:id/recover', async (req, reply) => { + try { + const body = RecoverBodySchema.parse(req.body) + const der = certWireToDer(body.cert) + if (der === null) throw new RenewRejectError(401) + const identity = parsePresentedCertIdentity( + der, + 'device', + deps.deviceCaAnchorsDer + ? { + caAnchorsDer: deps.deviceCaAnchorsDer, + nowMs: Date.now(), + expiredGraceMs: recoverGraceMs, + } + : undefined, + ) + const id = (req.params as { id: string }).id + rateLimiter.check(`device-recover:${identity.id}`) + + const record = await deps.devices.getDevice(id) + if ( + record === null || + record.status === 'revoked' || + record.accountId !== identity.accountId || + identity.id !== id || + !timingSafeEqualBytes(record.ecPubkeySpki, identity.publicKeySpki) + ) { + throw new RenewRejectError(403) + } + + const leaf = await deps.renewer.renewDeviceLeaf(id, decodeCsrWire(body.csr)) + await reply.code(201).send({ + cert: bytesToBase64(leaf.cert), + caChain: leaf.caChain.map((c) => bytesToBase64(c)), + notAfter: leaf.notAfter.toISOString(), + }) + } catch (err) { + sendError(reply, err) + } + }) + app.post('/device/:id/renew', async (req, reply) => { try { const der = presentedCert.presentedCertDer(req) diff --git a/control-plane/test/renew.test.ts b/control-plane/test/renew.test.ts index 92505af..d76d77e 100644 --- a/control-plane/test/renew.test.ts +++ b/control-plane/test/renew.test.ts @@ -672,3 +672,132 @@ describe('CP6d POST /recover — expired-leaf recovery', () => { expect(res.statusCode).toBe(401) }) }) + +/** + * CP6e · POST /device/:id/recover — the phone-track counterpart of `/recover`. + * + * A device certificate hits the identical deadlock as a host leaf: `/device/:id/renew` is + * mTLS-authenticated by the cert being renewed, and nginx refuses to forward an expired client cert + * in any mode. Without this route a phone whose cert lapsed has to be re-enrolled by hand. + */ +describe('CP6e POST /device/:id/recover — expired device-cert recovery', () => { + async function mintDeviceLeaf( + ctx: DeviceCtx, + accountId: string, + notBefore: Date, + notAfter: Date, + signer = ctx.ca.caSigner, + ): Promise { + const spiffe = `spiffe://relay.terminal.yaojia.wang/account/${accountId}/device/${ctx.deviceId}` + return assembleCertificate({ + subjectPublicKey: ctx.spki, + subject: `CN=web-terminal-device`, + issuer: ctx.ca.caCert.subjectName, + serialNumber: Uint8Array.from([0x0d]), + notBefore, + notAfter, + extensions: [ + new x509.SubjectAlternativeNameExtension([ + { type: 'dns', value: `alice.${ZONE}` }, + { type: 'url', value: spiffe }, + ]), + new x509.BasicConstraintsExtension(false, undefined, true), + new x509.KeyUsagesExtension(x509.KeyUsageFlags.digitalSignature, true), + new x509.ExtendedKeyUsageExtension([x509.ExtendedKeyUsage.clientAuth]), + ], + signer, + sigAlg: 'ecdsa-p256', + }) + } + + const b64 = (der: Uint8Array): string => Buffer.from(der).toString('base64') + + async function post(ctx: DeviceCtx, cert: Uint8Array, extra?: Partial) { + const app = appWith({ ...deviceDeps(ctx), deviceCaAnchorsDer: [ctx.ca.caDer], ...extra }) + await app.ready() + return app.inject({ + method: 'POST', + url: `/device/${ctx.deviceId}/recover`, + payload: { cert: b64(cert), csr: b64Csr(ctx.csr) }, + }) + } + + test('a device cert expired INSIDE the grace window is re-issued → 201', async () => { + const ctx = await deviceCtx('alice') + const rec = await ctx.devices.getDevice(ctx.deviceId) + const now = Date.now() + const res = await post( + ctx, + await mintDeviceLeaf(ctx, rec!.accountId, new Date(now - 9 * DAY_MS), new Date(now - 8 * DAY_MS)), + ) + expect(res.statusCode).toBe(201) + expect(JSON.parse(res.payload).cert).toBeTruthy() + }) + + test('a device cert expired BEYOND the grace window is refused → 401', async () => { + const ctx = await deviceCtx('alice') + const rec = await ctx.devices.getDevice(ctx.deviceId) + const now = Date.now() + const res = await post( + ctx, + await mintDeviceLeaf(ctx, rec!.accountId, new Date(now - 60 * DAY_MS), new Date(now - 31 * DAY_MS)), + ) + expect(res.statusCode).toBe(401) + }) + + /** Same load-bearing check as the host route: nginx validates nothing on this path. */ + test('a self-signed cert with a FORGED device SPIFFE SAN is refused → 401', async () => { + const ctx = await deviceCtx('alice') + const rogueCa = await makeP256Ca('rogue-CA') + const rec = await ctx.devices.getDevice(ctx.deviceId) + const now = Date.now() + const res = await post( + ctx, + await mintDeviceLeaf( + ctx, + rec!.accountId, + new Date(now - 9 * DAY_MS), + new Date(now - 8 * DAY_MS), + rogueCa.caSigner, + ), + ) + expect(res.statusCode).toBe(401) + }) + + test('recovery NEVER bypasses revocation — revoked device → 403', async () => { + const ctx = await deviceCtx('alice') + const rec = await ctx.devices.getDevice(ctx.deviceId) + const now = Date.now() + const cert = await mintDeviceLeaf(ctx, rec!.accountId, new Date(now - 9 * DAY_MS), new Date(now - 8 * DAY_MS)) + await ctx.devices.setDeviceStatus(ctx.deviceId, 'revoked') + const res = await post(ctx, cert) + expect(res.statusCode).toBe(403) + }) + + test('the path :id must match the cert identity — no cross-device smuggling → 403', async () => { + const ctx = await deviceCtx('alice') + const rec = await ctx.devices.getDevice(ctx.deviceId) + const now = Date.now() + const cert = await mintDeviceLeaf(ctx, rec!.accountId, new Date(now - 9 * DAY_MS), new Date(now - 8 * DAY_MS)) + const app = appWith({ ...deviceDeps(ctx), deviceCaAnchorsDer: [ctx.ca.caDer] }) + await app.ready() + const res = await app.inject({ + method: 'POST', + url: `/device/someone-else/recover`, + payload: { cert: b64(cert), csr: b64Csr(ctx.csr) }, + }) + expect(res.statusCode).toBe(403) + }) + + test('grace 0 disables device recovery entirely → 401', async () => { + const ctx = await deviceCtx('alice') + const rec = await ctx.devices.getDevice(ctx.deviceId) + const now = Date.now() + const res = await post( + ctx, + await mintDeviceLeaf(ctx, rec!.accountId, new Date(now - 2 * DAY_MS), new Date(now - DAY_MS)), + { expiredRenewGraceMs: 0 }, + ) + expect(res.statusCode).toBe(401) + }) +}) diff --git a/deploy/nginx/enroll-recover-location.md b/deploy/nginx/enroll-recover-location.md index 6a611fe..bb5fed4 100644 --- a/deploy/nginx/enroll-recover-location.md +++ b/deploy/nginx/enroll-recover-location.md @@ -45,7 +45,10 @@ and it is still proven end to end: Worst case for a replayed cert without the key: the attacker receives a certificate they cannot authenticate with. Revocation still bites, via registry status. -## The block to add +## The blocks to add + +Two routes, same rationale: `/recover` re-issues an expired **host** frp-client leaf, +`/device/:id/recover` does the same for an expired **device** cert (phone track). ```nginx # Expired-leaf recovery: NO client cert (see enroll-recover-location.md). The control-plane is @@ -58,6 +61,17 @@ authenticate with. Revocation still bites, via registry status. proxy_set_header x-client-cert ""; proxy_read_timeout 60s; } + # Same, for an expired DEVICE cert. Must sit ABOVE the `~ ^/device/[^/]+/renew$` mTLS location + # only if that regex could also match `/recover` — it cannot, but keep them adjacent so the pair + # is obvious to the next editor. + location ~ ^/device/[^/]+/recover$ { + limit_req zone=renew_recover burst=5 nodelay; + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header x-client-cert ""; + proxy_read_timeout 60s; + } ``` And once, in the `http` context (top of `enroll.conf` is fine) — the route is reachable