-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathplugins.test.js
More file actions
325 lines (296 loc) · 12.4 KB
/
Copy pathplugins.test.js
File metadata and controls
325 lines (296 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/**
* Plugin loader (#206) — createServer({ plugins }) end to end.
*
* A fixture plugin (written to disk per test run, in the #206 activate(api)
* shape both real consumers — Tideholm and bridge — already export) is
* loaded from config and verified against the whole api surface: HTTP
* routes under a WAC-exempt prefix (#582), auth.getAgent (#584), a
* WebSocket endpoint through ws.route (#588), private storage under the
* data root's dot-guard, config pass-through, and deactivate on close.
* Failure paths (missing module, no activate export, bad prefix) must fail
* listen() loudly rather than boot a server silently missing an app.
*/
import { describe, it, before, after, afterEach } from 'node:test';
import assert from 'node:assert';
import path from 'path';
import { WebSocket } from 'ws';
import fs from 'fs-extra';
import { createServer } from '../src/server.js';
import { pluginId } from '../src/plugins.js';
const TEST_DATA_DIR = './test-data-plugins';
const FIXTURE_DIR = './test-fixtures-plugins';
let server;
let baseUrl;
let originalDataRoot;
// The fixture records activation evidence into this file so tests can
// assert on what the plugin saw (config, prefix, storage dir, deactivate).
const EVIDENCE = path.resolve(FIXTURE_DIR, 'evidence.json');
const FIXTURE_PLUGIN = `
import fs from 'fs';
export async function activate(api) {
const dir = api.storage.pluginDir();
const evidence = {
prefix: api.prefix,
config: api.config,
pluginDir: dir,
hasGetAgent: typeof api.auth.getAgent === 'function',
deactivated: false,
};
const record = () =>
fs.writeFileSync(${JSON.stringify(EVIDENCE)}, JSON.stringify(evidence));
record();
api.fastify.all(api.prefix + '/echo', async (request, reply) => {
const agent = await api.auth.getAgent(request);
reply.code(200).send({ app: true, method: request.method, agent });
});
await api.ws.route(api.prefix + '/ws', (socket) => {
socket.on('message', (data) => socket.send('pong:' + String(data)));
});
await api.ws.route(api.prefix + '/ws-throw', () => {
throw new Error('plugin bug');
});
return {
deactivate() {
evidence.deactivated = true;
record();
},
};
}
`;
async function startWith(plugins) {
await fs.emptyDir(TEST_DATA_DIR);
server = createServer({
logger: false,
forceCloseConnections: true,
root: TEST_DATA_DIR,
plugins,
});
await server.listen({ port: 0, host: '127.0.0.1' });
const address = server.server.address();
baseUrl = `http://127.0.0.1:${address.port}`;
}
function evidence() {
return JSON.parse(fs.readFileSync(EVIDENCE, 'utf8'));
}
describe('plugin loader (#206)', () => {
before(async () => {
originalDataRoot = process.env.DATA_ROOT;
await fs.emptyDir(FIXTURE_DIR);
await fs.writeFile(path.join(FIXTURE_DIR, 'fixture-plugin.js'), FIXTURE_PLUGIN);
});
afterEach(async () => {
if (server) {
await server.close();
server = null;
}
await fs.remove(TEST_DATA_DIR);
});
after(async () => {
await fs.remove(FIXTURE_DIR);
if (originalDataRoot === undefined) delete process.env.DATA_ROOT;
else process.env.DATA_ROOT = originalDataRoot;
});
it('loads a plugin from config and serves its routes under a WAC-exempt prefix', async () => {
await startWith([
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/game', config: { bots: 3 } },
]);
// Unauthenticated POST reaches the app: the prefix joined appPaths.
const res = await fetch(`${baseUrl}/game/echo`, { method: 'POST' });
assert.strictEqual(res.status, 200);
const body = await res.json();
assert.strictEqual(body.app, true);
assert.strictEqual(body.method, 'POST');
assert.strictEqual(body.agent, null); // getAgent callable, anon -> null
});
it('passes prefix and config through to activate()', async () => {
await startWith([
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/game/', config: { bots: 3 } },
]);
const seen = evidence();
assert.strictEqual(seen.prefix, '/game'); // trailing slash normalized
assert.deepStrictEqual(seen.config, { bots: 3 });
assert.strictEqual(seen.hasGetAgent, true);
});
it('ws.route serves a WebSocket endpoint under the prefix', async () => {
await startWith([
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/game' },
]);
const ws = new WebSocket(`${baseUrl.replace('http', 'ws')}/game/ws`);
await new Promise((resolve, reject) => {
ws.on('open', resolve);
ws.on('error', reject);
});
const reply = await new Promise((resolve, reject) => {
ws.on('message', (data) => resolve(String(data)));
ws.on('error', reject);
ws.send('hello');
});
assert.strictEqual(reply, 'pong:hello');
ws.close();
});
it('pluginDir is created under the data root and shielded from LDP', async () => {
await startWith([
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/game' },
]);
const seen = evidence();
assert.ok(seen.pluginDir.includes(path.join('.plugins', 'fixture-plugin')));
assert.ok(fs.existsSync(seen.pluginDir));
// Write a secret; the dot-guard must keep it unreachable over HTTP.
await fs.writeFile(path.join(seen.pluginDir, 'secret.txt'), 'hush');
const res = await fetch(`${baseUrl}/.plugins/fixture-plugin/secret.txt`);
assert.notStrictEqual(res.status, 200);
});
it('deactivate() runs on server close', async () => {
await startWith([
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/game' },
]);
assert.strictEqual(evidence().deactivated, false);
await server.close();
server = null;
assert.strictEqual(evidence().deactivated, true);
});
it('sibling LDP paths keep full WAC enforcement', async () => {
await startWith([
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/game' },
]);
const res = await fetch(`${baseUrl}/somepod/private/thing`, { method: 'PUT', body: 'x' });
assert.ok([401, 403].includes(res.status), `expected WAC rejection, got ${res.status}`);
});
it('a plugin mounted at a dot prefix stays reachable (dotfile guard defers to the mount)', async () => {
// The webrtc plugin replaces core's wss://pod/.webrtc at the same URL,
// so a dot prefix must reach the app — HTTP and ws.route alike — while
// unrelated dotfiles keep the 403 guard.
await startWith([
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/.myapp' },
]);
const res = await fetch(`${baseUrl}/.myapp/echo`, { method: 'POST' });
assert.strictEqual(res.status, 200);
assert.strictEqual((await res.json()).app, true);
const ws = new WebSocket(`${baseUrl.replace('http', 'ws')}/.myapp/ws`);
await new Promise((resolve, reject) => {
ws.on('open', resolve);
ws.on('error', reject);
});
const reply = await new Promise((resolve, reject) => {
ws.on('message', (data) => resolve(String(data)));
ws.on('error', reject);
ws.send('hello');
});
assert.strictEqual(reply, 'pong:hello');
ws.close();
const guarded = await fetch(`${baseUrl}/.env`);
assert.strictEqual(guarded.status, 403);
});
it('a plugin that cannot be imported fails listen() loudly', async () => {
await fs.emptyDir(TEST_DATA_DIR);
server = createServer({
logger: false,
forceCloseConnections: true,
root: TEST_DATA_DIR,
plugins: [{ module: `${FIXTURE_DIR}/no-such-plugin.js`, prefix: '/x' }],
});
await assert.rejects(
server.listen({ port: 0, host: '127.0.0.1' }),
/cannot import/,
);
});
it('a throwing ws handler closes that socket but not the server', async () => {
await startWith([
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/game' },
]);
const ws = new WebSocket(`${baseUrl.replace('http', 'ws')}/game/ws-throw`);
await new Promise((resolve) => {
ws.on('close', resolve);
ws.on('error', resolve);
});
// The host survives its plugin's bug.
const res = await fetch(`${baseUrl}/game/echo`);
assert.strictEqual(res.status, 200);
});
it('derives collision-resistant ids and rejects duplicates', async () => {
// Bare specifiers keep their full path; file paths use the basename.
assert.strictEqual(pluginId({ module: '@scope1/pkg/plugin.js' }), 'scope1-pkg-plugin');
assert.strictEqual(pluginId({ module: '@scope2/pkg/plugin.js' }), 'scope2-pkg-plugin');
assert.strictEqual(pluginId({ module: '/some/machine/path/foo.js' }), 'foo');
assert.strictEqual(pluginId({ module: './x.js', id: 'Custom Id!' }), 'custom-id');
// Two entries reducing to the same id fail the boot, not share a dir.
await fs.emptyDir(TEST_DATA_DIR);
server = createServer({
logger: false,
forceCloseConnections: true,
root: TEST_DATA_DIR,
plugins: [
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/a' },
{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/b' },
],
});
await assert.rejects(
server.listen({ port: 0, host: '127.0.0.1' }),
/duplicate id/,
);
});
it('a generic basename (plugin.js/index.js) derives the parent dir, not "plugin" (#596)', async () => {
// The near-universal '<name>/plugin.js' convention: without this fallback
// every such file collides on the id 'plugin' (and 'index' for index.js).
assert.strictEqual(pluginId({ module: './relay/plugin.js' }), 'relay');
assert.strictEqual(pluginId({ module: '/abs/path/dashboard/plugin.js' }), 'dashboard');
assert.strictEqual(pluginId({ module: './chat/index.js' }), 'chat');
assert.strictEqual(pluginId({ module: './My-App/Plugin.mjs' }), 'my-app');
// A non-generic basename is unchanged (still the basename).
assert.strictEqual(pluginId({ module: './relay/relay.js' }), 'relay');
assert.strictEqual(pluginId({ module: '/some/machine/path/foo.js' }), 'foo');
// No usable parent → falls back to the basename; an explicit id still wins.
assert.strictEqual(pluginId({ module: './plugin.js' }), 'plugin');
assert.strictEqual(pluginId({ module: './relay/plugin.js', id: 'custom' }), 'custom');
// A parent directory whose own name ends in .js keeps it (only the FILE's
// extension is stripped, never the directory name) — so 'foo.js/' and
// 'foo/' don't both collapse to the same 'foo'.
assert.strictEqual(pluginId({ module: './foo.js/plugin.js' }), 'foo-js');
assert.strictEqual(pluginId({ module: './foo/plugin.js' }), 'foo');
});
it('two <name>/plugin.js files load together with no explicit ids (#596)', async () => {
// The exact case that failed before: the CLI '--plugin' form (which can't
// set an id) loading two conventionally-named plugins.
await fs.emptyDir(`${FIXTURE_DIR}/alpha`);
await fs.emptyDir(`${FIXTURE_DIR}/beta`);
await fs.writeFile(`${FIXTURE_DIR}/alpha/plugin.js`,
`export async function activate(api) { api.fastify.get('/alpha/ping', async () => ({ id: 'alpha' })); }`);
await fs.writeFile(`${FIXTURE_DIR}/beta/plugin.js`,
`export async function activate(api) { api.fastify.get('/beta/ping', async () => ({ id: 'beta' })); }`);
await fs.emptyDir(TEST_DATA_DIR);
server = createServer({
logger: false,
forceCloseConnections: true,
root: TEST_DATA_DIR,
plugins: [
{ module: `${FIXTURE_DIR}/alpha/plugin.js`, prefix: '/alpha' },
{ module: `${FIXTURE_DIR}/beta/plugin.js`, prefix: '/beta' },
],
});
// Boots (ids 'alpha' and 'beta', no collision) and both routes answer.
await server.listen({ port: 0, host: '127.0.0.1' });
const url = `http://127.0.0.1:${server.server.address().port}`;
assert.strictEqual((await (await fetch(`${url}/alpha/ping`)).json()).id, 'alpha');
assert.strictEqual((await (await fetch(`${url}/beta/ping`)).json()).id, 'beta');
});
it('an invalid prefix fails listen() loudly', async () => {
// Any provided prefix must validate — including falsy ones, which would
// otherwise mount the app without its WAC exemption.
for (const prefix of ['game', '', '/', 0, null]) {
await fs.emptyDir(TEST_DATA_DIR);
server = createServer({
logger: false,
forceCloseConnections: true,
root: TEST_DATA_DIR,
plugins: [{ module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix }],
});
await assert.rejects(
server.listen({ port: 0, host: '127.0.0.1' }),
/invalid prefix/,
`prefix ${JSON.stringify(prefix)} should be rejected`,
);
await server.close();
server = null;
}
});
});