-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathidp.test.js
More file actions
434 lines (361 loc) · 13.7 KB
/
idp.test.js
File metadata and controls
434 lines (361 loc) · 13.7 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
/**
* Identity Provider Tests
*/
import { describe, it, before, after, beforeEach } from 'node:test';
import assert from 'node:assert';
import { createServer } from '../src/server.js';
import fs from 'fs-extra';
import path from 'path';
const TEST_HOST = 'localhost';
import { createServer as createNetServer } from 'net';
/** Get an available port by briefly binding to port 0 */
async function getAvailablePort() {
return new Promise((resolve, reject) => {
const srv = createNetServer();
srv.on('error', (err) => reject(err));
srv.listen(0, TEST_HOST, () => {
const port = srv.address().port;
srv.close(() => resolve(port));
});
});
}
describe('Identity Provider', () => {
let server;
let baseUrl;
const DATA_DIR = './test-data-idp';
before(async () => {
await fs.remove(DATA_DIR);
await fs.ensureDir(DATA_DIR);
const port = await getAvailablePort();
baseUrl = `http://${TEST_HOST}:${port}`;
server = createServer({
logger: false,
root: DATA_DIR,
idp: true,
idpIssuer: baseUrl,
forceCloseConnections: true,
});
await server.listen({ port, host: TEST_HOST });
});
after(async () => {
await server.close();
await fs.remove(DATA_DIR);
});
describe('OIDC Discovery', () => {
it('should serve /.well-known/openid-configuration', async () => {
const res = await fetch(`${baseUrl}/.well-known/openid-configuration`);
assert.strictEqual(res.status, 200);
const config = await res.json();
// Issuer has trailing slash for CTH compatibility
assert.strictEqual(config.issuer, baseUrl + '/');
assert.ok(config.authorization_endpoint);
assert.ok(config.token_endpoint);
assert.ok(config.jwks_uri);
});
it('should include required Solid-OIDC endpoints', async () => {
const res = await fetch(`${baseUrl}/.well-known/openid-configuration`);
const config = await res.json();
assert.ok(config.registration_endpoint, 'should have registration endpoint');
assert.ok(config.scopes_supported.includes('webid'), 'should support webid scope');
assert.ok(config.dpop_signing_alg_values_supported, 'should support DPoP');
});
it('should serve /.well-known/jwks.json', async () => {
const res = await fetch(`${baseUrl}/.well-known/jwks.json`);
assert.strictEqual(res.status, 200);
const jwks = await res.json();
assert.ok(Array.isArray(jwks.keys));
assert.ok(jwks.keys.length > 0, 'should have at least one key');
// Keys should be public (no 'd' component)
assert.ok(!jwks.keys[0].d, 'should not expose private key component');
});
});
describe('Pod Creation with IdP', () => {
it('should require email when IdP is enabled', async () => {
const res = await fetch(`${baseUrl}/.pods`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'noemail' }),
});
assert.strictEqual(res.status, 400);
const body = await res.json();
assert.ok(body.error.includes('Email'));
});
it('should require password when IdP is enabled', async () => {
const res = await fetch(`${baseUrl}/.pods`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'nopass', email: '[email protected]' }),
});
assert.strictEqual(res.status, 400);
const body = await res.json();
assert.ok(body.error.includes('Password'));
});
it('should create pod with account', async () => {
const uniqueId = Date.now();
const res = await fetch(`${baseUrl}/.pods`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: `idpuser${uniqueId}`,
email: `idpuser${uniqueId}@example.com`,
password: 'securepassword123',
}),
});
assert.strictEqual(res.status, 201);
const body = await res.json();
assert.strictEqual(body.name, `idpuser${uniqueId}`);
assert.ok(body.webId.includes(`idpuser${uniqueId}`));
assert.ok(body.podUri.includes(`idpuser${uniqueId}`));
assert.ok(body.idpIssuer, 'should include IdP issuer');
assert.ok(body.loginUrl, 'should include login URL');
// Should NOT have simple token when IdP is enabled
assert.ok(!body.token, 'should not have simple token');
});
it('should reject duplicate email', async () => {
const uniqueId = Date.now();
const duplicateEmail = `duplicate${uniqueId}@example.com`;
// First user
await fetch(`${baseUrl}/.pods`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: `first${uniqueId}`,
email: duplicateEmail,
password: 'password123',
}),
});
// Second user with same email
const res = await fetch(`${baseUrl}/.pods`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: `second${uniqueId}`,
email: duplicateEmail,
password: 'password456',
}),
});
assert.strictEqual(res.status, 409);
const body = await res.json();
assert.ok(body.error.includes('Email'));
});
});
describe('Login Interaction', () => {
it('should respond to authorization endpoint', async () => {
const res = await fetch(`${baseUrl}/idp/auth?client_id=test&redirect_uri=http://localhost&response_type=code&scope=openid`, {
redirect: 'manual',
});
assert.ok(res.status >= 200 && res.status < 600, `got valid HTTP status ${res.status}`);
});
});
});
describe('Identity Provider - Accounts', () => {
let server;
let accountsUrl;
const ACCOUNTS_DATA_DIR = './test-data-idp-accounts';
before(async () => {
await fs.remove(ACCOUNTS_DATA_DIR);
await fs.ensureDir(ACCOUNTS_DATA_DIR);
const port = await getAvailablePort();
accountsUrl = `http://${TEST_HOST}:${port}`;
server = createServer({
logger: false,
root: ACCOUNTS_DATA_DIR,
idp: true,
idpIssuer: accountsUrl,
forceCloseConnections: true,
});
await server.listen({ port, host: TEST_HOST });
});
after(async () => {
await server.close();
await fs.remove(ACCOUNTS_DATA_DIR);
});
it('should store account data in .idp directory', async () => {
const uniqueName = `stored${Date.now()}`;
const uniqueEmail = `stored${Date.now()}@example.com`;
const res = await fetch(`${accountsUrl}/.pods`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: uniqueName,
email: uniqueEmail,
password: 'password123',
}),
});
assert.strictEqual(res.status, 201, 'pod creation should succeed');
// Check that account data exists
const accountsDir = path.join(ACCOUNTS_DATA_DIR, '.idp', 'accounts');
const exists = await fs.pathExists(accountsDir);
assert.ok(exists, 'accounts directory should exist');
// Check email index
const emailIndex = await fs.readJson(path.join(accountsDir, '_email_index.json'));
assert.ok(emailIndex[uniqueEmail], 'email index should contain account');
});
it('should hash passwords', async () => {
const uniqueName = `hashed${Date.now()}`;
const uniqueEmail = `hashed${Date.now()}@example.com`;
const res = await fetch(`${accountsUrl}/.pods`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: uniqueName,
email: uniqueEmail,
password: 'mypassword',
}),
});
assert.strictEqual(res.status, 201, 'pod creation should succeed');
// Read account file
const accountsDir = path.join(ACCOUNTS_DATA_DIR, '.idp', 'accounts');
const emailIndex = await fs.readJson(path.join(accountsDir, '_email_index.json'));
const accountId = emailIndex[uniqueEmail];
const account = await fs.readJson(path.join(accountsDir, `${accountId}.json`));
// Password should be hashed, not plain text
assert.ok(account.passwordHash, 'should have passwordHash');
assert.ok(account.passwordHash.startsWith('$2'), 'should be bcrypt hash');
assert.ok(!account.password, 'should not store plain password');
});
});
describe('Identity Provider - Credentials Endpoint', () => {
let server;
let credsUrl;
const CREDS_DATA_DIR = './data';
before(async () => {
await fs.emptyDir(CREDS_DATA_DIR);
const port = await getAvailablePort();
credsUrl = `http://${TEST_HOST}:${port}`;
server = createServer({
logger: false,
idp: true,
idpIssuer: credsUrl,
forceCloseConnections: true,
});
await server.listen({ port, host: TEST_HOST });
// Create a test user
const res = await fetch(`${credsUrl}/.pods`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'credtest',
email: '[email protected]',
password: 'testpassword123',
}),
});
if (!res.ok) {
throw new Error(`Failed to create test user: ${res.status} ${await res.text()}`);
}
});
after(async () => {
await server.close();
await fs.emptyDir(CREDS_DATA_DIR);
});
describe('GET /idp/credentials', () => {
it('should return endpoint info', async () => {
const res = await fetch(`${credsUrl}/idp/credentials`);
assert.strictEqual(res.status, 200);
const info = await res.json();
assert.ok(info.endpoint);
assert.strictEqual(info.method, 'POST');
assert.ok(info.parameters.email);
assert.ok(info.parameters.password);
});
});
describe('POST /idp/credentials', () => {
it('should return 400 for missing credentials', async () => {
const res = await fetch(`${credsUrl}/idp/credentials`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
assert.strictEqual(res.status, 400);
const body = await res.json();
assert.strictEqual(body.error, 'invalid_request');
});
it('should return 401 for wrong password', async () => {
const res = await fetch(`${credsUrl}/idp/credentials`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: '[email protected]',
password: 'wrongpassword',
}),
});
assert.strictEqual(res.status, 401);
const body = await res.json();
assert.strictEqual(body.error, 'invalid_grant');
});
it('should return 401 for unknown email', async () => {
const res = await fetch(`${credsUrl}/idp/credentials`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: '[email protected]',
password: 'anypassword',
}),
});
assert.strictEqual(res.status, 401);
});
it('should return access token for valid credentials', async () => {
const res = await fetch(`${credsUrl}/idp/credentials`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: '[email protected]',
password: 'testpassword123',
}),
});
assert.strictEqual(res.status, 200);
const body = await res.json();
assert.ok(body.access_token, 'should have access_token');
assert.strictEqual(body.token_type, 'Bearer');
assert.ok(body.expires_in > 0, 'should have expires_in');
assert.ok(body.webid.includes('credtest'), 'should have webid');
});
it('should return JWT token with webid claim', async () => {
const res = await fetch(`${credsUrl}/idp/credentials`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: '[email protected]',
password: 'testpassword123',
}),
});
const body = await res.json();
// JWT tokens have format: header.payload.signature
const parts = body.access_token.split('.');
assert.strictEqual(parts.length, 3, 'JWT token has 3 parts');
// Decode the payload (second part)
const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString());
assert.ok(payload.webid, 'token should have webid claim');
assert.ok(payload.webid.includes('credtest'), 'webid should reference user');
assert.ok(payload.exp > payload.iat, 'should have valid expiry');
});
it('should work with form-encoded body', async () => {
const res = await fetch(`${credsUrl}/idp/credentials`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'email=credtest%40example.com&password=testpassword123',
});
assert.strictEqual(res.status, 200);
const body = await res.json();
assert.ok(body.access_token);
});
it('should allow using token to access protected resource', async () => {
// Get access token
const tokenRes = await fetch(`${credsUrl}/idp/credentials`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: '[email protected]',
password: 'testpassword123',
}),
});
const { access_token } = await tokenRes.json();
// Try to access private resource
const res = await fetch(`${credsUrl}/credtest/private/`, {
headers: { 'Authorization': `Bearer ${access_token}` },
});
// Should succeed (not 401/403)
assert.ok([200, 404].includes(res.status), `expected 200 or 404, got ${res.status}`);
});
});
});