-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest-cli-security.js
More file actions
executable file
·293 lines (255 loc) · 8.25 KB
/
test-cli-security.js
File metadata and controls
executable file
·293 lines (255 loc) · 8.25 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
#!/usr/bin/env node
/**
* Security Testing Script for StackMemory CLI/API
* Tests input validation and security vulnerabilities
*/
import { spawn, execSync } from 'child_process';
import { existsSync, mkdirSync, rmSync } from 'fs';
import { join } from 'path';
const TEST_DIR = '/tmp/stackmemory-security-test';
const TESTS_PASSED = [];
const TESTS_FAILED = [];
// Color output helpers
const red = (str) => `\x1b[31m${str}\x1b[0m`;
const green = (str) => `\x1b[32m${str}\x1b[0m`;
const yellow = (str) => `\x1b[33m${str}\x1b[0m`;
const blue = (str) => `\x1b[34m${str}\x1b[0m`;
// Test runner
async function runTest(name, testFn) {
process.stdout.write(`Testing ${name}... `);
try {
await testFn();
TESTS_PASSED.push(name);
console.log(green('✓ PASSED'));
return true;
} catch (error) {
TESTS_FAILED.push({ name, error: error.message });
console.log(red('✗ FAILED'));
console.log(` ${yellow(error.message)}`);
return false;
}
}
// Execute CLI command safely
function execCLI(args, options = {}) {
try {
const result = execSync(`npx stackmemory ${args}`, {
cwd: TEST_DIR,
encoding: 'utf8',
stdio: 'pipe',
...options
});
return { success: true, output: result };
} catch (error) {
return {
success: false,
output: error.stdout || '',
error: error.stderr || error.message
};
}
}
// Setup test environment
function setupTestEnv() {
if (existsSync(TEST_DIR)) {
rmSync(TEST_DIR, { recursive: true, force: true });
}
mkdirSync(TEST_DIR, { recursive: true });
process.chdir(TEST_DIR);
// Initialize StackMemory
execSync('npx stackmemory init', { cwd: TEST_DIR, stdio: 'ignore' });
}
// Security Tests
const securityTests = {
// SQL Injection Tests
async testSQLInjection() {
const payloads = [
"'; DROP TABLE frames; --",
"1' OR '1'='1",
"1; DELETE FROM tasks WHERE 1=1; --",
"' UNION SELECT * FROM frames --",
"1' AND (SELECT * FROM (SELECT(SLEEP(5)))a)--"
];
for (const payload of payloads) {
const result = execCLI(`search "${payload}"`);
if (!result.success && result.error?.includes('DROP TABLE')) {
throw new Error(`SQL injection vulnerability detected with payload: ${payload}`);
}
}
},
// Command Injection Tests
async testCommandInjection() {
const payloads = [
'$(whoami)',
'`id`',
'; ls -la',
'| cat /etc/passwd',
'&& rm -rf /',
'\n/bin/sh',
'"; cat ~/.ssh/id_rsa; echo "'
];
for (const payload of payloads) {
const result = execCLI(`linear update "${payload}"`);
// Check if command was executed
if (result.output?.includes('root') || result.output?.includes('uid=')) {
throw new Error(`Command injection vulnerability with payload: ${payload}`);
}
}
},
// Path Traversal Tests
async testPathTraversal() {
const payloads = [
'../../../etc/passwd',
'..\\..\\..\\windows\\system32\\config\\sam',
'file:///etc/passwd',
'....//....//....//etc/passwd',
'%2e%2e%2f%2e%2e%2f%2e%2e%2fetc%2fpasswd'
];
for (const payload of payloads) {
// Test with project commands
const result = execCLI(`projects add "${payload}"`);
if (result.output?.includes('root:') || result.output?.includes('Administrator:')) {
throw new Error(`Path traversal vulnerability with payload: ${payload}`);
}
}
},
// Invalid Input Handling
async testInvalidInputs() {
const tests = [
{ cmd: 'linear sync --direction invalid', shouldFail: true },
{ cmd: 'linear config --set-interval -1', shouldFail: true },
{ cmd: 'linear config --set-quiet-start 25', shouldFail: true },
{ cmd: 'analytics --port abc', shouldFail: true },
{ cmd: 'search --limit notanumber', shouldFail: true }
];
for (const test of tests) {
const result = execCLI(test.cmd);
if (test.shouldFail && result.success) {
throw new Error(`Invalid input accepted: ${test.cmd}`);
}
}
},
// Buffer Overflow Tests
async testBufferOverflow() {
const largeString = 'A'.repeat(1000000); // 1MB string
const veryLargeString = 'B'.repeat(10000000); // 10MB string
// Test with large inputs
const result1 = execCLI(`search "${largeString}"`);
const result2 = execCLI(`linear create --title "${veryLargeString}"`);
// Should handle gracefully without crashing
if (result1.error?.includes('Segmentation fault') ||
result2.error?.includes('Segmentation fault')) {
throw new Error('Buffer overflow vulnerability detected');
}
},
// YAML/JSON Injection
async testYAMLInjection() {
const payloads = [
'!!python/object/apply:os.system ["ls"]',
'{"__proto__": {"isAdmin": true}}',
'{"constructor": {"prototype": {"isAdmin": true}}}',
'{ "$gt": "" }',
'{"$where": "sleep(1000)"}'
];
for (const payload of payloads) {
const result = execCLI(`config --import '${payload}'`);
if (result.output?.includes('isAdmin') ||
result.output?.includes('bin') ||
result.output?.includes('etc')) {
throw new Error(`YAML/JSON injection vulnerability with payload: ${payload}`);
}
}
},
// Environment Variable Injection
async testEnvVarInjection() {
const payloads = [
'$HOME',
'${PATH}',
'$(printenv)',
'%USERPROFILE%'
];
for (const payload of payloads) {
const result = execCLI(`linear setup --client-id "${payload}"`);
if (result.output?.includes('/home/') ||
result.output?.includes('/usr/') ||
result.output?.includes('Users')) {
throw new Error(`Environment variable injection with payload: ${payload}`);
}
}
},
// Integer Overflow Tests
async testIntegerOverflow() {
const tests = [
{ cmd: 'search --limit 999999999999999999999', field: 'limit' },
{ cmd: 'analytics --port 999999999', field: 'port' },
{ cmd: 'linear config --set-interval 2147483648', field: 'interval' }
];
for (const test of tests) {
const result = execCLI(test.cmd);
// Should validate numeric ranges
if (!result.error && result.success) {
throw new Error(`Integer overflow not handled for ${test.field}`);
}
}
},
// XSS in Terminal Output
async testXSSInTerminal() {
const payloads = [
'\x1b[31mRED\x1b[0m\x1b]0;HIJACKED\x07',
'<script>alert(1)</script>',
'\r\nInjected line',
'\x1b[2J\x1b[H' // Clear screen escape
];
for (const payload of payloads) {
const result = execCLI(`search "${payload}"`);
// Output should be sanitized
if (result.output?.includes('\x1b]0;') ||
result.output?.includes('\x1b[2J')) {
throw new Error('Terminal escape sequences not sanitized');
}
}
},
// Authentication Bypass Tests
async testAuthBypass() {
// Test accessing Linear commands without auth
const commands = [
'linear sync',
'linear list',
'linear update TEST-123'
];
// Unset LINEAR_API_KEY for test
delete process.env.LINEAR_API_KEY;
for (const cmd of commands) {
const result = execCLI(cmd);
// Should require authentication
if (result.success && !result.output?.includes('not configured')) {
throw new Error(`Authentication bypass for: ${cmd}`);
}
}
}
};
// Main test runner
async function main() {
console.log(blue('\n🔒 StackMemory CLI/API Security Testing\n'));
console.log('Setting up test environment...\n');
setupTestEnv();
// Run all security tests
for (const [name, testFn] of Object.entries(securityTests)) {
await runTest(name, testFn);
}
// Summary
console.log(blue('\n📊 Test Summary\n'));
console.log(green(`✓ Passed: ${TESTS_PASSED.length}`));
console.log(red(`✗ Failed: ${TESTS_FAILED.length}`));
if (TESTS_FAILED.length > 0) {
console.log(red('\n❌ Failed Tests:'));
TESTS_FAILED.forEach(({ name, error }) => {
console.log(` - ${name}: ${error}`);
});
}
// Cleanup
if (existsSync(TEST_DIR)) {
rmSync(TEST_DIR, { recursive: true, force: true });
}
process.exit(TESTS_FAILED.length > 0 ? 1 : 0);
}
// Run tests
main().catch(console.error);