Compare commits

...

3 Commits

Author SHA1 Message Date
diegosouzapw
7bf8759330 fix(security): drop the cookie header from plugin hook contexts too
The dashboard session token travels in a cookie, so it is a client credential like authorization and x-api-key.
2026-11-19 01:29:48 -03:00
diegosouzapw
c8c6243fd7 chore(changelog): name the fragment after #20566 2026-11-19 01:21:13 -03:00
diegosouzapw
0c59e7ebd1 fix(security): keep client credentials out of plugin hooks and document plugin privileges
Plugin hooks (onRequest/onResponse/onError) now get a copy of the context
without the authorization, x-api-key and proxy-authorization headers and
without the API key value or fingerprint. The Plugin SDK and marketplace
docs now describe the real model: plugins run as ordinary Node.js
processes with the OmniRoute user's privileges, and requires.permissions
only selects environment variables. The plugins page shows a warning.
2026-11-19 01:18:12 -03:00
8 changed files with 385 additions and 30 deletions

View File

@@ -0,0 +1 @@
- **fix(security):** plugin hooks (`onRequest`/`onResponse`/`onError`) no longer receive the client's `authorization`, `x-api-key` or `proxy-authorization` headers or the API key value; the Plugin SDK and marketplace docs now state that plugins run as ordinary Node.js processes with the OmniRoute user's privileges (`requires.permissions` only selects environment variables), and the plugins page shows a warning to that effect ([#20566](https://github.com/cheaper-inference/OmniRoute/pull/20566))

View File

@@ -50,8 +50,9 @@ Dashboard (/dashboard/plugins)
`plugin.json`.
- **Scanner** — `src/lib/plugins/scanner.ts`: discovers plugins on disk under
the plugin directory.
- **Loader** — `src/lib/plugins/loader.ts`: spawns each plugin in an isolated
child process and brokers hook calls over IPC.
- **Loader** — `src/lib/plugins/loader.ts`: spawns each plugin in a separate
Node.js child process and brokers hook calls over IPC. The child is not a
sandbox (see "Plugin execution isolation" below).
## Marketplace Catalog
@@ -242,6 +243,14 @@ silently falls back to the built-in seed registry and logs a warning.
### Plugin execution isolation
> **Plugins are not sandboxed.** The child is an ordinary Node.js process running
> as the OmniRoute user, with no VM context and no Node.js permission flags, so
> plugin code can read and write any file that user can, run programs and reach
> the network. `requires.permissions` only decides which environment variables
> the child receives; the other permissions are not enforced. Install only
> plugins you trust. The process boundary below contains crashes and hangs; it
> is not a security boundary.
- **Process isolation** — `loadPlugin()` (`src/lib/plugins/loader.ts`) spawns
each plugin in a separate Node.js child process and communicates over IPC.
Hook calls have a timeout with `SIGTERM` → `SIGKILL` escalation.
@@ -257,8 +266,12 @@ silently falls back to the built-in seed registry and logs a warning.
- **Optional integrity pin** — a manifest may declare an `integrity`
(`sha256-<base64>`, SRI format) field. When present, the loader verifies the
entry file hash at load time and refuses to activate on mismatch. It is
opt-in tamper-detection, **not** a security boundary — loopback-only routing
and the permission model are the real boundaries.
opt-in tamper-detection, **not** a security boundary: it does not limit what
a loaded plugin can do.
- **No client credentials in hooks** — the context passed to `onRequest`,
`onResponse` and `onError` has the `authorization`, `x-api-key`,
`proxy-authorization` and `cookie` headers removed, and the API key record carries no key
value (`redactPluginContext()` in `src/lib/plugins/hooks.ts`).
## Manifest (`plugin.json`)
@@ -282,7 +295,9 @@ Validated by `PluginManifestSchema` (`src/lib/plugins/manifest.ts`):
| `integrity` | string? | Optional `sha256-<base64>` entry-file pin |
Permissions are drawn from the enum
`network` / `file-read` / `file-write` / `env` / `exec`.
`network` / `file-read` / `file-write` / `env` / `exec`. Only `env` has a
runtime effect (a slightly larger environment-variable allowlist for the
child); the others are declarations and are not enforced.
## Lifecycle Flow
@@ -351,6 +366,9 @@ The dashboard page at `/dashboard/plugins`
- **Marketplace** — shows the catalog from `GET /api/plugins/marketplace` with a
field to set the custom registry URL.
The page always shows a warning that plugins run with the full privileges of
the OmniRoute process.
A per-plugin config page lives at `/dashboard/plugins/[name]/config`
(`src/app/(dashboard)/dashboard/plugins/[name]/config/page.tsx`).

View File

@@ -48,8 +48,8 @@ Block the request and optionally return a custom response.
```ts
onRequest: (ctx) => {
if (!ctx.headers["authorization"]) {
return blockRequest({ error: "Unauthorized", status: 401 });
if (!ctx.headers?.["x-client-team"]) {
return blockRequest({ error: "Missing x-client-team header", status: 400 });
}
};
```
@@ -76,15 +76,22 @@ onRequest: (ctx) => {
## Plugin Context (`PluginContext`)
| Field | Type | Description |
| ----------- | ------------------------- | ------------------------- |
| `requestId` | `string` | Unique request identifier |
| `model` | `string` | Requested model name |
| `provider` | `string` | Target provider ID |
| `body` | `Record<string, unknown>` | Request body |
| `headers` | `Record<string, string>` | Request headers |
| `metadata` | `Record<string, unknown>` | Mutable metadata |
| `timestamp` | `number` | Request timestamp |
| Field | Type | Description |
| ------------ | ------------------------- | --------------------------- |
| `requestId` | `string` | Unique request identifier |
| `model` | `string` | Requested model name |
| `provider` | `string` | Target provider ID |
| `body` | `Record<string, unknown>` | Request body |
| `headers` | `Record<string, string>` | Request headers (see note) |
| `metadata` | `Record<string, unknown>` | Mutable metadata |
| `timestamp` | `number` | Request timestamp |
| `apiKeyInfo` | `object` (optional) | API key metadata (see note) |
The context never carries the client's credentials: the `authorization`, `x-api-key`,
`proxy-authorization` and `cookie` headers are removed (any casing), and `apiKeyInfo` keeps the key's
metadata (such as `id`, `name` and `scopes`) but not the key value or its fingerprint
(`redactPluginContext()` in `src/lib/plugins/hooks.ts`). This applies to `onRequest`,
`onResponse` and `onError`.
## Manifest (`plugin.json`)
@@ -139,17 +146,22 @@ Or as simple booleans (default priority 100):
## Permission System
Plugins run in a sandboxed VM context. Access to external resources requires explicit permissions:
Plugins are **not sandboxed**. Each active plugin runs as a separate, ordinary Node.js child
process (`loadPlugin()` in `src/lib/plugins/loader.ts`) under the same operating-system user as
OmniRoute, with no VM context and no Node.js permission flags. Plugin code can use `node:fs`,
`node:child_process`, `fetch` and every other Node.js API: it can read and write any file the
OmniRoute user can (including the data directory), run programs and reach the network.
| Permission | Grants |
| ------------ | ------------------------------------------------------------ |
| `network` | `fetch`, `AbortController`, `Headers`, `Request`, `Response` |
| `file-read` | `fs.readFile`, `fs.readdir`, `fs.stat` |
| `file-write` | `fs.writeFile`, `fs.mkdir`, `fs.rm` |
| `env` | Read-only `process.env` proxy |
| `exec` | `child_process.exec`, `child_process.execSync` |
The manifest's `requires.permissions` accepts `network`, `file-read`, `file-write`, `env` and
`exec`, but today only `env` has an effect at runtime:
Without a permission, the corresponding globals are simply not available in the sandbox.
| Permission | Effect today |
| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `env` | The plugin process also receives `PORT`, `HOSTNAME`, `TZ` and `TMPDIR`. Without it, it receives only `PATH`, `HOME`, `USER`, `LANG`, `LC_ALL`, `NODE_ENV`, `PLUGIN_ENTRY` and `PLUGIN_NAME` (plus `SystemRoot` and `windir` on Windows). |
| `network`, `file-read`, `file-write`, `exec` | None. They are declarations only: nothing is blocked when they are missing. |
Installing a plugin is like installing any other program on the host. Install only plugins whose
source you trust.
## Config Schema
@@ -217,7 +229,7 @@ export default definePlugin({
name: "rate-limiter",
priority: 10,
onRequest: async (ctx) => {
const key = ctx.headers["x-api-key"] || "anonymous";
const key = ctx.apiKeyInfo?.id || "anonymous";
const now = Date.now();
const window = 60000; // 1 minute
const maxRequests = 100;

View File

@@ -2,8 +2,10 @@
import { useState, useEffect, useCallback } from "react";
import { PageHeader } from "@omniroute/ui-kit/page-header";
import { Alert } from "@omniroute/ui-kit/alert";
import { Card, Button, EmptyState } from "@/shared/components";
import Badge from "@/shared/components/Badge";
import Icon from "@/shared/components/Icon";
import { useNotificationStore } from "@/store/notificationStore";
import { useConfirmDialog } from "@/shared/hooks/useConfirmDialog";
import { useTranslations } from "next-intl";
@@ -112,6 +114,13 @@ export default function PluginsPage() {
</Button>
}
/>
<Alert
variant="warning"
dismissible={false}
icon={<Icon name="warning" size={18} />}
title={t("privilegesWarningTitle")}
description={t("privilegesWarningBody")}
/>
{plugins.length === 0 ? (
<EmptyState title={t("noPlugins")} description={t("noPluginsDescription")} />
) : (

View File

@@ -13434,6 +13434,8 @@
"scanForPlugins": "Scan for Plugins",
"noPlugins": "No plugins installed",
"noPluginsDescription": "Place plugin directories in ~/.omniroute/plugins/ and click Scan.",
"privilegesWarningTitle": "Plugins run with full privileges",
"privilegesWarningBody": "A plugin runs as a regular Node.js process with the same access as OmniRoute: it can read files, run programs and use the network, whatever permissions its manifest declares. Install only plugins you trust.",
"activate": "Activate",
"deactivate": "Deactivate",
"uninstall": "Uninstall",

View File

@@ -231,11 +231,55 @@ export interface PluginContext {
/** Client request headers available at the call site. Optional — not all callers
* have access to headers (e.g. internal triggers, retries). Exposed so
* observability/trace-export plugins can read request-scoped context sent by the
* client (trace ids, correlation ids, session markers). */
* client (trace ids, correlation ids, session markers). Credential headers are removed
* before a hook sees the context (see redactPluginContext). */
headers?: Record<string, string | string[] | undefined>;
metadata: Record<string, unknown>;
}
// ── Credential redaction ──
// Plugins are third-party code running as an ordinary Node process with the OmniRoute
// user's privileges, so anything in the hook context is readable by them. The client's
// credentials never go there: the request pipeline keeps its own (unmodified) copy.
const CREDENTIAL_HEADER_NAMES: ReadonlySet<string> = new Set([
"authorization",
"x-api-key",
"proxy-authorization",
// The dashboard session token travels in a cookie.
"cookie",
]);
/** API key record fields that carry the key itself or a fingerprint of it. */
const API_KEY_SECRET_FIELDS: ReadonlySet<string> = new Set(["key", "apiKey", "rawKey", "keyHash"]);
function omitFields(
record: Record<string, unknown>,
shouldOmit: (field: string) => boolean
): Record<string, unknown> {
return Object.fromEntries(Object.entries(record).filter(([field]) => !shouldOmit(field)));
}
/**
* Copy of a hook context without the client's credentials: drops the `authorization`,
* `x-api-key`, `proxy-authorization` and `cookie` headers (any casing) and the key value/fingerprint
* from the API key record. The input is never mutated.
*/
function redactPluginContext<T extends PluginContext>(ctx: T): T {
const redacted: T = { ...ctx };
if (ctx.headers && typeof ctx.headers === "object") {
redacted.headers = omitFields(ctx.headers, (name) =>
CREDENTIAL_HEADER_NAMES.has(name.toLowerCase())
) as PluginContext["headers"];
}
if (ctx.apiKeyInfo && typeof ctx.apiKeyInfo === "object") {
redacted.apiKeyInfo = omitFields(ctx.apiKeyInfo as Record<string, unknown>, (field) =>
API_KEY_SECRET_FIELDS.has(field)
);
}
return redacted;
}
export interface PluginResult {
blocked?: boolean;
response?: unknown;
@@ -330,7 +374,7 @@ export async function runOnRequest(ctx: PluginContext): Promise<PluginResult> {
// When no plugins exist, avoid lazy loading arbitrary plugin code in this request.
if (!canInitializeRequestPlugins()) return {};
await ensurePluginsLoaded();
return emitHookBlocking("onRequest", ctx);
return emitHookBlocking("onRequest", redactPluginContext(ctx));
}
/**
@@ -339,10 +383,11 @@ export async function runOnRequest(ctx: PluginContext): Promise<PluginResult> {
export async function runOnResponse(ctx: PluginContext, response: unknown): Promise<unknown> {
let currentResponse = response;
const list = hooks.get("onResponse") || [];
const hookCtx = redactPluginContext(ctx);
for (const reg of list) {
assertPluginHandlerAllowed();
try {
const result = await reg.handler({ ...ctx, response: currentResponse });
const result = await reg.handler({ ...hookCtx, response: currentResponse });
if (
result !== undefined &&
result !== null &&
@@ -363,7 +408,7 @@ export async function runOnResponse(ctx: PluginContext, response: unknown): Prom
* Run onError hooks — fire-and-forget notification.
*/
export async function runOnError(ctx: PluginContext, error: Error): Promise<void> {
await emitHook("onError", { ...ctx, error });
await emitHook("onError", { ...redactPluginContext(ctx), error });
}
/**

View File

@@ -0,0 +1,176 @@
// Plugin hooks must not receive the client's credentials. A plugin is third-party code
// running as a plain Node child process, so whatever the hook context carries is fully
// readable by it. The request headers handed to onRequest/onResponse/onError must not
// include `authorization`, `x-api-key`, `proxy-authorization` or `cookie` (any casing), and the
// API key record must not carry the key itself — only its id/name/scopes-style metadata.
import { test, afterEach } from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
const { registerHook, unregisterHooks, runOnResponse, runOnError } =
await import("../../src/lib/plugins/hooks.ts");
const { runPluginOnRequestHook } =
await import("../../open-sse/handlers/chatCore/pluginOnRequest.ts");
const { loadPlugin } = await import("../../src/lib/plugins/loader.ts");
const SECRET = "sk-client-secret-value-0001";
const CREDENTIAL_HEADERS = ["authorization", "x-api-key", "proxy-authorization", "cookie"];
function clientHeaders(): Record<string, string> {
return {
Authorization: `Bearer ${SECRET}`,
"X-Api-Key": SECRET,
"proxy-authorization": `Basic ${SECRET}`,
Cookie: `auth_token=${SECRET}; theme=dark`,
"x-trace-id": "trace-123",
"content-type": "application/json",
};
}
function apiKeyRecord() {
return {
id: "key-id-1",
name: "ci key",
scopes: ["chat"],
noLog: false,
key: SECRET,
keyHash: "fingerprint-of-the-key",
};
}
function assertNoCredentials(seen: unknown) {
const ctx = seen as { headers?: Record<string, unknown>; apiKeyInfo?: Record<string, unknown> };
assert.ok(ctx, "expected the hook to run");
const headerNames = Object.keys(ctx.headers ?? {}).map((h) => h.toLowerCase());
for (const name of CREDENTIAL_HEADERS) {
assert.equal(headerNames.includes(name), false, `hook received the ${name} header`);
}
assert.equal(ctx.headers?.["x-trace-id"], "trace-123", "non-credential headers stay visible");
assert.equal(ctx.apiKeyInfo?.id, "key-id-1");
assert.equal(ctx.apiKeyInfo?.name, "ci key");
assert.deepEqual(ctx.apiKeyInfo?.scopes, ["chat"]);
assert.equal("key" in (ctx.apiKeyInfo ?? {}), false, "hook received the API key value");
assert.equal("keyHash" in (ctx.apiKeyInfo ?? {}), false, "hook received the key fingerprint");
assert.equal(JSON.stringify(seen).includes(SECRET), false, "the client secret reached the hook");
}
const registered: string[] = [];
afterEach(() => {
for (const name of registered.splice(0)) unregisterHooks(name);
});
test("a real plugin process's onRequest hook never sees the client's credentials", async (t) => {
const pluginDir = await mkdtemp(join(tmpdir(), "omniroute-plugin-cred-"));
const entryPoint = join(pluginDir, "index.mjs");
await writeFile(
entryPoint,
`export async function onRequest(ctx) {
return { body: { seen: { headers: ctx.headers ?? null, apiKeyInfo: ctx.apiKeyInfo ?? null } } };
}
`,
"utf-8"
);
const loaded = await loadPlugin(entryPoint, {
name: "credential-probe",
version: "1.0.0",
license: "MIT",
main: "index.mjs",
source: "local",
tags: [],
requires: { permissions: [] },
hooks: { onRequest: true, onResponse: false, onError: false },
skills: [],
enabledByDefault: false,
configSchema: {},
} as unknown as Parameters<typeof loadPlugin>[1]);
t.after(async () => {
loaded.cleanup();
await rm(pluginDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
});
registerHook("onRequest", "credential-probe", loaded.plugin.onRequest as never);
registered.push("credential-probe");
const headers = clientHeaders();
const gate = await runPluginOnRequestHook({
requestId: "req-cred-1",
body: { messages: [{ role: "user", content: "hi" }] },
model: "gpt-x",
provider: "openai",
apiKeyInfo: apiKeyRecord(),
headers,
});
assert.equal(gate.blocked, false);
if (gate.blocked) return;
const body = gate.body as { seen?: unknown } | undefined;
assertNoCredentials(body?.seen);
// The caller's own header record is not mutated: the request pipeline still needs it.
assert.equal(headers.Authorization, `Bearer ${SECRET}`);
assert.equal(headers["X-Api-Key"], SECRET);
});
test("onResponse hooks never see the client's credentials", async () => {
let seen: unknown;
registerHook("onResponse", "credential-probe-response", async (ctx: unknown) => {
seen = ctx;
});
registered.push("credential-probe-response");
await runOnResponse(
{
requestId: "req-cred-2",
body: {},
model: "gpt-x",
provider: "openai",
apiKeyInfo: apiKeyRecord(),
headers: clientHeaders(),
metadata: {},
},
{ status: 200 }
);
assertNoCredentials(seen);
});
test("onError hooks never see the client's credentials", async () => {
let seen: unknown;
registerHook("onError", "credential-probe-error", async (ctx: unknown) => {
seen = ctx;
});
registered.push("credential-probe-error");
await runOnError(
{
requestId: "req-cred-3",
body: {},
model: "gpt-x",
provider: "openai",
apiKeyInfo: apiKeyRecord(),
headers: clientHeaders(),
metadata: {},
},
new Error("upstream failed")
);
assertNoCredentials(seen);
});
test("a context without headers or API key record still reaches the hook unchanged", async () => {
let seen: Record<string, unknown> | undefined;
registerHook("onError", "credential-probe-empty", async (ctx: unknown) => {
seen = ctx as Record<string, unknown>;
});
registered.push("credential-probe-empty");
await runOnError(
{ requestId: "req-cred-4", body: {}, model: "m", provider: "p", metadata: {} },
new Error("x")
);
assert.ok(seen);
assert.equal(seen!.headers, undefined);
assert.equal(seen!.apiKeyInfo, undefined);
assert.equal(seen!.requestId, "req-cred-4");
});

View File

@@ -0,0 +1,92 @@
// @vitest-environment jsdom
/**
* The plugins page must tell the operator that plugins run with the full privileges of the
* OmniRoute process. The manifest's `requires.permissions` is not a sandbox (it only selects
* which environment variables the plugin process receives), so the notice is shown whether
* or not any plugin is installed and cannot be dismissed.
*/
import React from "react";
import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { NextIntlClientProvider } from "next-intl";
import messages from "../../../src/i18n/messages/en.json";
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn() }),
usePathname: () => "/dashboard/plugins",
}));
vi.mock("@/store/notificationStore", () => ({
useNotificationStore: () => ({ addNotification: vi.fn() }),
}));
let pluginList: unknown[] = [];
vi.stubGlobal(
"fetch",
vi
.fn()
.mockImplementation(() =>
Promise.resolve({ ok: true, json: async () => ({ plugins: pluginList }) })
)
);
import PluginsPage from "../../../src/app/(dashboard)/dashboard/plugins/page";
describe("plugins page — full-privileges notice", () => {
let container: HTMLDivElement;
let root: ReturnType<typeof createRoot>;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(() => {
act(() => {
root.unmount();
});
document.body.removeChild(container);
pluginList = [];
});
async function renderPage() {
await act(async () => {
root.render(
<NextIntlClientProvider locale="en" messages={{ plugins: messages.plugins }}>
<PluginsPage />
</NextIntlClientProvider>
);
});
}
function notice(): HTMLElement | null {
return container.querySelector('[data-slot="alert"][data-variant="warning"]');
}
it("shows the notice when no plugin is installed", async () => {
await renderPage();
const alert = notice();
expect(alert).not.toBeNull();
expect(alert!.textContent).toContain(messages.plugins.privilegesWarningTitle);
expect(alert!.textContent).toContain(messages.plugins.privilegesWarningBody);
expect(alert!.querySelector("button.ci-alert__dismiss")).toBeNull();
});
it("shows the notice alongside installed plugins", async () => {
pluginList = [
{ name: "demo", version: "1.0.0", status: "active", enabled: true, hooks: ["onRequest"] },
];
await renderPage();
expect(container.textContent).toContain("demo");
expect(notice()?.textContent).toContain(messages.plugins.privilegesWarningTitle);
});
it("the notice says permissions are not a sandbox and to trust the plugin", () => {
const body = messages.plugins.privilegesWarningBody;
expect(body).toMatch(/whatever permissions its manifest declares/);
expect(body).toMatch(/only plugins you trust/);
});
});