Repository navigation
Expand file tree
/
Copy pathrouter-auth.test.mjs
More file actions
479 lines (435 loc) · 13.8 KB
/
Copy pathrouter-auth.test.mjs
File metadata and controls
479 lines (435 loc) · 13.8 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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import fs from 'node:fs';
import http from 'node:http';
import net from 'node:net';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import runtime from '../lib/runtime.js';
const {
RUNTIME_AUTH_HEADER,
RUNTIME_PORT_FIRST,
RUNTIME_PORT_LAST,
findAvailablePort,
startRuntime,
stopRuntime,
} = runtime;
const AUTH_TOKEN = 'test-runtime-auth-token';
const DESKTOP_DIR = path.resolve(
path.dirname( fileURLToPath( import.meta.url ) ),
'..'
);
function makeFixture() {
const wordpressDir = fs.mkdtempSync(
path.join( os.tmpdir(), 'cortext-router-auth-' )
);
fs.copyFileSync(
new URL( '../runtime/router.php', import.meta.url ),
path.join( wordpressDir, 'router.php' )
);
fs.copyFileSync(
new URL( '../runtime/bootstrap.php', import.meta.url ),
path.join( wordpressDir, 'cortext-runtime-bootstrap.php' )
);
fs.writeFileSync(
path.join( wordpressDir, 'index.php' ),
"<?php header( 'Content-Type: text/plain' ); echo 'dynamic';"
);
fs.writeFileSync( path.join( wordpressDir, 'static.txt' ), 'static' );
return wordpressDir;
}
function makeUnprotectedFixture() {
const wordpressDir = fs.mkdtempSync(
// PHP's -d parser treats an unquoted tilde as INI syntax. Windows CI
// commonly places temp files below RUNNER~1, so keep that case covered.
path.join( os.tmpdir(), 'cortext-router-legacy-RUNNER~1-' )
);
fs.writeFileSync(
path.join( wordpressDir, 'router.php' ),
"<?php header( 'Content-Type: text/plain' ); echo 'legacy';"
);
fs.writeFileSync( path.join( wordpressDir, 'index.php' ), 'legacy' );
fs.writeFileSync(
path.join( wordpressDir, 'wp-config.php' ),
"<?php if ( ! defined( 'WP_HOME' ) ) { define( 'WP_HOME', 'http://127.0.0.1:9402' ); } if ( ! defined( 'WP_SITEURL' ) ) { define( 'WP_SITEURL', 'http://127.0.0.1:9402' ); }"
);
fs.writeFileSync(
path.join( wordpressDir, 'origin.php' ),
"<?php require __DIR__ . '/wp-config.php'; header( 'Content-Type: text/plain' ); echo WP_HOME . \"\\n\" . WP_SITEURL;"
);
return wordpressDir;
}
// A throwaway port for fixture servers. Unlike the runtime allocator this is
// free to use the ephemeral range, since nothing here outlives the test.
async function reserveEphemeralPort() {
const server = net.createServer();
server.unref();
server.listen( 0, '127.0.0.1' );
await once( server, 'listening' );
const address = server.address();
assert.notEqual( address, null );
assert.equal( typeof address, 'object' );
const { port } = address;
server.close();
await once( server, 'close' );
return port;
}
function request( port, requestPath, authToken, requestOptions = {} ) {
return new Promise( ( resolve, reject ) => {
const headers = {};
if ( authToken !== undefined ) {
headers[ RUNTIME_AUTH_HEADER ] = authToken;
}
if ( requestOptions.host !== undefined ) {
headers.Host = requestOptions.host;
}
if ( requestOptions.origin !== undefined ) {
headers.Origin = requestOptions.origin;
}
const req = http.get(
{
host: '127.0.0.1',
port,
path: requestPath,
headers,
},
( response ) => {
let body = '';
response.setEncoding( 'utf8' );
response.on( 'data', ( chunk ) => {
body += chunk;
} );
response.on( 'end', () => {
resolve( {
statusCode: response.statusCode,
headers: response.headers,
body,
} );
} );
}
);
req.on( 'error', reject );
} );
}
async function waitForServer( child, port, stderr ) {
for ( let attempt = 0; attempt < 100; attempt++ ) {
if ( child.exitCode !== null ) {
throw new Error(
`PHP server exited before becoming ready: ${ stderr() }`
);
}
try {
await request( port, '/', undefined );
return;
} catch ( error ) {
if ( error.code !== 'ECONNREFUSED' ) {
throw error;
}
}
await new Promise( ( resolve ) => setTimeout( resolve, 25 ) );
}
throw new Error( `PHP server did not become ready: ${ stderr() }` );
}
async function startServer(
wordpressDir,
authToken,
{ configureEndpoint = true } = {}
) {
const port = await reserveEphemeralPort();
const env = { ...process.env };
if ( authToken === undefined ) {
delete env.CORTEXT_DESKTOP_AUTH_TOKEN;
} else {
env.CORTEXT_DESKTOP_AUTH_TOKEN = authToken;
}
if ( configureEndpoint ) {
env.CORTEXT_DESKTOP_RUNTIME_HOST = `127.0.0.1:${ port }`;
env.CORTEXT_DESKTOP_RUNTIME_ORIGIN = `http://127.0.0.1:${ port }`;
} else {
delete env.CORTEXT_DESKTOP_RUNTIME_HOST;
delete env.CORTEXT_DESKTOP_RUNTIME_ORIGIN;
}
const child = spawn(
'php',
[
'-S',
`127.0.0.1:${ port }`,
'-t',
wordpressDir,
path.join( wordpressDir, 'router.php' ),
],
{
cwd: wordpressDir,
env,
stdio: [ 'ignore', 'ignore', 'pipe' ],
}
);
let stderr = '';
child.stderr.setEncoding( 'utf8' );
child.stderr.on( 'data', ( chunk ) => {
stderr += chunk;
} );
try {
await waitForServer( child, port, () => stderr );
} catch ( error ) {
await stopServer( child );
fs.rmSync( wordpressDir, { recursive: true, force: true } );
throw error;
}
return { child, port };
}
async function stopServer( child ) {
if ( child.exitCode !== null || child.signalCode !== null ) {
return;
}
const exit = once( child, 'exit' );
child.kill( 'SIGTERM' );
await exit;
}
function registerCleanup( context, child, wordpressDir ) {
context.after( async () => {
await stopServer( child );
fs.rmSync( wordpressDir, { recursive: true, force: true } );
} );
}
test( 'startRuntime requires a non-empty auth token', () => {
const options = {
appDir: '/unused',
wordpressDir: '/unused',
};
assert.throws(
() => startRuntime( options ),
/startRuntime requires a non-empty authToken/
);
assert.throws(
() => startRuntime( { ...options, authToken: ' ' } ),
/startRuntime requires a non-empty authToken/
);
} );
test( 'startRuntime replaces an unprotected legacy router before listening', async ( context ) => {
const wordpressDir = makeUnprotectedFixture();
const port = await reserveEphemeralPort();
const handle = startRuntime( {
appDir: DESKTOP_DIR,
authToken: AUTH_TOKEN,
port,
runtime: 'php',
runtimeStateDir: path.join( wordpressDir, 'runtime-state' ),
wordpressDir,
} );
context.after( async () => {
await stopRuntime( handle );
fs.rmSync( wordpressDir, { recursive: true, force: true } );
} );
assert.match(
fs.readFileSync( path.join( wordpressDir, 'router.php' ), 'utf8' ),
/hash_equals/
);
await handle.ready;
assert.equal( handle.port, port );
assert.equal( handle.host, `127.0.0.1:${ port }` );
assert.equal( handle.origin, `http://127.0.0.1:${ port }` );
const unauthenticated = await request( port, '/', undefined );
assert.equal( unauthenticated.statusCode, 403 );
const authenticated = await request( port, '/', AUTH_TOKEN );
assert.equal( authenticated.statusCode, 200 );
assert.equal( authenticated.body, 'legacy' );
const migratedOrigin = await request( port, '/origin.php', AUTH_TOKEN, {
origin: handle.origin,
} );
assert.equal( migratedOrigin.statusCode, 200 );
assert.equal(
migratedOrigin.body,
`${ handle.origin }\n${ handle.origin }`
);
} );
test( 'findAvailablePort picks from the fixed band, not the ephemeral range', async () => {
const selected = await findAvailablePort();
assert.ok(
selected >= RUNTIME_PORT_FIRST && selected <= RUNTIME_PORT_LAST,
`expected a band port, got ${ selected }`
);
} );
test( 'findAvailablePort scans past an occupied band port', async ( context ) => {
const first = await findAvailablePort();
const blocker = net.createServer();
blocker.listen( first, '127.0.0.1' );
await once( blocker, 'listening' );
context.after(
() => new Promise( ( resolve ) => blocker.close( resolve ) )
);
const second = await findAvailablePort();
assert.ok(
second > first && second <= RUNTIME_PORT_LAST,
`expected a later band port than ${ first }, got ${ second }`
);
} );
test( 'findAvailablePort keeps an available preference over the band', async () => {
const outsideBand = await new Promise( ( resolve, reject ) => {
const probe = net.createServer();
probe.once( 'error', reject );
probe.listen( 0, '127.0.0.1', () => {
const { port } = probe.address();
probe.close( () => resolve( port ) );
} );
} );
assert.equal( await findAvailablePort( outsideBand ), outsideBand );
} );
test( 'startRuntime chooses a dynamic port when its preference is occupied', async ( context ) => {
const wordpressDir = makeUnprotectedFixture();
const blocker = net.createServer();
blocker.listen( 0, '127.0.0.1' );
await once( blocker, 'listening' );
const address = blocker.address();
assert.notEqual( address, null );
assert.equal( typeof address, 'object' );
const handle = startRuntime( {
appDir: DESKTOP_DIR,
authToken: AUTH_TOKEN,
port: address.port,
runtime: 'php',
runtimeStateDir: path.join( wordpressDir, 'runtime-state' ),
wordpressDir,
} );
context.after( async () => {
await stopRuntime( handle );
await new Promise( ( resolve ) => blocker.close( resolve ) );
fs.rmSync( wordpressDir, { recursive: true, force: true } );
} );
await handle.ready;
assert.notEqual( handle.port, address.port );
assert.ok(
handle.port >= RUNTIME_PORT_FIRST && handle.port <= RUNTIME_PORT_LAST,
`expected a band port, got ${ handle.port }`
);
assert.equal( handle.origin, `http://127.0.0.1:${ handle.port }` );
const authenticated = await request( handle.port, '/', AUTH_TOKEN, {
origin: handle.origin,
} );
assert.equal( authenticated.statusCode, 200 );
} );
test( 'startRuntime retries when its selected port is claimed before spawn', async ( context ) => {
const wordpressDir = makeUnprotectedFixture();
const blocker = net.createServer( ( socket ) => socket.destroy() );
blocker.listen( 0, '127.0.0.1' );
await once( blocker, 'listening' );
const blockedAddress = blocker.address();
assert.notEqual( blockedAddress, null );
assert.equal( typeof blockedAddress, 'object' );
const retryPort = await reserveEphemeralPort();
const preferredPort = await reserveEphemeralPort();
const allocatorCalls = [];
const handle = startRuntime( {
appDir: DESKTOP_DIR,
authToken: AUTH_TOKEN,
port: preferredPort,
portAllocator: async ( requestedPort ) => {
allocatorCalls.push( requestedPort );
return allocatorCalls.length === 1
? blockedAddress.port
: retryPort;
},
runtime: 'php',
runtimeStateDir: path.join( wordpressDir, 'runtime-state' ),
wordpressDir,
} );
context.after( async () => {
await stopRuntime( handle );
await new Promise( ( resolve ) => blocker.close( resolve ) );
fs.rmSync( wordpressDir, { recursive: true, force: true } );
} );
await handle.ready;
assert.deepEqual( allocatorCalls, [ preferredPort, undefined ] );
assert.equal( handle.port, retryPort );
const authenticated = await request( handle.port, '/', AUTH_TOKEN, {
origin: handle.origin,
} );
assert.equal( authenticated.statusCode, 200 );
} );
test( 'startRuntime fails before listening without its authenticated router', async () => {
const wordpressDir = makeUnprotectedFixture();
const port = await reserveEphemeralPort();
const appDir = fs.mkdtempSync(
path.join( os.tmpdir(), 'cortext-router-missing-app-' )
);
try {
assert.throws(
() =>
startRuntime( {
appDir,
authToken: AUTH_TOKEN,
port,
runtime: 'php',
runtimeStateDir: path.join( wordpressDir, 'runtime-state' ),
wordpressDir,
} ),
/Authenticated desktop router not found/
);
await assert.rejects( request( port, '/', undefined ), /ECONNREFUSED/ );
} finally {
fs.rmSync( appDir, { recursive: true, force: true } );
fs.rmSync( wordpressDir, { recursive: true, force: true } );
}
} );
test( 'router authenticates static and dynamic requests', async ( context ) => {
const wordpressDir = makeFixture();
const { child, port } = await startServer( wordpressDir, AUTH_TOKEN );
registerCleanup( context, child, wordpressDir );
for ( const requestPath of [ '/static.txt', '/dynamic' ] ) {
const missing = await request( port, requestPath, undefined );
assert.equal( missing.statusCode, 403 );
assert.equal( missing.headers[ 'cache-control' ], 'no-store' );
const wrong = await request( port, requestPath, 'wrong-token' );
assert.equal( wrong.statusCode, 403 );
const authenticated = await request( port, requestPath, AUTH_TOKEN );
assert.equal( authenticated.statusCode, 200 );
assert.equal(
authenticated.body,
requestPath === '/static.txt' ? 'static' : 'dynamic'
);
const authenticatedWithOrigin = await request(
port,
requestPath,
AUTH_TOKEN,
{ origin: `http://127.0.0.1:${ port }` }
);
assert.equal( authenticatedWithOrigin.statusCode, 200 );
for ( const requestOptions of [
{ host: `localhost:${ port }` },
{ host: `127.0.0.1:${ port + 1 }` },
{ origin: 'null' },
{ origin: 'https://example.com' },
] ) {
const rejected = await request(
port,
requestPath,
AUTH_TOKEN,
requestOptions
);
assert.equal( rejected.statusCode, 403 );
}
}
} );
test( 'router fails closed when its auth token is not configured', async ( context ) => {
const wordpressDir = makeFixture();
const { child, port } = await startServer( wordpressDir, undefined );
registerCleanup( context, child, wordpressDir );
for ( const requestPath of [ '/static.txt', '/dynamic' ] ) {
const missing = await request( port, requestPath, undefined );
assert.equal( missing.statusCode, 403 );
const supplied = await request( port, requestPath, AUTH_TOKEN );
assert.equal( supplied.statusCode, 403 );
}
} );
test( 'router fails closed without its expected runtime endpoint', async ( context ) => {
const wordpressDir = makeFixture();
const { child, port } = await startServer( wordpressDir, AUTH_TOKEN, {
configureEndpoint: false,
} );
registerCleanup( context, child, wordpressDir );
const response = await request( port, '/', AUTH_TOKEN );
assert.equal( response.statusCode, 403 );
} );