-
Notifications
You must be signed in to change notification settings - Fork 212
/
php.spec.ts
698 lines (650 loc) · 20.5 KB
/
php.spec.ts
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
import { getPHPLoaderModule, NodePHP } from '..';
import {
loadPHPRuntime,
SupportedPHPVersions,
__private__dont__use,
} from '@php-wasm/universal';
import { existsSync, rmSync, readFileSync } from 'fs';
const testDirPath = '/__test987654321';
const testFilePath = '/__test987654321.txt';
describe.each(SupportedPHPVersions)('PHP %s', (phpVersion) => {
let php: NodePHP;
beforeEach(async () => {
php = await NodePHP.load(phpVersion);
});
describe('Filesystem', () => {
// Unit tests for the filesystem methods of the
// PHP runtime.
it('writeFile() should create a file when it does not exist', () => {
php.writeFile(testFilePath, 'Hello World!');
expect(php.fileExists(testFilePath)).toEqual(true);
});
it('writeFile() should throw a useful error when parent directory does not exist', () => {
expect(() => {
php.writeFile('/a/b/c/d/e/f', 'Hello World!');
}).toThrowError(
'Could not write to "/a/b/c/d/e/f": There is no such file or directory OR the parent directory does not exist.'
);
});
it('writeFile() should throw a useful error when the specified path is a directory', () => {
php.mkdir('/dir');
expect(() => {
php.writeFile('/dir', 'Hello World!');
}).toThrowError(
new Error(
`Could not write to "/dir": There is a directory under that path.`
)
);
});
it('writeFile() should overwrite a file when it exists', () => {
php.writeFile(testFilePath, 'Hello World!');
php.writeFile(testFilePath, 'New contents');
expect(php.readFileAsText(testFilePath)).toEqual('New contents');
});
it('readFileAsText() should read a file as text', () => {
php.writeFile(testFilePath, 'Hello World!');
expect(php.readFileAsText(testFilePath)).toEqual('Hello World!');
});
it('readFileAsBuffer() should read a file as buffer', () => {
php.writeFile(testFilePath, 'Hello World!');
expect(php.readFileAsBuffer(testFilePath)).toEqual(
new TextEncoder().encode('Hello World!')
);
});
it('unlink() should delete a file', () => {
php.writeFile(testFilePath, 'Hello World!');
expect(php.fileExists(testFilePath)).toEqual(true);
php.unlink(testFilePath);
expect(php.fileExists(testFilePath)).toEqual(false);
});
it('mv() should move a file', () => {
php.mkdir(testDirPath);
const file1 = testDirPath + '/1.txt';
const file2 = testDirPath + '/2.txt';
php.writeFile(file1, '1');
php.mv(file1, file2);
expect(php.fileExists(file1)).toEqual(false);
expect(php.fileExists(file2)).toEqual(true);
expect(php.readFileAsText(file2)).toEqual('1');
});
it('mv() should replace target file if it exists', () => {
php.mkdir(testDirPath);
const file1 = testDirPath + '/1.txt';
const file2 = testDirPath + '/2.txt';
php.writeFile(file1, '1');
php.writeFile(file2, '2');
php.mv(file1, file2);
expect(php.fileExists(file1)).toEqual(false);
expect(php.fileExists(file2)).toEqual(true);
expect(php.readFileAsText(file2)).toEqual('1');
});
it('mv() should throw a useful error when source file does not exist', () => {
php.mkdir(testDirPath);
const file1 = testDirPath + '/1.txt';
const file2 = testDirPath + '/2.txt';
expect(() => {
php.mv(file1, file2);
}).toThrowError(
`Could not move "${testDirPath}/1.txt": There is no such file or directory OR the parent directory does not exist.`
);
});
it('mv() should throw a useful error when target directory does not exist', () => {
php.mkdir(testDirPath);
const file1 = testDirPath + '/1.txt';
const file2 = testDirPath + '/nowhere/2.txt';
php.writeFile(file1, '1');
expect(() => {
php.mv(file1, file2);
}).toThrowError(
`Could not move "${testDirPath}/1.txt": There is no such file or directory OR the parent directory does not exist.`
);
});
it('mkdir() should create a directory', () => {
php.mkdir(testDirPath);
expect(php.fileExists(testDirPath)).toEqual(true);
});
it('mkdir() should create all nested directories', () => {
php.mkdir(testDirPath + '/nested/doubly/triply');
expect(php.isDir(testDirPath + '/nested/doubly/triply')).toEqual(
true
);
});
it('unlink() should throw a useful error when parent directory does not exist', () => {
expect(() => {
php.unlink('/a/b/c/d/e/f');
}).toThrowError(
'Could not unlink "/a/b/c/d/e/f": There is no such file or directory OR the parent directory does not exist.'
);
});
it('isDir() should correctly distinguish between a file and a directory', () => {
php.mkdir(testDirPath);
expect(php.fileExists(testDirPath)).toEqual(true);
expect(php.isDir(testDirPath)).toEqual(true);
php.writeFile(testFilePath, 'Hello World!');
expect(php.fileExists(testFilePath)).toEqual(true);
expect(php.isDir(testFilePath)).toEqual(false);
});
it('listFiles() should return a list of files in a directory', () => {
php.mkdir(testDirPath);
php.writeFile(testDirPath + '/test.txt', 'Hello World!');
php.writeFile(testDirPath + '/test2.txt', 'Hello World!');
expect(php.listFiles(testDirPath)).toEqual([
'test.txt',
'test2.txt',
]);
});
it('listFiles() option prependPath should prepend given path to all files returned', () => {
php.mkdir(testDirPath);
php.writeFile(testDirPath + '/test.txt', 'Hello World!');
php.writeFile(testDirPath + '/test2.txt', 'Hello World!');
expect(php.listFiles(testDirPath, { prependPath: true })).toEqual([
testDirPath + '/test.txt',
testDirPath + '/test2.txt',
]);
});
});
describe('Stdio', () => {
it('should output strings (1)', async () => {
expect(
await php.run({ code: '<?php echo "Hello world!";' })
).toEqual({
headers: expect.any(Object),
httpStatusCode: 200,
bytes: new TextEncoder().encode('Hello world!'),
errors: '',
exitCode: 0,
});
});
it('should output strings (2) ', async () => {
expect(
await php.run({ code: '<?php echo "Hello world!\nI am PHP";' })
).toEqual({
headers: expect.any(Object),
httpStatusCode: 200,
bytes: new TextEncoder().encode('Hello world!\nI am PHP'),
errors: '',
exitCode: 0,
});
});
it('should output bytes ', async () => {
const results = await php.run({
code: '<?php echo chr(1).chr(0).chr(1).chr(0).chr(2); ',
});
expect(results).toEqual({
headers: expect.any(Object),
httpStatusCode: 200,
bytes: new Uint8Array([1, 0, 1, 0, 2]),
errors: '',
exitCode: 0,
});
});
it('should output strings when .run() is called twice', async () => {
expect(
await php.run({ code: '<?php echo "Hello world!";' })
).toEqual({
headers: expect.any(Object),
httpStatusCode: 200,
bytes: new TextEncoder().encode('Hello world!'),
errors: '',
exitCode: 0,
});
expect(
await php.run({ code: '<?php echo "Ehlo world!";' })
).toEqual({
headers: expect.any(Object),
httpStatusCode: 200,
bytes: new TextEncoder().encode('Ehlo world!'),
errors: '',
exitCode: 0,
});
});
it('should capture error data from stderr', async () => {
const code = `<?php
$stdErr = fopen('php://stderr', 'w');
fwrite($stdErr, "Hello from stderr!");
`;
expect(await php.run({ code })).toEqual({
headers: expect.any(Object),
httpStatusCode: 200,
bytes: new TextEncoder().encode(''),
errors: 'Hello from stderr!',
exitCode: 0,
});
});
it('should provide response text through .text', async () => {
const code = `<?php
echo "Hello world!";
`;
const response = await php.run({ code });
expect(response.text).toEqual('Hello world!');
});
it('should provide response JSON through .json', async () => {
const code = `<?php
echo json_encode(["hello" => "world"]);
`;
const response = await php.run({ code });
expect(response.json).toEqual({ hello: 'world' });
});
});
describe('Startup sequence – basics', () => {
/**
* This test ensures that the PHP runtime can be loaded twice.
*
* It protects from a regression that happened in the past
* after making the Emscripten module's main function the
* default export. Turns out, the generated Emscripten code
* replaces the default export with an instantiated module upon
* the first call.
*/
it('Should spawn two PHP runtimes', async () => {
const phpLoaderModule1 = await getPHPLoaderModule(phpVersion);
const runtimeId1 = await loadPHPRuntime(phpLoaderModule1);
const phpLoaderModule2 = await getPHPLoaderModule(phpVersion);
const runtimeId2 = await loadPHPRuntime(phpLoaderModule2);
expect(runtimeId1).not.toEqual(runtimeId2);
});
});
describe('Startup sequence', () => {
const testScriptPath = '/test.php';
afterEach(() => {
if (existsSync(testScriptPath)) {
rmSync(testScriptPath);
}
});
/**
* Issue https://github.com/WordPress/wordpress-playground/issues/169
*/
it('Should work with long POST body', () => {
php.writeFile(testScriptPath, '<?php echo "Hello world!"; ?>');
const body =
readFileSync(
new URL('./test-data/long-post-body.txt', import.meta.url)
.pathname,
'utf8'
) + '';
// 0x4000 is SAPI_POST_BLOCK_SIZE
expect(body.length).toBeGreaterThan(0x4000);
expect(async () => {
await php.run({
code: 'echo "A";',
relativeUri: '/test.php?a=b',
body,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
}).not.toThrowError();
});
it('Should run a script when no code snippet is provided', async () => {
php.writeFile(testScriptPath, '<?php echo "Hello world!"; ?>');
const response = await php.run({
scriptPath: testScriptPath,
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(bodyText).toEqual('Hello world!');
});
it('Should run a code snippet when provided, even if scriptPath is set', async () => {
php.writeFile(testScriptPath, '<?php echo "Hello world!"; ?>');
const response = await php.run({
scriptPath: testScriptPath,
code: '<?php echo "Hello from a code snippet!";',
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(bodyText).toEqual('Hello from a code snippet!');
});
it('Should have access to raw request data via the php://input stream', async () => {
const response = await php.run({
method: 'POST',
body: '{"foo": "bar"}',
code: `<?php echo file_get_contents('php://input');`,
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(bodyText).toEqual('{"foo": "bar"}');
});
it('Should expose urlencoded POST data in $_POST', async () => {
const response = await php.run({
code: `<?php echo json_encode($_POST);`,
method: 'POST',
body: 'foo=bar',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(bodyText).toEqual('{"foo":"bar"}');
});
it('Should expose urlencoded POST arrays in $_POST', async () => {
const response = await php.run({
code: `<?php echo json_encode($_POST);`,
method: 'POST',
body: 'foo[]=bar1&foo[]=bar2&indexed[key]=value',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(bodyText).toEqual(
'{"foo":["bar1","bar2"],"indexed":{"key":"value"}}'
);
});
it('Should expose multipart POST data in $_POST', async () => {
const response = await php.run({
code: `<?php echo json_encode($_POST);`,
method: 'POST',
body: `--boundary
Content-Disposition: form-data; name="foo"
bar`,
headers: {
'Content-Type': 'multipart/form-data; boundary=boundary',
},
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(bodyText).toEqual('{"foo":"bar"}');
});
it('Should expose multipart POST files in $_FILES', async () => {
const response = await php.run({
code: `<?php echo json_encode(array(
"files" => $_FILES,
"is_uploaded" => is_uploaded_file($_FILES["myFile"]["tmp_name"])
));`,
method: 'POST',
body: `--boundary
Content-Disposition: form-data; name="myFile"; filename="text.txt"
Content-Type: text/plain
bar
--boundary--`,
headers: {
'Content-Type': 'multipart/form-data; boundary=boundary',
},
});
const bodyText = new TextDecoder().decode(response.bytes);
const expectedResult = {
files: {
myFile: {
name: 'text.txt',
type: 'text/plain',
tmp_name: expect.any(String),
error: 0,
size: 3,
},
},
is_uploaded: true,
};
if (Number(phpVersion) > 8) {
(expectedResult.files.myFile as any).full_path = 'text.txt';
}
expect(JSON.parse(bodyText)).toEqual(expectedResult);
});
it('Should expose uploaded files in $_FILES', async () => {
const response = await php.run({
code: `<?php echo json_encode(array(
"files" => $_FILES,
"is_uploaded" => is_uploaded_file($_FILES["myFile"]["tmp_name"])
));`,
method: 'POST',
fileInfos: [
{
name: 'text.txt',
key: 'myFile',
data: new TextEncoder().encode('bar'),
type: 'text/plain',
},
],
headers: {
'Content-Type': 'multipart/form-data; boundary=boundary',
},
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(JSON.parse(bodyText)).toEqual({
files: {
myFile: {
name: 'text.txt',
type: 'text/plain',
tmp_name: expect.any(String),
error: '0',
size: '3',
},
},
is_uploaded: true,
});
});
it('Should expose both the multipart/form-data request body AND uploaded files in $_FILES', async () => {
const response = await php.run({
code: `<?php echo json_encode(array(
"files" => $_FILES,
"is_uploaded1" => is_uploaded_file($_FILES["myFile1"]["tmp_name"]),
"is_uploaded2" => is_uploaded_file($_FILES["myFile2"]["tmp_name"])
));`,
relativeUri: '/',
method: 'POST',
body: `--boundary
Content-Disposition: form-data; name="myFile1"; filename="from_body.txt"
Content-Type: text/plain
bar1
--boundary--`,
fileInfos: [
{
name: 'from_files.txt',
key: 'myFile2',
data: new TextEncoder().encode('bar2'),
type: 'application/json',
},
],
headers: {
'Content-Type': 'multipart/form-data; boundary=boundary',
},
});
const bodyText = new TextDecoder().decode(response.bytes);
const expectedResult = {
files: {
myFile1: {
name: 'from_body.txt',
type: 'text/plain',
tmp_name: expect.any(String),
error: 0,
size: 4,
},
myFile2: {
name: 'from_files.txt',
type: 'application/json',
tmp_name: expect.any(String),
error: '0',
size: '4',
},
},
is_uploaded1: true,
is_uploaded2: true,
};
if (Number(phpVersion) > 8) {
(expectedResult.files.myFile1 as any).full_path =
'from_body.txt';
}
expect(JSON.parse(bodyText)).toEqual(expectedResult);
});
it('Should provide the correct $_SERVER information', async () => {
php.writeFile(
testScriptPath,
'<?php echo json_encode($_SERVER); ?>'
);
const response = await php.run({
scriptPath: testScriptPath,
relativeUri: '/test.php?a=b',
method: 'POST',
body: `--boundary
Content-Disposition: form-data; name="myFile1"; filename="from_body.txt"
Content-Type: text/plain
bar1
--boundary--`,
fileInfos: [
{
name: 'from_files.txt',
key: 'myFile2',
data: new TextEncoder().encode('bar2'),
type: 'application/json',
},
],
headers: {
'Content-Type': 'multipart/form-data; boundary=boundary',
Host: 'https://example.com:1235',
'X-is-ajax': 'true',
},
});
const bodyText = new TextDecoder().decode(response.bytes);
const $_SERVER = JSON.parse(bodyText);
expect($_SERVER).toHaveProperty('REQUEST_URI', '/test.php?a=b');
expect($_SERVER).toHaveProperty('REQUEST_METHOD', 'POST');
expect($_SERVER).toHaveProperty(
'HTTP_CONTENT_TYPE',
'multipart/form-data; boundary=boundary'
);
expect($_SERVER).toHaveProperty(
'HTTP_HOST',
'https://example.com:1235'
);
expect($_SERVER).toHaveProperty(
'SERVER_NAME',
'https://example.com:1235'
);
expect($_SERVER).toHaveProperty('HTTP_X_IS_AJAX', 'true');
expect($_SERVER).toHaveProperty('SERVER_PORT', '1235');
});
});
/**
* libsqlite3 path needs to be explicitly provided in Dockerfile
* for PHP < 7.4 – let's make sure it works
*/
describe('PDO SQLite support', () => {
it('Should be able to create a database', async () => {
const response = await php.run({
code: `<?php
$db = new PDO('sqlite::memory:');
$db->exec('CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)');
$db->exec('INSERT INTO test (name) VALUES ("This is a test")');
$result = $db->query('SELECT name FROM test');
$rows = $result->fetchAll(PDO::FETCH_COLUMN);
echo json_encode($rows);
?>`,
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(JSON.parse(bodyText)).toEqual(['This is a test']);
});
it('Should support modern libsqlite (ON CONFLICT)', async () => {
const response = await php.run({
code: `<?php
$db = new PDO('sqlite::memory:');
$db->exec('CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)');
$db->exec('CREATE UNIQUE INDEX test_name ON test (name)');
$db->exec('INSERT INTO test (name) VALUES ("This is a test")');
$db->exec('INSERT INTO test (name) VALUES ("This is a test") ON CONFLICT DO NOTHING');
$result = $db->query('SELECT name FROM test');
$rows = $result->fetchAll(PDO::FETCH_COLUMN);
echo json_encode($rows);
?>`,
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(JSON.parse(bodyText)).toEqual(['This is a test']);
});
});
/**
* hash extension needs to be explicitly enabled in Dockerfile
* for PHP < 7.3 – let's make sure it works
*/
describe('Hash extension support', () => {
it('Should be able to hash a string', async () => {
const response = await php.run({
code: `<?php
echo json_encode([
'md5' => md5('test'),
'sha1' => sha1('test'),
'hash' => hash('sha256', 'test'),
]);
?>`,
});
const bodyText = new TextDecoder().decode(response.bytes);
expect(JSON.parse(bodyText)).toEqual({
md5: '098f6bcd4621d373cade4e832627b4f6',
sha1: 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3',
hash: '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08',
});
});
});
});
// @TODO Prevent crash on PHP versions 5.6, 7.2, 8.2
describe.each(['7.0', '7.1', '7.3', '7.4', '8.0', '8.1'])(
'PHP %s – process crash',
(phpVersion) => {
let php: NodePHP;
beforeEach(async () => {
php = await NodePHP.load(phpVersion as any);
php.setPhpIniEntry('allow_url_fopen', '1');
vi.restoreAllMocks();
});
it('Does not crash due to an unhandled Asyncify error ', async () => {
let caughtError;
try {
/**
* PHP is intentionally built without network support for __clone()
* because it's an extremely unlikely place for any network activity
* and not supporting it allows us to test the error handling here.
*
* `clone $x` will throw an asynchronous error out when attempting
* to do a network call ("unreachable" WASM instruction executed).
* This test should gracefully catch and handle that error.
*
* A failure to do so will crash the entire process
*/
await php.run({
code: `<?php
class Top {
function __clone() {
file_get_contents("http://127.0.0.1");
}
}
$x = new Top();
clone $x;
`,
});
} catch (error: unknown) {
caughtError = error;
if (error instanceof Error) {
expect(error.message).toMatch(
/Aborted|Program terminated with exit\(1\)|/
);
}
}
if (!caughtError) {
expect.fail('php.run should have thrown an error');
}
});
it('Does not crash due to an unhandled non promise error ', async () => {
let caughtError;
try {
const spy = vi.spyOn(php[__private__dont__use], 'ccall');
expect(spy.getMockName()).toEqual('ccall');
spy.mockImplementation((c_func) => {
if (c_func === 'wasm_sapi_handle_request') {
throw new Error('test');
}
});
await php.run({
code: `<?php
function top() {
file_get_contents("http://127.0.0.1");
}
top();
`,
});
} catch (error: unknown) {
caughtError = error;
if (error instanceof Error) {
expect(error.message).toMatch('test');
expect(error.stack).toContain('#handleRequest');
}
}
if (!caughtError) {
expect.fail('php.run should have thrown an error');
}
});
}
);