Files
web-terminal/control-plane/test/device-enroll.test.ts
Yaojia Wang e7f3bd05f0 feat(tunnel): zero-touch tunnel enrollment — control-plane PKI, host agent, iOS, nginx isolation
Customers install one command / log in once; hardware-generated keys never leave the
device; CSRs return certs + subdomain; frpc + base-app run as durable services. No .p12,
no manual cert import. Implements the MVP fast-path of docs/PLAN_TUNNEL_AUTOMATION.md.

Control-plane / PKI (control-plane/):
- ca/x509-assembler.ts: single KMS-signed real X.509 issuance primitive (Ed25519 + P-256)
- ca/csr-ec.ts: P-256 PKCS#10 proof-of-possession (verifyCsrPoPEc) + CSR-key routing
- ca/frpclient-issue.ts, ca/device-issue.ts: P-256 frp-client + device leaf signers
- ca/rotate.ts + api/renew.ts: real-X.509 /renew + /device/:id/renew (mTLS current cert)
- registry/devices.ts: device registry + per-account cap/rate-limit
- auth/session.ts: device:enroll capability token mint/verify
- api/device-enroll.ts: POST /device/enroll (ownership-gated, deny-by-default)
- pairing/native-redeem.ts + shared gateAndConsumePairingCode; api/provision.ts native arm
- boot/native-ca.ts + main.ts: wire two P-256 CAs + issuers + routers (dev / KMS fail-fast)

Contracts: relay-contracts enroll right; relay-auth SPIFFE /device/ arm + spiffeIdFor(kind)

Host agent (agent/):
- transport/frpcToml.ts; provision/frpcBinary.ts + untar.ts (verify-download + traversal-safe extract)
- keys P-256 keygen/CSR/loadIdentity; service two-unit install + BIND_HOST loopback S-GATE
- net/loopbackLiteral.ts strict guard; health/probe.ts + transport/frpSupervise.ts; cli pair --install

iOS (ios/Packages/ClientTLS): SecureEnclaveKey + CertificateSigningRequest + DeviceEnrollmentClient
+ Keychain enroll refactor (SecKey/Security.framework end-to-end, avoids the -25300 trap)

Isolation (deploy/nginx): njs/getCertSub.js SAN parser + zone-anchored map -> 403

Verified: 758 tests green (control-plane 246, agent 267, relay-auth 133, relay-contracts 85,
iOS ClientTLS 27), all tsc clean; real nginx+njs docker 403/200/400; Swift CSR accepted by
the real control-plane verifier; frpc extract byte-identical to `tar -xO`. Cross-validation
caught + fixed 5 real defects (1 critical, 4 high). Remaining = infra (KMS, nginx deploy,
VPS frps, physical iPhone) per PROGRESS_LOG runbook.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 16:11:13 +02:00

261 lines
9.9 KiB
TypeScript

/**
* A4 — POST /device/enroll + /device/attest/challenge (fastify inject, mirrors test/api.test.ts).
* Proves: a valid device:enroll bearer + valid P-256 CSR → 201 with a real X.509 leaf; missing /
* invalid / wrong-right bearers → 401/403 (uniform); over-cap → 429; a malformed CSR → uniform
* reject; the attest challenge stub returns a bound challenge. The bearer is verified through the
* SAME injected `CapabilityVerifier` seam the admin API uses (boot/verifier.ts in production).
*/
import 'reflect-metadata'
import { describe, test, expect, beforeEach } from 'vitest'
import Fastify, { type FastifyInstance } from 'fastify'
import * as x509 from '@peculiar/x509'
import { webcrypto } from 'node:crypto'
import type { CapabilityToken, CapabilityRight } from 'relay-contracts'
import type { CapabilityVerifier } from '../src/api/authz.js'
import { buildCsrEc } from '../src/ca/csr-ec.js'
import { inProcessP256CaSigner } from '../src/boot/ca-wiring.js'
import { createDeviceLeafSigner } from '../src/ca/device-issue.js'
import { createDeviceRegistry, createMemoryDeviceStore } from '../src/registry/devices.js'
import {
buildDeviceEnrollRouter,
type DeviceEnrollDeps,
type SubdomainOwnershipResolver,
} from '../src/api/device-enroll.js'
import { DEVICE_ENROLL_AUD } from '../src/auth/session.js'
x509.cryptoProvider.set(webcrypto)
const ACCOUNT_A = '11111111-1111-4111-8111-111111111111'
const ACCOUNT_B = '22222222-2222-4222-8222-222222222222'
// Fake verifier mirroring api.test.ts: 'enrollA'/'enrollB'→enroll right; 'attachA'→attach only; else reject.
const verifier: CapabilityVerifier = {
async verify(raw, expectedAud, now): Promise<CapabilityToken> {
const base = { aud: expectedAud, host: 'x', iat: now, exp: now + 600, jti: `jti-${raw}` }
if (raw === 'enrollA') return { ...base, sub: ACCOUNT_A, rights: ['enroll'] as CapabilityRight[] }
if (raw === 'enrollB') return { ...base, sub: ACCOUNT_B, rights: ['enroll'] as CapabilityRight[] }
if (raw === 'attachA') return { ...base, sub: ACCOUNT_A, rights: ['attach'] as CapabilityRight[] }
throw new Error('invalid token')
},
}
// Ownership source of truth (host-onboarding registry in production). ACCOUNT_A owns 'alice' + 'bob';
// everything else is unclaimed → deny-by-default.
const SUBDOMAIN_OWNERS: Readonly<Record<string, string>> = { alice: ACCOUNT_A, bob: ACCOUNT_A }
const ownership: SubdomainOwnershipResolver = {
async ownerOfSubdomain(sub) {
return SUBDOMAIN_OWNERS[sub] ?? null
},
}
async function csrBody(subdomain = 'alice'): Promise<Record<string, unknown>> {
const { der } = await buildCsrEc('CN=web-terminal-device')
return { csr: Buffer.from(der).toString('base64'), keyAlg: 'ec-p256', subdomain, deviceName: 'iphone' }
}
// The registry and the leaf signer MUST share ONE DeviceStore so the signer's gate finds the
// device the route just registered (mirrors host store sharing between registry + createRealLeafSigner).
function buildApp(opts: { deviceCap?: number; rateMax?: number } = {}): FastifyInstance {
const ca = inProcessP256CaSigner()
const store = createMemoryDeviceStore()
const deps: DeviceEnrollDeps = {
verifier,
ownership,
devices: createDeviceRegistry({ devices: store, deviceCap: opts.deviceCap ?? 5, rateMax: opts.rateMax ?? 50 }),
signer: createDeviceLeafSigner({
signer: ca,
issuer: 'CN=device-CA',
caChainDer: [ca.publicKeyRaw],
sanBaseDomain: 'terminal.yaojia.wang',
trustDomain: 'example.com',
devices: store,
}),
}
const app = Fastify({ logger: false })
void app.register(buildDeviceEnrollRouter(deps))
return app
}
let app: FastifyInstance
beforeEach(async () => {
app = buildApp()
await app.ready()
})
describe('A4 POST /device/enroll', () => {
test('valid enroll bearer + valid P-256 CSR → 201 with a real cert', async () => {
const res = await app.inject({
method: 'POST',
url: '/device/enroll',
headers: { authorization: 'Bearer enrollA' },
payload: await csrBody(),
})
expect(res.statusCode).toBe(201)
const body = JSON.parse(res.body)
expect(body.deviceId.length).toBeGreaterThan(0)
expect(Array.isArray(body.caChain)).toBe(true)
expect(typeof body.notAfter).toBe('string')
expect(typeof body.renewAfter).toBe('string')
// the returned cert is a real, re-parseable X.509 leaf
const der = new Uint8Array(Buffer.from(body.cert, 'base64'))
const leaf = new x509.X509Certificate(der)
const san = leaf.getExtension(x509.SubjectAlternativeNameExtension)
expect(san!.names.toJSON()).toContainEqual({ type: 'dns', value: 'alice.terminal.yaojia.wang' })
})
test('missing bearer → 401', async () => {
const res = await app.inject({ method: 'POST', url: '/device/enroll', payload: await csrBody() })
expect(res.statusCode).toBe(401)
})
test('invalid bearer → 401', async () => {
const res = await app.inject({
method: 'POST',
url: '/device/enroll',
headers: { authorization: 'Bearer bogus' },
payload: await csrBody(),
})
expect(res.statusCode).toBe(401)
})
test('wrong-right bearer (attach, not enroll) → 403', async () => {
const res = await app.inject({
method: 'POST',
url: '/device/enroll',
headers: { authorization: 'Bearer attachA' },
payload: await csrBody(),
})
expect(res.statusCode).toBe(403)
})
test('malformed body → 400 (Zod at the boundary)', async () => {
const res = await app.inject({
method: 'POST',
url: '/device/enroll',
headers: { authorization: 'Bearer enrollA' },
payload: { csr: '', keyAlg: 'rsa', subdomain: 'alice' },
})
expect(res.statusCode).toBe(400)
})
test('malformed CSR (valid shape, bad DER) → uniform reject 400', async () => {
const res = await app.inject({
method: 'POST',
url: '/device/enroll',
headers: { authorization: 'Bearer enrollA' },
payload: { csr: Buffer.from([0, 1, 2, 3]).toString('base64'), keyAlg: 'ec-p256', subdomain: 'alice', deviceName: 'x' },
})
expect(res.statusCode).toBe(400)
})
test('over per-account device cap → 429', async () => {
const capped = buildApp({ deviceCap: 1, rateMax: 50 })
await capped.ready()
const ok = await capped.inject({
method: 'POST',
url: '/device/enroll',
headers: { authorization: 'Bearer enrollA' },
payload: await csrBody('alice'),
})
expect(ok.statusCode).toBe(201)
const over = await capped.inject({
method: 'POST',
url: '/device/enroll',
headers: { authorization: 'Bearer enrollA' },
payload: await csrBody('bob'),
})
expect(over.statusCode).toBe(429)
})
test('over per-account rate-limit → 429', async () => {
const limited = buildApp({ deviceCap: 50, rateMax: 1 })
await limited.ready()
const first = await limited.inject({
method: 'POST',
url: '/device/enroll',
headers: { authorization: 'Bearer enrollA' },
payload: await csrBody('alice'),
})
expect(first.statusCode).toBe(201)
const second = await limited.inject({
method: 'POST',
url: '/device/enroll',
headers: { authorization: 'Bearer enrollA' },
payload: await csrBody('bob'),
})
expect(second.statusCode).toBe(429)
})
// ── Tenant-isolation gate (FIX C-native-3 / H-native-4) ──────────────────────────────────────────
test('account B requesting account A\'s subdomain → 403, no cert issued', async () => {
const res = await app.inject({
method: 'POST',
url: '/device/enroll',
headers: { authorization: 'Bearer enrollB' }, // valid enroll bearer for a DIFFERENT account
payload: await csrBody('alice'), // owned by ACCOUNT_A
})
expect(res.statusCode).toBe(403)
expect(JSON.parse(res.body).cert).toBeUndefined() // rejected before registration + issuance
})
test('unclaimed subdomain → 403 (uniform with foreign-owned: no existence oracle)', async () => {
const res = await app.inject({
method: 'POST',
url: '/device/enroll',
headers: { authorization: 'Bearer enrollA' },
payload: await csrBody('nobody'), // ACCOUNT_A does not own it
})
expect(res.statusCode).toBe(403)
})
test('reserved infra label (admin) → 400, never reaches a certificate SAN', async () => {
const res = await app.inject({
method: 'POST',
url: '/device/enroll',
headers: { authorization: 'Bearer enrollA' },
payload: await csrBody('admin'),
})
expect(res.statusCode).toBe(400)
})
test('subdomain that normalizes to an invalid label → 400', async () => {
const res = await app.inject({
method: 'POST',
url: '/device/enroll',
headers: { authorization: 'Bearer enrollA' },
payload: await csrBody('___'), // strips to empty → not a valid RFC-1123 label
})
expect(res.statusCode).toBe(400)
})
test('account A\'s own subdomain still enrolls (ownership gate does not affect the owner)', async () => {
const res = await app.inject({
method: 'POST',
url: '/device/enroll',
headers: { authorization: 'Bearer enrollA' },
payload: await csrBody('alice'),
})
expect(res.statusCode).toBe(201)
})
})
describe('A4 POST /device/attest/challenge (stub)', () => {
test('valid bearer → 200 with a challenge + expires_in 120', async () => {
const res = await app.inject({
method: 'POST',
url: '/device/attest/challenge',
headers: { authorization: 'Bearer enrollA' },
})
expect(res.statusCode).toBe(200)
const body = JSON.parse(res.body)
expect(typeof body.challenge).toBe('string')
expect(body.challenge.length).toBeGreaterThan(0)
expect(body.expires_in).toBe(120)
})
test('missing bearer → 401', async () => {
const res = await app.inject({ method: 'POST', url: '/device/attest/challenge' })
expect(res.statusCode).toBe(401)
})
})