Compare commits

..

1 Commits

Author SHA1 Message Date
diegosouzapw
0328768396 fix(security): authorize embedded-service WebSocket proxy upgrades
The embedded-services WebSocket proxy (EMBED_WS_PROXY_PORT, default 20131)
tunnelled any upgrade to the target service and added the service's own
Authorization header, without checking who asked. It now applies the same
decision as the HTTP embed route (LOCAL_ONLY + management auth) before it
opens a tunnel:

- the TCP peer must be loopback and carry no reverse-proxy hop header;
- a browser Origin must be one of the dashboard origins (same allow-list
  as the Live dashboard socket);
- the caller needs a dashboard session or a management-scope API key,
  unless dashboard login is disabled (same bar as the HTTP embed route).

A rejected upgrade gets 401/403 and never reaches the service, so the
service credential is only sent on behalf of an authorized caller. Auth
backend errors fail closed (503).

Service bootstrap no longer starts a service with a fixed fallback
credential when its stored key cannot be loaded; the service is skipped
and the on-demand /api/services/<name>/* path reports the key error.
2026-11-18 00:37:52 -03:00
15 changed files with 575 additions and 383 deletions

View File

@@ -1 +0,0 @@
- **fix(security):** `POST /api/plugins` now installs only from the `plugin-sources` directory next to the plugin root (canonicalized with `realpath`, symlinks escaping it refused, fail closed) and requires the management credential even when login is disabled

View File

@@ -0,0 +1 @@
- **fix(security):** the embedded-services WebSocket proxy now authorizes every upgrade like the HTTP embed route (loopback peer, dashboard Origin, dashboard session or management-scope key) before it opens a tunnel with the service credential, and service bootstrap no longer starts a service with a fallback credential when its key cannot be loaded

View File

@@ -624,7 +624,12 @@ This proxy:
- Rewrites HTML responses to inject `<base href>` and normalize absolute paths (`/foo` → `/dashboard/.../embed/foo`)
WebSocket upgrades for the embedded dashboard are handled by a companion server on a
dedicated port (see `src/lib/services/embedWsProxy.ts`).
dedicated port (see `src/lib/services/embedWsProxy.ts`). Every upgrade is authorized
before the tunnel opens, with the same rules as the HTTP embed route: the peer must be
loopback with no reverse-proxy forwarding header, a browser `Origin` must be a dashboard
origin (`LIVE_WS_ALLOWED_ORIGINS` / `LIVE_WS_ALLOWED_HOSTS` extend the loopback
defaults), and the caller needs a dashboard session or a management-scope API key unless
dashboard login is disabled.
**Security:** The embed proxy routes are classified under `LOCAL_ONLY_API_PREFIXES`
and can only be reached from loopback. An attacker who obtains a JWT via a

View File

@@ -94,7 +94,7 @@ loopback-only — `/api/plugins` and `/api/plugins/` are listed in
| Endpoint | Method | Description |
| -------------------------------- | ------ | --------------------------------------------------- |
| `/api/plugins` | GET | List installed plugins (optional `?status=` filter) |
| `/api/plugins` | POST | Install a plugin from the plugin sources directory |
| `/api/plugins` | POST | Install a plugin from an absolute local path |
| `/api/plugins/scan` | POST | Scan the plugin directory and register new plugins |
| `/api/plugins/marketplace` | GET | List marketplace catalog entries |
| `/api/plugins/[name]` | GET | Get installed plugin details |
@@ -123,20 +123,10 @@ curl -X POST http://localhost:20128/api/plugins \
-d '{ "path": "/absolute/path/to/my-plugin" }'
```
The `path` must be an **absolute** path to a directory **inside the plugin
sources directory**: `plugin-sources` next to the plugin root, so
`~/.omniroute/plugin-sources/` by default, or `<parent of OMNIROUTE_PLUGINS_DIR>/plugin-sources/`
when that variable is set (`getPluginSourcesDir()` in
`src/lib/plugins/installSource.ts`). Copy or clone the plugin there first. The
install is refused with `400` when the path contains `..` or a null byte, lies
outside that directory, resolves outside it through a symlink, contains a symlink
whose target is outside it, or when the directory does not exist. The source
directory must contain a valid `plugin.json` (or be a parent of one). On success
the response is `201` with the installed plugin row.
Unlike the other plugin routes, this one requires the management credential (a
dashboard session or a manage-scoped API key) even when login is disabled
(`requireLogin=false`): installing code is never an anonymous action.
The `path` must be **absolute** and may not contain `..` traversal segments or
null bytes (enforced by Zod). The source directory must contain a valid
`plugin.json` (or be a parent of one). On success the response is `201` with the
installed plugin row.
### Browse the marketplace
@@ -258,10 +248,6 @@ silently falls back to the built-in seed registry and logs a warning.
- **Env allowlist** — the child receives only an allowlisted set of environment
variables; the broader set is only granted when the manifest requests the
`env` permission.
- **Install source containment** — `POST /api/plugins` only reads from the plugin
sources directory (see "Install from a local path"): the path is canonicalized
with `realpath`, must stay strictly inside that directory, and a source tree
carrying a symlink that escapes it is refused before anything is copied.
- **Path containment** — install/upgrade/uninstall assert that the plugin
directory and `manifest.main` resolve **within** the managed plugin root
before any copy or recursive delete (guards against tampered DB paths and

View File

@@ -5,11 +5,34 @@
*/
import { z } from "zod";
import { resolve, normalize, isAbsolute } from "path";
import { toSafeMcpErrorMessage } from "../errorMessage";
import { listPlugins, getPluginByName, updatePluginConfig } from "../../../src/lib/db/plugins";
import { pluginManager } from "../../../src/lib/plugins/manager";
import { validatePluginConfig, type ConfigField } from "../../../src/lib/plugins/manifest";
/**
* Validate a path is safe for plugin installation.
* Prevents directory traversal and null byte injection.
*/
function validatePluginPath(path: string): string {
// Reject null bytes
if (path.includes("\0")) {
throw new Error("Invalid path: contains null bytes");
}
// Must be absolute
if (!isAbsolute(path)) {
throw new Error("Path must be absolute");
}
// Normalize and resolve to prevent traversal
const normalized = normalize(resolve(path));
// Reject paths with traversal patterns
if (normalized.includes("..") || normalized.includes("~")) {
throw new Error("Invalid path: directory traversal detected");
}
return normalized;
}
export const pluginTools = [
{
name: "plugin_list",
@@ -41,19 +64,14 @@ export const pluginTools = [
{
name: "plugin_install",
description: "Install a plugin from a local directory inside the plugin sources directory.",
description: "Install a plugin from a local directory path.",
scopes: ["write:plugins"],
inputSchema: z.object({
path: z
.string()
.describe(
"Absolute path to a plugin directory (containing plugin.json) inside the plugin sources directory"
),
path: z.string().describe("Absolute path to the plugin directory containing plugin.json"),
}),
handler: async (args: { path: string }) => {
// Same containment as POST /api/plugins: the source must resolve inside the
// plugin sources directory (src/lib/plugins/installSource.ts).
const plugin = await pluginManager.installFromLocalSource(args.path);
const safePath = validatePluginPath(args.path);
const plugin = await pluginManager.install(safePath);
return {
success: true,
plugin: {

View File

@@ -3,7 +3,6 @@ import { CORS_HEADERS, handleCorsOptions } from "@/shared/utils/cors";
import { buildErrorBody } from "@omniroute/open-sse/utils/error";
import { listPlugins } from "@/lib/db/plugins";
import { pluginManager } from "@/lib/plugins/manager";
import { PluginInstallSourceError } from "@/lib/plugins/installSource";
import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
import { z } from "zod";
@@ -41,12 +40,10 @@ export async function GET(request: NextRequest) {
}
/**
* POST /api/plugins — Install a plugin from a local path inside the plugin sources
* directory. Installing (and possibly activating) code is never anonymous, so the
* management credential is required even when login is disabled.
* POST /api/plugins — Install a plugin from a local path
*/
export async function POST(request: NextRequest) {
const authError = await requireManagementAuth(request, { alwaysRequireAuth: true });
const authError = await requireManagementAuth(request);
if (authError) return authError;
let body: unknown;
try {
@@ -58,13 +55,10 @@ export async function POST(request: NextRequest) {
);
}
const schema = z.object({
path: z
.string()
.min(1)
.refine(
(p) => !p.includes("\0") && !p.includes(".."),
"Path must not contain traversal patterns or null bytes"
),
path: z.string().min(1).regex(/^\/[^]*$/, "Path must be absolute").refine(
(p) => !p.includes("\0") && !p.includes(".."),
"Path must not contain traversal patterns or null bytes"
),
});
const parsed = schema.safeParse(body);
@@ -76,22 +70,12 @@ export async function POST(request: NextRequest) {
}
try {
const plugin = await pluginManager.installFromLocalSource(parsed.data.path);
const plugin = await pluginManager.install(parsed.data.path);
return NextResponse.json(
{ plugin: formatPlugin(plugin) },
{ status: 201, headers: CORS_HEADERS }
);
} catch (err: unknown) {
if (err instanceof PluginInstallSourceError) {
console.warn("[plugins] Refused plugin install source:", err.message);
return NextResponse.json(
buildErrorBody(
400,
"Plugin path must be an existing directory inside the plugin sources directory"
),
{ status: 400, headers: CORS_HEADERS }
);
}
console.error("[plugins] Failed to install plugin:", err);
return NextResponse.json(buildErrorBody(400, "Failed to install plugin"), {
status: 400,

View File

@@ -1,97 +0,0 @@
/**
* Install-source containment for the local-path plugin install.
*
* `POST /api/plugins` installs (and, with `enabledByDefault`, activates) the code
* found at a caller-supplied path. That path must live inside one operator-managed
* directory: the `plugin-sources` directory next to the plugin root
* (`~/.omniroute/plugin-sources` by default, or `<dirname(OMNIROUTE_PLUGINS_DIR)>/
* plugin-sources` when the plugin root is overridden). Anything else is refused.
*
* Every check fails closed: a missing root, a path that does not exist, a path that
* resolves (through symlinks) outside the root, or a symlink inside the source tree
* whose target escapes the root all reject the install.
*
* @module plugins/installSource
*/
import { lstat, readdir, realpath } from "fs/promises";
import { dirname, isAbsolute, join, resolve, sep } from "path";
export const PLUGIN_SOURCES_DIRNAME = "plugin-sources";
export class PluginInstallSourceError extends Error {
constructor(message: string) {
super(message);
this.name = "PluginInstallSourceError";
}
}
/** The directory local-path installs may read from, derived from the plugin root. */
export function getPluginSourcesDir(pluginDir: string): string {
return join(dirname(resolve(pluginDir)), PLUGIN_SOURCES_DIRNAME);
}
function isStrictlyInside(root: string, target: string): boolean {
return target.startsWith(root + sep);
}
async function assertNoEscapingSymlinks(dir: string, realRoot: string): Promise<void> {
const entries = await readdir(dir, { recursive: true, withFileTypes: true });
for (const entry of entries) {
if (!entry.isSymbolicLink()) continue;
const entryPath = join(entry.parentPath, entry.name);
const target = await realpath(entryPath).catch(() => null);
if (!target || !isStrictlyInside(realRoot, target)) {
throw new PluginInstallSourceError(
"Plugin source contains a symlink that resolves outside the plugin sources directory"
);
}
}
}
/**
* Validate a caller-supplied install path against the plugin sources root and
* return its canonical (symlink-free) form, which is what the installer must use.
*/
export async function resolvePluginInstallSource(
requestedPath: string,
sourcesRoot: string
): Promise<string> {
if (
typeof requestedPath !== "string" ||
requestedPath.length === 0 ||
requestedPath.includes("\0") ||
!isAbsolute(requestedPath)
) {
throw new PluginInstallSourceError("Plugin path must be an absolute path");
}
const root = resolve(sourcesRoot);
const realRoot = await realpath(root).catch(() => null);
if (!realRoot) {
throw new PluginInstallSourceError("Plugin sources directory does not exist");
}
// Lexical check first, so a path outside the root is refused without ever being
// touched on disk (no existence probe of arbitrary host paths).
const lexical = resolve(requestedPath);
if (!isStrictlyInside(root, lexical) && !isStrictlyInside(realRoot, lexical)) {
throw new PluginInstallSourceError("Plugin path is outside the plugin sources directory");
}
const realSource = await realpath(requestedPath).catch(() => null);
if (!realSource) {
throw new PluginInstallSourceError("Plugin path does not exist");
}
if (!isStrictlyInside(realRoot, realSource)) {
throw new PluginInstallSourceError("Plugin path is outside the plugin sources directory");
}
const info = await lstat(realSource);
if (!info.isDirectory()) {
throw new PluginInstallSourceError("Plugin path must be a directory");
}
await assertNoEscapingSymlinks(realSource, realRoot);
return realSource;
}

View File

@@ -13,7 +13,6 @@ import { join, dirname, resolve, sep } from "path";
import { randomUUID } from "crypto";
import { logger } from "../../../open-sse/utils/logger.ts";
import { getDefaultPluginDir, scanPluginDir } from "./scanner";
import { getPluginSourcesDir, resolvePluginInstallSource } from "./installSource";
import { loadPlugin, type LoadedPlugin } from "./loader";
import { registerHook, unregisterHooks, emitHook, type HookHandler, type Plugin } from "./hooks";
import {
@@ -122,21 +121,6 @@ class PluginManager {
return PluginManager.instance;
}
/** Directory that caller-supplied local install paths must live in. */
getSourcesDir(): string {
return getPluginSourcesDir(this.pluginDir);
}
/**
* Install from a caller-supplied local path (POST /api/plugins). The path must
* resolve inside {@link getSourcesDir}; see ./installSource for the checks.
* Throws PluginInstallSourceError when the path is refused.
*/
async installFromLocalSource(requestedPath: string): Promise<PluginRow> {
const source = await resolvePluginInstallSource(requestedPath, this.getSourcesDir());
return this.install(source);
}
/**
* Install a plugin from a source directory.
* Copies to a staging dir first, validates manifest.main containment, then

View File

@@ -186,6 +186,23 @@ function buildSpawnArgsFactory(
return () => cliproxySpawnArgs(cfg.port, apiKey);
}
/**
* The service's own credential (API key / admin token), "" when it needs none,
* or null when it cannot be loaded. A null key means the service is not started:
* a guessable stand-in would be worse than no service, and the on-demand
* /api/services/<tool>/* path reports the key error to the operator.
*/
async function loadServiceApiKey(cfg: ServiceEntry): Promise<string | null> {
if (!cfg.needsApiKey) return "";
try {
return await getOrCreateApiKey(cfg.tool);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
console.warn(`[Services] Not supervising ${cfg.tool}: its API key is unavailable. ${msg}`);
return null;
}
}
export async function bootstrapEmbeddedServices(): Promise<void> {
for (const cfg of SERVICES) {
if (getSupervisor(cfg.tool)) continue;
@@ -193,9 +210,8 @@ export async function bootstrapEmbeddedServices(): Promise<void> {
const row = await getVersionManagerTool(cfg.tool);
if (!row || row.status === "not_installed") continue;
const apiKey = cfg.needsApiKey
? await getOrCreateApiKey(cfg.tool).catch(() => "placeholder")
: "";
const apiKey = await loadServiceApiKey(cfg);
if (apiKey === null) continue;
// CLIProxyAPI's generated key is management-only; /v1/models uses its dedicated data-plane key.
const modelSyncApiKey =
cfg.tool === "cliproxy"

View File

@@ -13,8 +13,15 @@
* - Target host is always 127.0.0.1 and port comes from the registry — never
* from user input. No SSRF risk.
* - Server binds to 127.0.0.1 only (loopback) unless EMBED_WS_PROXY_HOST
* is set explicitly. The OmniRoute LOCAL_ONLY rule is enforced at the
* dashboard layer; the proxy itself is loopback-only as defence-in-depth.
* (or LIVE_WS_HOST) is set explicitly.
* - Every upgrade is authorized before the tunnel opens
* (authorizeEmbedWsUpgrade), with the same decision as the HTTP embed route
* (LOCAL_ONLY + management auth, Hard Rule #17): the TCP peer must be
* loopback with no reverse-proxy hop header, a browser Origin must be one of
* the dashboard origins, and the caller must hold a dashboard session or a
* management-scope API key (unless dashboard login is disabled). A rejected
* upgrade never reaches the service, so the injected service credential is
* only ever sent on behalf of an authorized caller. Errors fail closed.
* - Max 50 concurrent connections per service. The 51st request receives 503.
* - Idle timeout: 5 minutes without any data → both sockets are destroyed.
* - Hop-by-hop headers cookie/authorization/origin are stripped from the
@@ -27,6 +34,13 @@ import type { IncomingMessage } from "node:http";
import { getSupervisor } from "./registry";
import { getOrCreateApiKey } from "./apiKey";
import { getApiKeyMetadata } from "@/lib/db/apiKeys";
import { hasProxyHopHeader } from "@/server/authz/proxyHeaders";
import { isLoopbackHost } from "@/server/authz/routeGuard";
import { isOriginAllowed } from "@/server/ws/liveServerAllowList";
import { hasManageScope } from "@/shared/constants/managementScopes";
import { isAuthRequired, isDashboardSessionAuthenticated } from "@/shared/utils/apiAuth";
import { extractApiKey, isValidApiKey } from "@/sse/services/auth";
import {
attachRequestStreamGuards,
installProcessCrashGuard,
@@ -129,7 +143,96 @@ function buildUpstreamHeaders(rawHeaders: string[], port: number, apiKey: string
return lines;
}
export type EmbedWsUpgradeVerdict =
| { allow: true; via: "anonymous" | "dashboard_session" | "management_key" }
| { allow: false; status: number; message: string };
function deny(status: number, message: string): EmbedWsUpgradeVerdict {
return { allow: false, status, message };
}
/** True when the upgrade's real TCP peer is this machine and no proxy hop relayed it. */
function isLocalUpgradePeer(req: IncomingMessage): boolean {
if (hasProxyHopHeader(req.headers)) return false;
return isLoopbackHost(req.socket?.remoteAddress ?? null);
}
/**
* A browser always sends Origin on a WebSocket upgrade; it must be one of the
* dashboard origins (same allow-list as the Live dashboard socket:
* LIVE_WS_ALLOWED_ORIGINS / LIVE_WS_ALLOWED_HOSTS on top of the loopback
* defaults). A client without Origin is not a browser page; it still has to be
* local and authenticated.
*/
function isUpgradeOriginAllowed(origin: string | string[] | undefined): boolean {
if (origin === undefined) return true;
if (typeof origin !== "string" || origin.length === 0) return false;
return isOriginAllowed(origin, process.env);
}
function toHeaders(headers: IncomingMessage["headers"]): Headers {
const out = new Headers();
for (const [name, value] of Object.entries(headers)) {
if (typeof value === "string") out.set(name, value);
else if (Array.isArray(value)) {
out.set(name, value.join(name.toLowerCase() === "cookie" ? "; " : ", "));
}
}
return out;
}
/**
* Decide whether an upgrade may open a tunnel. Mirrors the management policy the
* HTTP embed route (`/dashboard/providers/services/<name>/embed/`) goes through:
* loopback only, then anonymous when dashboard login is off, otherwise a
* dashboard session or an API key with a management scope. Header-only
* credentials; a URL-borne token never counts.
*/
export async function authorizeEmbedWsUpgrade(
req: IncomingMessage
): Promise<EmbedWsUpgradeVerdict> {
if (!isLocalUpgradePeer(req)) {
return deny(403, "The embedded service WebSocket proxy only accepts local connections");
}
if (!isUpgradeOriginAllowed(req.headers.origin)) {
return deny(403, "Origin not allowed");
}
const authRequest = {
url: "http://127.0.0.1/dashboard/providers/services/embed-ws",
method: "GET",
headers: toHeaders(req.headers),
};
try {
if (!(await isAuthRequired(authRequest, { loopback: true }))) {
return { allow: true, via: "anonymous" };
}
if (await isDashboardSessionAuthenticated(authRequest)) {
return { allow: true, via: "dashboard_session" };
}
const apiKey = extractApiKey(authRequest, { allowUrl: false });
if (apiKey && (await isValidApiKey(apiKey))) {
const meta = await getApiKeyMetadata(apiKey);
if (meta && hasManageScope(meta.scopes ?? [])) {
return { allow: true, via: "management_key" };
}
}
return apiKey ? deny(403, "Invalid management token") : deny(401, "Authentication required");
} catch {
return deny(503, "Authentication backend unavailable");
}
}
async function proxyUpgrade(req: IncomingMessage, socket: net.Socket, head: Buffer): Promise<void> {
// Authorize before anything else: an unauthorized caller learns nothing about
// the registered services and never gets a tunnel carrying the service key.
const verdict = await authorizeEmbedWsUpgrade(req);
if (!verdict.allow) {
writeError(socket, verdict.status, verdict.message);
return;
}
const rawUrl = req.url ?? "/";
const match = PATH_RE.exec(rawUrl.split("?")[0]);
@@ -245,13 +348,13 @@ export function resolveEmbedWsHost(): string {
* Start the embed WebSocket proxy server.
* Idempotent — safe to call multiple times.
*/
export function initEmbedWsProxy(): void {
export function initEmbedWsProxy(): http.Server | undefined {
// Safety net: a client aborting a connection can emit `Error: aborted`/
// ECONNRESET on the request stream; without this the single missed listener
// becomes an uncaughtException that kills the server. Benign aborts are
// swallowed; genuine errors still crash loudly (#fix-dev-server-aborted).
installProcessCrashGuard();
if (globalThis.__omnirouteEmbedWsStarted) return;
if (globalThis.__omnirouteEmbedWsStarted) return undefined;
const host = resolveEmbedWsHost();
const port = parseInt(process.env.EMBED_WS_PROXY_PORT ?? String(DEFAULT_PORT), 10);
@@ -284,6 +387,8 @@ export function initEmbedWsProxy(): void {
globalThis.__omnirouteEmbedWsStarted = true;
console.log(`[EmbedWsProxy] Listening on ${host}:${port}`);
});
return server;
}
// ─── Exported for testing ────────────────────────────────────────────────────

View File

@@ -7,10 +7,9 @@
* must surface as a clean 400, while a well-formed body keeps its existing behavior.
*
* DB setup mirrors tests/unit/api-malformed-json-400.test.ts: a temp DATA_DIR with no
* configured password. Both POST /api/plugins and PATCH /api/relay/tokens/[id] always
* require management auth, so their requests carry a manage-scoped API key, as in
* tests/unit/relay-tokens-always-protected.test.ts; the relay requests target a seeded
* token. DB handles
* configured password, so POST /api/plugins needs no login. PATCH /api/relay/tokens/[id]
* always requires management auth, so its requests carry a manage-scoped API key, as in
* tests/unit/relay-tokens-always-protected.test.ts, and target a seeded token. DB handles
* are released in test.after (resetDbInstance), as unreleased SQLite handles hang the runner.
*/
@@ -70,21 +69,14 @@ test.after(() => {
test("POST /api/plugins — malformed JSON body returns 400", async () => {
const res = await pluginsRoute.POST(
managedJsonRequest("http://localhost/api/plugins", "POST", "not-json") as never
jsonRequest("http://localhost/api/plugins", "POST", "not-json") as never
);
assert.equal(res.status, 400);
});
test("POST /api/plugins — malformed JSON without credentials is still 401", async () => {
const res = await pluginsRoute.POST(
jsonRequest("http://localhost/api/plugins", "POST", "not-json") as never
);
assert.equal(res.status, 401);
});
test("POST /api/plugins — well-formed but invalid body still returns 400", async () => {
const res = await pluginsRoute.POST(
managedJsonRequest("http://localhost/api/plugins", "POST", JSON.stringify({})) as never
jsonRequest("http://localhost/api/plugins", "POST", JSON.stringify({})) as never
);
assert.equal(res.status, 400);
const body = (await res.json()) as { error?: string };

View File

@@ -1,172 +0,0 @@
// POST /api/plugins installs — and, with `enabledByDefault`, activates — the code at a
// caller-supplied path. Two guarantees are pinned here:
// 1. the install source must live inside the operator-managed `plugin-sources`
// directory next to the plugin root; any other absolute path, a path that
// resolves outside it through a symlink, or a source tree carrying a symlink
// that escapes it is refused before anything is copied;
// 2. the route needs a management credential even when login is disabled
// (requireLogin=false): "anonymous" is never the right audience for
// "install and run this code on the host".
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
const BASE_DIR = fs.mkdtempSync(
path.join(process.env.DATA_DIR || os.tmpdir(), "plugin-src-guard-")
);
const PLUGIN_ROOT = path.join(BASE_DIR, "plugins");
const SOURCES_ROOT = path.join(BASE_DIR, "plugin-sources");
const OUTSIDE_ROOT = path.join(BASE_DIR, "outside");
fs.mkdirSync(PLUGIN_ROOT, { recursive: true });
fs.mkdirSync(SOURCES_ROOT, { recursive: true });
fs.mkdirSync(OUTSIDE_ROOT, { recursive: true });
const ORIGINAL_ENV = {
OMNIROUTE_PLUGINS_DIR: process.env.OMNIROUTE_PLUGINS_DIR,
JWT_SECRET: process.env.JWT_SECRET,
API_KEY_SECRET: process.env.API_KEY_SECRET,
};
process.env.OMNIROUTE_PLUGINS_DIR = PLUGIN_ROOT;
process.env.JWT_SECRET = "plugin-src-guard-jwt-secret";
process.env.API_KEY_SECRET = "plugin-src-guard-api-key-secret";
const core = await import("../../src/lib/db/core.ts");
const pluginsDb = await import("../../src/lib/db/plugins.ts");
const { updateSettings } = await import("../../src/lib/db/settings.ts");
const pluginsRoute = await import("../../src/app/api/plugins/route.ts");
const loadInstallSource = () => import("../../src/lib/plugins/installSource.ts");
const URL_PLUGINS = "http://localhost:20128/api/plugins";
test.after(() => {
core.resetDbInstance();
fs.rmSync(BASE_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
for (const [key, value] of Object.entries(ORIGINAL_ENV)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});
function writePlugin(parent: string, name: string): string {
const dir = path.join(parent, name);
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
path.join(dir, "plugin.json"),
JSON.stringify({ name, version: "1.0.0", main: "index.js" })
);
fs.writeFileSync(path.join(dir, "index.js"), "module.exports = {};\n");
return dir;
}
function anonymousPost(body: unknown): Request {
return new Request(URL_PLUGINS, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
}
function sessionPost(body: unknown): Promise<Request> {
return makeManagementSessionRequest(URL_PLUGINS, { method: "POST", body: body as never });
}
async function assertRefused(response: Response, status: number): Promise<void> {
const text = await response.text();
assert.equal(response.status, status, `expected ${status}, got ${response.status}: ${text}`);
assert.ok(!text.includes("at /"), "error body must not leak a stack trace");
}
test("getPluginSourcesDir is the plugin-sources sibling of the plugin root", async () => {
const installSource = await loadInstallSource();
assert.equal(installSource.getPluginSourcesDir(PLUGIN_ROOT), SOURCES_ROOT);
});
test("resolvePluginInstallSource refuses paths outside the sources root", async () => {
const installSource = await loadInstallSource();
const outside = writePlugin(OUTSIDE_ROOT, "outside-direct");
const cases = [
outside,
"/etc",
"relative/plugin",
"",
`${SOURCES_ROOT}/../outside/outside-direct`,
SOURCES_ROOT,
`${SOURCES_ROOT}-sibling/x`,
`${SOURCES_ROOT}/x\0y`,
];
for (const candidate of cases) {
await assert.rejects(
installSource.resolvePluginInstallSource(candidate, SOURCES_ROOT),
installSource.PluginInstallSourceError,
`must refuse ${JSON.stringify(candidate)}`
);
}
});
test("resolvePluginInstallSource refuses symlinks that escape the sources root", async () => {
const installSource = await loadInstallSource();
const outside = writePlugin(OUTSIDE_ROOT, "outside-linked");
const linkedDir = path.join(SOURCES_ROOT, "linked-dir");
fs.symlinkSync(outside, linkedDir, "dir");
await assert.rejects(
installSource.resolvePluginInstallSource(linkedDir, SOURCES_ROOT),
installSource.PluginInstallSourceError
);
const inner = writePlugin(SOURCES_ROOT, "inner-escape");
fs.mkdirSync(path.join(inner, "lib"));
fs.symlinkSync(path.join(outside, "index.js"), path.join(inner, "lib", "evil.js"));
await assert.rejects(
installSource.resolvePluginInstallSource(inner, SOURCES_ROOT),
installSource.PluginInstallSourceError
);
});
test("resolvePluginInstallSource fails closed when the sources root does not exist", async () => {
const installSource = await loadInstallSource();
const missingRoot = path.join(BASE_DIR, "missing-root");
await assert.rejects(
installSource.resolvePluginInstallSource(path.join(missingRoot, "p"), missingRoot),
installSource.PluginInstallSourceError
);
});
test("resolvePluginInstallSource accepts a plugin directory inside the sources root", async () => {
const installSource = await loadInstallSource();
const good = writePlugin(SOURCES_ROOT, "inside-ok");
fs.symlinkSync(path.join(good, "index.js"), path.join(good, "alias.js"));
const resolved = await installSource.resolvePluginInstallSource(good, SOURCES_ROOT);
assert.equal(resolved, fs.realpathSync(good));
});
test("POST /api/plugins refuses an install source outside the plugin sources directory", async () => {
const outside = writePlugin(OUTSIDE_ROOT, "route-outside");
const response = await pluginsRoute.POST((await sessionPost({ path: outside })) as never);
await assertRefused(response, 400);
assert.equal(pluginsDb.getPluginByName("route-outside"), null, "nothing may be installed");
assert.equal(fs.existsSync(path.join(PLUGIN_ROOT, "route-outside")), false);
});
test("POST /api/plugins installs from inside the plugin sources directory", async () => {
const good = writePlugin(SOURCES_ROOT, "route-inside");
const response = await pluginsRoute.POST((await sessionPost({ path: good })) as never);
const text = await response.text();
assert.equal(response.status, 201, text);
assert.equal(JSON.parse(text).plugin.name, "route-inside");
assert.ok(pluginsDb.getPluginByName("route-inside"));
});
test("with login disabled, an anonymous POST /api/plugins is refused", async () => {
const good = writePlugin(SOURCES_ROOT, "route-anon");
await updateSettings({ requireLogin: false });
try {
const response = await pluginsRoute.POST(anonymousPost({ path: good }) as never);
await assertRefused(response, 401);
assert.equal(pluginsDb.getPluginByName("route-anon"), null, "nothing may be installed");
} finally {
await updateSettings({ requireLogin: true });
}
});

View File

@@ -22,11 +22,10 @@ function getTool(name: string) {
return tool!;
}
function writeTestPlugin(opts?: { name?: string; onRequest?: boolean; parent?: string }) {
function writeTestPlugin(opts?: { name?: string; onRequest?: boolean }) {
const name = opts?.name ?? "test-tools-plugin";
const onRequest = opts?.onRequest ?? true;
if (opts?.parent) fs.mkdirSync(opts.parent, { recursive: true });
const sourceDir = fs.mkdtempSync(path.join(opts?.parent ?? os.tmpdir(), "omniroute-plugin-src-"));
const sourceDir = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-plugin-src-"));
const pluginDir = path.join(sourceDir, name);
fs.mkdirSync(pluginDir, { recursive: true });
const manifest = {
@@ -127,12 +126,8 @@ test("plugin_list: filters by status", async () => {
// ── plugin_install ──
test("plugin_install: installs a valid plugin from the plugin sources directory", async () => {
const { pluginManager } = await import("../../src/lib/plugins/manager.ts");
const { sourceDir, name } = writeTestPlugin({
name: "install-tool",
parent: pluginManager.getSourcesDir(),
});
test("plugin_install: installs a valid plugin", async () => {
const { sourceDir, name } = writeTestPlugin({ name: "install-tool" });
activeSourceDirs.push(sourceDir);
const tool = getTool("plugin_install");
@@ -140,30 +135,16 @@ test("plugin_install: installs a valid plugin from the plugin sources directory"
assert.equal(result.success, true);
assert.equal(result.plugin.name, name);
const { pluginManager } = await import("../../src/lib/plugins/manager.ts");
await pluginManager.uninstall(name);
});
test("plugin_install: refuses a path outside the plugin sources directory", async () => {
const { sourceDir, name } = writeTestPlugin({ name: "install-tool-outside" });
activeSourceDirs.push(sourceDir);
const tool = getTool("plugin_install");
await assert.rejects(
() => tool.handler({ path: sourceDir }),
(err: Error) => {
assert.equal(err.name, "PluginInstallSourceError");
return true;
}
);
assert.equal(dbPlugins.getPluginByName(name), null, "nothing may be installed");
});
test("plugin_install: throws for invalid path", async () => {
const tool = getTool("plugin_install");
await assert.rejects(
() => tool.handler({ path: "/nonexistent/path" }),
(err: Error) => {
assert.equal(err.name, "PluginInstallSourceError");
assert.ok(err.message.includes("No valid plugin found"));
return true;
}
);

View File

@@ -0,0 +1,61 @@
/**
* bootstrapEmbeddedServices must not supervise a service whose API key cannot be
* loaded. The key is the service's own credential (9router API key, Mux auth token,
* Dario admin token, ...): starting the service with a fixed fallback string would hand
* it a credential anyone can guess. The service is skipped instead; the on-demand
* /api/services/<name>/* path then surfaces the key error to the operator.
*/
import { after, before, test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
const ORIGINAL_STORAGE_KEY = process.env.STORAGE_ENCRYPTION_KEY;
const ORIGINAL_DATA_DIR = process.env.DATA_DIR;
// Own database directory: another test file may share the inherited DATA_DIR.
const TEST_DATA_DIR = fs.mkdtempSync(
path.join(process.env.DATA_DIR || os.tmpdir(), "bootstrap-service-key-")
);
process.env.DATA_DIR = TEST_DATA_DIR;
// Without a storage key an encrypted column cannot be decrypted, which is the
// degraded state this test needs.
delete process.env.STORAGE_ENCRYPTION_KEY;
const core = await import("../../../src/lib/db/core.ts");
const { upsertVersionManagerTool } = await import("../../../src/lib/db/versionManager.ts");
const { getSupervisor, unregisterSupervisor } =
await import("../../../src/lib/services/registry.ts");
const { bootstrapEmbeddedServices } = await import("../../../src/lib/services/bootstrap.ts");
before(() => {
core.resetDbInstance();
});
after(() => {
unregisterSupervisor("mux");
unregisterSupervisor("9router");
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
if (ORIGINAL_DATA_DIR === undefined) delete process.env.DATA_DIR;
else process.env.DATA_DIR = ORIGINAL_DATA_DIR;
if (ORIGINAL_STORAGE_KEY === undefined) delete process.env.STORAGE_ENCRYPTION_KEY;
else process.env.STORAGE_ENCRYPTION_KEY = ORIGINAL_STORAGE_KEY;
});
test("a service whose stored key cannot be decrypted is not supervised", async () => {
// Installed, not auto-started, with an encrypted key that cannot be read back.
await upsertVersionManagerTool({
tool: "mux",
status: "installed",
autoStart: false,
apiKey: "enc:v1:00:00:00",
});
// A healthy service next to it keeps working.
await upsertVersionManagerTool({ tool: "9router", status: "installed", autoStart: false });
await bootstrapEmbeddedServices();
assert.equal(getSupervisor("mux"), null, "mux must not run with a fallback credential");
assert.notEqual(getSupervisor("9router"), null, "services with a readable key still register");
});

View File

@@ -0,0 +1,329 @@
/**
* The embedded-services WebSocket proxy (initEmbedWsProxy, default :20131) tunnels a
* client into an embedded service and adds that service's own Authorization header to
* the tunnel. It must therefore apply the same decision as the HTTP embed route
* (`/dashboard/providers/services/<name>/embed/`, LOCAL_ONLY + management auth) before
* it opens the tunnel:
*
* - the TCP peer is loopback and no reverse-proxy hop header is present;
* - a browser Origin, when sent, is one of the dashboard origins;
* - the caller holds a dashboard session or a management-scope API key, unless the
* dashboard itself runs without login (then loopback + Origin is the same bar the
* HTTP embed route applies).
*
* A rejected upgrade never reaches the upstream service, so the service credential is
* never sent for an unauthorized caller.
*
* The test drives the real server (initEmbedWsProxy) over TCP against a fake upstream
* that records what it receives.
*/
import { after, before, describe, test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { createManagementSessionToken } from "../../helpers/managementSession.ts";
const ENV_KEYS = [
"DATA_DIR",
"JWT_SECRET",
"API_KEY_SECRET",
"OMNIROUTE_API_KEY",
"ROUTER_API_KEY",
"INITIAL_PASSWORD",
"EMBED_WS_PROXY_HOST",
"EMBED_WS_PROXY_PORT",
"LIVE_WS_HOST",
"LIVE_WS_ALLOWED_ORIGINS",
"LIVE_WS_ALLOWED_HOSTS",
"PORT",
"DASHBOARD_PORT",
] as const;
const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
function getFreePort(): Promise<number> {
return new Promise((resolve, reject) => {
const srv = net.createServer();
srv.once("error", reject);
srv.listen(0, "127.0.0.1", () => {
const addr = srv.address();
const port = addr && typeof addr === "object" ? addr.port : null;
srv.close(() => (port ? resolve(port) : reject(new Error("no port"))));
});
});
}
const PROXY_PORT = await getFreePort();
// Own database directory: another test file may share the inherited DATA_DIR.
const TEST_DATA_DIR = fs.mkdtempSync(
path.join(process.env.DATA_DIR || os.tmpdir(), "embed-ws-upgrade-auth-")
);
process.env.DATA_DIR = TEST_DATA_DIR;
process.env.JWT_SECRET = "test-jwt-secret-embed-ws-upgrade-auth";
process.env.API_KEY_SECRET = "test-api-key-secret-embed-ws-upgrade-auth";
// The env master key is materialised with `manage` scope — keep it out of the matrix.
delete process.env.OMNIROUTE_API_KEY;
delete process.env.ROUTER_API_KEY;
delete process.env.INITIAL_PASSWORD;
delete process.env.LIVE_WS_HOST;
delete process.env.LIVE_WS_ALLOWED_ORIGINS;
delete process.env.LIVE_WS_ALLOWED_HOSTS;
delete process.env.PORT;
delete process.env.DASHBOARD_PORT;
// Bind every interface so the test can also reach the proxy from a non-loopback
// address of this machine (the documented LIVE_WS_HOST=0.0.0.0 exposure).
process.env.EMBED_WS_PROXY_HOST = "0.0.0.0";
process.env.EMBED_WS_PROXY_PORT = String(PROXY_PORT);
const core = await import("../../../src/lib/db/core.ts");
const apiKeysDb = await import("../../../src/lib/db/apiKeys.ts");
const { updateSettings } = await import("../../../src/lib/db/settings.ts");
const { upsertVersionManagerTool } = await import("../../../src/lib/db/versionManager.ts");
const { getOrCreateApiKey } = await import("../../../src/lib/services/apiKey.ts");
const { registerSupervisor, unregisterSupervisor } =
await import("../../../src/lib/services/registry.ts");
const embedWsProxy = await import("../../../src/lib/services/embedWsProxy.ts");
const DASHBOARD_ORIGIN = "http://127.0.0.1:20128";
const FOREIGN_ORIGIN = "https://attacker.example";
/** First non-internal IPv4 address of this machine, if any. */
function lanAddress(): string | null {
for (const list of Object.values(os.networkInterfaces())) {
for (const iface of list ?? []) {
if (iface.family === "IPv4" && !iface.internal) return iface.address;
}
}
return null;
}
// ── fake upstream service ──────────────────────────────────────────────────
const upstreamRequests: string[] = [];
const upstream = net.createServer((sock) => {
let buf = "";
let answered = false;
sock.on("data", (chunk) => {
buf += chunk.toString("latin1");
if (!answered && buf.includes("\r\n\r\n")) {
answered = true;
upstreamRequests.push(buf);
sock.write(
"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n"
);
}
});
sock.on("error", () => {});
});
/**
* Send a raw WebSocket upgrade for /9router/ws to the proxy and resolve with the
* response status code (0 when the connection closed without a status line).
*/
function attemptUpgrade(host: string, extraHeaders: Record<string, string> = {}): Promise<number> {
return new Promise((resolve, reject) => {
const sock = net.connect(PROXY_PORT, host);
let buf = "";
const timer = setTimeout(() => {
sock.destroy();
reject(new Error("timed out waiting for the upgrade response"));
}, 8000);
const finish = () => {
clearTimeout(timer);
const m = /^HTTP\/1\.1 (\d{3})/.exec(buf);
sock.destroy();
resolve(m ? Number(m[1]) : 0);
};
sock.on("connect", () => {
const lines = [
"GET /9router/ws HTTP/1.1",
`Host: ${host}:${PROXY_PORT}`,
"Connection: Upgrade",
"Upgrade: websocket",
"Sec-WebSocket-Version: 13",
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==",
...Object.entries(extraHeaders).map(([k, v]) => `${k}: ${v}`),
];
sock.write(`${lines.join("\r\n")}\r\n\r\n`);
});
sock.on("data", (chunk) => {
buf += chunk.toString("latin1");
if (buf.includes("\r\n\r\n")) finish();
});
sock.on("close", finish);
sock.on("error", () => {});
});
}
/** Run one upgrade and report the status plus how many requests reached upstream. */
async function probe(host: string, headers: Record<string, string> = {}) {
const before = upstreamRequests.length;
const status = await attemptUpgrade(host, headers);
const forwarded = upstreamRequests.slice(before);
return { status, forwarded };
}
async function waitForProxy(): Promise<void> {
const deadline = Date.now() + 10_000;
while (!globalThis.__omnirouteEmbedWsStarted) {
if (Date.now() > deadline) throw new Error("embed WS proxy did not start");
await new Promise((r) => setTimeout(r, 20));
}
}
let proxyServer: { close: (cb?: () => void) => unknown } | undefined;
let serviceKey = "";
let manageKey = "";
let readKey = "";
let sessionCookie = "";
before(async () => {
core.resetDbInstance();
await new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", () => resolve()));
const upstreamPort = (upstream.address() as net.AddressInfo).port;
await upsertVersionManagerTool({ tool: "9router", status: "installed", port: upstreamPort });
serviceKey = await getOrCreateApiKey("9router");
registerSupervisor({
getStatus: () => ({
tool: "9router",
state: "running",
port: upstreamPort,
pid: null,
health: "healthy",
startedAt: null,
lastError: null,
}),
} as never);
manageKey = (await apiKeysDb.createApiKey("operator", "machine-embed-ws", ["manage"])).key;
readKey = (await apiKeysDb.createApiKey("inference", "machine-embed-ws", ["read"])).key;
sessionCookie = `auth_token=${await createManagementSessionToken()}`;
globalThis.__omnirouteEmbedWsStarted = undefined;
proxyServer = embedWsProxy.initEmbedWsProxy() as typeof proxyServer;
await waitForProxy();
});
after(async () => {
unregisterSupervisor("9router");
await new Promise<void>((resolve) => upstream.close(() => resolve()));
if (proxyServer) await new Promise<void>((resolve) => proxyServer!.close(() => resolve()));
globalThis.__omnirouteEmbedWsStarted = undefined;
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
for (const k of ENV_KEYS) {
if (ORIGINAL_ENV[k] === undefined) delete process.env[k];
else process.env[k] = ORIGINAL_ENV[k];
}
});
describe("embed WS proxy — login required", () => {
before(async () => {
await updateSettings({ requireLogin: true, password: "hashed-password-for-test" });
});
test("an upgrade without any credential is rejected and never reaches the service", async () => {
const { status, forwarded } = await probe("127.0.0.1", { Origin: DASHBOARD_ORIGIN });
assert.equal(status, 401);
assert.equal(forwarded.length, 0, "the service must not see the upgrade");
});
test("an API key without a management scope is rejected", async () => {
const { status, forwarded } = await probe("127.0.0.1", {
Origin: DASHBOARD_ORIGIN,
Authorization: `Bearer ${readKey}`,
});
assert.equal(status, 403);
assert.equal(forwarded.length, 0);
});
test("a management key opens the tunnel and only the service credential is forwarded", async () => {
const { status, forwarded } = await probe("127.0.0.1", {
Origin: DASHBOARD_ORIGIN,
Authorization: `Bearer ${manageKey}`,
});
assert.equal(status, 101);
assert.equal(forwarded.length, 1);
const sent = forwarded[0];
assert.match(sent, new RegExp(`\\r\\nAuthorization: Bearer ${serviceKey}\\r\\n`));
assert.ok(!sent.includes(manageKey), "the caller's own key must not reach the service");
assert.ok(!/\r\norigin:/i.test(sent), "Origin is not forwarded");
});
test("a dashboard session cookie opens the tunnel and the cookie is not forwarded", async () => {
const { status, forwarded } = await probe("127.0.0.1", {
Origin: DASHBOARD_ORIGIN,
Cookie: sessionCookie,
});
assert.equal(status, 101);
assert.equal(forwarded.length, 1);
assert.ok(!/\r\ncookie:/i.test(forwarded[0]));
});
test("a foreign Origin is rejected even with a valid management key", async () => {
const { status, forwarded } = await probe("127.0.0.1", {
Origin: FOREIGN_ORIGIN,
Authorization: `Bearer ${manageKey}`,
});
assert.equal(status, 403);
assert.equal(forwarded.length, 0);
});
test("a request relayed by a reverse proxy is not treated as local", async () => {
const { status, forwarded } = await probe("127.0.0.1", {
Origin: DASHBOARD_ORIGIN,
Authorization: `Bearer ${manageKey}`,
"X-Forwarded-For": "203.0.113.9",
});
assert.equal(status, 403);
assert.equal(forwarded.length, 0);
});
test("a non-loopback peer is rejected even with a valid management key", async (t) => {
const lan = lanAddress();
if (!lan) {
t.skip("no non-loopback IPv4 interface on this machine");
return;
}
const { status, forwarded } = await probe(lan, {
Origin: DASHBOARD_ORIGIN,
Authorization: `Bearer ${manageKey}`,
});
assert.equal(status, 403);
assert.equal(forwarded.length, 0);
});
});
describe("embed WS proxy — dashboard login disabled", () => {
before(async () => {
await updateSettings({ requireLogin: false });
});
test("a loopback upgrade from the dashboard origin is accepted, as on the HTTP embed route", async () => {
const { status, forwarded } = await probe("127.0.0.1", { Origin: DASHBOARD_ORIGIN });
assert.equal(status, 101);
assert.equal(forwarded.length, 1);
});
test("a foreign Origin is still rejected", async () => {
const { status, forwarded } = await probe("127.0.0.1", { Origin: FOREIGN_ORIGIN });
assert.equal(status, 403);
assert.equal(forwarded.length, 0);
});
test("a non-loopback peer is still rejected", async (t) => {
const lan = lanAddress();
if (!lan) {
t.skip("no non-loopback IPv4 interface on this machine");
return;
}
const { status, forwarded } = await probe(lan, { Origin: DASHBOARD_ORIGIN });
assert.equal(status, 403);
assert.equal(forwarded.length, 0);
});
});