Compare commits

...

3 Commits

Author SHA1 Message Date
diegosouzapw
21c3a7a04b Merge remote-tracking branch 'origin/release/v3.8.55' into feat/plugin-permission-model-opt-in 2026-11-20 18:47:42 -03:00
diegosouzapw
661bf4a716 chore(changelog): name the fragment after PR #20781 2026-11-20 11:01:23 -03:00
diegosouzapw
a55e4a75ea feat(plugins): opt-in Node.js permission model for plugin processes
New feature flag PLUGIN_PERMISSION_MODEL_ENABLED (security, default off).
When it is on, pluginManager.activate() asks loadPlugin() to start the plugin
host with the Node.js permission model, built from the manifest by
buildPermissionModelArgs() (src/lib/plugins/permissionModel.ts):

- --permission (accepted by Node 22.22+, 24 and 26);
- --allow-fs-read for the generated host script and the plugin directory,
  plus the plugin data directory (plugin-data/<name> next to the plugin root)
  when file-read or file-write is declared;
- --allow-fs-write for the data directory only when file-write is declared;
- --allow-child-process only when exec is declared.

Workers, addons and WASI stay denied. network stays declarative because the
Node.js permission model does not gate outbound network access. With the flag
off the host argv and env are exactly as before.

PLUGIN_SDK.md gets a flag-off / flag-on permission table, PLUGIN_MARKETPLACE.md
and FEATURE_FLAGS.md document the flag, and the flag-count tests move to 127.
2026-11-20 10:29:23 -03:00
14 changed files with 587 additions and 42 deletions

View File

@@ -0,0 +1 @@
- **feat(plugins):** Opt-in `PLUGIN_PERMISSION_MODEL_ENABLED` feature flag (off by default) runs each plugin process under the Node.js permission model built from its manifest: reads confined to the plugin directory, writes only to its data directory with `file-write`, child processes only with `exec`; `network` stays declarative

View File

@@ -253,13 +253,17 @@ 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.
> **Plugins are not sandboxed by default.** 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. The opt-in `PLUGIN_PERMISSION_MODEL_ENABLED` feature flag (off by
> default) runs each plugin under the Node.js permission model built from those
> permissions, except `network`, which Node.js cannot restrict (see
> [`PLUGIN_SDK.md`](./PLUGIN_SDK.md#permission-system)). 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.

View File

@@ -146,22 +146,42 @@ Or as simple booleans (default priority 100):
## Permission System
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`,
By default 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.
The manifest's `requires.permissions` accepts `network`, `file-read`, `file-write`, `env` and
`exec`, but today only `env` has an effect at runtime:
`exec`. With the default settings only `env` has an effect at runtime.
| 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. |
### Opt-in permission model (`PLUGIN_PERMISSION_MODEL_ENABLED`)
Installing a plugin is like installing any other program on the host. Install only plugins whose
source you trust.
The `PLUGIN_PERMISSION_MODEL_ENABLED` feature flag (category `security`, **off by default**) starts
each plugin process with the
[Node.js permission model](https://nodejs.org/api/permissions.html) (`--permission`, accepted by
every supported Node.js line: 22.22+, 24 and 26). The flags are built from the manifest by
`buildPermissionModelArgs()` in `src/lib/plugins/permissionModel.ts`. The flag is read when a plugin
is activated, so it applies to plugins activated after the change; deactivate and activate a
running plugin to apply it.
The plugin data directory is `plugin-data/<plugin-name>` next to the plugin root
(`~/.omniroute/plugin-data/<plugin-name>` by default, `getPluginDataDir()`). With the flag on, its
path is passed to the plugin as `PLUGIN_DATA_DIR`.
| Permission | Flag off (default) | Flag on |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| (none) | Full privileges of the OmniRoute user. | File reads only inside the plugin directory. No file writes, no child processes, no worker threads, no native addons, no WASI. |
| `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). | Same as with the flag off. |
| `file-read` | None (declaration only). | The plugin data directory also becomes readable (it is created if missing). |
| `file-write` | None (declaration only). | The plugin data directory becomes readable and writable (`--allow-fs-write`). Nothing else is writable. |
| `exec` | None (declaration only). | Child processes are allowed (`--allow-child-process`). Node.js passes the permission flags on to child Node.js processes through `NODE_OPTIONS`, but any other program runs without restrictions, so `exec` effectively lifts the file-system limits. |
| `network` | None (declaration only). | None. The Node.js permission model does not restrict outbound network access, so `network` stays a declaration and is never enforced. |
Turning the flag on breaks plugins that read files outside their own directory (for example a
module resolved from a parent `node_modules`), write anywhere but their data directory, or spawn
processes without declaring `exec`. Even with the flag on the plugin keeps network access and runs
as the OmniRoute user, so install only plugins whose source you trust.
## Config Schema

View File

@@ -46,25 +46,26 @@ A boolean flag is considered **enabled** when its effective value is `"true"`,
## Flag Catalog
126 flags across 6 categories. **Default** is the definition default — the value
127 flags across 6 categories. **Default** is the definition default — the value
used when neither a DB override nor an environment variable is present.
### Security (12)
### Security (13)
| Key | Type | Default | Description |
| --------------------------------------- | ------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `REQUIRE_API_KEY` | boolean | `false` | Require an API key for all incoming requests. |
| `INPUT_SANITIZER_ENABLED` | boolean | `true` | Enable input sanitization for all requests. |
| `INJECTION_GUARD_MODE` | enum | `off` | Prompt injection guard mode. Values: `off`, `warn`, `block`, `redact`. |
| `PII_REDACTION_ENABLED` | boolean | `false` | Redact PII from requests (independent of `INPUT_SANITIZER_MODE`). |
| `PII_RESPONSE_SANITIZATION` | boolean | `false` | Sanitize PII from provider responses. |
| `PII_RESPONSE_SANITIZATION_MODE` | enum | `redact` | Mode for PII response sanitization. Values: `redact`, `warn`, `block`, `off`. |
| `PII_REVERSIBLE_VAULT_ENABLED` | boolean | `false` | Reversible PII vault: with `PII_REDACTION_ENABLED` on, request PII becomes per-request surrogate tokens instead of placeholders, and 2xx responses (SSE and JSON) get the originals back. |
| `OUTBOUND_SSRF_GUARD_ENABLED` | boolean | `true` | Legacy alias: a value saved on this flag's dashboard toggle is read before the environment; `false`, `0`, `no`, or `off` in either turns the outbound URL guard's host checks off like `OMNIROUTE_ALLOW_PRIVATE_PROVIDER_URLS`. |
| `ALLOW_API_KEY_REVEAL` | boolean | `false` | Allow authenticated dashboard users to reveal stored API keys instead of only seeing masked values. |
| `AUTH_LOG_INCLUDE_ACCOUNT_ID` | boolean | `false` | Include account prefix in AUTH log lines (e.g. "Using <provider> account: abc12345..."). Disabled by default so account identifiers are redacted from shared/multi-tenant process logs. Independent from Debug Mode; flipping Debug Mode does not reveal this. |
| `OMNIROUTE_OIDC_DISABLE_PASSWORD_LOGIN` | boolean | `false` | When OIDC is enabled, disable password login so users can only authenticate via OIDC Single Sign-On. When disabled (default), both password login and OIDC are available. |
| `API_KEY_AUDIT_CLIENT_DETAILS_ENABLED` | boolean | `false` | Record the caller's IP address and user-agent on the `api_key.auth.touch` audit-log rows written for successful API-key metadata and discovery reads (#17982). Off by default: those rows still record which key was used, when, and on which path, without IP or user-agent. |
| Key | Type | Default | Description |
| --------------------------------------- | ------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `REQUIRE_API_KEY` | boolean | `false` | Require an API key for all incoming requests. |
| `INPUT_SANITIZER_ENABLED` | boolean | `true` | Enable input sanitization for all requests. |
| `INJECTION_GUARD_MODE` | enum | `off` | Prompt injection guard mode. Values: `off`, `warn`, `block`, `redact`. |
| `PII_REDACTION_ENABLED` | boolean | `false` | Redact PII from requests (independent of `INPUT_SANITIZER_MODE`). |
| `PII_RESPONSE_SANITIZATION` | boolean | `false` | Sanitize PII from provider responses. |
| `PII_RESPONSE_SANITIZATION_MODE` | enum | `redact` | Mode for PII response sanitization. Values: `redact`, `warn`, `block`, `off`. |
| `PII_REVERSIBLE_VAULT_ENABLED` | boolean | `false` | Reversible PII vault: with `PII_REDACTION_ENABLED` on, request PII becomes per-request surrogate tokens instead of placeholders, and 2xx responses (SSE and JSON) get the originals back. |
| `OUTBOUND_SSRF_GUARD_ENABLED` | boolean | `true` | Legacy alias: a value saved on this flag's dashboard toggle is read before the environment; `false`, `0`, `no`, or `off` in either turns the outbound URL guard's host checks off like `OMNIROUTE_ALLOW_PRIVATE_PROVIDER_URLS`. |
| `ALLOW_API_KEY_REVEAL` | boolean | `false` | Allow authenticated dashboard users to reveal stored API keys instead of only seeing masked values. |
| `AUTH_LOG_INCLUDE_ACCOUNT_ID` | boolean | `false` | Include account prefix in AUTH log lines (e.g. "Using <provider> account: abc12345..."). Disabled by default so account identifiers are redacted from shared/multi-tenant process logs. Independent from Debug Mode; flipping Debug Mode does not reveal this. |
| `OMNIROUTE_OIDC_DISABLE_PASSWORD_LOGIN` | boolean | `false` | When OIDC is enabled, disable password login so users can only authenticate via OIDC Single Sign-On. When disabled (default), both password login and OIDC are available. |
| `API_KEY_AUDIT_CLIENT_DETAILS_ENABLED` | boolean | `false` | Record the caller's IP address and user-agent on the `api_key.auth.touch` audit-log rows written for successful API-key metadata and discovery reads (#17982). Off by default: those rows still record which key was used, when, and on which path, without IP or user-agent. |
| `PLUGIN_PERMISSION_MODEL_ENABLED` | boolean | `false` | Run each plugin process under the Node.js permission model, derived from the permissions its manifest declares: file reads limited to the plugin directory (plus its data directory with `file-read` or `file-write`), file writes only in the plugin data directory with `file-write`, child processes only with `exec`, and no worker threads, native addons or WASI. Network access is not restricted. Applies to plugins activated after the change. See [`PLUGIN_SDK.md`](../frameworks/PLUGIN_SDK.md#permission-system). |
### Network (32)
@@ -289,10 +290,10 @@ Returns every flag with its effective value, source, and a summary.
"requiresRestart": false,
"warningLevel": "caution",
},
// ... all 126 flags
// ... all 127 flags
],
"summary": {
"total": 126,
"total": 127,
"active": 0,
"inactive": 0,
"overriddenByDb": 0,

View File

@@ -10,14 +10,15 @@
import { spawn } from "child_process";
import type { ChildProcess } from "child_process";
import { writeFile, readFile } from "fs/promises";
import { writeFile, readFile, mkdir, realpath } from "fs/promises";
import { rmSync } from "fs";
import { join } from "path";
import { dirname, join } from "path";
import { tmpdir } from "os";
import { randomUUID, createHash } from "crypto";
import { logger } from "../../../open-sse/utils/logger.ts";
import type { PluginManifestWithDefaults, Permission } from "./manifest";
import type { Plugin, PluginContext, PluginResult } from "./index";
import { buildPermissionModelArgs } from "./permissionModel";
const log = logger("PLUGIN_LOADER");
@@ -58,6 +59,14 @@ export interface LoadedPlugin {
}
export interface LoadPluginOptions {
/** Run the plugin host under the Node.js permission model (PLUGIN_PERMISSION_MODEL_ENABLED).
* Off when omitted: the host is spawned exactly as without the flag. */
permissionModel?: boolean;
/** Directory the plugin may read under the permission model (default: the entry's dir). */
pluginDir?: string;
/** Plugin data directory, opened by `file-read` / `file-write` under the permission model. */
dataDir?: string;
/** Per-call IPC hook timeout in ms. Defaults to DEFAULT_HOOK_TIMEOUT (10s); injectable
* so tests can exercise the timeout paths without waiting out the production value. */
hookTimeoutMs?: number;
@@ -245,7 +254,21 @@ export async function loadPlugin(
PLUGIN_NAME: manifest.name,
};
const child = spawn(process.execPath, ["--no-warnings", hostScriptPath, entryPoint], {
// Opt-in sandbox: with the flag off the argv below is exactly ["--no-warnings", host, entry].
let permissionArgs: string[] = [];
if (options.permissionModel === true) {
try {
const sandbox = await preparePermissionModel(hostScriptPath, entryPoint, manifest, options);
permissionArgs = sandbox.args;
env.PLUGIN_DATA_DIR = sandbox.dataDir;
} catch (err) {
removeHostScript(hostScriptPath);
throw err;
}
}
const hostArgs = ["--no-warnings", ...permissionArgs, hostScriptPath, entryPoint];
const child = spawn(process.execPath, hostArgs, {
windowsHide: true,
env,
// #8395: stdout/stderr must be piped (not "ignore") so the plugin's own
@@ -434,6 +457,34 @@ export async function loadPlugin(
return { name: manifest.name, manifest, plugin, cleanup };
}
/**
* Resolve the Node.js permission-model flags for one plugin host. Paths are canonicalized
* because the permission model checks real paths; the data directory is created only when
* the manifest declares a permission that opens it.
*/
async function preparePermissionModel(
hostScriptPath: string,
entryPoint: string,
manifest: PluginManifestWithDefaults,
options: LoadPluginOptions
): Promise<{ args: string[]; dataDir: string }> {
const permissions = manifest.requires.permissions;
const pluginDir = await realpath(options.pluginDir ?? dirname(entryPoint));
let dataDir = options.dataDir ?? join(pluginDir, "data");
if (permissions.includes("file-write") || permissions.includes("file-read")) {
await mkdir(dataDir, { recursive: true });
dataDir = await realpath(dataDir);
}
const args = buildPermissionModelArgs({
hostScriptPath: await realpath(hostScriptPath),
pluginDir,
dataDir,
permissions,
});
log.info("loader.permission_model", { name: manifest.name, args });
return { args, dataDir };
}
/**
* Filter environment variables based on permissions.
* Uses allowlist approach — only pass explicitly safe vars.

View File

@@ -15,6 +15,8 @@ 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 { getPluginDataDir } from "./permissionModel";
import { isPluginPermissionModelEnabled } from "../../shared/utils/featureFlags";
import { registerHook, unregisterHooks, emitHook, type HookHandler, type Plugin } from "./hooks";
import {
insertPlugin,
@@ -426,7 +428,11 @@ class PluginManager {
}
try {
const loaded = await loadPlugin(entryPoint, manifest);
const loaded = await loadPlugin(entryPoint, manifest, {
permissionModel: isPluginPermissionModelEnabled(),
pluginDir: resolvedPluginDir,
dataDir: getPluginDataDir(this.pluginDir, name),
});
const hookNames: LifecycleHookName[] = [
"onRequest",

View File

@@ -0,0 +1,65 @@
/**
* Opt-in Node.js permission model for plugin child processes.
*
* With the `PLUGIN_PERMISSION_MODEL_ENABLED` feature flag on, `loadPlugin()` starts each
* plugin host with Node's permission model, derived from the manifest's
* `requires.permissions`:
*
* - file-system reads are limited to the generated host script and the plugin's own
* directory, plus the plugin's data directory when `file-read` or `file-write` is declared;
* - file-system writes are allowed only in the plugin's data directory, and only when
* `file-write` is declared;
* - child processes are allowed only when `exec` is declared;
* - worker threads, native addons and WASI stay denied.
*
* `network` is not enforced: the Node.js permission model does not gate outbound network
* access, so it stays a declaration. With the flag off nothing here runs and the plugin
* host is spawned exactly as before.
*
* @module plugins/permissionModel
*/
import { dirname, join, resolve } from "path";
import type { Permission } from "./manifest";
export const PLUGIN_DATA_DIRNAME = "plugin-data";
/** Per-plugin writable directory: `plugin-data/<name>` next to the plugin root. */
export function getPluginDataDir(pluginRoot: string, name: string): string {
return join(dirname(resolve(pluginRoot)), PLUGIN_DATA_DIRNAME, name);
}
/**
* The flag that turns the permission model on. Every supported Node.js line accepts
* `--permission` (22.x keeps `--experimental-permission` as an alias); the fallback only
* matters for a runtime that predates the stable name.
*/
export function resolvePermissionFlag(
allowedFlags: ReadonlySet<string> = process.allowedNodeEnvironmentFlags
): string {
return allowedFlags.has("--permission") ? "--permission" : "--experimental-permission";
}
export interface PermissionModelArgsInput {
hostScriptPath: string;
pluginDir: string;
dataDir: string;
permissions: readonly Permission[];
permissionFlag?: string;
}
/** Node.js CLI flags that sandbox one plugin host process. One path per flag. */
export function buildPermissionModelArgs(input: PermissionModelArgsInput): string[] {
const { hostScriptPath, pluginDir, dataDir, permissions } = input;
const canWrite = permissions.includes("file-write");
const canReadData = canWrite || permissions.includes("file-read");
const args = [
input.permissionFlag ?? resolvePermissionFlag(),
`--allow-fs-read=${hostScriptPath}`,
`--allow-fs-read=${pluginDir}`,
];
if (canReadData) args.push(`--allow-fs-read=${dataDir}`);
if (canWrite) args.push(`--allow-fs-write=${dataDir}`);
if (permissions.includes("exec")) args.push("--allow-child-process");
return args;
}

View File

@@ -1,6 +1,7 @@
import type { FeatureFlagDefinition } from "./featureFlagTypes";
import { SEARCH_FEATURE_FLAG_DEFINITIONS } from "./searchFeatureFlagDefinitions";
import { FAL_NATIVE_ENABLED_FLAG } from "./featureFlagDefinitionsFal";
import { PLUGIN_PERMISSION_MODEL_ENABLED_FLAG } from "./featureFlagDefinitionsPlugins";
import { CODE_ASSIST_LEGACY_TIER_FLAG } from "./featureFlagDefinitionsCodeAssist";
import { SYSTEM_ONE_FEATURE_FLAG_DEFINITIONS } from "./featureFlagDefinitionsSystemOne";
import {
@@ -132,6 +133,7 @@ export const FEATURE_FLAG_DEFINITIONS: FeatureFlagDefinition[] = [
requiresRestart: false,
warningLevel: "info",
},
PLUGIN_PERMISSION_MODEL_ENABLED_FLAG,
// ──────────────── Network (7) ────────────────
{
key: "ENABLE_TLS_FINGERPRINT",

View File

@@ -0,0 +1,15 @@
import type { FeatureFlagDefinition } from "./featureFlagTypes";
/** Kept in its own module so the definitions registry stays under the file-size cap. */
export const PLUGIN_PERMISSION_MODEL_ENABLED_FLAG: FeatureFlagDefinition = {
key: "PLUGIN_PERMISSION_MODEL_ENABLED",
label: "Plugin Permission Model",
description:
"Run each plugin process under the Node.js permission model, derived from the permissions its manifest declares: file reads limited to the plugin directory (plus its data directory with file-read or file-write), file writes only in the plugin data directory with file-write, child processes only with exec, and no worker threads, native addons or WASI. Network access is not restricted. Applies to plugins activated after the change. Off by default: plugins run with the full privileges of the OmniRoute user, as before.",
descriptionI18nKey: "featureFlagPluginPermissionModelEnabledDescription",
category: "security",
defaultValue: "false",
type: "boolean",
requiresRestart: false,
warningLevel: "caution",
};

View File

@@ -699,3 +699,19 @@ export function isFalNativeEnabled(): boolean {
return false;
}
}
/**
* Opt-in Node.js permission model for plugin processes. Read when a plugin is activated.
* Fail closed to the pre-flag behavior: an unreadable flag store keeps it disabled.
*/
export function isPluginPermissionModelEnabled(): boolean {
try {
return isFeatureFlagEnabled("PLUGIN_PERMISSION_MODEL_ENABLED");
} catch (error) {
console.error(
"[featureFlags] Failed to resolve PLUGIN_PERMISSION_MODEL_ENABLED, defaulting to disabled:",
error instanceof Error ? error.message : error
);
return false;
}
}

View File

@@ -76,7 +76,8 @@ const {
// PII_REVERSIBLE_VAULT_ENABLED (#18017 wiring, default off) takes it to 123;
// SYSTEMONE_CLOUDFLARE_BACKEND_ENABLED (#16676), SYSTEMONE_OLLAMA_LOCAL_BACKEND_ENABLED (#14667)
// and COMBO_JEV_STRATEGY_ENABLED (#15279), all default off, take it to 126.
const EXPECTED_FEATURE_FLAG_COUNT = 126;
// PLUGIN_PERMISSION_MODEL_ENABLED (opt-in plugin sandbox, default off) takes it to 127.
const EXPECTED_FEATURE_FLAG_COUNT = 127;
// tool_call wrapper repair, default on) to 86; OPENCODE_V2_CLIENT_FINGERPRINT_ENABLED
// (#16571, OpenCode v2 client fingerprint, default off) to 87.
// tool_call wrapper repair, default on) to 86; CLAUDE_OAUTH_SUMMARIZED_THINKING_UNREDACTED

View File

@@ -0,0 +1,123 @@
// pluginManager.activate() wires PLUGIN_PERMISSION_MODEL_ENABLED into the loader: with the
// flag on, an activated plugin that declares no permissions cannot read a file outside its
// directory or spawn a child process; with it off (the default) both still work.
import test from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
const BASE_DIR = await mkdtemp(join(tmpdir(), "omniroute-plugin-perm-manager-"));
const PLUGIN_ROOT = join(BASE_DIR, "plugins");
const SOURCE_ROOT = join(BASE_DIR, "plugin-sources");
const OUTSIDE_FILE = join(BASE_DIR, "outside", "secret.txt");
const ORIGINAL_ENV = {
OMNIROUTE_PLUGINS_DIR: process.env.OMNIROUTE_PLUGINS_DIR,
PLUGIN_PERMISSION_MODEL_ENABLED: process.env.PLUGIN_PERMISSION_MODEL_ENABLED,
};
process.env.OMNIROUTE_PLUGINS_DIR = PLUGIN_ROOT;
delete process.env.PLUGIN_PERMISSION_MODEL_ENABLED;
await mkdir(PLUGIN_ROOT, { recursive: true });
await mkdir(join(BASE_DIR, "outside"), { recursive: true });
await writeFile(OUTSIDE_FILE, "outside-secret", "utf-8");
const core = await import("../../src/lib/db/core.ts");
const { pluginManager } = await import("../../src/lib/plugins/manager.ts");
test.after(async () => {
for (const name of ["perm-manager-off", "perm-manager-on"]) {
await pluginManager.deactivate(name).catch(() => {});
}
core.resetDbInstance();
await rm(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;
}
});
async function writeProbePlugin(name: string): Promise<string> {
const dir = join(SOURCE_ROOT, name);
await mkdir(dir, { recursive: true });
await writeFile(
join(dir, "plugin.json"),
JSON.stringify({
name,
version: "1.0.0",
main: "index.mjs",
hooks: { onRequest: true },
requires: { permissions: [] },
})
);
await writeFile(
join(dir, "index.mjs"),
`
import { readFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
function attempt(fn) {
try {
return { ok: true, value: fn() };
} catch (err) {
return { ok: false, code: err && err.code ? err.code : String(err) };
}
}
export async function onRequest(ctx) {
return {
metadata: {
outsideRead: attempt(() => readFileSync(ctx.metadata.outsideFile, "utf-8")),
exec: attempt(() =>
execFileSync(process.execPath, ["-e", "process.stdout.write('child-ran')"]).toString()
),
},
};
}
`
);
return dir;
}
async function probeActivated(name: string) {
await pluginManager.install(await writeProbePlugin(name));
await pluginManager.activate(name);
const loaded = pluginManager.getLoaded(name);
assert.ok(loaded?.plugin.onRequest, `${name} must be loaded with an onRequest hook`);
const result = (await loaded.plugin.onRequest({
requestId: name,
body: {},
model: "m",
metadata: { outsideFile: OUTSIDE_FILE },
})) as { metadata?: Record<string, unknown> } | undefined;
assert.ok(result?.metadata, `${name} must answer its onRequest hook`);
return result.metadata;
}
test(
"flag off (default): an activated plugin keeps full process privileges",
{
timeout: 60_000,
},
async () => {
const probe = await probeActivated("perm-manager-off");
assert.deepEqual(probe.outsideRead, { ok: true, value: "outside-secret" });
assert.deepEqual(probe.exec, { ok: true, value: "child-ran" });
}
);
test(
"flag on: an activated plugin without permissions is confined",
{
timeout: 60_000,
},
async () => {
process.env.PLUGIN_PERMISSION_MODEL_ENABLED = "true";
try {
const probe = await probeActivated("perm-manager-on");
assert.deepEqual(probe.outsideRead, { ok: false, code: "ERR_ACCESS_DENIED" });
assert.deepEqual(probe.exec, { ok: false, code: "ERR_ACCESS_DENIED" });
} finally {
delete process.env.PLUGIN_PERMISSION_MODEL_ENABLED;
}
}
);

View File

@@ -0,0 +1,239 @@
// Opt-in Node.js permission model for plugin processes (PLUGIN_PERMISSION_MODEL_ENABLED).
//
// With the flag off, a plugin is spawned exactly as before: a plugin that declares no
// permissions can still read any file the OmniRoute user can and run child processes.
// With it on, the same plugin is confined to its own directory: reading a file outside it
// and spawning a child process both fail with ERR_ACCESS_DENIED. Declared `file-write`
// opens the plugin's data directory for writes and declared `exec` allows child processes.
import test from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { loadPlugin, type LoadedPlugin } from "../../src/lib/plugins/loader.ts";
import type { Permission, PluginManifestWithDefaults } from "../../src/lib/plugins/manifest.ts";
import {
buildPermissionModelArgs,
getPluginDataDir,
resolvePermissionFlag,
} from "../../src/lib/plugins/permissionModel.ts";
import { FEATURE_FLAG_DEFINITIONS } from "../../src/shared/constants/featureFlagDefinitions.ts";
const BASE_DIR = await mkdtemp(join(tmpdir(), "omniroute-plugin-permission-model-"));
const PLUGIN_DIR = join(BASE_DIR, "plugins", "perm-probe");
const DATA_DIR = join(BASE_DIR, "plugin-data", "perm-probe");
const OUTSIDE_FILE = join(BASE_DIR, "outside", "secret.txt");
const ENTRY = join(PLUGIN_DIR, "index.mjs");
await mkdir(PLUGIN_DIR, { recursive: true });
await mkdir(join(BASE_DIR, "outside"), { recursive: true });
await writeFile(OUTSIDE_FILE, "outside-secret", "utf-8");
// The probe reports what it could do through its onRequest return value, so the test
// does not depend on the probe being able to write anywhere.
await writeFile(
ENTRY,
`
import { readFileSync, writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { join } from "node:path";
function attempt(fn) {
try {
return { ok: true, value: fn() };
} catch (err) {
return { ok: false, code: err && err.code ? err.code : String(err) };
}
}
export async function onRequest(ctx) {
const outsideFile = ctx.metadata.outsideFile;
const dataDir = process.env.PLUGIN_DATA_DIR || ctx.metadata.dataDir;
return {
metadata: {
ownRead: attempt(() => readFileSync(new URL(import.meta.url), "utf-8").length > 0),
outsideRead: attempt(() => readFileSync(outsideFile, "utf-8")),
exec: attempt(() =>
execFileSync(process.execPath, ["-e", "process.stdout.write('child-ran')"]).toString()
),
dataWrite: attempt(() => {
writeFileSync(join(dataDir, "probe.txt"), "written");
return readFileSync(join(dataDir, "probe.txt"), "utf-8");
}),
pluginDataDirEnv: process.env.PLUGIN_DATA_DIR ?? null,
},
};
}
`,
"utf-8"
);
test.after(async () => {
await rm(BASE_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
});
function makeManifest(permissions: Permission[]): PluginManifestWithDefaults {
return {
name: "perm-probe",
version: "1.0.0",
license: "MIT",
main: "index.mjs",
source: "local",
tags: [],
requires: { permissions },
hooks: {
onRequest: true,
onResponse: false,
onError: false,
onInstall: false,
onActivate: false,
onDeactivate: false,
onUninstall: false,
onStreamComplete: false,
},
skills: [],
enabledByDefault: false,
configSchema: {},
} as PluginManifestWithDefaults;
}
type Attempt = { ok: boolean; value?: unknown; code?: string };
type Probe = {
ownRead: Attempt;
outsideRead: Attempt;
exec: Attempt;
dataWrite: Attempt;
pluginDataDirEnv: string | null;
};
async function runProbe(
permissions: Permission[],
options: Parameters<typeof loadPlugin>[2]
): Promise<Probe> {
let loaded: LoadedPlugin | undefined;
try {
loaded = await loadPlugin(ENTRY, makeManifest(permissions), {
hookTimeoutMs: 20_000,
...options,
});
const result = (await loaded.plugin.onRequest?.({
requestId: "perm-probe",
body: {},
model: "m",
metadata: { outsideFile: OUTSIDE_FILE, dataDir: DATA_DIR },
})) as { metadata?: Probe } | undefined;
assert.ok(result?.metadata, "the probe plugin must answer its onRequest hook");
return result.metadata;
} finally {
loaded?.cleanup();
}
}
test("the permission model flag is defined and off by default", () => {
const flag = FEATURE_FLAG_DEFINITIONS.find(
(entry) => entry.key === "PLUGIN_PERMISSION_MODEL_ENABLED"
);
assert.ok(flag, "PLUGIN_PERMISSION_MODEL_ENABLED must be a defined feature flag");
assert.equal(flag.defaultValue, "false");
assert.equal(flag.type, "boolean");
assert.equal(flag.category, "security");
});
test(
"flag off: a plugin without permissions still reads outside its dir and runs children",
{
timeout: 60_000,
},
async () => {
await mkdir(DATA_DIR, { recursive: true });
const probe = await runProbe([], {});
assert.equal(probe.ownRead.ok, true);
assert.deepEqual(probe.outsideRead, { ok: true, value: "outside-secret" });
assert.deepEqual(probe.exec, { ok: true, value: "child-ran" });
assert.equal(probe.dataWrite.ok, true);
assert.equal(probe.pluginDataDirEnv, null, "flag off must not change the plugin env");
}
);
test(
"flag on: a plugin without permissions cannot read outside its dir or run children",
{
timeout: 60_000,
},
async () => {
const probe = await runProbe([], {
permissionModel: true,
pluginDir: PLUGIN_DIR,
dataDir: DATA_DIR,
});
assert.equal(probe.ownRead.ok, true, "the plugin must still read its own directory");
assert.deepEqual(probe.outsideRead, { ok: false, code: "ERR_ACCESS_DENIED" });
assert.deepEqual(probe.exec, { ok: false, code: "ERR_ACCESS_DENIED" });
assert.deepEqual(probe.dataWrite, { ok: false, code: "ERR_ACCESS_DENIED" });
}
);
test(
"flag on: declared file-write and exec are granted, outside reads stay denied",
{
timeout: 60_000,
},
async () => {
await rm(DATA_DIR, { recursive: true, force: true });
const probe = await runProbe(["file-write", "exec"], {
permissionModel: true,
pluginDir: PLUGIN_DIR,
dataDir: DATA_DIR,
});
assert.equal(probe.pluginDataDirEnv, DATA_DIR);
assert.deepEqual(probe.dataWrite, { ok: true, value: "written" });
assert.equal(await readFile(join(DATA_DIR, "probe.txt"), "utf-8"), "written");
assert.deepEqual(probe.exec, { ok: true, value: "child-ran" });
assert.deepEqual(probe.outsideRead, { ok: false, code: "ERR_ACCESS_DENIED" });
}
);
test("buildPermissionModelArgs maps manifest permissions to Node.js flags", () => {
const base = {
hostScriptPath: "/tmp/host.mjs",
pluginDir: "/p/plugins/x",
dataDir: "/p/plugin-data/x",
permissionFlag: "--permission",
};
assert.deepEqual(buildPermissionModelArgs({ ...base, permissions: [] }), [
"--permission",
"--allow-fs-read=/tmp/host.mjs",
"--allow-fs-read=/p/plugins/x",
]);
assert.deepEqual(
buildPermissionModelArgs({ ...base, permissions: ["network", "env", "file-read"] }),
[
"--permission",
"--allow-fs-read=/tmp/host.mjs",
"--allow-fs-read=/p/plugins/x",
"--allow-fs-read=/p/plugin-data/x",
]
);
assert.deepEqual(buildPermissionModelArgs({ ...base, permissions: ["file-write", "exec"] }), [
"--permission",
"--allow-fs-read=/tmp/host.mjs",
"--allow-fs-read=/p/plugins/x",
"--allow-fs-read=/p/plugin-data/x",
"--allow-fs-write=/p/plugin-data/x",
"--allow-child-process",
]);
});
test("resolvePermissionFlag prefers --permission and falls back for older runtimes", () => {
assert.equal(resolvePermissionFlag(new Set(["--permission"])), "--permission");
assert.equal(resolvePermissionFlag(new Set()), "--experimental-permission");
// Every supported Node.js line (>=22.22.2, 24, 26) accepts the stable name.
assert.equal(resolvePermissionFlag(), "--permission");
});
test("getPluginDataDir is plugin-data/<name> next to the plugin root", () => {
assert.equal(
getPluginDataDir(join(BASE_DIR, "plugins"), "perm-probe"),
join(BASE_DIR, "plugin-data", "perm-probe")
);
assert.equal(existsSync(join(BASE_DIR, "plugins")), true);
});

View File

@@ -81,8 +81,9 @@ describe("feature-flags-settings count update", () => {
// CODE_ASSIST_INELIGIBLE_ONBOARD_LEGACY_TIER (#18060) the 122nd;
// PII_REVERSIBLE_VAULT_ENABLED (#18017 wiring, default off) the 123rd;
// SYSTEMONE_CLOUDFLARE_BACKEND_ENABLED, SYSTEMONE_OLLAMA_LOCAL_BACKEND_ENABLED and
// COMBO_JEV_STRATEGY_ENABLED (System One, default off) to 126.
assert.equal(FEATURE_FLAG_DEFINITIONS.length, 126);
// COMBO_JEV_STRATEGY_ENABLED (System One, default off) to 126;
// PLUGIN_PERMISSION_MODEL_ENABLED (opt-in plugin sandbox, default off) to 127.
assert.equal(FEATURE_FLAG_DEFINITIONS.length, 127);
// COMPRESSION_CACHE_AUTOMATIC_PREFIX_ESTIMATE (#17114, default off) to 114.
// CURSOR_GROK_47_DROP_MAX_EFFORT (#17386, default off) to 112.
// UNPRICED_USAGE_BUDGET_POLICY (#14604, default fail_closed) to 113.