-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-api.js
More file actions
191 lines (163 loc) · 5.47 KB
/
Copy pathtest-api.js
File metadata and controls
191 lines (163 loc) · 5.47 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
#!/usr/bin/env node
import { spawn } from 'child_process';
import fetch from 'node-fetch';
console.log('🌐 Testing KubeKavach API Server\n');
console.log('=' .repeat(60));
// Set environment variables for testing
process.env.KUBEKAVACH_API_KEY = 'test-api-key-123456';
const results = {
passed: [],
failed: [],
warnings: []
};
// Start the server
async function startServer() {
console.log('Starting API server...');
// Create a simple config file
const configContent = `
users:
- username: testuser
apiKey: test-api-key-123456
roles: ['admin', 'scanner', 'viewer']
api:
port: 3333
host: 127.0.0.1
`;
// Write config
const fs = await import('fs');
const os = await import('os');
const path = await import('path');
const configDir = path.join(os.homedir(), '.kubekavach');
const configPath = path.join(configDir, 'config.yaml');
try {
await fs.promises.mkdir(configDir, { recursive: true });
await fs.promises.writeFile(configPath, configContent);
console.log('✅ Test configuration created');
} catch (err) {
console.log('⚠️ Could not create config:', err.message);
}
return new Promise((resolve) => {
const server = spawn('node', ['dist/server.js'], {
cwd: '/Users/alokemajumder/Downloads/Github-Projects/kubekavach/packages/api',
env: { ...process.env }
});
server.stdout.on('data', (data) => {
const output = data.toString();
if (output.includes('Server started') || output.includes('listening')) {
results.passed.push('✅ Server started successfully');
resolve(server);
}
});
server.stderr.on('data', (data) => {
const error = data.toString();
if (!error.includes('Dynamic require')) { // Ignore known ESM issues
console.error('Server error:', error);
}
});
// Give it 3 seconds to start
setTimeout(() => {
results.warnings.push('⚠️ Server did not report successful start');
resolve(server);
}, 3000);
});
}
// Test endpoints
async function testEndpoints(server) {
console.log('\n🔍 Testing API Endpoints...\n');
const baseUrl = 'http://127.0.0.1:3333';
const headers = { 'x-api-key': 'test-api-key-123456' };
// Test 1: Health endpoint (no auth)
try {
const res = await fetch(`${baseUrl}/health`);
if (res.ok) {
results.passed.push('✅ /health endpoint works');
} else {
results.failed.push(`❌ /health returned ${res.status}`);
}
} catch (err) {
results.failed.push(`❌ /health endpoint failed: ${err.message}`);
}
// Test 2: Rules endpoint (needs auth)
try {
const res = await fetch(`${baseUrl}/rules`, { headers });
if (res.ok) {
const rules = await res.json();
if (Array.isArray(rules)) {
results.passed.push(`✅ /rules endpoint works (${rules.length} rules)`);
} else {
results.failed.push('❌ /rules did not return array');
}
} else if (res.status === 401) {
results.failed.push('❌ /rules authentication failed');
} else {
results.failed.push(`❌ /rules returned ${res.status}`);
}
} catch (err) {
results.failed.push(`❌ /rules endpoint failed: ${err.message}`);
}
// Test 3: Scan endpoint
try {
const res = await fetch(`${baseUrl}/scan`, {
method: 'POST',
headers: { ...headers, 'Content-Type': 'application/json' },
body: JSON.stringify({ namespace: 'default' })
});
if (res.ok) {
const data = await res.json();
if (data.jobId || data.id) {
results.passed.push('✅ /scan endpoint works');
} else {
results.warnings.push('⚠️ /scan returned unexpected format');
}
} else {
results.failed.push(`❌ /scan returned ${res.status}`);
}
} catch (err) {
results.failed.push(`❌ /scan endpoint failed: ${err.message}`);
}
// Test 4: AI status endpoint
try {
const res = await fetch(`${baseUrl}/ai/status`, { headers });
if (res.ok) {
const status = await res.json();
results.passed.push(`✅ /ai/status endpoint works (AI ${status.enabled ? 'enabled' : 'disabled'})`);
} else if (res.status === 404) {
results.warnings.push('⚠️ AI endpoints not available');
} else {
results.failed.push(`❌ /ai/status returned ${res.status}`);
}
} catch (err) {
results.warnings.push(`⚠️ /ai/status endpoint not available`);
}
// Clean up
server.kill();
}
// Run tests
async function runAPITest() {
try {
const server = await startServer();
await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for server to be ready
await testEndpoints(server);
// Print results
console.log('\n' + '='.repeat(60));
console.log('📊 API TEST RESULTS\n');
console.log(`✅ Passed: ${results.passed.length}`);
results.passed.forEach(msg => console.log(` ${msg}`));
console.log(`\n⚠️ Warnings: ${results.warnings.length}`);
results.warnings.forEach(msg => console.log(` ${msg}`));
console.log(`\n❌ Failed: ${results.failed.length}`);
results.failed.forEach(msg => console.log(` ${msg}`));
process.exit(results.failed.length > 0 ? 1 : 0);
} catch (err) {
console.error('Test failed:', err);
process.exit(1);
}
}
// Check if fetch is available
import('node-fetch').then(module => {
global.fetch = module.default;
runAPITest();
}).catch(() => {
console.error('❌ node-fetch not installed. Run: npm install -g node-fetch');
process.exit(1);
});