wishforge-ide/apps/ide/policy/test/backend-guard.test.cjs
eust-w 0ef99b1e6d style: add Prettier and EditorConfig, format the codebase
Adds prettier 3.9.8 (exact) with a shared config (single quotes,
120 columns, trailing commas), .prettierignore, .editorconfig and the
`format` / `format:check` scripts, then formats all TypeScript,
JavaScript, CSS, JSON and YAML sources.

Purely mechanical: no behaviour change. Typecheck passes, the vitest
suite and the 74 IDE node tests produce the same results as before
(socket-binding tests still cannot run inside this sandbox).
Previously the longest source line was ~3000 characters; reviewing the
following semantic changes now produces readable diffs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:32:43 +08:00

368 lines
14 KiB
JavaScript

'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const {
Uint8ArrayReadBuffer,
Uint8ArrayWriteBuffer,
} = require('@theia/core/lib/common/message-rpc/uint8-array-message-buffer');
const {
MsgPackMessageDecoder,
MsgPackMessageEncoder,
} = require('@theia/core/lib/common/message-rpc/rpc-message-encoder');
const {
BatchingChannel,
RPCProtocolImpl,
createProxyIdentifier,
} = require('@theia/plugin-ext/lib/common/rpc-protocol');
const { ConnectionImpl } = require('@theia/plugin-ext/lib/common/connection');
const { ForwardingDebugChannel } = require('@theia/debug/lib/common/debug-service');
const { Emitter } = require('@theia/core/lib/common/event');
const { filterPluginRpc, guardDebugChannel, MAX_BATCH_MESSAGES } = require('../plugin-dap-guard.cjs');
const { Coordinator, DEBUG_LEASE_MS } = require('../../coordination/index.cjs');
const encoder = new MsgPackMessageEncoder();
const decoder = new MsgPackMessageDecoder();
const deny = () => {
throw new Error('DEBUG_FORBIDDEN');
};
function rpc(method, service, id = 1, type = 1, rest = []) {
const writer = new Uint8ArrayWriteBuffer();
if (type === 2) encoder.notification(writer, method, [service, ...rest], id);
else encoder.request(writer, id, method, [service, ...rest]);
return writer.getCurrentContents();
}
function batch(...messages) {
const writer = new Uint8ArrayWriteBuffer();
writer.writeLength(messages.length);
for (const message of messages) writer.writeBytes(message);
return writer.getCurrentContents();
}
function decode(payload) {
if (!payload) return [];
const reader = new Uint8ArrayReadBuffer(payload);
const count = reader.readLength();
return Array.from({ length: count }, () => decoder.parse(new Uint8ArrayReadBuffer(reader.readBytes())));
}
function memoryChannel() {
const messages = new Emitter();
const errors = new Emitter();
const closes = new Emitter();
const sent = [];
let closed = false;
return {
sent,
get closed() {
return closed;
},
onMessage: messages.event,
onError: errors.event,
onClose: closes.event,
getWriteBuffer() {
const writer = new Uint8ArrayWriteBuffer();
writer.onCommit(value => sent.push(value));
return writer;
},
close() {
closed = true;
closes.fire({ code: 1000, reason: 'closed' });
},
receive(bytes) {
messages.fire(() => new Uint8ArrayReadBuffer(bytes));
},
};
}
test('real Theia RPCProtocol emits the DebugExt wire shape gated by the filter', async () => {
const wire = memoryChannel();
const protocol = new RPCProtocolImpl(wire);
const pending = protocol
.getProxy(createProxyIdentifier('DebugExt'))
.$createDebugSession({ type: 'pwa-node', name: 'test' }, 'file:///workspace');
const rejected = assert.rejects(pending, /DEBUG_CONTROL_REQUIRED/);
await new Promise(resolve => setImmediate(resolve));
assert.equal(wire.sent.length, 1);
const actual = decode(wire.sent[0]);
assert.equal(actual[0].method, '$createDebugSession');
assert.equal(actual[0].args[0], 'DebugExt');
const result = filterPluginRpc(wire.sent[0], deny);
assert.equal(result.forwarded, null);
assert.equal(result.denied, 1);
wire.receive(result.replies);
await rejected;
protocol.dispose();
});
test('unauthorized plugin create/terminate/send/delete requests never enter the forwarded host batch', () => {
const calls = [
rpc('$createDebugSession', 'DebugExt', 10),
rpc('$terminateDebugSession', 'DebugExt', 11),
rpc('$sendMessage', 'ConnectionExt', 12, 1, ['session', '{"command":"continue"}']),
rpc('$deleteConnection', 'ConnectionExt', 13),
];
const result = filterPluginRpc(batch(...calls), deny);
assert.equal(result.forwarded, null);
assert.equal(result.denied, 4);
assert.deepEqual(
decode(result.replies).map(message => ({ type: message.type, id: message.id, error: message.err.message })),
[10, 11, 12, 13].map(id => ({ type: 4, id, error: 'DEBUG_CONTROL_REQUIRED' })),
);
});
test('denied plugin DAP reaches real frontend RPCProtocol and ConnectionMain as a failed response', async () => {
const wire = memoryChannel();
const protocol = new RPCProtocolImpl(wire);
const proxy = protocol.getProxy(createProxyIdentifier('ConnectionExt'));
const connectionMain = protocol.set(createProxyIdentifier('ConnectionMain'), new ConnectionImpl(proxy));
const frontendChannel = await connectionMain.doEnsureConnection('session-real');
const received = [];
frontendChannel.onMessage(message => received.push(JSON.parse(message)));
let previousSequence = 0;
try {
for (const [seq, command] of [
[31, 'next'],
[32, 'continue'],
]) {
const pending = proxy.$sendMessage(
'session-real',
JSON.stringify({ type: 'request', seq, command, arguments: { threadId: 1 } }),
);
const rejected = assert.rejects(pending, /DEBUG_CONTROL_REQUIRED/);
await new Promise(resolve => setImmediate(resolve));
const result = filterPluginRpc(wire.sent.at(-1), deny);
assert.equal(result.forwarded, null);
assert.equal(result.denied, 1);
const messages = decode(result.replies);
assert.equal(messages[0].type, 4);
assert.equal(messages[1].type, 2);
assert.equal(messages[1].method, '$sendMessage');
assert.deepEqual(messages[1].args.slice(0, 2), ['ConnectionMain', 'session-real']);
wire.receive(result.replies);
await rejected;
const response = received.at(-1);
assert.ok(Number.isSafeInteger(response.seq) && response.seq > previousSequence);
previousSequence = response.seq;
assert.deepEqual(
{ ...response, seq: undefined },
{
seq: undefined,
type: 'response',
request_seq: seq,
command,
success: false,
message: 'WishForge debug controller lease required',
},
);
}
assert.equal(received.length, 2);
} finally {
protocol.dispose();
}
});
test('denied DAP carried as an RPC notification receives only a DAP failure notification', () => {
const request = JSON.stringify({ type: 'request', seq: 4, command: 'disconnect' });
const result = filterPluginRpc(batch(rpc('$sendMessage', 'ConnectionExt', 42, 2, ['session-one', request])), deny);
assert.equal(result.forwarded, null);
assert.equal(result.denied, 1);
const replies = decode(result.replies);
assert.equal(replies.length, 1);
assert.equal(replies[0].type, 2);
assert.deepEqual(replies[0].args.slice(0, 2), ['ConnectionMain', 'session-one']);
assert.equal(JSON.parse(replies[0].args[2]).request_seq, 4);
});
test('malformed or nonrequest denied plugin DAP never fabricates a DAP response', () => {
const cases = [
['session', 'bad-json'],
['session', 'null'],
['session', '[]'],
['session', '{"type":"event","seq":1,"command":"next"}'],
['session', '{"type":"request","seq":"1","command":"next"}'],
['session', '{"type":"request","seq":-1,"command":"next"}'],
['session', '{"type":"request","seq":1}'],
['session', '{"type":"request","seq":1,"command":""}'],
['session', { type: 'request', seq: 1, command: 'next' }],
['', '{"type":"request","seq":1,"command":"next"}'],
[5, '{"type":"request","seq":1,"command":"next"}'],
];
for (const args of cases) {
const result = filterPluginRpc(batch(rpc('$sendMessage', 'ConnectionExt', 42, 1, args)), deny);
assert.equal(result.forwarded, null);
assert.equal(result.denied, 1);
const replies = decode(result.replies);
assert.equal(replies.length, 1);
assert.equal(replies[0].type, 4);
assert.equal(replies[0].err.message, 'DEBUG_CONTROL_REQUIRED');
}
});
test('ordinary RPC forwards byte-for-byte while denied notifications do not fabricate replies', () => {
const ordinary = rpc('$acceptModelChanged', 'EditorsAndDocumentsExt', 1, 2);
const reply = new Uint8ArrayWriteBuffer();
encoder.replyOK(reply, 8, { success: true });
const result = filterPluginRpc(
batch(ordinary, rpc('$sendMessage', 'ConnectionExt', 2, 2), reply.getCurrentContents()),
deny,
);
assert.deepEqual(result.forwarded, batch(ordinary, reply.getCurrentContents()));
assert.equal(result.replies, null);
assert.equal(result.denied, 1);
});
test('controller forwarding preserves actual BatchingChannel bytes and rechecks authorization for every command', () => {
const wire = memoryChannel();
const batching = new BatchingChannel(wire);
const first = batching.getWriteBuffer();
encoder.request(first, 1, '$createDebugSession', ['DebugExt']);
first.commit();
const second = batching.getWriteBuffer();
encoder.request(second, 2, '$sendMessage', ['ConnectionExt', 'session', '{}']);
second.commit();
batching.sendAccumulated();
const payload = wire.sent[0];
let checks = 0;
const allowed = filterPluginRpc(payload, () => {
checks++;
});
assert.deepEqual(allowed.forwarded, payload);
assert.equal(allowed.replies, null);
assert.equal(checks, 2);
checks = 0;
const revokedMidBatch = filterPluginRpc(payload, () => {
if (++checks === 2) deny();
});
assert.equal(decode(revokedMidBatch.forwarded).length, 1);
assert.equal(decode(revokedMidBatch.replies)[0].id, 2);
batching.close();
});
test('malformed, truncated, oversized or trailing frames fail atomically before any forwarding', () => {
const good = batch(rpc('$createDebugSession', 'DebugExt'));
const excessive = new Uint8ArrayWriteBuffer();
excessive.writeLength(MAX_BATCH_MESSAGES + 1);
const invalidInner = new Uint8ArrayWriteBuffer();
invalidInner.writeLength(100);
invalidInner.writeRaw(new Uint8Array([1]));
const wrongShape = new Uint8ArrayWriteBuffer();
encoder.encode(wrongShape, { type: 1, id: 3, method: '$sendMessage', args: { 0: 'ConnectionExt' } });
for (const bytes of [
new Uint8Array(),
good.slice(0, -1),
new Uint8Array([...good, 0]),
excessive.getCurrentContents(),
batch(invalidInner.getCurrentContents()),
batch(wrongShape.getCurrentContents()),
new Uint8Array([129, 129, 129, 129, 129, 0]),
]) {
let invoked = false;
assert.throws(
() =>
filterPluginRpc(bytes, () => {
invoked = true;
}),
/PLUGIN_RPC|RPC_BATCH_LIMIT/,
);
assert.equal(invoked, false);
}
// Prevent reading into extra bytes from a websocket buffer outside the actual view.
const backed = new Uint8Array([...good, ...good]);
assert.throws(() => filterPluginRpc(backed.subarray(0, good.length - 1), deny), /PLUGIN_RPC/);
assert.deepEqual(filterPluginRpc(batch(), deny), { forwarded: null, replies: null, denied: 0 });
});
test('guard cannot accidentally authorize on a false or asynchronous decision', () => {
const payload = batch(rpc('$sendMessage', 'ConnectionExt'));
for (const callback of [() => false, () => Promise.resolve(true)])
assert.equal(filterPluginRpc(payload, callback).forwarded, null);
assert.throws(() => filterPluginRpc(payload), /DEBUG_GUARD_REQUIRED/);
});
test('real coordinator lease owner, renewal, expiry and revocation govern plugin forwarding', t => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'wishforge-debug-guard-'));
const workspaceRoot = path.join(directory, 'source');
fs.mkdirSync(workspaceRoot);
let now = 1000;
const coordinator = new Coordinator({ workspaceRoot, stateDirectory: path.join(directory, 'state'), now: () => now });
t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
const alice = coordinator.debugAcquire('alice');
const payload = batch(rpc('$sendMessage', 'ConnectionExt'));
assert.equal(filterPluginRpc(payload, () => coordinator.assertDebugController('bob', alice.token)).forwarded, null);
assert.equal(
filterPluginRpc(payload, () => coordinator.assertDebugController('alice', 'another-tab-token')).forwarded,
null,
);
const permitted = () => coordinator.assertDebugController('alice', alice.token);
assert.deepEqual(filterPluginRpc(payload, permitted).forwarded, payload);
now += 10_000;
coordinator.debugAcquire('alice', alice.token);
now += DEBUG_LEASE_MS - 10_000;
assert.deepEqual(filterPluginRpc(payload, permitted).forwarded, payload);
now += 10_000;
assert.equal(filterPluginRpc(payload, permitted).forwarded, null);
const next = coordinator.debugAcquire('alice');
assert.deepEqual(
filterPluginRpc(payload, () => coordinator.assertDebugController('alice', next.token)).forwarded,
payload,
);
coordinator.revoke('alice');
assert.equal(filterPluginRpc(payload, () => coordinator.assertDebugController('alice', next.token)).forwarded, null);
});
test('native DAP wrapper checks the live lease before adapter callback and sends decodable denials', () => {
const wire = memoryChannel();
const raw = new ForwardingDebugChannel(wire);
let allowed = false;
const guarded = guardDebugChannel(raw, () => {
if (!allowed) deny();
});
const received = [];
guarded.onMessage(message => received.push(JSON.parse(message)));
const incoming = (seq, command) => {
const writer = new Uint8ArrayWriteBuffer();
writer.writeString(JSON.stringify({ type: 'request', seq, command }));
wire.receive(writer.getCurrentContents());
};
incoming(1, 'launch');
incoming(2, 'continue');
assert.deepEqual(received, []);
const errors = wire.sent.map(bytes => JSON.parse(new Uint8ArrayReadBuffer(bytes).readString()));
assert.deepEqual(
errors.map(error => [error.seq, error.request_seq, error.command, error.success]),
[
[1, 1, 'launch', false],
[2, 2, 'continue', false],
],
);
allowed = true;
incoming(3, 'next');
assert.equal(received[0].command, 'next');
allowed = false;
incoming(4, 'disconnect');
assert.equal(received.length, 1);
guarded.send(JSON.stringify({ type: 'event', event: 'stopped' }));
assert.equal(JSON.parse(new Uint8ArrayReadBuffer(wire.sent.at(-1)).readString()).event, 'stopped');
guarded.close();
assert.equal(wire.closed, true);
});
test('unauthorized malformed native DAP closes channel without reaching adapter', () => {
for (const message of ['bad-json', 'null', '{"type":"event","event":"stopped"}', '{"type":"request","seq":1}']) {
const wire = memoryChannel();
const guarded = guardDebugChannel(new ForwardingDebugChannel(wire), deny);
let reached = false;
guarded.onMessage(() => {
reached = true;
});
const writer = new Uint8ArrayWriteBuffer();
writer.writeString(message);
wire.receive(writer.getCurrentContents());
assert.equal(reached, false);
assert.equal(wire.closed, true);
assert.equal(wire.sent.length, 0);
}
});