mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 07:07:31 +00:00
feat(plugins): sandbox hardening — OS permission model, egress choke point, bound acting user, author signatures
Closes the four gaps the security review surfaced: - OS permission model on the prod plugin child (Node --permission with fs-read scoped to the compiled server dir + the plugin's own code dir, no fs-write/child_process/worker/native). A plugin can no longer read trek.db or the .jwt_secret/.encryption_key files, nor shell out — the direct-fs and RCE escapes that bypassed the RPC layer. Opt-out via TREK_PLUGIN_PERMISSIONS=off. - Egress guard extended from fetch to the net.Socket connect choke point, so node:http/https/net/tls obey the declared-egress allowlist too (no declared egress = no outbound). Under the permission model there is no clean escape to an unwrapped runtime. Kernel/network-namespace containment remains the container step. - Trip reads are membership-checked against the acting user the HOST binds from the authenticated invocation, not an asUserId the plugin supplies; a job/onLoad (no user) can't read user-scoped trips. - Optional minisign (Ed25519) author signatures verified offline, TOFU-pinned (migration 158). Unsigned plugins install on sha256 alone; a signed plugin can't silently drop its signature or swap its author key. Server suite green (permission-model activation verified against the Koffi reference plugin on dev1).
This commit is contained in:
@@ -16,7 +16,9 @@ function fakeTransport() {
|
||||
describe('createPluginContext', () => {
|
||||
it('maps each ctx method onto the right RPC call', async () => {
|
||||
const { transport, rpc } = fakeTransport();
|
||||
const ctx = createPluginContext('p', {}, transport);
|
||||
// An invocation-scoped ctx: trip reads carry `_inv` so the host can bind the
|
||||
// acting user to this invocation.
|
||||
const ctx = createPluginContext('p', {}, transport, 'inv-1');
|
||||
|
||||
await ctx.db.query('SELECT 1', 'a');
|
||||
expect(rpc).toHaveBeenCalledWith('db.query', { sql: 'SELECT 1', args: ['a'] });
|
||||
@@ -24,8 +26,8 @@ describe('createPluginContext', () => {
|
||||
await ctx.db.migrate('001', 'CREATE TABLE t (x)');
|
||||
expect(rpc).toHaveBeenCalledWith('db.migrate', { id: '001', sql: 'CREATE TABLE t (x)' });
|
||||
|
||||
await ctx.trips.getById(1, 42);
|
||||
expect(rpc).toHaveBeenCalledWith('trips.getById', { tripId: 1, asUserId: 42 });
|
||||
await ctx.trips.getById(1);
|
||||
expect(rpc).toHaveBeenCalledWith('trips.getById', { tripId: 1, _inv: 'inv-1' });
|
||||
|
||||
await ctx.ws.broadcastToTrip(1, 'ping', { a: 1 });
|
||||
expect(rpc).toHaveBeenCalledWith('ws.broadcastToTrip', { tripId: 1, event: 'ping', data: { a: 1 } });
|
||||
@@ -36,11 +38,11 @@ describe('createPluginContext', () => {
|
||||
await ctx.db.exec('DELETE FROM t');
|
||||
expect(rpc).toHaveBeenCalledWith('db.exec', { sql: 'DELETE FROM t', args: [] });
|
||||
|
||||
await ctx.trips.getPlaces(1, 42);
|
||||
expect(rpc).toHaveBeenCalledWith('trips.getPlaces', { tripId: 1, asUserId: 42 });
|
||||
await ctx.trips.getPlaces(1);
|
||||
expect(rpc).toHaveBeenCalledWith('trips.getPlaces', { tripId: 1, _inv: 'inv-1' });
|
||||
|
||||
await ctx.trips.getReservations(1, 42);
|
||||
expect(rpc).toHaveBeenCalledWith('trips.getReservations', { tripId: 1, asUserId: 42 });
|
||||
await ctx.trips.getReservations(1);
|
||||
expect(rpc).toHaveBeenCalledWith('trips.getReservations', { tripId: 1, _inv: 'inv-1' });
|
||||
|
||||
await ctx.ws.broadcastToUser(9, 'poke', { x: 2 });
|
||||
expect(rpc).toHaveBeenCalledWith('ws.broadcastToUser', { userId: 9, event: 'poke', data: { x: 2 } });
|
||||
|
||||
@@ -81,11 +81,12 @@ describe('PluginsProxyController', () => {
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.headers['content-type']).toBe('application/json');
|
||||
expect(res.body).toBe('{"ok":true}');
|
||||
// the child receives only a whitelisted user view, never the token/cookie
|
||||
// the child receives only a whitelisted user view, never the token/cookie;
|
||||
// the acting user (5) is bound server-side as the 4th invoke arg
|
||||
expect(runtime.invoke).toHaveBeenCalledWith('p', 'invoke.route', expect.objectContaining({
|
||||
routeId: 0,
|
||||
req: expect.objectContaining({ user: { id: 5, username: 'ada', isAdmin: false } }),
|
||||
}));
|
||||
}), 5);
|
||||
});
|
||||
|
||||
it('a public (auth:false) route skips the session check', async () => {
|
||||
@@ -94,9 +95,10 @@ describe('PluginsProxyController', () => {
|
||||
await new PluginsProxyController(runtime).proxy('p', fakeReq('POST', '/webhook'), res as never);
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(extractTokenMock).not.toHaveBeenCalled();
|
||||
// a public route has no session user → no bound acting user (undefined)
|
||||
expect(runtime.invoke).toHaveBeenCalledWith('p', 'invoke.route', expect.objectContaining({
|
||||
req: expect.objectContaining({ user: null }),
|
||||
}));
|
||||
}), undefined);
|
||||
});
|
||||
|
||||
it('strips unsafe response headers from the child', async () => {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest';
|
||||
import { isKnownPermission, METHOD_PERMISSION, KNOWN_METHODS } from '../../../src/nest/plugins/protocol/envelope';
|
||||
import path from 'node:path';
|
||||
import { pluginsCodeRoot, pluginsDataRoot, pluginCodeDir, pluginDbFile, resolveChildEntry } from '../../../src/nest/plugins/paths';
|
||||
import { pluginsCodeRoot, pluginsDataRoot, pluginCodeDir, pluginDbFile, resolveChildEntry, serverCodeRoot, pluginPermissionArgs } from '../../../src/nest/plugins/paths';
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.TREK_PLUGINS_DIR;
|
||||
@@ -47,5 +47,25 @@ describe('paths', () => {
|
||||
const r = resolveChildEntry();
|
||||
expect(r.entry).toMatch(/plugin-host-entry\.(js|ts)$/);
|
||||
expect(Array.isArray(r.execArgv)).toBe(true);
|
||||
expect(typeof r.jsMode).toBe('boolean');
|
||||
});
|
||||
|
||||
it('builds scoped OS-permission flags for a plugin child (default on)', () => {
|
||||
delete process.env.TREK_PLUGIN_PERMISSIONS;
|
||||
const args = pluginPermissionArgs('flight-tracker');
|
||||
expect(args).toContain('--permission');
|
||||
// read is scoped to the compiled server dir + this plugin's own code dir…
|
||||
expect(args.some((a) => a === `--allow-fs-read=${serverCodeRoot()}`)).toBe(true);
|
||||
expect(args.some((a) => a === `--allow-fs-read=${pluginCodeDir('flight-tracker')}`)).toBe(true);
|
||||
// …and never grants fs-write / child_process / the data root.
|
||||
expect(args.some((a) => a.startsWith('--allow-fs-write'))).toBe(false);
|
||||
expect(args.some((a) => a.startsWith('--allow-child-process'))).toBe(false);
|
||||
expect(serverCodeRoot()).not.toContain(`${require('node:path').sep}data`);
|
||||
});
|
||||
|
||||
it('lets an operator opt out of the permission model', () => {
|
||||
process.env.TREK_PLUGIN_PERMISSIONS = 'off';
|
||||
expect(pluginPermissionArgs('flight-tracker')).toEqual([]);
|
||||
delete process.env.TREK_PLUGIN_PERMISSIONS;
|
||||
});
|
||||
});
|
||||
|
||||
@@ -64,7 +64,8 @@ describe('PluginRpcHost — capability enforcement', () => {
|
||||
|
||||
it('db:read:trips reads a trip the acting user can access', async () => {
|
||||
const host = new PluginRpcHost('p', new Set(['db:read:trips']), deps);
|
||||
const res = await host.dispatch(req('trips.getById', { tripId: 1, asUserId: 42 }));
|
||||
// The acting user is bound by the HOST (2nd dispatch arg), never from params.
|
||||
const res = await host.dispatch(req('trips.getById', { tripId: 1 }), 42);
|
||||
expect(ok(res)).toBe(true);
|
||||
// returns the ACTUAL trip row (title/start_date), not the access-check object
|
||||
expect((res as RpcResponse).result).toMatchObject({ id: 1, title: 'Japan', start_date: '2027-01-01' });
|
||||
@@ -73,17 +74,25 @@ describe('PluginRpcHost — capability enforcement', () => {
|
||||
|
||||
it('db:read:trips is still RESOURCE_FORBIDDEN when the user is not a member', async () => {
|
||||
const host = new PluginRpcHost('p', new Set(['db:read:trips']), deps);
|
||||
const res = await host.dispatch(req('trips.getById', { tripId: 1, asUserId: 99 }));
|
||||
const res = await host.dispatch(req('trips.getById', { tripId: 1 }), 99);
|
||||
expect((res as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
|
||||
});
|
||||
|
||||
it('a trip read with NO bound acting user is RESOURCE_FORBIDDEN (jobs / forged calls)', async () => {
|
||||
const host = new PluginRpcHost('p', new Set(['db:read:trips']), deps);
|
||||
// A plugin-supplied asUserId is ignored; without a host-bound user, deny.
|
||||
const res = await host.dispatch(req('trips.getById', { tripId: 1, asUserId: 42 }), undefined);
|
||||
expect((res as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
|
||||
expect(deps.canAccessTrip).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('trips.getPlaces is membership-checked before the core read', async () => {
|
||||
const host = new PluginRpcHost('p', new Set(['db:read:trips']), deps);
|
||||
const forbidden = await host.dispatch(req('trips.getPlaces', { tripId: 2, asUserId: 42 }));
|
||||
const forbidden = await host.dispatch(req('trips.getPlaces', { tripId: 2 }), 42);
|
||||
expect((forbidden as RpcError).error.code).toBe('RESOURCE_FORBIDDEN');
|
||||
expect(deps.db.prepare).not.toHaveBeenCalled();
|
||||
|
||||
const allowed = await host.dispatch(req('trips.getPlaces', { tripId: 1, asUserId: 42 }));
|
||||
const allowed = await host.dispatch(req('trips.getPlaces', { tripId: 1 }), 42);
|
||||
expect(ok(allowed)).toBe(true);
|
||||
expect((allowed as RpcResponse).result).toEqual([{ id: 7, name: 'Place' }]);
|
||||
});
|
||||
@@ -142,7 +151,7 @@ describe('PluginRpcHost — capability enforcement', () => {
|
||||
|
||||
it('trips.getReservations is membership-checked and reads reservations', async () => {
|
||||
const host = new PluginRpcHost('p', new Set(['db:read:trips']), deps);
|
||||
const res = await host.dispatch(req('trips.getReservations', { tripId: 1, asUserId: 42 }));
|
||||
const res = await host.dispatch(req('trips.getReservations', { tripId: 1 }), 42);
|
||||
expect(ok(res)).toBe(true);
|
||||
expect(deps.db.prepare).toHaveBeenCalledWith(expect.stringContaining('FROM reservations'));
|
||||
});
|
||||
@@ -169,8 +178,8 @@ describe('PluginRpcHost — capability enforcement', () => {
|
||||
|
||||
it('coerces numeric string params and tolerates a missing params object', async () => {
|
||||
const host = new PluginRpcHost('p', new Set(['db:read:trips', 'db:own']), deps);
|
||||
// tripId/asUserId as strings -> coerced to numbers
|
||||
const res = await host.dispatch(req('trips.getById', { tripId: '1', asUserId: '42' }));
|
||||
// tripId as a string -> coerced to a number; acting user is the bound host arg
|
||||
const res = await host.dispatch(req('trips.getById', { tripId: '1' }), 42);
|
||||
expect(ok(res)).toBe(true);
|
||||
// a request with no params object at all -> BAD_PARAMS (sql missing), not a crash
|
||||
const noParams = await host.dispatch({ k: 'req', id: 'y', method: 'db.query', params: undefined });
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Author-signature verification (#plugins, #4). Ed25519 via node:crypto, in the
|
||||
* minisign shapes TREK accepts: bare raw key+sig, minisign legacy ('Ed', signs
|
||||
* the file), and minisign prehashed ('ED', signs BLAKE2b-512 of the file).
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import crypto from 'node:crypto';
|
||||
import { verifyAuthorSignature, SignatureError } from '../../../src/nest/plugins/install/verify-signature';
|
||||
|
||||
// A raw Ed25519 keypair, exported as the 32-byte raw public key + a signer.
|
||||
function makeKeypair() {
|
||||
const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
|
||||
const rawPub = publicKey.export({ format: 'der', type: 'spki' }).subarray(-32); // last 32 bytes = the key
|
||||
return {
|
||||
rawPub,
|
||||
sign: (msg: Buffer) => crypto.sign(null, msg, privateKey),
|
||||
};
|
||||
}
|
||||
|
||||
const KEY_ID = Buffer.from('0011223344556677', 'hex');
|
||||
const b64 = (b: Buffer) => b.toString('base64');
|
||||
|
||||
describe('verifyAuthorSignature', () => {
|
||||
const bytes = Buffer.from('the exact plugin.zip bytes');
|
||||
|
||||
it('accepts a bare raw Ed25519 key + 64-byte signature over the file', () => {
|
||||
const { rawPub, sign } = makeKeypair();
|
||||
expect(verifyAuthorSignature(bytes, b64(sign(bytes)), b64(rawPub))).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a valid signature from a different key', () => {
|
||||
const a = makeKeypair();
|
||||
const b = makeKeypair();
|
||||
expect(verifyAuthorSignature(bytes, b64(a.sign(bytes)), b64(b.rawPub))).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a signature over tampered bytes', () => {
|
||||
const { rawPub, sign } = makeKeypair();
|
||||
const sig = b64(sign(bytes));
|
||||
expect(verifyAuthorSignature(Buffer.from('tampered'), sig, b64(rawPub))).toBe(false);
|
||||
});
|
||||
|
||||
it('verifies the minisign legacy format (Ed — signs the raw file)', () => {
|
||||
const { rawPub, sign } = makeKeypair();
|
||||
const pub = b64(Buffer.concat([Buffer.from('Ed'), KEY_ID, rawPub]));
|
||||
const sig = b64(Buffer.concat([Buffer.from('Ed'), KEY_ID, sign(bytes)]));
|
||||
expect(verifyAuthorSignature(bytes, sig, pub)).toBe(true);
|
||||
});
|
||||
|
||||
it('verifies the minisign prehashed format (ED — signs BLAKE2b-512 of the file)', () => {
|
||||
const { rawPub, sign } = makeKeypair();
|
||||
const hash = crypto.createHash('blake2b512').update(bytes).digest();
|
||||
const pub = b64(Buffer.concat([Buffer.from('Ed'), KEY_ID, rawPub]));
|
||||
const sig = b64(Buffer.concat([Buffer.from('ED'), KEY_ID, sign(hash)]));
|
||||
expect(verifyAuthorSignature(bytes, sig, pub)).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects when the key ids in key and signature disagree', () => {
|
||||
const { rawPub, sign } = makeKeypair();
|
||||
const pub = b64(Buffer.concat([Buffer.from('Ed'), KEY_ID, rawPub]));
|
||||
const otherId = Buffer.from('8899aabbccddeeff', 'hex');
|
||||
const sig = b64(Buffer.concat([Buffer.from('Ed'), otherId, sign(bytes)]));
|
||||
expect(verifyAuthorSignature(bytes, sig, pub)).toBe(false);
|
||||
});
|
||||
|
||||
it('parses a two-line minisign key (comment + base64)', () => {
|
||||
const { rawPub, sign } = makeKeypair();
|
||||
const pub = `untrusted comment: minisign public key ABC\n${b64(Buffer.concat([Buffer.from('Ed'), KEY_ID, rawPub]))}`;
|
||||
const sig = `untrusted comment: signature\n${b64(Buffer.concat([Buffer.from('Ed'), KEY_ID, sign(bytes)]))}`;
|
||||
expect(verifyAuthorSignature(bytes, sig, pub)).toBe(true);
|
||||
});
|
||||
|
||||
it('throws SignatureError on a malformed key', () => {
|
||||
expect(() => verifyAuthorSignature(bytes, b64(Buffer.alloc(64)), b64(Buffer.alloc(7)))).toThrow(SignatureError);
|
||||
});
|
||||
|
||||
it('throws SignatureError on a malformed signature', () => {
|
||||
const { rawPub } = makeKeypair();
|
||||
expect(() => verifyAuthorSignature(bytes, b64(Buffer.alloc(10)), b64(rawPub))).toThrow(SignatureError);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user