-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbashful.test.ts
More file actions
1459 lines (1217 loc) · 56.5 KB
/
Copy pathbashful.test.ts
File metadata and controls
1459 lines (1217 loc) · 56.5 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
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import {
splitSegments,
parseSchema,
buildCLIArgs,
tokenizeArgs,
PayloadError,
parseConfig,
normalizeConfig,
extractOptions,
parseHostHeader,
isLoopbackHost,
isAllowedHost,
buildCorsHeaders,
isJsonContentType,
wantsJson,
parseNumberOption,
extractFlagNames,
effectiveFlagPolicy,
authorizeCommand,
authorizeFlags,
authorizeValues,
extractFlagValues,
authorizeRequest,
filterSchema,
DEFAULT_CONFIG,
type BashfulConfig,
} from './bashful';
// ── splitSegments ─────────────────────────────────────────────────────────────
describe('splitSegments', () => {
test('single command', () => {
expect(splitSegments(['curl'])).toEqual([['curl']]);
});
test('single command with extra args (pipe mode)', () => {
expect(splitSegments(['curl', '--help'])).toEqual([['curl', '--help']]);
});
test('escaped pipe symbol evaluates correctly (Windows compat)', () => {
expect(splitSegments(['curl', '\\|', 'wget'])).toEqual([['curl'], ['wget']]);
});
test('two commands separated by |', () => {
expect(splitSegments(['curl', '|', 'wget'])).toEqual([['curl'], ['wget']]);
});
test('three commands separated by |', () => {
expect(splitSegments(['curl', '|', 'wget', '|', 'ping'])).toEqual([
['curl'], ['wget'], ['ping']
]);
});
test('pipe mode segments with multiple words', () => {
expect(splitSegments(['curl', '--help', '|', 'wget', '--help'])).toEqual([
['curl', '--help'], ['wget', '--help']
]);
});
test('leading | is ignored', () => {
expect(splitSegments(['|', 'curl'])).toEqual([['curl']]);
});
test('trailing | is ignored', () => {
expect(splitSegments(['curl', '|'])).toEqual([['curl']]);
});
test('empty args returns empty array', () => {
expect(splitSegments([])).toEqual([]);
});
});
// ── tokenizeArgs ──────────────────────────────────────────────────────────────
describe('tokenizeArgs', () => {
test('splits on whitespace', () => {
expect(tokenizeArgs('http://example.com --silent')).toEqual(['http://example.com', '--silent']);
});
test('collapses runs of whitespace', () => {
expect(tokenizeArgs(' a b \t c ')).toEqual(['a', 'b', 'c']);
});
test('keeps a double-quoted value with spaces together', () => {
expect(tokenizeArgs('--data "hello world"')).toEqual(['--data', 'hello world']);
});
test('keeps a single-quoted value with spaces together', () => {
expect(tokenizeArgs("--data 'hello world'")).toEqual(['--data', 'hello world']);
});
test('quotes can be embedded mid-token', () => {
expect(tokenizeArgs('--header="A: 1"')).toEqual(['--header=A: 1']);
});
test('the other quote survives inside a quoted run', () => {
expect(tokenizeArgs(`--msg "it's fine"`)).toEqual(['--msg', "it's fine"]);
});
test('an explicitly empty argument is preserved', () => {
expect(tokenizeArgs('--value ""')).toEqual(['--value', '']);
});
test('empty input yields no args', () => {
expect(tokenizeArgs('')).toEqual([]);
expect(tokenizeArgs(' ')).toEqual([]);
});
});
// ── parseSchema ───────────────────────────────────────────────────────────────
describe('parseSchema', () => {
test('returns empty schema for empty help text', () => {
expect(parseSchema('')).toEqual({});
});
test('returns empty schema for text with no flags', () => {
expect(parseSchema('Usage: curl [options] <url>\nTransfer data from a server.')).toEqual({});
});
test('parses a boolean long flag', () => {
const schema = parseSchema(' --silent Silent mode');
expect(schema['silent']).toMatchObject({
longFlag: '--silent',
type: 'boolean',
description: 'Silent mode',
});
});
test('parses a long flag with short flag', () => {
const schema = parseSchema(' -s, --silent Silent mode');
expect(schema['silent']).toMatchObject({
shortFlag: '-s',
longFlag: '--silent',
type: 'boolean',
});
});
test('parses a flag with angle-bracket value type', () => {
const schema = parseSchema(' -o, --output <file> Write output to file');
expect(schema['output']).toMatchObject({
shortFlag: '-o',
longFlag: '--output',
type: 'file',
description: 'Write output to file',
});
});
test('parses a flag with bracket value type', () => {
const schema = parseSchema(' --retry [num] Retry count');
expect(schema['retry']).toMatchObject({
longFlag: '--retry',
type: 'num',
});
});
test('parses a flag with ALLCAPS value type', () => {
const schema = parseSchema(' --connect-timeout SECONDS Max time for connection');
expect(schema['connect-timeout']).toMatchObject({
longFlag: '--connect-timeout',
type: 'SECONDS',
});
});
test('parses multiple flags from realistic help text', () => {
const helpText = `
Usage: curl [options...] <url>
-s, --silent Silent mode
-o, --output <file> Write to file instead of stdout
-L, --location Follow redirects
--max-time SECONDS Maximum time allowed
`;
const schema = parseSchema(helpText);
expect(Object.keys(schema)).toEqual(
expect.arrayContaining(['silent', 'output', 'location', 'max-time'])
);
expect(schema['silent'].type).toBe('boolean');
expect(schema['output'].type).toBe('file');
expect(schema['location'].type).toBe('boolean');
expect(schema['max-time'].type).toBe('SECONDS');
});
test('trims trailing whitespace from descriptions', () => {
const schema = parseSchema(' --verbose Be verbose ');
expect(schema['verbose'].description).toBe('Be verbose');
});
test('parses a short-only flag (no long form)', () => {
const schema = parseSchema(' -v Be verbose');
expect(schema['v']).toMatchObject({
shortFlag: '-v',
longFlag: '-v', // what actually gets emitted
type: 'boolean',
description: 'Be verbose',
});
expect(buildCLIArgs({ v: true }, schema)).toEqual(['-v']);
});
test('parses a short-only flag that takes a value', () => {
const schema = parseSchema(' -X <method> Request method');
expect(schema['X']).toMatchObject({ longFlag: '-X', type: 'method' });
expect(buildCLIArgs({ X: 'POST' }, schema)).toEqual(['-X', 'POST']);
});
test('parses the --flag=<value> form', () => {
const schema = parseSchema(' --output=<file> Write output here');
expect(schema['output']).toMatchObject({
longFlag: '--output',
type: 'file',
description: 'Write output here',
});
// The '=' is a help-text convention; we still emit the conventional form.
expect(buildCLIArgs({ output: 'f.txt' }, schema)).toEqual(['--output', 'f.txt']);
});
test('parses a flag with no description', () => {
const schema = parseSchema(' --silent');
expect(schema['silent']).toMatchObject({ longFlag: '--silent', type: 'boolean', description: '' });
});
test('parses a valueless flag at end of line with a short partner', () => {
const schema = parseSchema(' -s, --silent');
expect(schema['silent']).toMatchObject({ shortFlag: '-s', longFlag: '--silent' });
});
test('an all-caps word in the description is not mistaken for a value type', () => {
// Two+ spaces means the description started; a value is separated by one.
const schema = parseSchema(' --quiet URL fetching stays silent');
expect(schema['quiet'].type).toBe('boolean');
expect(schema['quiet'].description).toBe('URL fetching stays silent');
});
test('the first definition of a flag wins over later mentions', () => {
const schema = parseSchema([
' -o, --output <file> Write to file',
'Examples:',
' --output',
].join('\n'));
expect(schema['output']).toMatchObject({ type: 'file', description: 'Write to file' });
});
test('a short flag and a long flag on separate lines stay separate entries', () => {
const schema = parseSchema([
' -v Be verbose',
' --version Print version',
].join('\n'));
expect(schema['v'].longFlag).toBe('-v');
expect(schema['version'].longFlag).toBe('--version');
});
});
// ── parseSchema against real help text ────────────────────────────────────────
//
// The regex is the most fragile part of Bashful: it is a heuristic over a format
// with no standard. These fixtures are the real, captured output of real tools,
// so a regex change that quietly stops recognising a common shape fails here.
const fixture = (name: string) =>
parseSchema(readFileSync(join(import.meta.dir, 'tests', 'fixtures', `${name}-help.txt`), 'utf8'));
describe('parseSchema: real help text', () => {
test('curl: every flag in its help output is parsed', () => {
const schema = fixture('curl');
expect(Object.keys(schema)).toHaveLength(14);
});
test('curl: short flag, long flag, type and description are all recovered', () => {
const schema = fixture('curl');
expect(schema['output']).toEqual({
shortFlag: '-o',
longFlag: '--output',
type: 'file',
description: 'Write to file instead of stdout',
});
expect(schema['silent']).toMatchObject({ shortFlag: '-s', type: 'boolean', description: 'Silent mode' });
// The short flag letter often differs from the long name's initial.
expect(schema['head']).toMatchObject({ shortFlag: '-I', type: 'boolean' });
expect(schema['header']).toMatchObject({ shortFlag: '-H', type: 'header/@file' });
});
test('curl: trailing prose does not become a flag', () => {
// The help text ends with lines like: Use "--help all" to list all options
const schema = fixture('curl');
expect(schema['help']).toMatchObject({ type: 'subject' }); // the real -h, --help <subject>
for (const key of Object.keys(schema)) {
expect(key).toMatch(/^[a-zA-Z0-9][a-zA-Z0-9-]*$/);
}
});
test('bun and node: a large flag surface parses without malformed keys', () => {
for (const [name, atLeast] of [['bun', 50], ['node', 90]] as const) {
const schema = fixture(name);
expect(Object.keys(schema).length).toBeGreaterThanOrEqual(atLeast);
for (const [key, def] of Object.entries(schema)) {
expect(key).toMatch(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/);
expect(def.longFlag.startsWith('-')).toBe(true);
}
}
});
test('node: the --flag=<value> form is recognised', () => {
// node's help writes e.g. --env-file-if-exists=file
const schema = fixture('node');
const withValues = Object.values(schema).filter((d: any) => d.type !== 'boolean');
expect(withValues.length).toBeGreaterThan(0);
});
test('every parsed flag round-trips through buildCLIArgs', () => {
const schema = fixture('curl');
expect(buildCLIArgs({ silent: true, output: 'f.txt', header: ['A: 1', 'B: 2'] }, schema))
.toEqual(['--silent', '--output', 'f.txt', '--header', 'A: 1', '--header', 'B: 2']);
});
});
// ── buildCLIArgs ──────────────────────────────────────────────────────────────
const curlSchema = {
silent: { shortFlag: '-s', longFlag: '--silent', type: 'boolean' },
output: { shortFlag: '-o', longFlag: '--output', type: 'file' },
verbose: { shortFlag: '-v', longFlag: '--verbose', type: 'boolean' },
};
describe('buildCLIArgs', () => {
test('empty payload returns empty array', () => {
expect(buildCLIArgs({}, curlSchema)).toEqual([]);
});
test('_args as array', () => {
expect(buildCLIArgs({ _args: ['http://example.com'] }, curlSchema))
.toEqual(['http://example.com']);
});
test('_args as string', () => {
expect(buildCLIArgs({ _args: 'http://example.com' }, curlSchema))
.toEqual(['http://example.com']);
});
test('boolean flag set to true', () => {
expect(buildCLIArgs({ silent: true }, curlSchema)).toContain('--silent');
});
test('boolean flag set to false is omitted', () => {
expect(buildCLIArgs({ silent: false }, curlSchema)).not.toContain('--silent');
});
test('boolean flag set to string "false" is omitted', () => {
expect(buildCLIArgs({ silent: 'false' }, curlSchema)).not.toContain('--silent');
});
test('value flag appends the value after the long flag', () => {
const args = buildCLIArgs({ output: 'result.html' }, curlSchema);
expect(args).toEqual(['--output', 'result.html']);
});
test('multiple flags combined with _args', () => {
const args = buildCLIArgs(
{ _args: ['http://example.com'], silent: true, output: 'out.html' },
curlSchema
);
expect(args[0]).toBe('http://example.com');
expect(args).toContain('--silent');
expect(args).toContain('--output');
expect(args).toContain('out.html');
});
test('unknown single-char key treated as short flag (boolean)', () => {
const args = buildCLIArgs({ v: true }, {});
expect(args).toContain('-v');
});
test('unknown single-char key treated as short flag (value)', () => {
const args = buildCLIArgs({ x: 'GET' }, {});
expect(args).toEqual(['-x', 'GET']);
});
test('unknown multi-char key treated as long flag (boolean)', () => {
const args = buildCLIArgs({ verbose: true }, {});
expect(args).toContain('--verbose');
});
test('unknown multi-char key treated as long flag (value)', () => {
const args = buildCLIArgs({ timeout: '30' }, {});
expect(args).toEqual(['--timeout', '30']);
});
test('unknown single-char flag with false value is omitted', () => {
expect(buildCLIArgs({ v: false }, {})).toEqual([]);
});
test('unknown multi-char flag with false value is omitted', () => {
expect(buildCLIArgs({ verbose: false }, {})).toEqual([]);
});
// Repeatable flags — curl -H, docker -e, and friends.
test('an array repeats the flag once per element', () => {
const schema = { header: { longFlag: '--header', type: 'string' } };
expect(buildCLIArgs({ header: ['A: 1', 'B: 2'] }, schema))
.toEqual(['--header', 'A: 1', '--header', 'B: 2']);
});
test('an array on an unknown key repeats too', () => {
expect(buildCLIArgs({ H: ['a', 'b'] }, {})).toEqual(['-H', 'a', '-H', 'b']);
});
test('a single-element array behaves like a bare value', () => {
expect(buildCLIArgs({ output: ['f.txt'] }, curlSchema)).toEqual(['--output', 'f.txt']);
});
test('an empty array emits nothing', () => {
expect(buildCLIArgs({ output: [] }, curlSchema)).toEqual([]);
});
test('numbers are rendered as values', () => {
expect(buildCLIArgs({ retry: 3 }, {})).toEqual(['--retry', '3']);
});
test('null and undefined emit nothing', () => {
expect(buildCLIArgs({ output: null, silent: undefined }, curlSchema)).toEqual([]);
});
test('an object value is rejected rather than passed as [object Object]', () => {
expect(() => buildCLIArgs({ output: { a: 1 } }, curlSchema)).toThrow(PayloadError);
expect(() => buildCLIArgs({ output: { a: 1 } }, curlSchema)).toThrow(/not a valid value/);
});
test('an object inside an array is rejected', () => {
expect(() => buildCLIArgs({ header: [{ a: 1 }] }, {})).toThrow(PayloadError);
});
test('a nested array is rejected', () => {
expect(() => buildCLIArgs({ header: [['a']] }, {})).toThrow(PayloadError);
});
test('a non-string _args is rejected', () => {
expect(() => buildCLIArgs({ _args: { url: 'x' } }, curlSchema)).toThrow(PayloadError);
expect(() => buildCLIArgs({ _args: [{ url: 'x' }] }, curlSchema)).toThrow(PayloadError);
});
test('numeric positional args are accepted', () => {
expect(buildCLIArgs({ _args: [8080] }, {})).toEqual(['8080']);
});
test('_stdin is not emitted as a flag', () => {
expect(buildCLIArgs({ _stdin: 'hello', silent: true }, curlSchema)).toEqual(['--silent']);
});
test('a non-string _stdin is rejected', () => {
expect(() => buildCLIArgs({ _stdin: { a: 1 } }, {})).toThrow(PayloadError);
expect(() => buildCLIArgs({ _stdin: 42 }, {})).toThrow(/must be a string/);
});
});
// ── Config parsing ────────────────────────────────────────────────────────────
describe('normalizeConfig / parseConfig', () => {
test('null config yields the permissive default', () => {
expect(normalizeConfig(null)).toEqual(DEFAULT_CONFIG);
});
test('defaults to blacklist mode', () => {
expect(normalizeConfig({}).mode).toBe('blacklist');
});
test('parses a full config', () => {
const config = parseConfig(JSON.stringify({
mode: 'whitelist',
commands: { allow: ['curl'], deny: ['rm'] },
flags: { curl: { allow: ['silent'], deny: ['config'], denyCombinations: [['output', 'upload-file']] } },
}));
expect(config.mode).toBe('whitelist');
expect(config.commands.allow).toEqual(['curl']);
expect(config.flags['curl']!.denyCombinations).toEqual([['output', 'upload-file']]);
});
test('rejects an unknown mode', () => {
expect(() => normalizeConfig({ mode: 'allowlist' })).toThrow(/mode/);
});
test('rejects a non-object root', () => {
expect(() => normalizeConfig(['curl'])).toThrow(/root/);
});
test('rejects a non-string entry in a command list', () => {
expect(() => normalizeConfig({ commands: { deny: ['rm', 7] } })).toThrow(/commands.deny/);
});
test('rejects combinations that are not arrays of arrays', () => {
expect(() => normalizeConfig({ flags: { curl: { denyCombinations: ['output'] } } }))
.toThrow(/denyCombinations/);
});
test('rejects invalid JSON', () => {
expect(() => parseConfig('{ not json')).toThrow(/invalid JSON/);
});
});
// ── extractOptions ────────────────────────────────────────────────────────────
describe('extractOptions', () => {
test('no options leaves args untouched, and GET exec is off by default', () => {
const opts = extractOptions(['curl', '|', 'wget']);
expect(opts.rest).toEqual(['curl', '|', 'wget']);
expect(opts.allowGet).toBe(false);
expect(opts.allowOrigin).toBeUndefined();
expect(opts.configPath).toBeUndefined();
});
test('--config <path> is removed from args', () => {
const opts = extractOptions(['--config', 'policy.json', 'curl']);
expect(opts.configPath).toBe('policy.json');
expect(opts.rest).toEqual(['curl']);
});
test('--config=<path> is removed from args', () => {
expect(extractOptions(['--config=policy.json', 'curl']).configPath).toBe('policy.json');
});
test('--allow-get is a boolean switch', () => {
const opts = extractOptions(['--allow-get', 'curl']);
expect(opts.allowGet).toBe(true);
expect(opts.rest).toEqual(['curl']);
});
test('--allow-origin takes a value in both spellings', () => {
expect(extractOptions(['--allow-origin', 'https://a.test', 'curl']).allowOrigin).toBe('https://a.test');
expect(extractOptions(['--allow-origin=https://a.test', 'curl']).allowOrigin).toBe('https://a.test');
});
test('all options combine, leaving only the command', () => {
const opts = extractOptions(['--config', 'p.json', '--allow-get', '--allow-origin=https://a.test', 'curl', '|', 'wget']);
expect(opts).toMatchObject({ configPath: 'p.json', allowGet: true, allowOrigin: 'https://a.test' });
expect(opts.rest).toEqual(['curl', '|', 'wget']);
});
test('--timeout is taken in seconds and stored as ms', () => {
expect(extractOptions(['--timeout', '2.5', 'curl']).timeoutMs).toBe(2500);
expect(extractOptions(['curl']).timeoutMs).toBe(0); // no limit by default
});
test('--max-concurrency overrides the default cap', () => {
expect(extractOptions(['curl']).maxConcurrent).toBe(16);
expect(extractOptions(['--max-concurrency=1', 'curl']).maxConcurrent).toBe(1);
expect(extractOptions(['--max-concurrency', '0', 'curl']).maxConcurrent).toBe(0); // unlimited
});
test('a nonsense numeric option is rejected at startup', () => {
expect(() => extractOptions(['--timeout', 'soon', 'curl'])).toThrow(/non-negative number/);
expect(() => extractOptions(['--max-concurrency=-3', 'curl'])).toThrow(/non-negative number/);
});
test('an option with no value throws', () => {
expect(() => extractOptions(['--config'])).toThrow(/--config requires a value/);
expect(() => extractOptions(['--allow-origin'])).toThrow(/--allow-origin requires a value/);
});
test('an option followed by a flag throws', () => {
expect(() => extractOptions(['--config', '--allow-get', 'curl'])).toThrow(/requires a value/);
});
});
// ── Request hardening ─────────────────────────────────────────────────────────
describe('parseHostHeader', () => {
test('strips the port', () => {
expect(parseHostHeader('localhost:3000')).toBe('localhost');
expect(parseHostHeader('127.0.0.1:3000')).toBe('127.0.0.1');
});
test('handles a bare hostname', () => {
expect(parseHostHeader('localhost')).toBe('localhost');
});
test('handles bracketed IPv6', () => {
expect(parseHostHeader('[::1]:3000')).toBe('::1');
});
test('lowercases', () => {
expect(parseHostHeader('LOCALHOST:3000')).toBe('localhost');
});
test('returns null for a missing or empty header', () => {
expect(parseHostHeader(null)).toBeNull();
expect(parseHostHeader(' ')).toBeNull();
});
});
describe('isLoopbackHost', () => {
test('accepts loopback names and addresses', () => {
for (const host of ['localhost', '127.0.0.1', '127.1.2.3', '::1']) {
expect(isLoopbackHost(host)).toBe(true);
}
});
test('rejects everything else', () => {
for (const host of ['evil.example', '0.0.0.0', '192.168.1.5', '127.0.0.1.evil.example']) {
expect(isLoopbackHost(host)).toBe(false);
}
});
});
describe('isAllowedHost', () => {
test('accepts a loopback Host when bound to loopback', () => {
expect(isAllowedHost('localhost:3000', '127.0.0.1')).toBe(true);
});
test('rejects a foreign Host when bound to loopback (DNS rebinding)', () => {
// The name resolves to 127.0.0.1, but the Host header gives the attacker away.
expect(isAllowedHost('evil.example:3000', '127.0.0.1')).toBe(false);
});
test('rejects a missing Host header when bound to loopback', () => {
expect(isAllowedHost(null, '127.0.0.1')).toBe(false);
});
test('accepts any Host when the operator bound a public interface', () => {
expect(isAllowedHost('bashful.internal:3000', '0.0.0.0')).toBe(true);
});
});
describe('buildCorsHeaders', () => {
test('sends no CORS headers by default — this is the point', () => {
expect(buildCorsHeaders('https://evil.example', undefined)).toEqual({});
});
test('echoes a matching configured origin', () => {
const headers = buildCorsHeaders('https://app.test', 'https://app.test');
expect(headers['Access-Control-Allow-Origin']).toBe('https://app.test');
expect(headers['Vary']).toBe('Origin');
});
test('sends nothing for an origin that does not match', () => {
expect(buildCorsHeaders('https://evil.example', 'https://app.test')).toEqual({});
});
test("'*' is honoured, but only when explicitly configured", () => {
expect(buildCorsHeaders('https://evil.example', '*')['Access-Control-Allow-Origin']).toBe('*');
});
});
describe('wantsJson', () => {
test('detects an application/json Accept header', () => {
expect(wantsJson('application/json')).toBe(true);
expect(wantsJson('application/json, text/plain;q=0.9')).toBe(true);
expect(wantsJson('text/html, application/json;q=0.8')).toBe(true);
});
test('anything else streams', () => {
expect(wantsJson('text/plain')).toBe(false);
expect(wantsJson('*/*')).toBe(false);
expect(wantsJson(null)).toBe(false);
});
});
describe('parseNumberOption', () => {
test('accepts non-negative numbers', () => {
expect(parseNumberOption('0', '--timeout')).toBe(0);
expect(parseNumberOption('2.5', '--timeout')).toBe(2.5);
});
test('rejects negatives and non-numbers', () => {
expect(() => parseNumberOption('-1', '--timeout')).toThrow(/non-negative/);
expect(() => parseNumberOption('soon', '--timeout')).toThrow(/non-negative/);
expect(() => parseNumberOption('', '--timeout')).toThrow(/non-negative/);
});
});
describe('isJsonContentType', () => {
test('accepts application/json with or without parameters', () => {
expect(isJsonContentType('application/json')).toBe(true);
expect(isJsonContentType('application/json; charset=utf-8')).toBe(true);
expect(isJsonContentType('APPLICATION/JSON')).toBe(true);
});
test('rejects the content types a cross-origin form/simple request can set', () => {
expect(isJsonContentType('text/plain')).toBe(false);
expect(isJsonContentType('application/x-www-form-urlencoded')).toBe(false);
expect(isJsonContentType('multipart/form-data')).toBe(false);
expect(isJsonContentType(null)).toBe(false);
});
});
// ── extractFlagNames ──────────────────────────────────────────────────────────
describe('extractFlagNames', () => {
test('lists flag keys', () => {
expect(extractFlagNames({ silent: true, output: 'out.html' })).toEqual(['silent', 'output']);
});
test('omits false-valued flags (they never reach the shell)', () => {
expect(extractFlagNames({ silent: false, verbose: 'false', output: 'o' })).toEqual(['output']);
});
test('counts non-empty _args as a governable flag name', () => {
expect(extractFlagNames({ _args: ['http://example.com'] })).toEqual(['_args']);
expect(extractFlagNames({ _args: 'http://example.com' })).toEqual(['_args']);
});
test('ignores empty _args', () => {
expect(extractFlagNames({ _args: [] })).toEqual([]);
expect(extractFlagNames({ _args: '' })).toEqual([]);
});
// These must agree with buildCLIArgs — a value that emits nothing must not be
// judged by the policy, or a rule could fire for a flag that never runs.
test('omits values that build to nothing', () => {
expect(extractFlagNames({ a: null, b: undefined, c: [], d: false, e: 'x' })).toEqual(['e']);
});
test('an array counts once', () => {
expect(extractFlagNames({ header: ['A', 'B'] })).toEqual(['header']);
});
test('_stdin is governable — it is input to the command like any flag', () => {
expect(extractFlagNames({ _stdin: 'data' })).toEqual(['_stdin']);
expect(extractFlagNames({ _stdin: '' })).toEqual([]);
});
});
// ── effectiveFlagPolicy ───────────────────────────────────────────────────────
describe('effectiveFlagPolicy', () => {
test('returns an empty policy when nothing is configured', () => {
expect(effectiveFlagPolicy('curl', DEFAULT_CONFIG)).toEqual({});
});
test('merges the wildcard policy with the command policy', () => {
const config = normalizeConfig({
flags: { '*': { deny: ['config'] }, curl: { deny: ['proxy'], allow: ['silent'] } },
});
const policy = effectiveFlagPolicy('curl', config);
expect(policy.deny).toEqual(['config', 'proxy']);
expect(policy.allow).toEqual(['silent']);
});
test('a command with no policy of its own still inherits the wildcard', () => {
const config = normalizeConfig({ flags: { '*': { deny: ['config'] } } });
expect(effectiveFlagPolicy('wget', config).deny).toEqual(['config']);
});
});
// ── authorizeCommand ──────────────────────────────────────────────────────────
describe('authorizeCommand', () => {
test('allows anything with no config', () => {
expect(authorizeCommand('rm', DEFAULT_CONFIG)).toEqual({ allowed: true });
});
test('blacklist: denied command is rejected', () => {
const config = normalizeConfig({ commands: { deny: ['rm'] } });
const decision = authorizeCommand('rm', config);
expect(decision.allowed).toBe(false);
expect(decision.allowed === false && decision.reason).toMatch(/denied/);
});
test('blacklist: everything else is allowed', () => {
const config = normalizeConfig({ commands: { deny: ['rm'] } });
expect(authorizeCommand('curl', config).allowed).toBe(true);
});
test('whitelist: only listed commands are allowed', () => {
const config = normalizeConfig({ mode: 'whitelist', commands: { allow: ['curl'] } });
expect(authorizeCommand('curl', config).allowed).toBe(true);
expect(authorizeCommand('wget', config).allowed).toBe(false);
});
test('whitelist with no allow list denies everything', () => {
expect(authorizeCommand('curl', normalizeConfig({ mode: 'whitelist' })).allowed).toBe(false);
});
test('deny beats allow', () => {
const config = normalizeConfig({ mode: 'whitelist', commands: { allow: ['curl'], deny: ['curl'] } });
expect(authorizeCommand('curl', config).allowed).toBe(false);
});
test("'*' in the allow list permits any command", () => {
const config = normalizeConfig({ mode: 'whitelist', commands: { allow: ['*'] } });
expect(authorizeCommand('anything', config).allowed).toBe(true);
});
});
// ── authorizeFlags ────────────────────────────────────────────────────────────
describe('authorizeFlags', () => {
test('allows any flag with no config', () => {
expect(authorizeFlags('curl', ['silent', 'output'], DEFAULT_CONFIG).allowed).toBe(true);
});
test('denies a blacklisted flag', () => {
const config = normalizeConfig({ flags: { curl: { deny: ['config'] } } });
const decision = authorizeFlags('curl', ['silent', 'config'], config);
expect(decision.allowed).toBe(false);
expect(decision.allowed === false && decision.reason).toContain("flag 'config'");
});
test('a wildcard flag policy applies to every command', () => {
const config = normalizeConfig({ flags: { '*': { deny: ['output'] } } });
expect(authorizeFlags('wget', ['output'], config).allowed).toBe(false);
});
test('an allow list on a command implies whitelisting for that command', () => {
const config = normalizeConfig({ flags: { curl: { allow: ['silent', '_args'] } } });
expect(authorizeFlags('curl', ['silent', '_args'], config).allowed).toBe(true);
expect(authorizeFlags('curl', ['silent', 'output'], config).allowed).toBe(false);
});
test('whitelist mode denies any flag when no allow list exists', () => {
const config = normalizeConfig({ mode: 'whitelist', commands: { allow: ['curl'] } });
expect(authorizeFlags('curl', ['silent'], config).allowed).toBe(false);
expect(authorizeFlags('curl', [], config).allowed).toBe(true); // no flags, nothing to check
});
test('denyCombinations rejects only the full combination', () => {
const config = normalizeConfig({
flags: { curl: { denyCombinations: [['output', 'upload-file']] } },
});
expect(authorizeFlags('curl', ['output'], config).allowed).toBe(true);
expect(authorizeFlags('curl', ['upload-file'], config).allowed).toBe(true);
const decision = authorizeFlags('curl', ['output', 'upload-file', 'silent'], config);
expect(decision.allowed).toBe(false);
expect(decision.allowed === false && decision.reason).toContain('combination');
});
test('allowCombinations requires the used flags to fit inside one combination', () => {
const config = normalizeConfig({
flags: { curl: { allowCombinations: [['silent', 'output'], ['verbose', '_args']] } },
});
expect(authorizeFlags('curl', ['silent'], config).allowed).toBe(true);
expect(authorizeFlags('curl', ['silent', 'output'], config).allowed).toBe(true);
expect(authorizeFlags('curl', ['verbose', '_args'], config).allowed).toBe(true);
// Valid individually, but they span two different allowed combinations.
expect(authorizeFlags('curl', ['silent', 'verbose'], config).allowed).toBe(false);
});
test('empty payload passes allowCombinations', () => {
const config = normalizeConfig({ flags: { curl: { allowCombinations: [['silent']] } } });
expect(authorizeFlags('curl', [], config).allowed).toBe(true);
});
test('deny beats allow for flags', () => {
const config = normalizeConfig({ flags: { curl: { allow: ['output'], deny: ['output'] } } });
expect(authorizeFlags('curl', ['output'], config).allowed).toBe(false);
});
});
// ── authorizeValues ───────────────────────────────────────────────────────────
describe('extractFlagValues', () => {
test('collects the values a payload would emit', () => {
expect(extractFlagValues({ output: 'f.txt', retry: 3 })).toEqual({ output: ['f.txt'], retry: ['3'] });
});
test('an array yields every value', () => {
expect(extractFlagValues({ header: ['A', 'B'] })).toEqual({ header: ['A', 'B'] });
});
test('bare booleans emit no value to check', () => {
expect(extractFlagValues({ silent: true, verbose: 'true', quiet: false })).toEqual({});
});
});
describe('authorizeValues', () => {
test('allows anything when no patterns are configured', () => {
expect(authorizeValues('curl', { output: '/etc/passwd' }, DEFAULT_CONFIG).allowed).toBe(true);
});
test('constrains a flag value to its pattern', () => {
const config = normalizeConfig({ flags: { curl: { values: { output: '^/tmp/' } } } });
expect(authorizeValues('curl', { output: '/tmp/out.html' }, config).allowed).toBe(true);
const decision = authorizeValues('curl', { output: '/etc/passwd' }, config);
expect(decision.allowed).toBe(false);
expect(decision.allowed === false && decision.reason).toContain('/etc/passwd');
});
test('constrains positional args — the URL curl is allowed to fetch', () => {
const config = normalizeConfig({ flags: { curl: { values: { _args: '^https://api\\.example\\.com/' } } } });
expect(authorizeValues('curl', { _args: ['https://api.example.com/v1/users'] }, config).allowed).toBe(true);
expect(authorizeValues('curl', { _args: ['https://evil.example/'] }, config).allowed).toBe(false);
});
test('every element of an array must match', () => {
const config = normalizeConfig({ flags: { curl: { values: { _args: '^https://' } } } });
expect(authorizeValues('curl', { _args: ['https://a.test', 'http://b.test'] }, config).allowed).toBe(false);
});
test('a flag used as a bare boolean has no value to constrain', () => {
const config = normalizeConfig({ flags: { curl: { values: { output: '^/tmp/' } } } });
expect(authorizeValues('curl', { output: true }, config).allowed).toBe(true);
});
test('a pattern for an unused flag is inert', () => {
const config = normalizeConfig({ flags: { curl: { values: { output: '^/tmp/' } } } });
expect(authorizeValues('curl', { silent: true }, config).allowed).toBe(true);
});
test("a command's pattern overrides the wildcard's for the same flag", () => {
const config = normalizeConfig({
flags: { '*': { values: { output: '^/tmp/' } }, curl: { values: { output: '^/var/' } } },
});
expect(authorizeValues('curl', { output: '/var/x' }, config).allowed).toBe(true);
expect(authorizeValues('curl', { output: '/tmp/x' }, config).allowed).toBe(false);
// wget has no override, so it still inherits the wildcard.
expect(authorizeValues('wget', { output: '/tmp/x' }, config).allowed).toBe(true);
});
test('a broken regex is rejected at config load, not at request time', () => {
expect(() => normalizeConfig({ flags: { curl: { values: { output: '[unclosed' } } } }))
.toThrow(/not a valid regex/);
});
test('a non-string pattern is rejected', () => {
expect(() => normalizeConfig({ flags: { curl: { values: { output: 3 } } } }))
.toThrow(/must be a regex string/);
});
});
// ── authorizeRequest ──────────────────────────────────────────────────────────
describe('authorizeRequest', () => {
const config: BashfulConfig = normalizeConfig({
mode: 'whitelist',
commands: { allow: ['curl'] },
flags: { curl: { allow: ['silent', 'output', '_args'], denyCombinations: [['silent', 'output']] } },
});
test('allows a permitted command + payload', () => {
expect(authorizeRequest('curl', { silent: true, _args: ['http://example.com'] }, config).allowed).toBe(true);
});
test('rejects a command outside the whitelist', () => {
expect(authorizeRequest('wget', { silent: true }, config).allowed).toBe(false);
});
test('rejects a flag outside the whitelist', () => {
expect(authorizeRequest('curl', { proxy: 'http://evil' }, config).allowed).toBe(false);
});
test('rejects a denied combination', () => {
expect(authorizeRequest('curl', { silent: true, output: 'f' }, config).allowed).toBe(false);
});
test('a false-valued flag does not trip a combination rule', () => {
// `silent: false` builds to nothing, so this is really just `--output f`.
expect(authorizeRequest('curl', { silent: false, output: 'f' }, config).allowed).toBe(true);
});
test('value patterns are enforced as part of the full request check', () => {
const strict = normalizeConfig({
mode: 'whitelist',
commands: { allow: ['curl'] },
flags: { curl: { allow: ['_args', 'output'], values: { _args: '^https://ok\\.test/' } } },
});
expect(authorizeRequest('curl', { _args: ['https://ok.test/a'] }, strict).allowed).toBe(true);
expect(authorizeRequest('curl', { _args: ['https://evil.test/a'] }, strict).allowed).toBe(false);
});
});
// ── filterSchema ──────────────────────────────────────────────────────────────
describe('filterSchema', () => {
const schema = {
silent: { longFlag: '--silent', type: 'boolean' },
output: { longFlag: '--output', type: 'file' },
config: { longFlag: '--config', type: 'file' },
};
test('returns the schema unchanged with no config', () => {
expect(filterSchema('curl', schema, DEFAULT_CONFIG)).toEqual(schema);
});
test('hides denied flags', () => {
const config = normalizeConfig({ flags: { curl: { deny: ['config'] } } });
expect(Object.keys(filterSchema('curl', schema, config))).toEqual(['silent', 'output']);
});
test('whitelist mode hides everything not allowed', () => {
const config = normalizeConfig({ mode: 'whitelist', flags: { curl: { allow: ['silent'] } } });
expect(Object.keys(filterSchema('curl', schema, config))).toEqual(['silent']);
});
test('combination rules do not hide individually-valid flags', () => {
const config = normalizeConfig({ flags: { curl: { denyCombinations: [['silent', 'output']] } } });
expect(Object.keys(filterSchema('curl', schema, config))).toEqual(['silent', 'output', 'config']);
});
});
// ── Integration Tests ────────────────────────────────────────────────────────
import { spawn } from 'bun';
describe('Integration: HTTP Server Routing', () => {
let serverProcess: ReturnType<typeof spawn>;
const PORT = 3005; // Use a specific port for testing
const baseUrl = `http://localhost:${PORT}`;
beforeAll(async () => {
// Spawn the bashful server with a distinct port