Skip to content

Commit 2f5ff20

Browse files
committed
fix(cli): forward tls/protocol/node from an intercepted serve() entry
1 parent 2e7a135 commit 2f5ff20

8 files changed

Lines changed: 301 additions & 15 deletions

File tree

‎docs/1.guide/06.tls.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,4 +98,10 @@ While the plugin is active, [`request.tls`](/guide/handler#requesttls) provides:
9898
> - **Deno** (2.8+) — works through the Node adapter, which runs on Deno via `node:https`. (Native `Deno.serve` cannot request client certificates.)
9999
> - **Bun** — not currently supported: neither native `Bun.serve` nor Bun's `node:http(s)` server exposes the peer certificate to the handler, so the plugin throws. Tracked in [oven-sh/bun#16254](https://github.com/oven-sh/bun/issues/16254).
100100
101+
If a request nevertheless reaches the plugin over a plain (non-TLS) socket, it is answered with `496 Client certificate required` instead of running your handler with `request.tls` left `undefined`.
102+
103+
### Running a TLS entry through the CLI
104+
105+
An entry that configures `tls` (and `mtlsPlugin()`) keeps both when it is started with the [`srvx` CLI](/guide/cli): the CLI serves it over `https://` and preserves the client-certificate requirement. `--tls --cert --key` still take precedence over the entry's own settings. See [TLS precedence](/guide/cli#tls-precedence).
106+
101107
[PeerCertificate]: https://nodejs.org/api/tls.html#certificate-object

‎docs/1.guide/10.cli.md‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,16 @@ The port and host are resolved with the following precedence (highest first):
105105
3. Environment variable (`PORT` / `HOST`)
106106
4. Default (`3000` / all interfaces)
107107
108+
## TLS precedence
109+
110+
The CLI serves over HTTPS whenever TLS is configured, resolved with the following precedence (highest first):
111+
112+
1. CLI flags (`--tls --cert --key`) — `--tls` requires both `--cert` and `--key`
113+
2. Module option (`tls` exported from your server entry)
114+
3. The `tls` passed to a `serve()` call the entry makes itself (see [Loading entries that start a server](#loading-entries-that-start-a-server))
115+
116+
An entry configured for TLS is therefore served over `https://` under the CLI too, and the listening URL the CLI prints reflects that. As with a direct run, TLS also enables HTTP/2 (HTTP/1.1 still allowed). Mutual TLS configured through [`mtlsPlugin()`](/guide/tls#mutual-tls-mtls) is carried over as well, so the client-certificate requirement stays enforced.
117+
108118
## Exit codes
109119
110120
In **fetch mode**, `srvx fetch` exits with code **`22`** for any non-2xx response, and `0` for a 2xx response.
@@ -195,7 +205,7 @@ const loaded = await loadServerEntry({
195205
server = serve({ fetch: loaded.fetch!, port: 3000 });
196206
```
197207
198-
Anything the entry exports alongside its handler is on `loaded.module`, so you can read its [server options](/guide/options) and merge them with your own.
208+
Anything the entry exports alongside its handler is on `loaded.module`, so you can read its [server options](/guide/options) and merge them with your own. Options the entry passed to its own `serve()` call are on `loaded.srvxServer.options` instead — forward the listener-level ones (`tls`, `protocol`, `node`) to your own `serve()`, as the srvx CLI does, or an entry configured for TLS ends up served in cleartext. Do **not** forward `middleware`/`plugins`: `loaded.fetch` already has them applied, so re-adding them would run them twice.
199209
200210
If the entry instead calls `http.createServer(handler).listen()`, the loader captures `handler` and lets the entry run to completion without binding a port. Its listen callback still fires, so setup code that runs after listen is not skipped.
201211

‎src/cli/serve.ts‎

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,32 @@ export async function cliServe(cliOpts: CLIOptions): Promise<void> {
2626
},
2727
});
2828

29-
const { serve: srvxServe } = loaded.nodeCompat
30-
? await import("srvx/node")
31-
: await import("srvx");
29+
// Options the entry passed to its *own* `serve()` call. The loader constructs
30+
// that server but returns before it ever listens, so anything only reachable
31+
// through `options` (TLS above all) is lost unless the CLI forwards it here.
32+
//
33+
// Only listener-level options are forwarded. `middleware`/`plugins` are
34+
// deliberately excluded: the intercepted server already folded them into
35+
// `loaded.fetch` via `wrapFetch()`, so re-applying them would run them twice.
36+
// `port`/`hostname` stay CLI-owned (see "Port and host precedence" in
37+
// docs/1.guide/10.cli.md).
38+
const nested = loaded.srvxServer?.options as Partial<ServerOptions> | undefined;
39+
40+
// Mutual TLS reaches the listener through node server options (`ca` /
41+
// `requestCert`, written by `mtlsPlugin()`), which only srvx's Node.js adapter
42+
// understands. Re-serving such an entry through a native Deno/Bun adapter
43+
// would silently drop the client-certificate requirement — the same class of
44+
// downgrade one level down — so serve it with `srvx/node` instead.
45+
const nestedNode = nested?.node as Record<string, unknown> | undefined;
46+
const nestedMTLS = !!nestedNode && ("requestCert" in nestedNode || "ca" in nestedNode);
47+
if (nestedMTLS && loaded.srvxServer?.runtime !== "node") {
48+
throw new Error(
49+
`[srvx] The server entry configures mutual TLS, which requires srvx's Node.js adapter (import { serve } from "srvx/node").`,
50+
);
51+
}
52+
53+
const { serve: srvxServe } =
54+
loaded.nodeCompat || nestedMTLS ? await import("srvx/node") : await import("srvx");
3255
const { staticMiddleware } = await import("srvx/static");
3356
const { loggerMiddleware } = await import("srvx/log");
3457

@@ -60,21 +83,35 @@ export async function cliServe(cliOpts: CLIOptions): Promise<void> {
6083

6184
// F42: only override the entry module's `tls` when CLI flags actually supply
6285
// TLS. A bare `--tls` (no cert/key) must error rather than silently downgrade.
63-
let tls = serverOptions.tls;
86+
// Entry-level TLS is honored whether it arrives as a module export or through
87+
// the entry's own intercepted `serve({ tls })` call — dropping the latter
88+
// served TLS/mTLS entries over plaintext HTTP with no warning.
89+
let tls = serverOptions.tls ?? nested?.tls;
90+
let protocol = serverOptions.protocol ?? nested?.protocol;
6491
if (cliOpts.tls) {
6592
if (!cliOpts.cert || !cliOpts.key) {
6693
throw new Error("--tls requires both --cert and --key.");
6794
}
6895
tls = { cert: cliOpts.cert, key: cliOpts.key };
96+
protocol = undefined; // explicit flags win over an entry's `protocol: "http"`
6997
}
7098

99+
// Carries `mtlsPlugin()`'s `ca`/`requestCert`/`rejectUnauthorized` plus any raw
100+
// node server options the entry set. Module exports win over the nested call.
101+
const nodeOptions =
102+
nested?.node || serverOptions.node
103+
? ({ ...nested?.node, ...serverOptions.node } as ServerOptions["node"])
104+
: undefined;
105+
71106
printInfo(cliOpts, loaded);
72107
server = srvxServe({
73108
...serverOptions,
74109
gracefulShutdown: !!cliOpts.prod,
75110
port: cliOpts.port ?? serverOptions.port,
76111
hostname: cliOpts.hostname ?? cliOpts.host ?? serverOptions.hostname,
77112
tls,
113+
protocol,
114+
node: nodeOptions,
78115
error: (error) => {
79116
console.error(error);
80117
return renderError(cliOpts, error);

‎src/mtls.ts‎

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,8 @@ export interface MTLSPluginOptions {
103103
* `node:http(s)` server do not expose the peer certificate, so the plugin throws there
104104
* rather than silently doing nothing. It also requires the server to be configured for
105105
* TLS (`tls.cert` / `tls.key`) and throws otherwise, since mutual TLS cannot run over
106-
* plain HTTP.
106+
* plain HTTP. A request that still reaches the plugin over a plain socket (TLS dropped
107+
* after construction by an outer host) is answered with `496` rather than run.
107108
*
108109
* With the default `rejectUnauthorized: true`, unauthenticated clients are rejected
109110
* during the TLS handshake and never reach the `fetch` handler. Set it to `false` to
@@ -181,16 +182,25 @@ export function mtlsPlugin(options: MTLSPluginOptions = {}): ServerPlugin {
181182
// Expose the peer certificate on each request from the raw TLS socket.
182183
server.options.middleware.unshift((request, next) => {
183184
const socket = request.runtime?.node?.req?.socket as TLS.TLSSocket | undefined;
184-
// Plain (non-TLS) sockets have no `getPeerCertificate`.
185-
if (socket && typeof socket.getPeerCertificate === "function") {
186-
request.tls = {
187-
peerCertificate: socket.getPeerCertificate(),
188-
authorized: socket.authorized,
189-
authorizationError: socket.authorizationError ?? undefined,
190-
protocol: socket.getProtocol?.() ?? undefined,
191-
cipher: socket.getCipher?.(),
192-
};
185+
// Plain (non-TLS) sockets have no `getPeerCertificate`. The HTTPS check above
186+
// runs at construction time, so arriving here on a plain socket means the TLS
187+
// configuration was dropped between construction and listen — e.g. by a host
188+
// that re-serves this handler on a listener of its own. Fail closed: leaving
189+
// `request.tls` undefined would hand an unauthenticated client the very
190+
// handler the client certificate was meant to protect.
191+
if (!socket || typeof socket.getPeerCertificate !== "function") {
192+
return new Response("Client certificate required", {
193+
status: 496, // nginx's "SSL Certificate Required"
194+
headers: { "content-type": "text/plain; charset=UTF-8" },
195+
});
193196
}
197+
request.tls = {
198+
peerCertificate: socket.getPeerCertificate(),
199+
authorized: socket.authorized,
200+
authorizationError: socket.authorizationError ?? undefined,
201+
protocol: socket.getProtocol?.() ?? undefined,
202+
cipher: socket.getCipher?.(),
203+
};
194204
return next();
195205
});
196206
};

‎test/cli.test.ts‎

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,25 @@ import { mkdtemp, writeFile, rm } from "node:fs/promises";
66
import { tmpdir } from "node:os";
77
import { execa, type Options as ExecaOptions } from "execa";
88
import { getRandomPort, waitForPort } from "get-port-please";
9+
import { fetch as undiciFetch, Agent } from "undici";
10+
import { getTLSCert } from "./_utils.ts";
911

1012
const runnerPath = fileURLToPath(new URL("./_cli-run.ts", import.meta.url));
1113
const fixtureDir = fileURLToPath(new URL("./fixtures/cli", import.meta.url));
1214
const entryFile = resolve(fixtureDir, "server.ts");
15+
const tlsEntryFile = resolve(fixtureDir, "tls-server.ts");
16+
17+
const tlsCert = await getTLSCert();
18+
19+
// undici dispatcher trusting the fixture CA, optionally presenting a client cert.
20+
function clientAgent(opts: { withClientCert?: boolean } = {}) {
21+
return new Agent({
22+
connect: {
23+
ca: tlsCert.ca,
24+
...(opts.withClientCert ? { cert: tlsCert.clientCert, key: tlsCert.clientKey } : {}),
25+
},
26+
});
27+
}
1328

1429
function runCli(
1530
args: string[],
@@ -23,6 +38,23 @@ function runCli(
2338
} as ExecaOptions);
2439
}
2540

41+
// Start the CLI on a free port, run `fn`, then always tear the child down.
42+
async function withServedCli(
43+
args: string[],
44+
opts: { env?: Record<string, string> },
45+
fn: (port: number) => Promise<void>,
46+
): Promise<void> {
47+
const port = await getRandomPort("localhost");
48+
const child = runCli([...args, "--port", String(port)], opts);
49+
try {
50+
await waitForPort(port, { host: "localhost", delay: 50, retries: 100 });
51+
await fn(port);
52+
} finally {
53+
child.kill("SIGTERM");
54+
await child.catch(() => {});
55+
}
56+
}
57+
2658
describe("cli", () => {
2759
describe("info flags", () => {
2860
it("--version prints srvx and runtime versions", async () => {
@@ -232,6 +264,108 @@ describe("cli", () => {
232264
});
233265
});
234266

267+
// The loader intercepts an entry's own `serve()` call before the adapter ever
268+
// resolves TLS, so the CLI has to forward the intercepted options itself.
269+
// Dropping them served TLS/mTLS entries over plaintext HTTP with no warning.
270+
describe("serve mode: TLS from an intercepted serve() call", () => {
271+
const tlsEnv = { SRVX_TEST_CERT: tlsCert.cert, SRVX_TEST_KEY: tlsCert.key };
272+
273+
it("a nested `serve({ tls })` entry is served over HTTPS, not plaintext", async () => {
274+
await withServedCli(["--prod", "--entry", tlsEntryFile], { env: tlsEnv }, async (port) => {
275+
const dispatcher = clientAgent();
276+
try {
277+
const res = await undiciFetch(`https://localhost:${port}/`, { dispatcher });
278+
expect(res.status).toBe(200);
279+
// `mwCount: 1` pins that the entry's middleware is not double-applied:
280+
// it is already folded into the intercepted server's composed `fetch`.
281+
expect(await res.json()).toMatchObject({ ok: true, mwCount: 1 });
282+
} finally {
283+
await dispatcher.close();
284+
}
285+
// ...and the same port must not answer plain HTTP any more.
286+
await expect(undiciFetch(`http://localhost:${port}/`)).rejects.toThrow();
287+
});
288+
});
289+
290+
it("`--tls --cert --key` still overrides a nested `serve({ tls })`", async () => {
291+
// The nested cert is unusable; the run only succeeds if the CLI flags win.
292+
const certFile = fileURLToPath(new URL("./.tmp/tls/server.crt", import.meta.url));
293+
const keyFile = fileURLToPath(new URL("./.tmp/tls/server.key", import.meta.url));
294+
await withServedCli(
295+
["--prod", "--entry", tlsEntryFile, "--tls", "--cert", certFile, "--key", keyFile],
296+
{ env: { SRVX_TEST_CERT: "/nonexistent.crt", SRVX_TEST_KEY: "/nonexistent.key" } },
297+
async (port) => {
298+
const dispatcher = clientAgent();
299+
try {
300+
const res = await undiciFetch(`https://localhost:${port}/`, { dispatcher });
301+
expect(res.status).toBe(200);
302+
} finally {
303+
await dispatcher.close();
304+
}
305+
},
306+
);
307+
});
308+
309+
it("mTLS: the client certificate reaches the handler through the CLI", async () => {
310+
await withServedCli(
311+
["--prod", "--entry", tlsEntryFile],
312+
{
313+
env: {
314+
...tlsEnv,
315+
SRVX_TEST_CA: tlsCert.ca,
316+
SRVX_TEST_REJECT_UNAUTHORIZED: "false",
317+
},
318+
},
319+
async (port) => {
320+
const withCert = clientAgent({ withClientCert: true });
321+
try {
322+
const res = await undiciFetch(`https://localhost:${port}/`, { dispatcher: withCert });
323+
expect(await res.json()).toMatchObject({
324+
authorized: true,
325+
subjectCN: "Test Client",
326+
});
327+
} finally {
328+
await withCert.close();
329+
}
330+
const withoutCert = clientAgent();
331+
try {
332+
const res = await undiciFetch(`https://localhost:${port}/`, {
333+
dispatcher: withoutCert,
334+
});
335+
expect(await res.json()).toMatchObject({ authorized: false });
336+
} finally {
337+
await withoutCert.close();
338+
}
339+
},
340+
);
341+
});
342+
343+
it("mTLS: rejectUnauthorized (default) is enforced at the handshake", async () => {
344+
await withServedCli(
345+
["--prod", "--entry", tlsEntryFile],
346+
{ env: { ...tlsEnv, SRVX_TEST_CA: tlsCert.ca } },
347+
async (port) => {
348+
const withoutCert = clientAgent();
349+
try {
350+
await expect(
351+
undiciFetch(`https://localhost:${port}/`, { dispatcher: withoutCert }),
352+
).rejects.toThrow();
353+
} finally {
354+
await withoutCert.close();
355+
}
356+
const withCert = clientAgent({ withClientCert: true });
357+
try {
358+
const res = await undiciFetch(`https://localhost:${port}/`, { dispatcher: withCert });
359+
expect(res.status).toBe(200);
360+
expect(await res.json()).toMatchObject({ authorized: true });
361+
} finally {
362+
await withCert.close();
363+
}
364+
},
365+
);
366+
});
367+
});
368+
235369
describe("errors", () => {
236370
it("F44: an unknown flag prints a one-line message + usage hint (no stack trace)", async () => {
237371
const { stderr, exitCode } = await runCli(["--nope"]);

‎test/fixtures/cli/tls-server.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Fixture: an entry that starts its *own* TLS (optionally mutual-TLS) server by
2+
// calling srvx's `serve()` at import time — the pattern documented in
3+
// docs/1.guide/06.tls.md. The CLI's loader intercepts that call, so this fixture
4+
// pins that the CLI forwards the intercepted server's `tls`/`node` options to its
5+
// own listener instead of silently serving the handler over plaintext HTTP.
6+
//
7+
// Configured through env vars so one fixture covers both the plain-TLS and the
8+
// mutual-TLS cases (see the "serve mode: entry TLS" block in test/cli.test.ts).
9+
import { serve } from "../../../src/adapters/node.ts";
10+
import { mtlsPlugin } from "../../../src/mtls.ts";
11+
import type { ServerPlugin } from "../../../src/types.ts";
12+
13+
const env = process.env;
14+
15+
const plugins: ServerPlugin[] = env.SRVX_TEST_CA
16+
? [
17+
mtlsPlugin({
18+
ca: env.SRVX_TEST_CA,
19+
requestCert: true,
20+
rejectUnauthorized: env.SRVX_TEST_REJECT_UNAUTHORIZED !== "false",
21+
}),
22+
]
23+
: [];
24+
25+
serve({
26+
// Must be ignored: the CLI owns port/hostname.
27+
port: 1,
28+
tls: { cert: env.SRVX_TEST_CERT!, key: env.SRVX_TEST_KEY! },
29+
plugins,
30+
// Counts how often the entry's own middleware runs for a single request. The
31+
// CLI must not re-apply `middleware`/`plugins`: they are already folded into
32+
// the intercepted server's composed `fetch`.
33+
middleware: [
34+
(request, next) => {
35+
const req = request as unknown as { __mwCount?: number };
36+
req.__mwCount = (req.__mwCount || 0) + 1;
37+
return next();
38+
},
39+
],
40+
fetch: (request) =>
41+
Response.json({
42+
ok: true,
43+
mwCount: (request as unknown as { __mwCount?: number }).__mwCount || 0,
44+
authorized: request.tls?.authorized ?? null,
45+
subjectCN: request.tls?.peerCertificate?.subject?.CN ?? null,
46+
}),
47+
});

‎test/loader.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { describe, it, expect } from "vitest";
22
import { resolve } from "node:path";
33
import { pathToFileURL } from "node:url";
44
import { loadServerEntry } from "../src/loader.ts";
5+
import { getTLSCert } from "./_utils.ts";
56

67
const fixturesDir = resolve(import.meta.dirname, "fixtures");
78

@@ -97,6 +98,28 @@ describe("loadServerEntry", () => {
9798
});
9899
});
99100

101+
describe("intercepted serve()", () => {
102+
it("exposes the intercepted server's options (including tls)", async () => {
103+
// Hosts re-serving `loaded.fetch` (the srvx CLI among them) can only keep an
104+
// entry's TLS if the intercepted server's options survive the interception.
105+
const tls = await getTLSCert();
106+
process.env.SRVX_TEST_CERT = tls.cert;
107+
process.env.SRVX_TEST_KEY = tls.key;
108+
try {
109+
const result = await loadServerEntry({
110+
entry: resolve(fixturesDir, "cli/tls-server.ts"),
111+
});
112+
expect(result.notFound).toBeUndefined();
113+
expect(result.fetch).toBeDefined();
114+
expect(result.srvxServer).toBeDefined();
115+
expect(result.srvxServer!.options.tls).toEqual({ cert: tls.cert, key: tls.key });
116+
} finally {
117+
delete process.env.SRVX_TEST_CERT;
118+
delete process.env.SRVX_TEST_KEY;
119+
}
120+
});
121+
});
122+
100123
describe("notFound", () => {
101124
it("returns notFound when no entry is found", async () => {
102125
const result = await loadServerEntry({

0 commit comments

Comments
 (0)