diff --git a/.changeset/host-check-each-listener.md b/.changeset/host-check-each-listener.md new file mode 100644 index 000000000..09d48d5d8 --- /dev/null +++ b/.changeset/host-check-each-listener.md @@ -0,0 +1,27 @@ +--- +"@procedures/client": minor +"@procedures/server": minor +"@procedures/mark": minor +"@procedures/lib": minor +"@procedures/mcp-server": minor +--- + +**Breaking change:** each listener examines the `Host` header. By default, only `localhost`, `127.0.0.1`, `[::1]` and IP addresses pass. Give each other name with `--allowed-host` or `allowedHosts`. + +The browser checks examine the `Host` header on each listener. Before, they examined it only on a loopback address. A server on a LAN address (`0.0.0.0`) accepted each host name. + +A request must name one of these hosts in its `Host` header: + +- A loopback name: `localhost`, `127.0.0.1` or `[::1]`. +- An IP address, for example `192.168.1.20` or `[fe80::1]`. +- A name of `browser.allowedHosts` of the host policy, with any letter case. + +A request with another name gets `FORBIDDEN` (403) with the reason `host-header-not-allowed`. A request without a `Host` header gets it too. The message of the refusal names `allowedHosts` and `--allowed-host`. `browser.allowedHosts: "*"` turns the check off. + +The server command and `mark --server` get the option `--allowed-host `. Repeat the option, or separate the names with commas. `@procedures/server` exports `parseAllowedHosts`. + +Migration steps: + +- A server that a LAN, a proxy or a container network reaches by a name: give the name in `browser.allowedHosts` of `hostPolicy()`. Or start the server with `--allowed-host `. +- An MCP face on HTTP that clients reach by a name: give the name in `http.allowedHosts` of the face, or in `browser.allowedHosts` of the policy. +- A server that clients reach by `localhost` or by an IP address: no change. diff --git a/packages/client-lib/src/cli-flags.ts b/packages/client-lib/src/cli-flags.ts index 1d4a78749..b48740164 100644 --- a/packages/client-lib/src/cli-flags.ts +++ b/packages/client-lib/src/cli-flags.ts @@ -42,6 +42,13 @@ export const CLI_GLOBAL_FLAGS: readonly CliGlobalFlag[] = [ { long: "server", takesValue: false, mode: true, description: "Start the CLI server" }, { long: "port", takesValue: true, serverOption: true, description: "The port of the CLI server (with --server)" }, { long: "host", takesValue: true, serverOption: true, description: "The host of the CLI server (with --server)" }, + { + long: "allowed-host", + takesValue: true, + serverOption: true, + repeatable: true, + description: "A name that a request can give in its Host header, besides localhost and the IP addresses (with --server)", + }, { long: "probe-port", takesValue: true, diff --git a/packages/client-mcp/README.md b/packages/client-mcp/README.md index 76b0b5867..d3f7129fe 100644 --- a/packages/client-mcp/README.md +++ b/packages/client-mcp/README.md @@ -115,7 +115,7 @@ When the server reads cookies, the face trusts a request with a cookie only from The Streamable HTTP face checks each request before the request reaches the MCP SDK. The face has no token check of its own. -- The browser checks come first, with `guardMcpRequest`. A request on a loopback address must name a loopback host, or a host of `allowedHosts` (the default is `browser.allowedHosts` of the policy), in its `Host` header. Thus DNS rebinding cannot reach the tools. An `Origin` header must name the server or a permitted origin (the default is `browser.allowedOrigins` of the policy). +- The browser checks come first, with `guardMcpRequest`. Each request must name a loopback host, an IP address or a host of `allowedHosts` (the default is `browser.allowedHosts` of the policy) in its `Host` header, on each listener. Thus DNS rebinding cannot reach the tools. An `Origin` header must name the server or a permitted origin (the default is `browser.allowedOrigins` of the policy). - Then the admission of the server checks the credentials. With a token, each request sends `Authorization: Bearer `. The scheme has any case, for example `bearer` (RFC 7235). The check is `tokenMatches` of the core: its time does not tell the token. A refused request gets 401 with a `WWW-Authenticate` header. - The token of a host is the token of its policy. A `token` of the HTTP face of `createMcpHost` becomes the token of the policy, and two different tokens stop the host with an error. `McpServerTransport` refuses a token in its HTTP options: give the token to the server. Refer to [Deprecated token options](#deprecated-token-options). - `guardMcpRequest` refuses a `token` option. The first call with it throws a `TypeError` that names the migration. Each later call with it gives a refusal with the status 500, without an error. Thus each request stays refused, and the log gets one error. diff --git a/packages/client-mcp/src/face.ts b/packages/client-mcp/src/face.ts index 9964ad92e..eb0663e17 100644 --- a/packages/client-mcp/src/face.ts +++ b/packages/client-mcp/src/face.ts @@ -53,7 +53,7 @@ export interface McpFaceOptions extends Omit Promise> = []; afterEach(async () => { @@ -227,10 +227,59 @@ describe("checkBrowserRequest", () => { expect(isLoopbackAddress("192.168.1.5")).toBe(false); }); - it("checks the host only on a loopback address", () => { + // A request on a socket with this local address + const on = (localAddress: string, headers: Record, options: BrowserGuardOptions = {}) => + checkBrowserRequest({ method: "POST", headers: { "content-type": "application/json", "content-length": "2", ...headers }, socket: { localAddress } }, options, true); + const reasonOf = (result: GuardResult) => (result.ok ? "ok" : result.reason); + + it("checks the host on a loopback address", () => { expect(check({ host: "evil.example" }).ok).toBe(false); expect(check({ host: "evil.example" }, { allowedHosts: ["evil.example"] }).ok).toBe(true); - expect(checkBrowserRequest({ method: "POST", headers: { host: "my-server.lan" }, socket: { localAddress: "192.168.1.5" } }, {}, true).ok).toBe(true); + }); + + it("checks the host on a LAN address too: a DNS rebinding page is not the origin of the server", () => { + // The page http://evil.example:3000 after its name resolves to the LAN address of the host + const rebound = { host: "evil.example:3000", origin: "http://evil.example:3000" }; + expect(reasonOf(on("192.168.1.20", rebound))).toBe("host-header-not-allowed"); + expect(reasonOf(on("::ffff:192.168.1.20", rebound))).toBe("host-header-not-allowed"); + expect(reasonOf(on("fe80::1", rebound))).toBe("host-header-not-allowed"); + expect(reasonOf(on("192.168.1.5", { host: "my-server.lan" }))).toBe("host-header-not-allowed"); + // A request with no Host header names no permitted host + expect(reasonOf(on("192.168.1.20", {}))).toBe("host-header-not-allowed"); + }); + + it("accepts the loopback names and the IP addresses on each listener", () => { + for (const local of ["127.0.0.1", "::1", "192.168.1.20", "::ffff:192.168.1.20", "172.17.0.2"]) { + for (const host of ["localhost:3000", "127.0.0.1:3000", "[::1]:3000", "LOCALHOST", "192.168.1.20:3000", "10.0.0.7", "[fe80::1]:3000", "[::ffff:c0a8:114]"]) { + expect(reasonOf(on(local, { host })), `${host} on ${local}`).toBe("ok"); + } + } + // The page of an IP address is the origin of the server at that address + expect(reasonOf(on("192.168.1.20", { host: "192.168.1.20:3000", origin: "http://192.168.1.20:3000" }))).toBe("ok"); + }); + + it("refuses a name that only looks like an IP address", () => { + for (const host of ["1.2.3.4.evil.example", "256.1.1.1", "1.2.3", "1.2.3.4.5", "0x7f.0.0.1", "[evil.example]", "[]", "[:]x", "127.0.0.1.nip.io"]) { + expect(reasonOf(on("192.168.1.20", { host })), host).toBe("host-header-not-allowed"); + } + }); + + it("accepts a name of allowedHosts on each listener, in any case, and each name with '*'", () => { + const options: BrowserGuardOptions = { allowedHosts: ["My-Server.lan"] }; + expect(reasonOf(on("192.168.1.5", { host: "my-server.lan:3000" }, options))).toBe("ok"); + expect(reasonOf(on("192.168.1.5", { host: "MY-SERVER.LAN" }, options))).toBe("ok"); + expect(reasonOf(on("127.0.0.1", { host: "my-server.lan" }, options))).toBe("ok"); + expect(reasonOf(on("192.168.1.5", { host: "other.lan" }, options))).toBe("host-header-not-allowed"); + expect(reasonOf(on("192.168.1.5", { host: "other.lan" }, { allowedHosts: "*" }))).toBe("ok"); + }); + + it("names allowedHosts and --allowed-host in the refusal of a name", () => { + const refused = on("192.168.1.5", { host: "My-Server.lan:3000" }); + expect(refused.ok === false && refused.message).toBe( + 'Forbidden: the host "my-server.lan" is not allowed. To permit it, add it to allowedHosts of the host policy, or start the server with --allowed-host my-server.lan' + ); + const noHost = on("192.168.1.5", {}); + expect(noHost.ok === false && noHost.message).toBe("Forbidden: the request has no Host header"); }); it("refuses the origin 'null' (a sandboxed frame or a file) unless every origin is allowed", () => { diff --git a/packages/client/src/server/browser-guard.ts b/packages/client/src/server/browser-guard.ts index b31ee848d..f180d59c0 100644 --- a/packages/client/src/server/browser-guard.ts +++ b/packages/client/src/server/browser-guard.ts @@ -7,8 +7,9 @@ * ran any procedure, and the WebSocket server accepted a connection from any page * (cross-site WebSocket hijacking). The checks here are on by default in both transports: * - * - A connection that arrives on a loopback address must name a loopback host in its `Host` - * header. A DNS rebinding attack sends the name of the attacker's site. + * - Each request must name a permitted host in its `Host` header: a loopback name, an IP address, + * or a name of `allowedHosts`. A DNS rebinding attack sends the name of the attacker's site. + * The check is on each listener, also on a LAN address (`0.0.0.0`). * - A browser request (an `Origin` header) must come from the server's own origin, or from an * origin in `allowedOrigins`. * - A request that the browser marks `Sec-Fetch-Site: cross-site` or `same-site` and that has @@ -33,9 +34,10 @@ export interface BrowserGuardOptions { */ allowedOrigins?: readonly string[] | "*" | ((origin: string) => boolean) | undefined; /** - * The host names that a request on a loopback address can name in its `Host` header, - * besides the loopback names. `"*"` turns the check off. - * @default [] (only `localhost`, `127.0.0.1` and `[::1]`) + * The host names that a request can name in its `Host` header, besides the loopback names and + * the IP addresses. The check is on each listener. A server that a LAN or a proxy reaches by a + * name lists that name here. `"*"` turns the check off. + * @default [] (only `localhost`, `127.0.0.1`, `[::1]` and the IP addresses) */ allowedHosts?: readonly string[] | "*" | undefined; /** @@ -95,6 +97,26 @@ export function isLoopbackHost(host: string): boolean { return LOOPBACK_NAMES.has(host.toLowerCase()); } +/** + * True for a host name that is an IP address: four decimal numbers from 0 to 255 (`192.168.1.20`), + * or an IPv6 address in brackets (`[fe80::1]`). A browser writes an IP address of a URL in these + * forms in the `Host` header. A DNS rebinding attack needs a name, not an IP address. + */ +function isIpAddressHost(name: string): boolean { + if (name.startsWith("[")) { + // The URL parser accepts only a valid IPv6 address in brackets + if (!/^\[[0-9a-f:.]+\]$/.test(name)) return false; + try { + return new URL(`http://${name}/`).hostname.startsWith("["); + } catch { + return false; + } + } + // path-check: the four numbers of an IPv4 address, not the parts of a path + const parts = name.split("."); + return parts.length === 4 && parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255); +} + /** True for a local socket address on the loopback interface (IPv4, IPv6, or IPv4 in IPv6). */ export function isLoopbackAddress(address: string | undefined): boolean { if (!address) return false; @@ -187,11 +209,19 @@ export function checkBrowserRequest( ): GuardResult { const { headers } = req; - // DNS rebinding: a request on a loopback address must name a loopback host - if (options.allowedHosts !== "*" && isLoopbackAddress(req.socket?.localAddress)) { + // DNS rebinding: each request names a loopback host, an IP address or a permitted name, on each + // listener. The check of the origin below compares the origin with this Host header. + if (options.allowedHosts !== "*") { const name = hostNameOf(headers.host); - if (!LOOPBACK_NAMES.has(name) && !(options.allowedHosts ?? []).includes(name)) { - return refusal("host-header-not-allowed", `Forbidden: the host "${name}" is not allowed`); + const allowed = options.allowedHosts ?? []; + if (!LOOPBACK_NAMES.has(name) && !isIpAddressHost(name) && !allowed.some((host) => host.toLowerCase() === name)) { + // The refusal names the two settings that permit a name, so an operator finds the change + return refusal( + "host-header-not-allowed", + name === "" + ? "Forbidden: the request has no Host header" + : `Forbidden: the host "${name}" is not allowed. To permit it, add it to allowedHosts of the host policy, or start the server with --allowed-host ${name}` + ); } } diff --git a/packages/documentation/WIRE-PROTOCOL.md b/packages/documentation/WIRE-PROTOCOL.md index 846f23e61..e81188ced 100644 --- a/packages/documentation/WIRE-PROTOCOL.md +++ b/packages/documentation/WIRE-PROTOCOL.md @@ -406,7 +406,7 @@ A `FORBIDDEN` error tells its reason in the metadata key `reason`. The HTTP body | `partition-not-allowed` | The collection procedures | The partition resolver of the collection refuses the partition of the call (CLI-17). | | `write-not-allowed` | The collection procedures | The guard of the collection (`admission.guard`) refuses a write. The storage does not change (CLI-41). | | `origin-not-allowed` | The browser checks | The `Origin` of the request is not the origin of the server or a permitted origin. A cross-site request without a permitted origin gets it too. | -| `host-header-not-allowed` | The browser checks | A request on a loopback address names a `Host` that is not permitted (DNS rebinding). | +| `host-header-not-allowed` | The browser checks | The `Host` of the request is not a loopback name, an IP address or a permitted name (DNS rebinding). The check is on each listener. | | `method-not-allowed` | The browser checks of HTTP | The HTTP method is `GET` or `HEAD`, and the option `allowGet` is off. | | `media-type-not-allowed` | The browser checks of HTTP | The request body is not JSON. | diff --git a/packages/mark/README.md b/packages/mark/README.md index ef949391d..cd864eed0 100644 --- a/packages/mark/README.md +++ b/packages/mark/README.md @@ -140,7 +140,7 @@ The package provides a `mark` binary for command-line usage. mark [global options] [positional...] [--options] mark serve [--procedures pkgs] [--port N] [--token T | --no-token] [--expose patterns] [--events topics] [--fs-root folder] [--probe-port N] mark mcp [--bundles list] [--tool-timeout ms] [--read-only] [--http port] [--max-sessions n] [--fs-root folder] [--debug] -mark --server [--port N] [--host H] [--transport http|websocket|both] [--events topics] [--probe-port N] [--idle-timeout ms] +mark --server [--port N] [--host H] [--allowed-host names] [--transport http|websocket|both] [--events topics] [--probe-port N] [--idle-timeout ms] mark -i mark --fs-root ``` @@ -249,7 +249,7 @@ A flag before the command path is a global flag. After the path, a flag is the c | `--local` | | Run the command in this process, not on the CLI server | | `--json ` | | Execute raw procedure reference | | `--fs-root ` | | Keep each path of each procedure in the folder, also in the nested calls, and refuse the procedures that it cannot confine. Give it before the command. | -| `--server` | | Start the CLI server (with `--port`, `--host`, `--transport`, `--events`) | +| `--server` | | Start the CLI server (with `--port`, `--host`, `--allowed-host`, `--transport`, `--events`) | | `--interactive` | `-i` | Start the REPL | #### Exit Codes and Failures diff --git a/packages/mark/src/args.test.ts b/packages/mark/src/args.test.ts index 132f63086..461451051 100644 --- a/packages/mark/src/args.test.ts +++ b/packages/mark/src/args.test.ts @@ -75,6 +75,14 @@ describe("global flags and procedure flags (CLI-7)", () => { expect(parseLeadingGlobals(["--fs-root"]).errors).toEqual(["--fs-root needs a value"]); }); + it("collects a repeated --allowed-host of --server", () => { + expect(parseLeadingGlobals(["--server", "--host", "0.0.0.0", "--allowed-host", "box.lan", "--allowed-host=api.lan"]).globals).toEqual({ + server: true, + host: "0.0.0.0", + "allowed-host": "box.lan,api.lan", + }); + }); + it("reports a flag that neither the procedure nor the globals have", () => { expect(parse(["fs", "exists", "x", "--bogus"]).errors).toEqual(["Unknown option for mark fs exists: --bogus"]); expect(parse(["docker", "exec", "-iz", "box", "sh"]).errors).toEqual(["Unknown option -z in -iz"]); diff --git a/packages/mark/src/args.ts b/packages/mark/src/args.ts index 49a877d2f..2e1d9036d 100644 --- a/packages/mark/src/args.ts +++ b/packages/mark/src/args.ts @@ -30,6 +30,7 @@ export type GlobalName = | "server" | "port" | "host" + | "allowed-host" | "transport" | "events" | "probe-port" diff --git a/packages/mark/src/cli.test.ts b/packages/mark/src/cli.test.ts index bab9f5b71..8c532fc65 100644 --- a/packages/mark/src/cli.test.ts +++ b/packages/mark/src/cli.test.ts @@ -91,6 +91,7 @@ describe("exit codes (CLI-8)", () => { expect(await exitCodeOf(["fs", "exists", "x", "--server"])).toBe(1); expect(await exitCodeOf(["fs", "exists", "x", "--port", "4000"])).toBe(1); expect(await exitCodeOf(["fs", "exists", "x", "--events", "orders.*"])).toBe(1); + expect(await exitCodeOf(["fs", "exists", "x", "--allowed-host", "box.lan"])).toBe(1); }); it("is 1 for an --fs-root that is not the root of the run, and 0 for the same root", async () => { diff --git a/packages/mark/src/cli.ts b/packages/mark/src/cli.ts index 84539297f..b469b9221 100644 --- a/packages/mark/src/cli.ts +++ b/packages/mark/src/cli.ts @@ -88,7 +88,7 @@ function showRootHelp(procedures: readonly CommandLike[]): void { footer: [ "Hosts: 'mark serve [--procedures pkgs] [--port N] [--expose patterns] [--events topics]' (the procedure server),", " 'mark mcp' (the dev-tools MCP server over stdio).", - "Modes: 'mark --server [--port N] [--host H] [--transport http|websocket|both] [--events topics] [--probe-port N] [--idle-timeout ms]' and 'mark -i' (the REPL).", + "Modes: 'mark --server [--port N] [--host H] [--allowed-host names] [--transport http|websocket|both] [--events topics] [--probe-port N] [--idle-timeout ms]' and 'mark -i' (the REPL).", "Root: 'mark --fs-root ' keeps each path of each procedure in the folder, also in each mode and host.", " It refuses the procedures that it cannot confine: git, pnpm, docker run, a program (FORBIDDEN, outside-root).", ], @@ -97,7 +97,7 @@ function showRootHelp(procedures: readonly CommandLike[]): void { } /** The global flags that only `--server` takes. */ -const SERVER_OPTIONS = ["port", "host", "transport", "events", "probe-port", "idle-timeout"] as const; +const SERVER_OPTIONS = ["port", "host", "allowed-host", "transport", "events", "probe-port", "idle-timeout"] as const; /** True when the global flags give an option of `--server`. */ function hasServerOption(globals: Readonly>): boolean { @@ -111,6 +111,13 @@ async function eventPatterns(value: string | boolean | undefined): Promise { + if (value === undefined) return undefined; + const { parseAllowedHosts } = await import("@procedures/server"); + return parseAllowedHosts(String(value)); +} + /** * CLI execution context, created once and reused */ @@ -290,7 +297,7 @@ export async function executeArgs( return; } if (hasServerOption(globals)) { - fail("--port, --host, --transport, --events, --probe-port and --idle-timeout are options of --server."); + fail("--port, --host, --allowed-host, --transport, --events, --probe-port and --idle-timeout are options of --server."); return; } // The root applies to the whole run: the procedures load with it, and a warm server must have it @@ -736,6 +743,8 @@ async function run(argv: string[], options: RunCliOptions = {}): Promise { const host = globals.host === undefined ? "127.0.0.1" : String(globals.host); const transport = globals.transport === undefined ? "http" : parseTransport(String(globals.transport)); const events = await eventPatterns(globals.events); + // --allowed-host: the names of the Host check, besides localhost and the IP addresses + const allowedHosts = await allowedHostNames(globals["allowed-host"]); // --probe-port: the probes answer on a port of their own (CLI-9, decision D5) const probePort = globals["probe-port"] === undefined ? undefined : parsePort(String(globals["probe-port"])); // --idle-timeout: the server stops by itself after this time with no call (CLI-27) @@ -746,6 +755,7 @@ async function run(argv: string[], options: RunCliOptions = {}): Promise { transport, verbose, events, + ...(allowedHosts !== undefined ? { allowedHosts } : {}), ...(probePort !== undefined ? { probePort } : {}), ...(idleTimeoutMs !== undefined ? { idleTimeoutMs } : {}), ...(fsRoot !== undefined ? { fsRoot } : {}), @@ -754,7 +764,7 @@ async function run(argv: string[], options: RunCliOptions = {}): Promise { } // Before, `mark --port 4000 serve` ignored --port without a word if (hasServerOption(globals)) { - fail("--port, --host, --transport, --events, --probe-port and --idle-timeout are options of --server.", "For mark serve, give them after serve."); + fail("--port, --host, --allowed-host, --transport, --events, --probe-port and --idle-timeout are options of --server.", "For mark serve, give them after serve."); return; } diff --git a/packages/mark/src/command.ts b/packages/mark/src/command.ts index f75e62d79..4a34cf471 100644 --- a/packages/mark/src/command.ts +++ b/packages/mark/src/command.ts @@ -117,6 +117,8 @@ export interface MarkHostConfig { readonly token?: string | undefined; /** The topic patterns of the remote events (`--events`). The default is none. */ readonly events?: readonly string[] | undefined; + /** The names of the Host check (`--allowed-host`), besides localhost and the IP addresses. The default is none. */ + readonly allowedHosts?: readonly string[] | "*" | undefined; } /** @@ -127,7 +129,11 @@ export interface MarkHostConfig { export async function markHostOptions(config: MarkHostConfig): Promise { const { hostPolicy } = await import("@procedures/client"); const { peerHostOptions } = await import("@procedures/peer"); - const policy = hostPolicy({ ...(config.token !== undefined ? { token: config.token } : {}), events: { topics: [...(config.events ?? [])] } }); + const policy = hostPolicy({ + ...(config.token !== undefined ? { token: config.token } : {}), + events: { topics: [...(config.events ?? [])] }, + ...(config.allowedHosts !== undefined ? { browser: { allowedHosts: config.allowedHosts } } : {}), + }); return peerHostOptions({ id: config.id, transports: [...config.transports], registry: config.registry, policy }, "procedures"); } diff --git a/packages/mark/src/server-mode.start.test.ts b/packages/mark/src/server-mode.start.test.ts index 7d792fb5a..de3becc12 100644 --- a/packages/mark/src/server-mode.start.test.ts +++ b/packages/mark/src/server-mode.start.test.ts @@ -23,6 +23,7 @@ interface HostOptions { transports: Array<{ type: string; port: number; host: string; basePath?: string }>; token: string; events: string[]; + allowedHosts?: string[] | "*"; } const fake = vi.hoisted(() => ({ @@ -126,6 +127,18 @@ describe("startServerMode", () => { expect(text()).toContain("[probes]"); }); + it("gives the names of --allowed-host to the host, and tells a LAN server about the option", async () => { + await startServerMode({ port: 3000 }); + expect(fake.hostOptions).not.toHaveProperty("allowedHosts"); + expect(text()).not.toContain("--allowed-host"); + await startServerMode({ port: 3000, host: "0.0.0.0" }); + expect(text()).toContain("needs --allowed-host "); + fake.lines = []; + await startServerMode({ port: 3000, host: "0.0.0.0", allowedHosts: ["box.lan"] }); + expect(fake.hostOptions?.allowedHosts).toEqual(["box.lan"]); + expect(text()).not.toContain("needs --allowed-host"); + }); + it("gives the idle stop of --idle-timeout to the host, and shows it (CLI-27)", async () => { await startServerMode({ port: 3000 }); expect(fake.config).not.toHaveProperty("idle"); diff --git a/packages/mark/src/server-mode.ts b/packages/mark/src/server-mode.ts index 2c0e3efaf..400cca9ab 100644 --- a/packages/mark/src/server-mode.ts +++ b/packages/mark/src/server-mode.ts @@ -31,6 +31,11 @@ export interface ServerModeOptions { events?: readonly string[] | undefined; /** The folder that confines each path of the `fs.*` procedures (`--fs-root`). */ fsRoot?: string | undefined; + /** + * The host names that a request can name in its `Host` header (`--allowed-host`), besides the + * loopback names and the IP addresses. `"*"` turns the check off. The default is none. + */ + allowedHosts?: readonly string[] | "*" | undefined; /** * The port of the probe server (`--probe-port`, CLI-9), on the address of `host`. Without it, each * listener answers the probes under `/_probes`. @@ -104,6 +109,9 @@ export async function startServerMode(options: ServerModeOptions, run?: Procedur const host = options.host ?? "127.0.0.1"; if (!["127.0.0.1", "localhost", "::1"].includes(host)) { print.warning(`The server listens on ${host}: other computers can reach it. Every request needs its token.`); + if (options.allowedHosts === undefined) { + print.info("A client that uses a name of this computer, not its IP address, needs --allowed-host ."); + } } if (options.transport === "websocket") { print.warning("A WebSocket-only server takes no `mark` commands: `mark` sends its commands over HTTP."); @@ -126,7 +134,7 @@ export async function startServerMode(options: ServerModeOptions, run?: Procedur const running = await runProcedureHost({ name: "mark-server", mode: "background", - host: await markHostOptions({ id, registry, transports, token, events }), + host: await markHostOptions({ id, registry, transports, token, events, ...(options.allowedHosts !== undefined ? { allowedHosts: options.allowedHosts } : {}) }), lockfile: { pid: process.pid, port, diff --git a/packages/server/README.md b/packages/server/README.md index 5476fbf31..97b1f8900 100644 --- a/packages/server/README.md +++ b/packages/server/README.md @@ -157,6 +157,7 @@ procedure-server -p @procedures/mongo/register -t http,websocket | `--transport` | `-t` | `http` | Transports: http, websocket, local | | `--port` | - | `3000` | Port for the primary transport | | `--host` | - | `127.0.0.1` | Host to bind to. `0.0.0.0` serves every loaded procedure to the network | +| `--allowed-host` | - | no names | The host names that a request can give in its `Host` header, besides `localhost` and the IP addresses. Give the name that a LAN or a proxy uses for this computer. Repeat the option, or separate the names with commas. `*` turns the check off. | | `--base-path` | - | `/api` | Base path for HTTP transport | | `--cors` | - | off | Enable CORS | | `--no-cors` | - | - | Disable CORS | diff --git a/packages/server/src/config.test.ts b/packages/server/src/config.test.ts index 7ff07e32b..0ca12f889 100644 --- a/packages/server/src/config.test.ts +++ b/packages/server/src/config.test.ts @@ -4,7 +4,7 @@ */ import { describe, it, expect } from "vitest"; -import { parseConfig } from "./config.js"; +import { parseAllowedHosts, parseConfig } from "./config.js"; describe("parseConfig", () => { it("gives a loopback HTTP server by default", () => { @@ -36,6 +36,25 @@ describe("parseConfig", () => { expect(parseConfig([]).fsRoot).toBeUndefined(); }); + it("reads the names of --allowed-host, repeated or comma-separated, in lower case", () => { + expect(parseConfig(["--allowed-host", "Box.LAN", "--allowed-host=api.example.com, box.lan"]).allowedHosts).toEqual([ + "box.lan", + "api.example.com", + ]); + expect(parseConfig(["--allowed-host", "box.lan,*"]).allowedHosts).toBe("*"); + expect(parseConfig([]).allowedHosts).toBeUndefined(); + expect(parseAllowedHosts("my-server")).toEqual(["my-server"]); + }); + + it("reports an invalid name of --allowed-host", () => { + expect(() => parseConfig(["--allowed-host", "box.lan:3000"])).toThrow('Invalid host name: "box.lan:3000"'); + expect(() => parseConfig(["--allowed-host", "http://box.lan"])).toThrow('Invalid host name: "http://box.lan"'); + expect(() => parseConfig(["--allowed-host=-box.lan"])).toThrow('Invalid host name: "-box.lan"'); + expect(() => parseConfig(["--allowed-host", "box..lan"])).toThrow('Invalid host name: "box..lan"'); + expect(() => parseConfig(["--allowed-host", " , "])).toThrow("--allowed-host needs a host name"); + expect(() => parseConfig(["--allowed-host"])).toThrow("--allowed-host needs a value"); + }); + it("reads the port of the probe server (CLI-9)", () => { expect(parseConfig(["--probe-port", "9090"]).probePort).toBe(9090); expect(parseConfig(["--probe-port=9091", "--port", "4000"]).probePort).toBe(9091); diff --git a/packages/server/src/config.ts b/packages/server/src/config.ts index 8e3affae8..19fd6e984 100644 --- a/packages/server/src/config.ts +++ b/packages/server/src/config.ts @@ -43,6 +43,29 @@ export function parseTopicPatterns(value: string): string[] { return patterns; } +/** + * This function gives the host names of an `--allowed-host` value: comma-separated names without a + * port (`my-server.lan`), or `"*"` when a name is `*`. A request names a loopback host, an IP address + * or one of these names in its `Host` header. Each other name gets `FORBIDDEN` (`host-header-not-allowed`). + */ +export function parseAllowedHosts(value: string): string[] | "*" { + const names = [ + ...new Set( + value + .split(",") + .map((name) => name.trim().toLowerCase()) + .filter((name) => name.length > 0) + ), + ]; + if (names.length === 0) throw new Error("--allowed-host needs a host name (for example my-server.lan) or *"); + for (const name of names) { + if (name !== "*" && !/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/.test(name)) { + throw new Error(`Invalid host name: "${name}". Give a name without a port or a scheme (for example my-server.lan) or *.`); + } + } + return names.includes("*") ? "*" : names; +} + /** * Parse command line arguments into server configuration. * @@ -66,6 +89,7 @@ export function parseConfig(argv: string[]): ServerConfig { const events: string[] = []; let fsRoot: string | undefined; let probePort: number | undefined; + const allowedHostValues: string[] = []; for (let i = 0; i < argv.length; i++) { const token = argv[i]!; @@ -93,6 +117,10 @@ export function parseConfig(argv: string[]): ServerConfig { case "--host": host = value(); break; + case "--allowed-host": + // Repeatable: each value adds its names to the Host check of each listener + allowedHostValues.push(value()); + break; case "--probe-port": probePort = parsePort(value()); break; @@ -183,6 +211,7 @@ export function parseConfig(argv: string[]): ServerConfig { events, ...(fsRoot !== undefined ? { fsRoot } : {}), ...(probePort !== undefined ? { probePort } : {}), + ...(allowedHostValues.length > 0 ? { allowedHosts: parseAllowedHosts(allowedHostValues.join(",")) } : {}), }; } @@ -207,6 +236,12 @@ OPTIONS: Default: 127.0.0.1 (0.0.0.0 exposes every procedure to the network) + --allowed-host The host names that a request can name in its + Host header, besides localhost and the IP + addresses: for example the LAN name of the + computer. Repeatable, or comma-separated. + * turns the check off. Default: none + --base-path Base path for HTTP transport Default: /api diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts index 25d6b9c7d..101d5b73a 100644 --- a/packages/server/src/index.ts +++ b/packages/server/src/index.ts @@ -6,7 +6,7 @@ * runs a procedures host under `run()`, and `startServer()` starts a server outside a service. */ -export { parseConfig, parseTopicPatterns } from "./config.js"; +export { parseAllowedHosts, parseConfig, parseTopicPatterns } from "./config.js"; export { runServer, startServer, loadProcedureModule, type RunningServer, type ServerRunOptions } from "./run.js"; // The runner entry of the procedures host (CLI-8): the only entry that starts run() export { runProcedureHost, HOST_PROFILES, type ProcedureHostRunConfig, type RunningHost, type HostRunMode } from "./host.js"; diff --git a/packages/server/src/run.test.ts b/packages/server/src/run.test.ts index 7f7b9a258..88b041c7e 100644 --- a/packages/server/src/run.test.ts +++ b/packages/server/src/run.test.ts @@ -5,6 +5,7 @@ import { describe, it, expect, afterEach } from "vitest"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { request as httpRequest } from "node:http"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; @@ -115,8 +116,42 @@ describe("startServer", () => { expect(await call(port, "server/connections")).toBe(200); expect(await call(port, "fixture/hello")).toBe(404); }); + + it("checks the Host header against --allowed-host", async () => { + const named = await start(["--allowed-host", "box.lan"]); + const plain = await start([]); + expect(named.server.policy.browser?.allowedHosts).toEqual(["box.lan"]); + expect(plain.server.policy.browser?.allowedHosts).toBeUndefined(); + expect(await statusWithHost(named.port, "box.lan")).toBe(200); + expect(await statusWithHost(plain.port, "box.lan")).toBe(403); + expect(await statusWithHost(named.port, "other.lan")).toBe(403); + // The loopback names and the IP addresses pass without the option + expect(await statusWithHost(plain.port, "localhost")).toBe(200); + expect(await statusWithHost(plain.port, "192.168.1.20")).toBe(200); + }); }); +/** The status of a call of `server.connections` with this name in the Host header. */ +function statusWithHost(port: number, name: string): Promise { + return new Promise((resolve, reject) => { + const request = httpRequest( + { + host: "127.0.0.1", + port, + path: "/api/server/connections", + method: "POST", + headers: { host: `${name}:${port}`, "content-type": "application/json", "content-length": "2", authorization: "Bearer t" }, + }, + (response) => { + response.resume(); + response.on("end", () => resolve(response.statusCode)); + } + ); + request.on("error", reject); + request.end("{}"); + }); +} + describe("the remote events of the server (--events, EVENTS.md)", () => { it("serves a subscription over WebSocket and HTTP, and a procedure publishes on its bus", async () => { // The expose list does not apply to events.subscribe: the topic rule is its expose rule diff --git a/packages/server/src/run.ts b/packages/server/src/run.ts index ac45d5108..8880bf19c 100644 --- a/packages/server/src/run.ts +++ b/packages/server/src/run.ts @@ -220,6 +220,9 @@ async function prepareServer(config: ServerConfig, log: (line: string) => void, // the topic rule is empty, so each subscription gets TOPIC_NOT_FOUND. The bus is the global // bus, which is also the ctx.bus of the procedures. events: { topics: config.events ?? [] }, + // --allowed-host: the names of the Host check of each listener, besides localhost and the IP + // addresses. A LAN listener (0.0.0.0) that a client reaches by a name needs that name. + ...(config.allowedHosts !== undefined ? { browser: { allowedHosts: config.allowedHosts } } : {}), }); return { registry, policy, token, generated, confined }; } diff --git a/packages/server/src/types.ts b/packages/server/src/types.ts index d7d5f3bb9..88521f307 100644 --- a/packages/server/src/types.ts +++ b/packages/server/src/types.ts @@ -35,6 +35,11 @@ export interface ServerConfig { * under `/_probes`, and the server has no probe server. */ probePort?: number | undefined; + /** + * The host names that a request can name in its `Host` header (`--allowed-host`), besides the + * loopback names and the IP addresses. `"*"` turns the check off. Undefined: no other names. + */ + allowedHosts?: string[] | "*" | undefined; } export interface ServerCreateResult { diff --git a/packages/server/test/api/public-api.txt b/packages/server/test/api/public-api.txt index 9dd5d57a2..c3a38451e 100644 --- a/packages/server/test/api/public-api.txt +++ b/packages/server/test/api/public-api.txt @@ -34,6 +34,7 @@ TELEMETRY_FLUSH_PHASE: dist/host.d.ts#TELEMETRY_FLUSH_PHASE type TransportConfig: dist/types.d.ts#TransportConfig hostProcedures: dist/module.d.ts#hostProcedures loadProcedureModule: dist/run.d.ts#loadProcedureModule +parseAllowedHosts: dist/config.d.ts#parseAllowedHosts parseConfig: dist/config.d.ts#parseConfig parseTopicPatterns: dist/config.d.ts#parseTopicPatterns registerServerProcedures: dist/module.d.ts#registerServerProcedures @@ -68,6 +69,9 @@ procedure-server: ./dist/cli.js ## Declarations +### dist/config.d.ts#parseAllowedHosts +export declare function parseAllowedHosts(value: string): string[] | "*"; + ### dist/config.d.ts#parseConfig export declare function parseConfig(argv: string[]): ServerConfig; @@ -240,6 +244,7 @@ export interface ServerConfig { events?: string[] | undefined; fsRoot?: string | undefined; probePort?: number | undefined; + allowedHosts?: string[] | "*" | undefined; } ### dist/types.d.ts#ServerCreateResult