Files
Netcatty/electron/plugins/extensionProviderService.test.cjs
T

478 lines
17 KiB
JavaScript

"use strict";
const assert = require("node:assert/strict");
const test = require("node:test");
const { PluginExtensionProviderService } = require("./extensionProviderService.cjs");
function fixture(options = {}) {
const identity = Object.freeze({
pluginId: "com.example.transport",
pluginVersion: "1.0.0",
runtimeId: "runtime-1",
runtimeKind: "browser",
securityPrincipal: "local:com.example.transport",
});
const providers = [
{
id: "com.example.transport.connection",
kind: "connection",
...(options.connectionConfigurationSchema === undefined
? {}
: { configurationSchema: options.connectionConfigurationSchema }),
},
{ id: "com.example.transport.auth", kind: "authentication" },
{ id: "com.example.transport.importer", kind: "importer" },
];
const contributionService = {
listProviders({ kind }) {
return providers.filter((provider) => provider.kind === kind).map((provider) => ({
pluginId: provider.kind === "connection" && options.connectionOwnerPluginId
? options.connectionOwnerPluginId
: identity.pluginId,
pluginVersion: identity.pluginVersion,
provider,
}));
},
async activateProvider(providerId) {
const provider = providers.find((candidate) => candidate.id === providerId);
if (!provider) throw new Error("missing provider");
return {
plugin: {
id: identity.pluginId,
activeVersion: identity.pluginVersion,
manifest: { id: identity.pluginId },
},
provider,
identity,
};
},
};
const permissions = [];
const permissionEngine = {
async authorize(context, descriptor) { permissions.push({ context, descriptor }); return { scope: "application" }; },
};
const streamHandlers = [];
const rpcRegistry = {
registerIncomingStream(handler) { streamHandlers.push(handler); return { dispose() {} }; },
};
const runtimeListeners = [];
const writes = [];
const issuedLeases = [];
const revokedOperations = [];
const leaseStore = {
issue(params) {
issuedLeases.push(params);
return Object.freeze({
kind: "secret-lease",
id: "authentication-secret-lease-000000000001",
operationId: params.operationId,
expiresAt: Date.now() + (params.ttlMs ?? 30_000),
});
},
revokeOperation(pluginId, operationId) { revokedOperations.push({ pluginId, operationId }); },
};
const runtimeSupervisor = {
onDidChangeRuntime(listener) { runtimeListeners.push(listener); return { dispose() {} }; },
async request(pluginId, method, params) {
return options.request({ pluginId, method, params, identity, accept: streamHandlers[0] });
},
async openStream(_pluginId, streamId) {
return {
async write(bytes) { writes.push([streamId, Buffer.from(bytes)]); },
async end() { writes.push([streamId, "end"]); },
cancel() { writes.push([streamId, "cancel"]); },
};
},
};
const service = new PluginExtensionProviderService({
contributionService,
leaseStore,
permissionEngine,
rpcRegistry,
runtimeSupervisor,
});
return { identity, issuedLeases, permissions, revokedOperations, runtimeListeners, service, writes };
}
function incoming(streamId, emit) {
return {
streamId,
signal: new AbortController().signal,
bind(handlers) { queueMicrotask(() => emit(handlers)); },
cancel() {},
};
}
test("connection providers bind bidirectional streams to an exact runtime and clean up on runtime exit", async () => {
let h;
const output = [];
h = fixture({
async request({ params, identity, accept }) {
const stream = incoming(params.payload.outputStreamId, async (handlers) => {
await handlers.onChunk({ encoding: "binary", bytes: Uint8Array.from([65, 66]) }, () => {});
});
assert.equal(await accept(stream, identity), true);
return {
requestId: params.requestId,
status: "ok",
result: { connectionId: "connection-1", status: "connected" },
};
},
});
const opened = await h.service.openConnection({
providerId: "com.example.transport.connection",
sessionId: "session-1",
configuration: { endpoint: "example" },
columns: 120,
rows: 40,
}, { onData: (bytes) => output.push(...bytes) });
assert.deepEqual(opened, {
sessionId: "session-1",
providerId: "com.example.transport.connection",
status: "connected",
diagnostics: [],
});
await new Promise((resolve) => setImmediate(resolve));
assert.deepEqual(output, [65, 66]);
await h.service.write("session-1", Uint8Array.from([1, 2]));
assert.deepEqual([...h.writes[0][1]], [1, 2]);
await h.service.write("session-1", "hello \u4e16\u754c");
assert.equal(h.writes[1][1].toString("utf8"), "hello \u4e16\u754c");
assert.equal(h.permissions[0].descriptor.permission, "provider.connection");
assert.equal(h.revokedOperations.length, 1);
assert.equal(h.revokedOperations[0].pluginId, h.identity.pluginId);
assert.match(h.revokedOperations[0].operationId, /^connection:/u);
h.runtimeListeners[0]({ pluginId: h.identity.pluginId, runtimeId: h.identity.runtimeId, status: "stopped" });
assert.throws(() => h.service.getSession("session-1"), /not found/i);
});
test("connection controls preserve host-owned connection and operation identities", async () => {
let h;
const controls = [];
h = fixture({
async request({ params, identity, accept }) {
if (params.operation === "open") {
const stream = incoming(params.payload.outputStreamId, async () => {});
assert.equal(await accept(stream, identity), true);
return {
requestId: params.requestId,
status: "ok",
result: { connectionId: "provider-connection-1", status: "connected" },
};
}
controls.push(params);
return { requestId: params.requestId, status: "ok", result: null };
},
});
await h.service.openConnection({
providerId: "com.example.transport.connection",
sessionId: "session-control",
configuration: {},
columns: 80,
rows: 24,
});
await h.service.control("session-control", "resize", {
connectionId: "renderer-forged-connection",
operationId: "renderer-forged-operation",
columns: 100,
rows: 30,
});
assert.equal(controls.length, 1);
assert.equal(controls[0].payload.connectionId, "provider-connection-1");
assert.notEqual(controls[0].payload.operationId, "renderer-forged-operation");
assert.match(controls[0].payload.operationId, /^connection:resize:/u);
assert.deepEqual(h.revokedOperations.at(-1), {
pluginId: h.identity.pluginId,
operationId: controls[0].payload.operationId,
});
});
test("connection configuration is host-validated before invoking plugin code", async () => {
let requests = 0;
const h = fixture({
connectionConfigurationSchema: {
type: "object",
properties: {
endpoint: { type: "string", minLength: 1, maxLength: 64 },
},
required: ["endpoint"],
additionalProperties: false,
},
async request() {
requests += 1;
throw new Error("plugin code must not run for invalid configuration");
},
});
await assert.rejects(h.service.invoke({
kind: "connection",
providerId: "com.example.transport.connection",
operation: "validateConfiguration",
payload: { configuration: { endpoint: "", undeclared: true } },
}), /host schema validation/i);
assert.equal(requests, 0);
});
test("authentication secret challenges enter the runtime only as operation-bound one-use leases", async () => {
const responses = [];
const h = fixture({
async request({ params }) {
if (params.operation === "begin") {
return {
requestId: params.requestId,
status: "ok",
result: { status: "challenge", challenge: { id: "otp", kind: "otp", title: "One-time code" } },
};
}
responses.push(params.payload.response);
return {
requestId: params.requestId,
status: "ok",
result: { status: "authenticated", credential: { kind: "credential", id: "credential-reference-1234" } },
};
},
});
const result = await h.service.authenticate({
providerId: "com.example.transport.auth",
connectionProviderId: "com.example.transport.connection",
configuration: {},
}, async (challenge) => {
assert.equal(challenge.kind, "otp");
return "123456";
});
assert.equal(result.status, "authenticated");
assert.equal(responses.length, 1);
assert.equal(responses[0].kind, "secret-lease");
assert.equal(typeof responses[0].id, "string");
assert.equal(h.issuedLeases.length, 1);
assert.equal(h.issuedLeases[0].pluginId, h.identity.pluginId);
assert.equal(h.issuedLeases[0].runtimeId, h.identity.runtimeId);
assert.equal(h.issuedLeases[0].operationId, responses[0].operationId);
assert.deepEqual(h.issuedLeases[0].credential, {
kind: "authentication-challenge",
challengeId: "otp",
});
assert.equal(h.issuedLeases[0].resolveSecret(), "123456");
assert.deepEqual(h.revokedOperations, [{
pluginId: h.identity.pluginId,
operationId: responses[0].operationId,
}]);
assert.equal(h.permissions[0].descriptor.permission, "provider.authentication");
});
test("authentication providers fail closed on malformed nested challenge contracts", async () => {
const h = fixture({
async request({ params }) {
return {
requestId: params.requestId,
status: "ok",
result: {
status: "challenge",
challenge: { id: "choice", kind: "choice", title: "Choose", choices: [{ label: "Missing value" }] },
},
};
},
});
await assert.rejects(h.service.authenticate({
providerId: "com.example.transport.auth",
connectionProviderId: "com.example.transport.connection",
configuration: {},
}, async () => "unused"), /failed validation|challenge/i);
});
test("authentication responses are host-validated against the exact challenge before plugin delivery", async () => {
const operations = [];
const h = fixture({
async request({ params }) {
operations.push(params.operation);
if (params.operation === "begin") {
return {
requestId: params.requestId,
status: "ok",
result: {
status: "challenge",
challenge: {
id: "choice",
kind: "choice",
title: "Choose",
choices: [{ id: "allowed", label: "Allowed" }],
},
},
};
}
return {
requestId: params.requestId,
status: "ok",
result: { status: "cancelled" },
};
},
});
await assert.rejects(h.service.authenticate({
providerId: "com.example.transport.auth",
connectionProviderId: "com.example.transport.connection",
configuration: {},
}, async () => "undeclared-choice"), /choice response is invalid/i);
await new Promise((resolve) => setImmediate(resolve));
assert.deepEqual(operations, ["begin", "cancel"]);
});
test("cross-plugin authentication cannot transfer a plugin-owned secret reference", async () => {
const h = fixture({
connectionOwnerPluginId: "org.example.connection",
async request({ params }) {
if (params.operation === "cancel") {
return { requestId: params.requestId, status: "ok", result: { status: "cancelled" } };
}
return {
requestId: params.requestId,
status: "ok",
result: {
status: "authenticated",
credential: { kind: "secret", id: "plugin-secret-reference-0001", key: "token" },
},
};
},
});
await assert.rejects(h.service.authenticate({
providerId: "com.example.transport.auth",
connectionProviderId: "com.example.transport.connection",
configuration: {},
}, async () => true), /host-owned CredentialRef/i);
});
test("importer providers produce a validated preview without mutating Vault state", async () => {
let h;
const jsonl = [
JSON.stringify({ type: "progress", completed: 1, total: 2, message: "Reading source" }),
JSON.stringify({ type: "draft", draft: { kind: "host", value: { label: "Imported" } } }),
JSON.stringify({ type: "warning", message: "Missing optional color" }),
"",
].join("\n");
h = fixture({
async request({ params, identity, accept }) {
const stream = incoming(params.payload.outputStreamId, async (handlers) => {
await handlers.onChunk({ encoding: "binary", bytes: new TextEncoder().encode(jsonl) }, () => {});
await handlers.onClose("end");
});
assert.equal(await accept(stream, identity), true);
await new Promise((resolve) => setImmediate(resolve));
return {
requestId: params.requestId,
status: "ok",
result: { parsed: 1, warnings: 1, errors: 0 },
};
},
});
const progress = [];
const preview = await h.service.parseImporter({
providerId: "com.example.transport.importer",
fileName: "hosts.json",
sourceByteLength: 6,
source: (async function* source() {
yield new TextEncoder().encode("sou");
yield new TextEncoder().encode("rce");
}()),
}, { onProgress: (record) => progress.push(record) });
assert.equal(preview.records.length, 3);
assert.equal(preview.records[0].type, "progress");
assert.equal(preview.records[1].type, "draft");
assert.equal(preview.records[2].type, "warning");
assert.deepEqual(progress, [{ type: "progress", completed: 1, total: 2, message: "Reading source" }]);
assert.equal(preview.result.parsed, 1);
assert.equal(Buffer.concat(h.writes.filter(([, value]) => Buffer.isBuffer(value)).map(([, value]) => value)).toString(), "source");
assert.equal(h.writes.at(-1)[1], "end");
assert.equal(h.permissions[0].descriptor.permission, "provider.importer");
assert.equal(h.revokedOperations.length, 1);
assert.equal(h.revokedOperations[0].pluginId, h.identity.pluginId);
assert.match(h.revokedOperations[0].operationId, /^importer:/u);
});
test("importer input streams fail closed if the selected file changes size", async () => {
let h;
h = fixture({
async request({ params, identity, accept }) {
const stream = incoming(params.payload.outputStreamId, async (handlers) => {
await handlers.onClose("end");
});
assert.equal(await accept(stream, identity), true);
return {
requestId: params.requestId,
status: "ok",
result: { parsed: 0, warnings: 0, errors: 0 },
};
},
});
await assert.rejects(h.service.parseImporter({
providerId: "com.example.transport.importer",
sourceByteLength: 5,
source: (async function* source() { yield new TextEncoder().encode("changed"); }()),
}), /changed while it was being read|unexpected size/i);
assert.equal(h.revokedOperations.length, 1);
assert.match(h.revokedOperations[0].operationId, /^importer:/u);
});
test("importer providers cannot report completion counts that disagree with the bounded stream", async () => {
let h;
h = fixture({
async request({ params, identity, accept }) {
const stream = incoming(params.payload.outputStreamId, async (handlers) => {
await handlers.onChunk({
encoding: "binary",
bytes: new TextEncoder().encode(`${JSON.stringify({ type: "warning", message: "one" })}\n`),
}, () => {});
await handlers.onClose("end");
});
assert.equal(await accept(stream, identity), true);
await new Promise((resolve) => setImmediate(resolve));
return {
requestId: params.requestId,
status: "ok",
result: { parsed: 1, warnings: 0, errors: 0 },
};
},
});
await assert.rejects(h.service.parseImporter({
providerId: "com.example.transport.importer",
fileName: "hosts.json",
data: new TextEncoder().encode("source"),
}), /counts do not match/i);
});
test("unsolicited plugin streams are not claimed by the extension Provider service", async () => {
const h = fixture({ request() { throw new Error("unused"); } });
const accepted = await h.service.acceptIncomingStream({ streamId: "unsolicited" }, h.identity);
assert.equal(accepted, false);
});
test("connection startup reports a provider rejection without waiting for the output-stream deadline", async () => {
const h = fixture({
async request() {
throw new Error("provider rejected open");
},
});
await assert.rejects(h.service.openConnection({
providerId: "com.example.transport.connection",
sessionId: "session-rejected",
configuration: {},
columns: 80,
rows: 24,
deadlineMs: 300_000,
}), /provider rejected open/);
assert.equal(h.service.expectations.size, 0);
});
test("import parsing reports a provider rejection without waiting for the output-stream deadline", async () => {
const h = fixture({
async request() {
throw new Error("provider rejected parse");
},
});
await assert.rejects(h.service.parseImporter({
providerId: "com.example.transport.importer",
fileName: "hosts.json",
data: new TextEncoder().encode("source"),
deadlineMs: 300_000,
}), /provider rejected parse/);
assert.equal(h.service.expectations.size, 0);
});