mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-01 17:03:15 +00:00
feat(plugins): activation, HTTP route proxy + instance settings (M2)
Wires the isolated runtime into TREK. Admins can now activate a plugin from the panel and its HTTP routes work end to end, still behind the kill switch. - PluginRuntimeService owns the supervisor: activate spawns the child with its granted permissions + decrypted instance config, deactivate kills it, status and errors are persisted to the plugins / plugin_error_log tables, and active plugins are booted on startup (OnModuleInit). - Bidirectional RPC: the child now handles host→child invokes (routes/jobs) and reports its declared routes on load; the supervisor gained invoke()/routesOf(). - /api/plugins/:id/* proxy controller — a single static route that matches the plugin's declared routes, enforces per-route auth (auth:false routes are public for OAuth callbacks/webhooks), forwards only a whitelisted request view (never the session cookie), and strips unsafe response headers. - Admin endpoints: POST :id/activate, POST :id/deactivate, GET/PUT :id/config — instance settings with secret fields encrypted (apiKeyCrypto) and masked. - Kill switch moved to its own module so it never collides with test config mocks. Photo/calendar hook consumers are deferred to a later slice.
This commit is contained in:
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* The plugin HTTP proxy (#plugins, M2): route matching, per-route auth (auth:false
|
||||
* routes are public), the whitelisted request view forwarded to the child, and
|
||||
* error/404 handling — all without a real fork (the runtime is faked).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { pluginsEnabledMock, extractTokenMock, verifyMock } = vi.hoisted(() => ({
|
||||
pluginsEnabledMock: vi.fn(() => true),
|
||||
extractTokenMock: vi.fn(() => 'tok'),
|
||||
verifyMock: vi.fn(() => ({ id: 5, username: 'ada', is_admin: false })),
|
||||
}));
|
||||
vi.mock('../../../src/nest/plugins/kill-switch', () => ({ pluginsEnabled: pluginsEnabledMock }));
|
||||
vi.mock('../../../src/middleware/auth', () => ({ extractToken: extractTokenMock, verifyJwtAndLoadUser: verifyMock }));
|
||||
|
||||
import { PluginsProxyController } from '../../../src/nest/plugins/plugins-proxy.controller';
|
||||
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
|
||||
|
||||
function fakeRes() {
|
||||
const res = {
|
||||
statusCode: 0,
|
||||
headers: {} as Record<string, string>,
|
||||
body: undefined as unknown,
|
||||
status(c: number) { res.statusCode = c; return res; },
|
||||
setHeader(k: string, v: string) { res.headers[k] = v; },
|
||||
json(b: unknown) { res.body = b; return res; },
|
||||
send(b: unknown) { res.body = b; return res; },
|
||||
};
|
||||
return res;
|
||||
}
|
||||
function fakeReq(method: string, sub: string, extra: Record<string, unknown> = {}) {
|
||||
return { method, params: { 0: sub.replace(/^\//, '') }, query: {}, body: null, ...extra } as never;
|
||||
}
|
||||
|
||||
function makeRuntime(over: Partial<PluginRuntimeService> = {}): PluginRuntimeService {
|
||||
return {
|
||||
isActive: vi.fn(() => true),
|
||||
routesOf: vi.fn(() => [{ i: 0, method: 'GET', path: '/status', auth: true }]),
|
||||
invoke: vi.fn(async () => ({ status: 200, headers: { 'content-type': 'application/json' }, body: '{"ok":true}' })),
|
||||
...over,
|
||||
} as unknown as PluginRuntimeService;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
pluginsEnabledMock.mockClear().mockReturnValue(true);
|
||||
verifyMock.mockClear().mockReturnValue({ id: 5, username: 'ada', is_admin: false });
|
||||
extractTokenMock.mockClear().mockReturnValue('tok');
|
||||
});
|
||||
|
||||
describe('PluginsProxyController', () => {
|
||||
it('404 when the runtime is disabled', async () => {
|
||||
pluginsEnabledMock.mockReturnValue(false);
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(makeRuntime()).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('404 when the plugin is not active', async () => {
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(makeRuntime({ isActive: vi.fn(() => false) } as never)).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('404 when no declared route matches', async () => {
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(makeRuntime()).proxy('p', fakeReq('GET', '/nope'), res as never);
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('401 on an auth route without a valid session', async () => {
|
||||
verifyMock.mockReturnValue(null as never);
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(makeRuntime()).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it('forwards an authenticated request and returns the child response', async () => {
|
||||
const runtime = makeRuntime();
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(runtime).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
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
|
||||
expect(runtime.invoke).toHaveBeenCalledWith('p', 'invoke.route', expect.objectContaining({
|
||||
routeId: 0,
|
||||
req: expect.objectContaining({ user: { id: 5, username: 'ada', isAdmin: false } }),
|
||||
}));
|
||||
});
|
||||
|
||||
it('a public (auth:false) route skips the session check', async () => {
|
||||
const runtime = makeRuntime({ routesOf: vi.fn(() => [{ i: 1, method: 'POST', path: '/webhook', auth: false }]) } as never);
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(runtime).proxy('p', fakeReq('POST', '/webhook'), res as never);
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(extractTokenMock).not.toHaveBeenCalled();
|
||||
expect(runtime.invoke).toHaveBeenCalledWith('p', 'invoke.route', expect.objectContaining({
|
||||
req: expect.objectContaining({ user: null }),
|
||||
}));
|
||||
});
|
||||
|
||||
it('strips unsafe response headers from the child', async () => {
|
||||
const runtime = makeRuntime({
|
||||
invoke: vi.fn(async () => ({ status: 200, headers: { 'content-type': 'text/plain', 'set-cookie': 'evil=1' }, body: 'ok' })),
|
||||
} as never);
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(runtime).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
expect(res.headers['content-type']).toBe('text/plain');
|
||||
expect(res.headers['set-cookie']).toBeUndefined(); // a plugin cannot set cookies
|
||||
});
|
||||
|
||||
it('502 when the plugin invoke throws', async () => {
|
||||
const runtime = makeRuntime({ invoke: vi.fn(async () => { throw new Error('down'); }) } as never);
|
||||
const res = fakeRes();
|
||||
await new PluginsProxyController(runtime).proxy('p', fakeReq('GET', '/status'), res as never);
|
||||
expect(res.statusCode).toBe(502);
|
||||
});
|
||||
});
|
||||
@@ -9,7 +9,9 @@ const { testDb } = vi.hoisted(() => {
|
||||
const db = new Database(':memory:');
|
||||
db.exec(`CREATE TABLE plugins (
|
||||
id TEXT PRIMARY KEY, name TEXT, description TEXT, type TEXT, icon TEXT, version TEXT,
|
||||
status TEXT, reviewed_at TEXT, source_repo TEXT, sort_order INTEGER DEFAULT 0)`);
|
||||
status TEXT, reviewed_at TEXT, source_repo TEXT, config TEXT DEFAULT '{}', updated_at TEXT,
|
||||
sort_order INTEGER DEFAULT 0);
|
||||
CREATE TABLE plugin_settings_fields (plugin_id TEXT, field_key TEXT, scope TEXT, secret INTEGER);`);
|
||||
return { testDb: db };
|
||||
});
|
||||
vi.mock('../../../src/db/database', () => ({ db: testDb }));
|
||||
@@ -19,6 +21,7 @@ import { PluginsController } from '../../../src/nest/plugins/plugins.controller'
|
||||
|
||||
beforeEach(() => {
|
||||
testDb.exec('DELETE FROM plugins');
|
||||
testDb.exec('DELETE FROM plugin_settings_fields');
|
||||
delete process.env.TREK_PLUGINS_ENABLED;
|
||||
});
|
||||
afterEach(() => {
|
||||
@@ -46,8 +49,82 @@ describe('PluginsService.list', () => {
|
||||
|
||||
it('controller delegates to the service', () => {
|
||||
const svc = { list: vi.fn(() => ({ enabled: false, plugins: [] })) } as unknown as PluginsService;
|
||||
const res = new PluginsController(svc).list();
|
||||
const runtime = {} as unknown as import('../../../src/nest/plugins/plugin-runtime.service').PluginRuntimeService;
|
||||
const res = new PluginsController(svc, runtime).list();
|
||||
expect(svc.list).toHaveBeenCalled();
|
||||
expect(res).toEqual({ enabled: false, plugins: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('PluginsController M2 endpoints', () => {
|
||||
const svc = {
|
||||
getInstanceConfig: vi.fn(() => ({ a: 1 })),
|
||||
updateInstanceConfig: vi.fn(() => ({ a: 2 })),
|
||||
} as unknown as PluginsService;
|
||||
|
||||
beforeEach(() => {
|
||||
(svc.getInstanceConfig as ReturnType<typeof vi.fn>).mockClear();
|
||||
(svc.updateInstanceConfig as ReturnType<typeof vi.fn>).mockClear();
|
||||
process.env.TREK_PLUGINS_ENABLED = 'true';
|
||||
});
|
||||
|
||||
it('get/update config delegate to the service', () => {
|
||||
const rt = { activate: vi.fn(), deactivate: vi.fn(), isActive: vi.fn() } as never;
|
||||
const c = new PluginsController(svc, rt);
|
||||
expect(c.getConfig('x')).toEqual({ config: { a: 1 } });
|
||||
expect(c.updateConfig('x', { a: 2 })).toEqual({ config: { a: 2 } });
|
||||
});
|
||||
|
||||
it('activate spawns via the runtime when enabled', async () => {
|
||||
const rt = { activate: vi.fn(async () => {}), isActive: vi.fn(() => true) } as never;
|
||||
const out = await new PluginsController(svc, rt).activate('x');
|
||||
expect(out).toEqual({ status: 'active' });
|
||||
});
|
||||
|
||||
it('activate is 503 when the runtime is disabled', async () => {
|
||||
process.env.TREK_PLUGINS_ENABLED = 'false';
|
||||
const rt = { activate: vi.fn(), isActive: vi.fn() } as never;
|
||||
await expect(new PluginsController(svc, rt).activate('x')).rejects.toMatchObject({ status: 503 });
|
||||
});
|
||||
|
||||
it('activate surfaces an activation error as 400', async () => {
|
||||
const rt = { activate: vi.fn(async () => { throw new Error('bad code'); }), isActive: vi.fn(() => false) } as never;
|
||||
await expect(new PluginsController(svc, rt).activate('x')).rejects.toMatchObject({ status: 400 });
|
||||
});
|
||||
|
||||
it('deactivate stops the plugin', async () => {
|
||||
const rt = { deactivate: vi.fn(async () => {}) } as never;
|
||||
expect(await new PluginsController(svc, rt).deactivate('x')).toEqual({ status: 'inactive' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('PluginsService instance config', () => {
|
||||
it('encrypts secret fields on write and masks them on read; keeps plaintext for non-secrets', () => {
|
||||
testDb.prepare("INSERT INTO plugins (id, name, status, config) VALUES ('x','X','inactive','{}')").run();
|
||||
testDb.prepare("INSERT INTO plugin_settings_fields (plugin_id, field_key, scope, secret) VALUES ('x','api_key','instance',1)").run();
|
||||
|
||||
const svc = new PluginsService();
|
||||
const masked = svc.updateInstanceConfig('x', { api_key: 'super-secret', server: 'https://h' });
|
||||
// client gets the masked view
|
||||
expect(masked.api_key).toBe('••••••••');
|
||||
expect(masked.server).toBe('https://h');
|
||||
|
||||
// stored value is encrypted, not plaintext
|
||||
const stored = JSON.parse((testDb.prepare("SELECT config FROM plugins WHERE id='x'").get() as { config: string }).config);
|
||||
expect(stored.api_key).not.toBe('super-secret');
|
||||
expect(String(stored.api_key)).toMatch(/^enc:/);
|
||||
expect(stored.server).toBe('https://h');
|
||||
|
||||
// an unchanged mask does not overwrite the stored secret
|
||||
svc.updateInstanceConfig('x', { api_key: '••••••••' });
|
||||
const still = JSON.parse((testDb.prepare("SELECT config FROM plugins WHERE id='x'").get() as { config: string }).config);
|
||||
expect(still.api_key).toBe(stored.api_key);
|
||||
|
||||
expect(svc.getInstanceConfig('x').api_key).toBe('••••••••');
|
||||
});
|
||||
|
||||
it('throws for an unknown plugin', () => {
|
||||
expect(() => new PluginsService().updateInstanceConfig('nope', {})).toThrow(/not found/);
|
||||
expect(() => new PluginsService().getInstanceConfig('nope')).toThrow(/not found/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -151,4 +151,24 @@ describe('PluginRpcHost — capability enforcement', () => {
|
||||
expect((res as RpcError).error.code).toBe('HOST_ERROR');
|
||||
expect((res as RpcError).error.message).toBe('disk gone');
|
||||
});
|
||||
|
||||
it('a non-Error thrown by a handler still maps to HOST_ERROR', async () => {
|
||||
(deps.data.query as ReturnType<typeof vi.fn>).mockImplementation(() => {
|
||||
throw 'raw string';
|
||||
});
|
||||
const host = new PluginRpcHost('p', new Set(['db:own']), deps);
|
||||
const res = await host.dispatch(req('db.query', { sql: 'SELECT 1' }));
|
||||
expect((res as RpcError).error.code).toBe('HOST_ERROR');
|
||||
expect((res as RpcError).error.message).toBe('internal error');
|
||||
});
|
||||
|
||||
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' }));
|
||||
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 });
|
||||
expect((noParams as RpcError).error.code).toBe('BAD_PARAMS');
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user