bash-json-guard.test.js
2.3 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
/**
* bash-json-guard 单测
*/
const { jsonGuard, bashHooks, INLINE_JSON_PATTERNS } = require('../../../src/tools/devloop/bash-json-guard');
describe('bash-json-guard', () => {
describe('jsonGuard', () => {
it('passes plain commands', () => {
expect(jsonGuard('ls -la').ok).toBe(true);
expect(jsonGuard('node server.js').ok).toBe(true);
});
it('passes curl with @file', () => {
expect(jsonGuard('curl -X POST -d @/tmp/payload.json http://x').ok).toBe(true);
});
it('blocks curl -d single-quoted inline JSON', () => {
const r = jsonGuard(`curl -d '{"k":"v"}' http://x`);
expect(r.ok).toBe(false);
expect(r.reason).toMatch(/inline JSON/i);
});
it('blocks curl --data inline JSON', () => {
const r = jsonGuard(`curl --data '{"k":"v"}' http://x`);
expect(r.ok).toBe(false);
});
it('blocks curl --data-raw inline JSON', () => {
const r = jsonGuard(`curl --data-raw '{"a":1}' http://x`);
expect(r.ok).toBe(false);
});
it('blocks curl --data-binary inline JSON', () => {
const r = jsonGuard(`curl --data-binary '{"big":true}' http://x`);
expect(r.ok).toBe(false);
});
it('blocks double-quoted form too', () => {
const r = jsonGuard(`curl -d "{\\"k\\":\\"v\\"}" http://x`);
expect(r.ok).toBe(false);
});
it('returns matched_pattern on block', () => {
const r = jsonGuard(`curl -d '{}' http://x`);
expect(r.ok).toBe(false);
expect(typeof r.matched_pattern).toBe('string');
});
it('passes non-string input safely', () => {
expect(jsonGuard(null).ok).toBe(true);
expect(jsonGuard(undefined).ok).toBe(true);
expect(jsonGuard(123).ok).toBe(true);
});
});
describe('bashHooks.preExecute', () => {
it('throws JSON_GUARD_BLOCK on offending command', () => {
const hook = bashHooks.preExecute[0];
let err = null;
try { hook(`curl -d '{"x":1}' http://x`); } catch (e) { err = e; }
expect(err).not.toBeNull();
expect(err.code).toBe('JSON_GUARD_BLOCK');
});
it('returns silently on safe command', () => {
const hook = bashHooks.preExecute[0];
expect(() => hook('echo hello')).not.toThrow();
});
});
it('exports 4 INLINE_JSON_PATTERNS', () => {
expect(INLINE_JSON_PATTERNS.length).toBe(4);
});
});