From e6c55c90524aa80ba2fbbbb89cde1c3fc17b0dfb Mon Sep 17 00:00:00 2001 From: ryan-wong-coder Date: Sun, 19 Jul 2026 15:07:30 +0800 Subject: [PATCH] fix(plugins): close remaining authorization races --- electron/plugins/filesystemBroker.cjs | 5 +-- electron/plugins/filesystemBroker.test.cjs | 40 ++++++++++++++++++++++ electron/plugins/permissionEngine.cjs | 5 +++ electron/plugins/permissionEngine.test.cjs | 35 +++++++++++++++++++ electron/plugins/runtime/runtimePeer.mjs | 15 +++++++- electron/plugins/runtimePeer.test.cjs | 10 +++++- packages/plugin-cli/src/cli.test.ts | 26 ++++++++++++++ packages/plugin-cli/src/manifest.ts | 26 ++++++++++++++ 8 files changed, 158 insertions(+), 4 deletions(-) diff --git a/electron/plugins/filesystemBroker.cjs b/electron/plugins/filesystemBroker.cjs index a787603e6..7ef6ec756 100644 --- a/electron/plugins/filesystemBroker.cjs +++ b/electron/plugins/filesystemBroker.cjs @@ -106,7 +106,7 @@ async function resolveWritePath(requestedPath, fileSystem = fsp) { try { const existing = await resolveExistingPath(requestedPath, fileSystem); if (!existing.stats.isFile()) throw invalidArgument("Plugin filesystem write target is not a file"); - return existing.canonical; + return existing; } catch (error) { if (error?.code === "ENOENT") { throw new PluginRpcError( @@ -264,7 +264,7 @@ class PluginFilesystemBroker { async writeFile(params, context) { const value = assertSecureWriteMode(assertWriteParams(params)); assertAuthorizedPath(context, "filesystem.write", value.path); - const canonical = await resolveWritePath(value.path, this.fileSystem); + const { canonical, stats } = await resolveWritePath(value.path, this.fileSystem); assertAuthorizedPath(context, "filesystem.write", canonical); this.quotaManager?.chargeBytes(context.runtimeId, "filesystem", value.bytes.byteLength); await context.assertActive(); @@ -276,6 +276,7 @@ class PluginFilesystemBroker { handle.stat(), this.fileSystem.stat(canonical), ]); + assertSameOpenedFile(openedStats, stats); assertSameOpenedFile(openedStats, pathStats); await context.assertActive(); if (value.overwrite) await handle.truncate(0); diff --git a/electron/plugins/filesystemBroker.test.cjs b/electron/plugins/filesystemBroker.test.cjs index ac1d24181..e14eabfae 100644 --- a/electron/plugins/filesystemBroker.test.cjs +++ b/electron/plugins/filesystemBroker.test.cjs @@ -328,6 +328,46 @@ test("filesystem reads reject a replacement inode opened after authorization", a ); }); +test("filesystem writes reject a replacement inode opened after authorization", async (context) => { + const root = createRoot(context); + const target = path.join(root, "selected.txt"); + const original = path.join(root, "original.txt"); + const replacement = path.join(root, "replacement.txt"); + await Promise.all([ + fsp.writeFile(target, "allowed"), + fsp.writeFile(replacement, "secret"), + ]); + let swapped = false; + const broker = new PluginFilesystemBroker({ + fileSystem: { + ...fsp, + async open(filePath, flags, mode) { + if (!swapped) { + swapped = true; + await fsp.rename(target, original); + await fsp.rename(replacement, target); + } + return fsp.open(filePath, flags, mode); + }, + }, + }); + const authorization = broker.describeWriteAuthorization({ + path: target, + data: "overwritten", + overwrite: true, + }); + await assert.rejects( + broker.writeFile({ + path: target, + data: "overwritten", + overwrite: true, + }, runtimeContext(authorization)), + (error) => error.code === RPC_ERRORS.permissionDenied, + ); + assert.equal(await fsp.readFile(original, "utf8"), "allowed"); + assert.equal(await fsp.readFile(target, "utf8"), "secret"); +}); + test("filesystem broker rejects oversized and non-canonical payloads", async (context) => { const root = createRoot(context); const target = path.join(root, "target.bin"); diff --git a/electron/plugins/permissionEngine.cjs b/electron/plugins/permissionEngine.cjs index 547f2b0ba..e7ac6f50a 100644 --- a/electron/plugins/permissionEngine.cjs +++ b/electron/plugins/permissionEngine.cjs @@ -558,6 +558,11 @@ class PluginPermissionEngine { await this.authorize(context, { permission: declaration.permission, resources: declaration.resources.length ? declaration.resources : ["*"], + ...(declaration.resources.length + && (declaration.permission === "filesystem.read" + || declaration.permission === "filesystem.write") + ? { resourceKinds: declaration.resources.map(() => "directory") } + : {}), reason: declaration.reason || `Required by ${plugin.id}`, operationId: `activation:${plugin.activeVersion}`, }); diff --git a/electron/plugins/permissionEngine.test.cjs b/electron/plugins/permissionEngine.test.cjs index 8a3040b4d..7e5dbe6e8 100644 --- a/electron/plugins/permissionEngine.test.cjs +++ b/electron/plugins/permissionEngine.test.cjs @@ -470,6 +470,41 @@ test("required preflight grants non-resource permissions but defers concrete res database.close(); }); +test("required filesystem preflight preserves declared directory scope", async (context) => { + const database = createDatabase(context); + const root = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-required-directory-")); + context.after(() => fs.rmSync(root, { recursive: true, force: true })); + const child = path.join(root, "child.txt"); + let prompts = 0; + const requests = []; + const engine = new PluginPermissionEngine({ + database, + requestDecision: async (request) => { + prompts += 1; + requests.push(request); + return { requestId: request.requestId, decision: "allow", scope: "application" }; + }, + }); + const pluginManifest = manifest({ required: [{ + permission: "filesystem.read", + resources: [root], + }] }); + await engine.authorizeRequired({ + id: pluginManifest.id, + activeVersion: pluginManifest.version, + manifest: pluginManifest, + }); + assert.deepEqual(requests[0].resourceKinds, ["directory"]); + await engine.authorize(runtimeContext(pluginManifest), { + permission: "filesystem.read", + resources: [child], + resourceKinds: ["exact"], + reason: "Read declared descendant", + }); + assert.equal(prompts, 1); + database.close(); +}); + test("permission middleware rejects unclassified methods and permits explicit public methods", async (context) => { const database = createDatabase(context); const engine = new PluginPermissionEngine({ database }); diff --git a/electron/plugins/runtime/runtimePeer.mjs b/electron/plugins/runtime/runtimePeer.mjs index 9dc2d7bcb..ee8fd65aa 100644 --- a/electron/plugins/runtime/runtimePeer.mjs +++ b/electron/plugins/runtime/runtimePeer.mjs @@ -2,6 +2,7 @@ import { CancellationTokenSource, DisposableStore, PluginError, + PLUGIN_ERROR_WIRE_CODES, pluginErrorToRpcError, } from "@netcatty/plugin-sdk"; import { createMessagePortStreamEnvelope } from "@netcatty/plugin-contract"; @@ -14,6 +15,18 @@ const RPC_ERRORS = { unsupported: -32012, }; +const PLUGIN_ERROR_NAMES_BY_WIRE_CODE = new Map( + Object.entries(PLUGIN_ERROR_WIRE_CODES).map(([name, code]) => [code, name]), +); + +function pluginErrorNameFromRpcError(error) { + if (typeof error?.data?.pluginCode === "string") return error.data.pluginCode; + if (error?.code === RPC_ERRORS.methodNotFound) return "unsupported"; + if (error?.code === RPC_ERRORS.invalidParams) return "invalid_argument"; + if (error?.code === RPC_ERRORS.internal) return "internal"; + return PLUGIN_ERROR_NAMES_BY_WIRE_CODE.get(error?.code) ?? "unknown"; +} + function messageData(value) { return value && typeof value === "object" && "data" in value ? value.data : value; } @@ -90,7 +103,7 @@ function createHostClient(transport) { pending.delete(`${typeof message.id}:${String(message.id)}`); if (message.error) { request.reject(new PluginError( - message.error.data?.pluginCode ?? "unknown", + pluginErrorNameFromRpcError(message.error), message.error.message, message.error.data?.details, )); diff --git a/electron/plugins/runtimePeer.test.cjs b/electron/plugins/runtimePeer.test.cjs index abf812b24..097ff77c1 100644 --- a/electron/plugins/runtimePeer.test.cjs +++ b/electron/plugins/runtimePeer.test.cjs @@ -4,7 +4,7 @@ const assert = require("node:assert/strict"); const test = require("node:test"); const { MessageChannel } = require("node:worker_threads"); -const { PluginRpcRouter } = require("./rpcRouter.cjs"); +const { PluginRpcError, PluginRpcRouter, RPC_ERRORS } = require("./rpcRouter.cjs"); test("runtime peer exposes secure host capabilities over the canonical RPC transport", async () => { const { startPluginRuntime } = await import("./runtime/runtimePeer.mjs"); @@ -16,6 +16,9 @@ test("runtime peer exposes secure host capabilities over the canonical RPC trans pluginId: "com.example.peer", send(message) { port1.postMessage(message); }, handlers: { + "storage.get": async () => { + throw new PluginRpcError(RPC_ERRORS.invalidArgument, "Invalid storage key"); + }, "storage.set": async ({ key, value }) => { values.set(key, value); return null; }, "secrets.set": async ({ key, value }) => { calls.push(["secret", key, value]); @@ -71,6 +74,11 @@ test("runtime peer exposes secure host capabilities over the canonical RPC trans default: { async activate(context) { lifecycle.push("activate"); + await assert.rejects( + context.storage.get("invalid"), + (error) => error?.code === "invalid_argument" + && error?.message === "Invalid storage key", + ); await context.storage.set("answer", 42); const secret = await context.secrets.set("api-key", "value"); const lease = await context.credentials.createLease(secret, { diff --git a/packages/plugin-cli/src/cli.test.ts b/packages/plugin-cli/src/cli.test.ts index 0c10721a5..9da4bc932 100644 --- a/packages/plugin-cli/src/cli.test.ts +++ b/packages/plugin-cli/src/cli.test.ts @@ -217,6 +217,32 @@ test("manifest validation reports permission and contribution mistakes", () => { assert.match(result.errors.join("\n"), /undeclared command/); }); +test("manifest validation applies the runtime resource limit for each permission", () => { + for (const [permission, length, expectedLimit] of [ + ["network", 2_049, 2_048], + ["storage", 2_049, 2_048], + ["companion.execute", 193, 192], + ] as const) { + const result = validateManifestValue(manifest({ + permissions: { + required: [{ permission, resources: ["x".repeat(length)] }], + }, + })); + assert.equal(result.valid, false); + assert.match( + result.errors.join("\n"), + new RegExp(`Permission resource for ${permission.replace(".", "\\.")} exceeds ${expectedLimit}`), + ); + } + + const filesystem = validateManifestValue(manifest({ + permissions: { + required: [{ permission: "filesystem.read", resources: [`/${"x".repeat(4_096)}`] }], + }, + })); + assert.equal(filesystem.valid, true, filesystem.errors.join("\n")); +}); + test("Node utility entrypoints require the explicit advanced-runtime permission", () => { const missing = validateManifestValue(manifest({ main: { node: "dist/index.js" }, diff --git a/packages/plugin-cli/src/manifest.ts b/packages/plugin-cli/src/manifest.ts index 5487050ae..ffbcee21f 100644 --- a/packages/plugin-cli/src/manifest.ts +++ b/packages/plugin-cli/src/manifest.ts @@ -134,6 +134,31 @@ function permissionName(declaration: PermissionDeclaration): PluginPermission { return typeof declaration === "string" ? declaration : declaration.permission; } +function permissionResourceLimit(permission: PluginPermission): number { + if (permission === "filesystem.read" || permission === "filesystem.write") return 8_192; + if (permission === "companion.execute") return 192; + return 2_048; +} + +function validatePermissionResourceLimits(manifest: PluginManifest): string[] { + const errors: string[] = []; + for (const declaration of [ + ...(manifest.permissions?.required ?? []), + ...(manifest.permissions?.optional ?? []), + ]) { + if (typeof declaration === "string") continue; + const maximum = permissionResourceLimit(declaration.permission); + for (const resource of declaration.resources) { + if (resource.length > maximum) { + errors.push( + `Permission resource for ${declaration.permission} exceeds ${maximum} characters`, + ); + } + } + } + return errors; +} + function findDuplicateIds(manifest: PluginManifest): string[] { const errors: string[] = []; const groups = [ @@ -185,6 +210,7 @@ function validateSemantics(manifest: PluginManifest): string[] { const errors = [ ...findDuplicateIds(manifest), ...validateOwnedContributionIds(manifest), + ...validatePermissionResourceLimits(manifest), ]; for (const [engine, range] of Object.entries(manifest.engines)) { if (validRange(range) === null) {