-
-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathtest-token.js
More file actions
233 lines (192 loc) · 6.98 KB
/
test-token.js
File metadata and controls
233 lines (192 loc) · 6.98 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
#!/usr/bin/env node
// API Token Integration Test Script using cosmos-cloud-sdk
// Usage: node test-token.js <base_url> <admin_token> <readonly_token>
// Example: node test-token.js https://localhost cosmos_abc123 cosmos_xyz789
//
// Requires Node.js 18+ (built-in fetch). No external dependencies.
// Accepts self-signed certs.
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
const { createClient } = require('./sdk/dist/index.js');
const [,, baseUrl, adminToken, readonlyToken] = process.argv;
if (!baseUrl || !adminToken || !readonlyToken) {
console.error('Usage: node test-token.js <base_url> <admin_token> <readonly_token>');
process.exit(2);
}
// --- Create SDK clients ---
const admin = createClient({ baseUrl, token: adminToken });
const readonly = createClient({ baseUrl, token: readonlyToken });
// Raw request helper (for no-token and invalid-token tests)
async function rawRequest(path, method, token, body) {
const url = `${baseUrl}${path}`;
const headers = { 'Content-Type': 'application/json' };
if (token) headers['Authorization'] = `Bearer ${token}`;
const opts = { method, headers };
if (body !== undefined) opts.body = JSON.stringify(body);
const res = await fetch(url, opts);
let data = null;
try { data = await res.json(); } catch { }
return { status: res.status, data };
}
// --- Test framework ---
let passed = 0;
let failed = 0;
async function test(name, fn) {
try {
await fn();
passed++;
console.log(`[PASS] ${name}`);
} catch (err) {
failed++;
console.log(`[FAIL] ${name} — ${err.message}`);
}
}
function expectStatus(res, expected, label) {
if (res.status !== expected) {
throw new Error(`${label}: expected ${expected}, got ${res.status}`);
}
}
// --- Test Groups ---
async function group1_sdkBasicCalls() {
console.log('\n— Group 1: SDK Basic Calls —');
await test('admin.getStatus()', async () => {
const res = await admin.getStatus();
if (res.status !== 'OK') throw new Error('Expected status OK, got ' + res.status);
});
await test('readonly.getStatus()', async () => {
const res = await readonly.getStatus();
if (res.status !== 'OK') throw new Error('Expected status OK, got ' + res.status);
});
await test('admin.isOnline()', async () => {
const res = await admin.isOnline();
if (res.status !== 'OK') throw new Error('Expected status OK');
});
}
async function group2_sdkReadEndpoints() {
console.log('\n— Group 2: SDK Read Endpoints —');
await test('admin.config.get()', async () => {
const res = await admin.config.get();
if (res.status !== 'OK') throw new Error('Expected OK');
});
await test('readonly.config.get()', async () => {
const res = await readonly.config.get();
if (res.status !== 'OK') throw new Error('Expected OK');
});
await test('admin.docker.list()', async () => {
const res = await admin.docker.list();
if (res.status !== 'OK') throw new Error('Expected OK');
});
await test('readonly.docker.list()', async () => {
const res = await readonly.docker.list();
if (res.status !== 'OK') throw new Error('Expected OK');
});
await test('admin.users.list()', async () => {
const res = await admin.users.list();
if (res.status !== 'OK') throw new Error('Expected OK');
});
await test('readonly.users.list()', async () => {
const res = await readonly.users.list();
if (res.status !== 'OK') throw new Error('Expected OK');
});
await test('admin.apiTokens.list()', async () => {
const res = await admin.apiTokens.list();
if (res.status !== 'OK') throw new Error('Expected OK');
});
await test('readonly.apiTokens.list()', async () => {
const res = await readonly.apiTokens.list();
if (res.status !== 'OK') throw new Error('Expected OK');
});
}
async function group3_sdkWriteEndpoints() {
console.log('\n— Group 3: SDK Write Endpoints (admin vs read-only) —');
// admin: create + delete probe token
let probeCreated = false;
try {
await test('admin.apiTokens.create() - probe', async () => {
const res = await admin.apiTokens.create({ name: '__test_probe__' });
if (res.status !== 'OK') throw new Error('Expected OK, got ' + res.status);
probeCreated = true;
});
await test('admin.apiTokens.remove() - cleanup probe', async () => {
const res = await admin.apiTokens.remove('__test_probe__');
if (res.status !== 'OK') throw new Error('Expected OK');
probeCreated = false;
});
} finally {
if (probeCreated) {
try { await admin.apiTokens.remove('__test_probe__'); } catch { }
}
}
// readonly: create should fail
await test('readonly.apiTokens.create() - denied', async () => {
try {
await readonly.apiTokens.create({ name: '__test_probe__' });
throw new Error('Should have thrown');
} catch (e) {
if (!e.code && !e.status) throw e;
// Expected: error thrown (403)
}
});
// readonly: delete should fail
await test('readonly.apiTokens.remove() - denied', async () => {
try {
await readonly.apiTokens.remove('__test_probe__');
throw new Error('Should have thrown');
} catch (e) {
if (!e.code && !e.status) throw e;
}
});
// admin: idempotent config write-back
await test('admin.config.set() - idempotent write-back', async () => {
const getRes = await admin.config.get();
const config = getRes.data;
const putRes = await admin.config.set(config);
if (putRes.status !== 'OK') throw new Error('Expected OK');
});
// readonly: config set denied
await test('readonly.config.set() - denied', async () => {
try {
await readonly.config.set({});
throw new Error('Should have thrown');
} catch (e) {
if (!e.code && !e.status) throw e;
}
});
}
async function group4_noToken() {
console.log('\n— Group 4: No-Token Rejection —');
for (const [path, label] of [
['/cosmos/api/config', 'config'],
['/cosmos/api/servapps', 'servapps'],
['/cosmos/api/users', 'users'],
]) {
await test(`GET ${label} - no token rejected`, async () => {
expectStatus(await rawRequest(path, 'GET', null), 401, 'no token');
});
}
}
async function group5_invalidToken() {
console.log('\n— Group 5: Invalid Token —');
await test('status - invalid token rejected', async () => {
expectStatus(await rawRequest('/cosmos/api/status', 'GET', 'cosmos_invalidtoken'), 401, 'invalid token');
});
}
// --- Run ---
async function main() {
console.log(`Testing API tokens via cosmos-cloud-sdk against ${baseUrl}`);
console.log(`Admin token: ${adminToken.slice(0, 12)}...`);
console.log(`Readonly token: ${readonlyToken.slice(0, 12)}...`);
await group1_sdkBasicCalls();
await group2_sdkReadEndpoints();
await group3_sdkWriteEndpoints();
await group4_noToken();
await group5_invalidToken();
console.log(`\nResults: ${passed}/${passed + failed} passed`);
if (failed > 0) {
console.log(`${failed} test(s) FAILED`);
process.exit(1);
}
}
main().catch(err => {
console.error('Fatal error:', err);
process.exit(1);
});