diff --git a/oxlint.config.ts b/oxlint.config.ts index 1fbb2fb949..2832014d1a 100644 --- a/oxlint.config.ts +++ b/oxlint.config.ts @@ -109,6 +109,7 @@ export default defineConfig({ files: ["packages/web/server/**/*.ts", "packages/web/bin/**/*.ts"], rules: { "openchamber/server-js-specifiers": "error", + "openchamber/origin-check-awaited": "error", "typescript/no-non-null-assertion": "error", "typescript/ban-ts-comment": ["error", { "ts-ignore": "allow-with-description", diff --git a/packages/web/server/lib/security/DOCUMENTATION.md b/packages/web/server/lib/security/DOCUMENTATION.md index d8cb24fd35..0ffd52f97d 100644 --- a/packages/web/server/lib/security/DOCUMENTATION.md +++ b/packages/web/server/lib/security/DOCUMENTATION.md @@ -27,8 +27,7 @@ HTTP and WebSocket consumers. `../ui-auth` owns credentials and session cookies; LAN address is invisible inside a container. An invalid value is ignored. - Bind helpers receive strings already resolved by server startup or the CLI. HTTP headers and the stored `publicOrigin` retain string validation at use. -- Origin decisions return either a boolean immediately or a promise when - reading settings. Upgrade consumers must support both forms. +- Origin decisions always return a promise, including the packaged-origin and same-host fast paths, and `RequestOriginChecker` says so. A consumer awaits the decision; reading the return value directly would treat a pending lookup as allowed, which is the regression the contract exists to prevent; the `openchamber/origin-check-awaited` lint rule rejects an unawaited check in a condition. Malformed headers reject the promise instead of throwing. - Forwarded-host and host arrays use their first entry. Empty arrays still fail instead of becoming an absent header. Malformed cookie escapes return their raw value. diff --git a/packages/web/server/lib/security/request-security.test.js b/packages/web/server/lib/security/request-security.test.js index 8e4c1ff6d7..fde4a685c8 100644 --- a/packages/web/server/lib/security/request-security.test.js +++ b/packages/web/server/lib/security/request-security.test.js @@ -144,6 +144,24 @@ describe('request security runtime', () => { expect(await allowed({ host: '127.0.0.1:3000' })).toBe(true); }); + test('answers every origin check with a promise, on the fast path and the settings path', async () => { + const runtime = createRuntime(); + + const fastPath = runtime.isRequestOriginAllowed({ + headers: { origin: 'openchamber-ui://app', host: '192.168.1.130:1202' }, + socket: {}, + }); + expect(fastPath).toBeInstanceOf(Promise); + expect(await fastPath).toBe(true); + + const settingsPath = runtime.isRequestOriginAllowed({ + headers: { origin: 'https://dash.example.com', host: '127.0.0.1:3000' }, + socket: {}, + }); + expect(settingsPath).toBeInstanceOf(Promise); + expect(await settingsPath).toBe(false); + }); + test('lets only the app, its shells and named embedders frame it', () => { expect(buildFrameAncestorsPolicy()).toBe("frame-ancestors 'self' openchamber-ui://app capacitor://localhost https://localhost"); expect(buildFrameAncestorsPolicy({ allowLocalDevOrigins: true })).toContain('http://127.0.0.1:*'); @@ -176,10 +194,12 @@ describe('request security runtime', () => { expect(await runtime.isRequestOriginAllowed({ headers: { origin: 'https://public.example', 'x-forwarded-host': ['public.example', 'other.example'] }, })).toBe(true); - expect(runtime.isRequestOriginAllowed({ headers: { origin: ['https://public.example'] } })).toBe(false); - expect(() => runtime.isRequestOriginAllowed({ + expect(await runtime.isRequestOriginAllowed({ headers: { origin: ['https://public.example'] } })).toBe(false); + const malformed = runtime.isRequestOriginAllowed({ headers: { origin: 'https://public.example', 'x-forwarded-host': [] }, - })).toThrow(TypeError); + }); + expect(malformed).toBeInstanceOf(Promise); + await expect(malformed).rejects.toThrow(TypeError); expect(runtime.getUiSessionTokenFromRequest({ headers: { cookie: ['oc_ui_session=value'] } })).toBeNull(); expect(runtime.getUiSessionTokenFromRequest({ headers: { cookie: 'oc_ui_session=%bad' } })).toBe('%bad'); }); diff --git a/packages/web/server/lib/security/request-security.ts b/packages/web/server/lib/security/request-security.ts index 085bb10e6d..4cc6776fe4 100644 --- a/packages/web/server/lib/security/request-security.ts +++ b/packages/web/server/lib/security/request-security.ts @@ -21,7 +21,7 @@ export interface PublicOriginSettings { publicOrigin?: string; } -export type RequestOriginChecker = (req: SecurityRequest) => boolean | Promise; +export type RequestOriginChecker = (req: SecurityRequest) => Promise; const isString = (value: unknown): value is string => typeof value === 'string'; @@ -160,7 +160,7 @@ export const createRequestSecurityRuntime = (deps: RequestSecurityDependencies) return { origins, hosts }; }; - const isRequestOriginAllowed = (req: SecurityRequest) => { + const isRequestOriginAllowed = async (req: SecurityRequest): Promise => { const originHeader = isString(req.headers.origin) ? req.headers.origin.trim() : ''; if (!originHeader) { return false; @@ -187,9 +187,8 @@ export const createRequestSecurityRuntime = (deps: RequestSecurityDependencies) const host = forwardedHost || firstHeaderValue(hostHeader, 'trim').trim().toLowerCase(); if (host && host === origin.host.toLowerCase()) return true; - return getRequestOriginCandidates(req).then((candidates) => ( - candidates.origins.has(origin.origin) || candidates.hosts.has(origin.host.toLowerCase()) - )); + const candidates = await getRequestOriginCandidates(req); + return candidates.origins.has(origin.origin) || candidates.hosts.has(origin.host.toLowerCase()); }; return { diff --git a/packages/web/server/lib/terminal/runtime.ts b/packages/web/server/lib/terminal/runtime.ts index b21a95d1b7..d63ffaf4d3 100644 --- a/packages/web/server/lib/terminal/runtime.ts +++ b/packages/web/server/lib/terminal/runtime.ts @@ -751,18 +751,10 @@ export function createTerminalRuntime({ } }; const checkOrigin = () => { - try { - const result = isRequestOriginAllowed(req); - if (!(result instanceof Promise)) { - if (result) accept(); - else rejectWebSocketUpgrade(socket, 403, 'Invalid origin'); - return; - } - void result.then((allowed) => { - if (allowed) accept(); - else rejectWebSocketUpgrade(socket, 403, 'Invalid origin'); - }).catch((error) => { logUpgradeFailure({ error }); rejectWebSocketUpgrade(socket, 500, 'Upgrade failed'); }); - } catch (error) { logUpgradeFailure({ error }); rejectWebSocketUpgrade(socket, 500, 'Upgrade failed'); } + void isRequestOriginAllowed(req).then((allowed) => { + if (allowed) accept(); + else rejectWebSocketUpgrade(socket, 403, 'Invalid origin'); + }).catch((error) => { logUpgradeFailure({ error }); rejectWebSocketUpgrade(socket, 500, 'Upgrade failed'); }); }; if (isOpaqueOriginRequest(req)) { rejectWebSocketUpgrade(socket, 403, 'Invalid origin'); return; } if (!uiAuthController?.enabled) { diff --git a/scripts/openchamber-lint-rules.test.mjs b/scripts/openchamber-lint-rules.test.mjs index 642b803da1..7eea26eaba 100644 --- a/scripts/openchamber-lint-rules.test.mjs +++ b/scripts/openchamber-lint-rules.test.mjs @@ -7,7 +7,7 @@ import { after, before, test } from 'node:test'; import { fileURLToPath } from 'node:url'; const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); -const RULES = ['gatekeeper-standard-library', 'no-app-imports-in-opencode', 'no-module-mocks-in-tests', 'no-real-waits-in-tests', 'no-source-text-in-tests', 'no-comments', 'no-cross-runtime-imports', 'no-effects-in-components', 'no-raw-fetch', 'no-timers', 'no-wire-client-imports', 'no-valueof-type-escape']; +const RULES = ['gatekeeper-standard-library', 'no-app-imports-in-opencode', 'no-module-mocks-in-tests', 'no-real-waits-in-tests', 'no-source-text-in-tests', 'no-comments', 'no-cross-runtime-imports', 'no-effects-in-components', 'no-raw-fetch', 'no-timers', 'no-wire-client-imports', 'no-valueof-type-escape', 'origin-check-awaited']; const FILES = { 'packages/web/server/lib/type-escape.ts': [ @@ -16,6 +16,22 @@ const FILES = { 'Number.prototype.valueOf.call(input);', 'input.valueOf();', ], + 'packages/web/server/lib/origin-guard.ts': [ + 'export const guard = async (req: unknown, runtime: { isRequestOriginAllowed: (req: unknown) => Promise }, isPasswordlessSocketOriginAllowed: (req: unknown) => Promise) => {', + ' if (!runtime.isRequestOriginAllowed(req)) return 403;', + ' if (isPasswordlessSocketOriginAllowed(req) && req) return 200;', + ' const verdict = runtime.isRequestOriginAllowed(req) ? 200 : 403;', + ' if (!await runtime.isRequestOriginAllowed(req)) return 403;', + ' if (req && await isPasswordlessSocketOriginAllowed(req)) return verdict;', + ' const pending = runtime.isRequestOriginAllowed(req);', + ' if (!pending) return 403;', + ' const awaited = await runtime.isRequestOriginAllowed(req);', + ' if (!awaited) return 403;', + ' const later = isPasswordlessSocketOriginAllowed(req);', + ' if (!await later) return 403;', + ' return runtime.isRequestOriginAllowed(req).then((allowed) => (allowed ? 200 : 403));', + '};', + ], 'packages/web/server/lib/spaces/gatekeeper-program.cjs': [ "const fs = require('node:fs');", "const http = require('http');", @@ -302,6 +318,10 @@ test('lib/opencode takes no import from the app folders beyond its listed edges' assert.deepEqual(linesOf('packages/web/server/lib/settings/frame.js', 'no-app-imports-in-opencode'), []); }); +test('an origin check decides a condition only after it is awaited', () => { + assert.deepEqual(linesOf('packages/web/server/lib/origin-guard.ts', 'origin-check-awaited'), [2, 3, 4, 7]); +}); + test('the standalone gatekeeper imports only the Node standard library', () => { assert.deepEqual(linesOf('packages/web/server/lib/spaces/gatekeeper-program.cjs', 'gatekeeper-standard-library'), [3, 4, 6, 7, 8]); assert.deepEqual(linesOf('packages/web/server/lib/spaces/gatekeeper-program.test.js', 'gatekeeper-standard-library'), []); diff --git a/tools/oxlint/openchamber/index.ts b/tools/oxlint/openchamber/index.ts index 9a18dbe78a..79b8a5a6e0 100644 --- a/tools/oxlint/openchamber/index.ts +++ b/tools/oxlint/openchamber/index.ts @@ -15,6 +15,7 @@ import { noTimersRule } from "./rules/no-timers.ts"; import { noValueofTypeEscapeRule } from "./rules/no-valueof-type-escape.ts"; import { noVirtualizerReturnFromHooksRule } from "./rules/no-virtualizer-return-from-hooks.ts"; import { noWireClientImportsRule } from "./rules/no-wire-client-imports.ts"; +import { originCheckAwaitedRule } from "./rules/origin-check-awaited.ts"; import { serverJsSpecifiersRule } from "./rules/server-js-specifiers.ts"; /** @@ -40,6 +41,7 @@ const openchamberPlugin = eslintCompatPlugin({ "no-valueof-type-escape": noValueofTypeEscapeRule, "no-virtualizer-return-from-hooks": noVirtualizerReturnFromHooksRule, "no-wire-client-imports": noWireClientImportsRule, + "origin-check-awaited": originCheckAwaitedRule, "server-js-specifiers": serverJsSpecifiersRule, }, }); diff --git a/tools/oxlint/openchamber/rules/origin-check-awaited.ts b/tools/oxlint/openchamber/rules/origin-check-awaited.ts new file mode 100644 index 0000000000..84cc198d09 --- /dev/null +++ b/tools/oxlint/openchamber/rules/origin-check-awaited.ts @@ -0,0 +1,66 @@ +import { defineRule } from "@oxlint/plugins"; +import type { ESTree } from "@oxlint/plugins"; + +const ORIGIN_CHECKS = new Set(["isRequestOriginAllowed", "isPasswordlessSocketOriginAllowed"]); + +const calleeName = (callee: ESTree.Node) => { + if (callee.type === "Identifier") return callee.name; + if (callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier") return callee.property.name; + return ""; +}; + +const isTestOf = (node: ESTree.Node, parent: ESTree.Node) => { + switch (parent.type) { + case "IfStatement": + case "WhileStatement": + case "DoWhileStatement": + case "ForStatement": + case "ConditionalExpression": + return parent.test === node; + case "CallExpression": + return parent.callee.type === "Identifier" && parent.callee.name === "Boolean" && parent.arguments[0] === node; + default: + return false; + } +}; + +const decidesCondition = (node: ESTree.Node) => { + let current: ESTree.Node = node; + for (let parent = node.parent; parent; current = parent, parent = parent.parent) { + if (parent.type === "UnaryExpression" && parent.operator === "!") return true; + if (parent.type === "LogicalExpression") { + if (parent.left === current && parent.operator !== "??") return true; + continue; + } + return isTestOf(current, parent); + } + return false; +}; + +export const originCheckAwaitedRule = defineRule({ + meta: { + type: "problem", + docs: { description: "Require an origin check to be awaited before it decides a condition." }, + messages: { + unawaited: + "Origin checks return a promise, and a promise is always truthy: `!check(req)` never rejects and `check(req) && ...` always passes. Await the check before using it as a condition.", + }, + }, + createOnce(context) { + return { + CallExpression(node) { + if (!ORIGIN_CHECKS.has(calleeName(node.callee))) return; + if (decidesCondition(node)) { + context.report({ node, messageId: "unawaited" }); + return; + } + const declarator = node.parent; + if (declarator?.type !== "VariableDeclarator" || declarator.init !== node || declarator.id.type !== "Identifier") return; + const stored = context.sourceCode.getDeclaredVariables(declarator).flatMap((variable) => variable.references); + if (stored.some((reference) => reference.isRead() && decidesCondition(reference.identifier))) { + context.report({ node, messageId: "unawaited" }); + } + }, + }; + }, +});