-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathlws-cid.test.js
More file actions
705 lines (640 loc) · 24.1 KB
/
lws-cid.test.js
File metadata and controls
705 lines (640 loc) · 24.1 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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
/**
* LWS10-CID JWT verifier tests
*
* Covers the verifier logic in isolation by stubbing global.fetch so we
* can hand-craft both the JWT and the profile document. Real end-to-end
* tests against a running server are filed as a follow-up.
*/
import { describe, it, before, beforeEach, after } from 'node:test';
import assert from 'node:assert';
import { secp256k1 } from '@noble/curves/secp256k1';
import { sha256 } from '@noble/hashes/sha256';
import * as jose from 'jose';
import { hasLwsCidAuth, verifyLwsCidAuth, _clearProfileCacheForTests } from '../src/auth/lws-cid.js';
// --- helpers ---------------------------------------------------------
function b64u(bytes) {
return Buffer.from(bytes).toString('base64')
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function jwkFromSecp256k1(privKey) {
const pub = secp256k1.getPublicKey(privKey, /*compressed=*/false); // 65 bytes: 0x04 || x || y
return {
kty: 'EC',
crv: 'secp256k1',
x: b64u(pub.slice(1, 33)),
y: b64u(pub.slice(33, 65)),
alg: 'ES256K',
};
}
function makeJwt({ privKey, header, payload }) {
const h64 = b64u(Buffer.from(JSON.stringify(header)));
const p64 = b64u(Buffer.from(JSON.stringify(payload)));
const signingInput = Buffer.from(`${h64}.${p64}`, 'utf8');
const msgHash = sha256(signingInput);
const sig = secp256k1.sign(msgHash, privKey);
// Compact 64-byte r||s — what JWS expects.
return `${h64}.${p64}.${b64u(sig.toCompactRawBytes())}`;
}
function makeRequest(token, { host = 'example.com', proto = 'https' } = {}) {
return {
headers: {
authorization: `Bearer ${token}`,
host,
},
protocol: proto,
};
}
const WEBID = 'https://example.com/profile/card.jsonld#me';
const DOC_URL = 'https://example.com/profile/card.jsonld';
const VM_ID = `${DOC_URL}#nostr-key-1`;
const POD_ORIGIN = 'https://example.com';
// Minimal CID-shaped profile.
function buildProfile(jwk, { withAuthRef = true, controller = WEBID } = {}) {
return {
'@context': {
cid: 'https://www.w3.org/ns/cid/v1#',
controller: { '@id': 'cid:controller', '@type': '@id' },
verificationMethod: { '@id': 'cid:verificationMethod', '@container': '@set' },
authentication: { '@id': 'cid:authentication', '@type': '@id', '@container': '@set' },
publicKeyJwk: { '@id': 'cid:publicKeyJwk', '@type': '@json' },
},
'@id': WEBID,
controller,
verificationMethod: [
{
id: VM_ID,
type: 'JsonWebKey',
controller: WEBID,
publicKeyJwk: jwk,
},
],
...(withAuthRef ? { authentication: [VM_ID] } : {}),
};
}
// --- fetch stub ------------------------------------------------------
const realFetch = global.fetch;
let nextProfile = null;
let nextStatus = 200;
// Per-URL response overrides — set { status, headers, body } per URL to
// inject redirects, oversized bodies, or non-default content-types.
let urlResponses = new Map();
function installFetchStub() {
global.fetch = async (url) => {
const u = String(url);
if (urlResponses.has(u)) {
const { status = 200, headers = {}, body = '' } = urlResponses.get(u);
return new Response(body, { status, headers });
}
if (u === DOC_URL) {
return new Response(JSON.stringify(nextProfile), {
status: nextStatus,
headers: { 'content-type': 'application/ld+json' },
});
}
return new Response('not found', { status: 404 });
};
}
function restoreFetch() { global.fetch = realFetch; }
// --- tests -----------------------------------------------------------
describe('hasLwsCidAuth', () => {
it('detects Bearer JWT with URL kid', () => {
const token = makeJwt({
privKey: secp256k1.utils.randomPrivateKey(),
header: { alg: 'ES256K', kid: VM_ID, typ: 'JWT' },
payload: { sub: WEBID, iss: WEBID, client_id: WEBID, iat: Math.floor(Date.now()/1000) },
});
assert.strictEqual(hasLwsCidAuth(makeRequest(token)), true);
});
it('rejects Bearer JWT with opaque fingerprint kid (looks like IDP JWT)', () => {
const token = makeJwt({
privKey: secp256k1.utils.randomPrivateKey(),
header: { alg: 'ES256K', kid: 'c1f52577', typ: 'JWT' },
payload: { sub: WEBID, iss: WEBID, client_id: WEBID, iat: Math.floor(Date.now()/1000) },
});
assert.strictEqual(hasLwsCidAuth(makeRequest(token)), false);
});
it('rejects DPoP', () => {
assert.strictEqual(hasLwsCidAuth({ headers: { authorization: 'DPoP eyJ...' } }), false);
});
it('rejects Nostr', () => {
assert.strictEqual(hasLwsCidAuth({ headers: { authorization: 'Nostr abc' } }), false);
});
it('rejects no authorization header', () => {
assert.strictEqual(hasLwsCidAuth({ headers: {} }), false);
});
it('rejects malformed JWT', () => {
assert.strictEqual(hasLwsCidAuth(makeRequest('not.a.jwt')), false);
});
it('rejects JWT with kid using non-http(s) scheme', () => {
const token = makeJwt({
privKey: secp256k1.utils.randomPrivateKey(),
header: { alg: 'ES256K', kid: 'urn:foo:bar#k1' },
payload: { sub: WEBID },
});
assert.strictEqual(hasLwsCidAuth(makeRequest(token)), false);
});
it('rejects JWT with unaccepted alg (e.g. HS256)', () => {
const token = makeJwt({
privKey: secp256k1.utils.randomPrivateKey(),
header: { alg: 'HS256', kid: VM_ID },
payload: { sub: WEBID },
});
assert.strictEqual(hasLwsCidAuth(makeRequest(token)), false);
});
});
describe('verifyLwsCidAuth', () => {
let priv;
let jwk;
// Default valid claims — tests can override per-case.
function claims(now = Math.floor(Date.now() / 1000), extra = {}) {
return { sub: WEBID, iss: WEBID, client_id: WEBID, aud: [POD_ORIGIN], iat: now, exp: now + 60, ...extra };
}
before(() => {
installFetchStub();
});
after(() => {
restoreFetch();
});
beforeEach(() => {
priv = secp256k1.utils.randomPrivateKey();
jwk = jwkFromSecp256k1(priv);
nextStatus = 200;
nextProfile = buildProfile(jwk);
urlResponses = new Map();
// Cache must not survive between tests; otherwise nextProfile
// changes are masked by a stale hit on DOC_URL.
_clearProfileCacheForTests();
});
it('verifies a valid ES256K JWT against a CID-shaped profile', async () => {
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID, typ: 'JWT' },
payload: claims(),
});
const result = await verifyLwsCidAuth(makeRequest(token));
assert.strictEqual(result.error, null);
assert.strictEqual(result.webId, WEBID);
});
it('rejects "none" alg', async () => {
const token = makeJwt({
privKey: priv,
header: { alg: 'none', kid: VM_ID, typ: 'JWT' },
payload: claims(),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.strictEqual(r.webId, null);
assert.match(r.error, /none/);
});
it('rejects missing alg with a distinct error (not the "none" message)', async () => {
// Built without an alg header. The detector would normally screen
// these out, but the verifier should still produce a clear error
// if called directly (defense-in-depth).
const h64 = b64u(Buffer.from(JSON.stringify({ kid: VM_ID, typ: 'JWT' })));
const p64 = b64u(Buffer.from(JSON.stringify(claims())));
const sig = b64u(Buffer.from('not-a-real-signature'));
const token = `${h64}.${p64}.${sig}`;
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /missing alg/);
assert.doesNotMatch(r.error, /"none"/);
});
it('rejects when sub != iss', async () => {
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(undefined, { iss: 'https://other.example/profile#me' }),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /sub.*iss.*client_id/);
});
it('rejects when kid is in a different document than sub', async () => {
const otherKid = 'https://other.example/profile/card.jsonld#k1';
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: otherKid },
payload: claims(),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /not in the subject/);
});
it('rejects expired JWT', async () => {
const past = Math.floor(Date.now() / 1000) - 3600;
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(past, { iat: past - 60, exp: past }),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /expired/);
});
it('rejects nbf in the future', async () => {
const now = Math.floor(Date.now() / 1000);
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(now, { nbf: now + 600 }),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /not yet valid/);
});
it('rejects iat too far in the future', async () => {
const now = Math.floor(Date.now() / 1000);
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(now, { iat: now + 600, exp: now + 1200 }),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /iat is in the future/);
});
it('rejects iat too old', async () => {
const now = Math.floor(Date.now() / 1000);
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(now, { iat: now - 7200, exp: now + 60 }),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /iat too old/);
});
it('rejects non-numeric exp', async () => {
const now = Math.floor(Date.now() / 1000);
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(now, { exp: '9999999999' }),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /exp claim/);
});
it('rejects non-numeric iat', async () => {
const now = Math.floor(Date.now() / 1000);
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(now, { iat: 'right-now' }),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /iat claim/);
});
it('rejects missing exp', async () => {
const now = Math.floor(Date.now() / 1000);
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(now, { exp: undefined }),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /exp claim is required/);
});
it('rejects missing iat', async () => {
const now = Math.floor(Date.now() / 1000);
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(now, { iat: undefined }),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /iat claim is required/);
});
it('rejects lifetime > 1 hour (replay window cap)', async () => {
const now = Math.floor(Date.now() / 1000);
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(now, { iat: now, exp: now + 7200 }),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /lifetime exceeds maximum/);
});
it('rejects exp <= iat', async () => {
const now = Math.floor(Date.now() / 1000);
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(now, { iat: now, exp: now }),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /exp must be after iat/);
});
it('rejects missing aud', async () => {
const now = Math.floor(Date.now() / 1000);
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(now, { aud: undefined }),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /aud claim is required/);
});
it('rejects when kid does not match any VM in the profile', async () => {
const ghostKid = `${DOC_URL}#nope`;
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: ghostKid },
payload: claims(),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /no verificationMethod/);
});
it('rejects when VM is not in authentication list', async () => {
nextProfile = buildProfile(jwk, { withAuthRef: false });
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /not listed in authentication/);
});
it('rejects when audience does not include this server', async () => {
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(undefined, { aud: ['https://elsewhere.example/'] }),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /aud.*does not include/);
});
it('rejects when server origin cannot be determined', async () => {
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(),
});
// No host header, no x-forwarded-host, no fastify hostname.
const req = { headers: { authorization: `Bearer ${token}` } };
const r = await verifyLwsCidAuth(req);
assert.match(r.error, /cannot determine server origin/);
});
it('honors x-forwarded-proto/host for aud check (behind reverse proxy)', async () => {
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(undefined, { aud: ['https://public.example'] }),
});
const req = {
headers: {
authorization: `Bearer ${token}`,
host: 'internal:8080',
'x-forwarded-proto': 'https',
'x-forwarded-host': 'public.example',
},
protocol: 'http',
};
const r = await verifyLwsCidAuth(req);
assert.strictEqual(r.error, null);
assert.strictEqual(r.webId, WEBID);
});
it('rejects tampered signature', async () => {
const valid = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(),
});
const parts = valid.split('.');
const sigBuf = Buffer.from(parts[2].replace(/-/g, '+').replace(/_/g, '/'), 'base64');
sigBuf[0] ^= 0xff;
parts[2] = b64u(sigBuf);
const tampered = parts.join('.');
const r = await verifyLwsCidAuth(makeRequest(tampered));
assert.match(r.error, /signature/);
});
it('rejects when VM is signed with different key than JWT', async () => {
const otherPriv = secp256k1.utils.randomPrivateKey();
nextProfile = buildProfile(jwkFromSecp256k1(otherPriv));
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /signature/);
});
it('rejects when profile fetch fails', async () => {
nextStatus = 404;
nextProfile = null;
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /could not fetch/);
});
it('rejects when CID document declares no subject (no @id / id)', async () => {
// Profile that's structurally complete enough to find a VM, but
// declares no top-level subject. This is rejected by the
// subject-identity check (which fires before the controller check
// — both layers exist as defense-in-depth).
nextProfile = {
'@context': { cid: 'https://www.w3.org/ns/cid/v1#' },
verificationMethod: [{
id: VM_ID,
type: 'JsonWebKey',
controller: WEBID,
publicKeyJwk: jwk,
}],
authentication: [VM_ID],
};
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /declares no subject/);
});
it("rejects when CID document's subject differs from JWT sub", async () => {
// Profile DOES declare a subject, but it's a different fragment
// than the JWT claims. Without this check, an attacker could
// serve a profile whose @id is "#bob" while the JWT claims "#alice"
// and reuse a VM controlled by bob.
nextProfile = {
...buildProfile(jwk),
'@id': 'https://example.com/profile/card.jsonld#bob',
};
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(), // sub = "...#me"
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /subject.*does not match JWT sub/);
});
it('normalizes origin (default port and case) on both sides of aud check', async () => {
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
// aud uses the explicit default port and uppercase scheme.
payload: claims(undefined, { aud: ['HTTPS://Example.COM:443'] }),
});
const req = {
headers: {
authorization: `Bearer ${token}`,
host: 'example.com', // no port, lowercase
},
protocol: 'https',
};
const r = await verifyLwsCidAuth(req);
assert.strictEqual(r.error, null);
assert.strictEqual(r.webId, WEBID);
});
it('rejects http: kid early with a clear message (not a generic SSRF failure)', async () => {
const httpKid = 'http://example.com/profile/card.jsonld#k1';
const httpSub = 'http://example.com/profile/card.jsonld#me';
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: httpKid },
payload: claims(undefined, { sub: httpSub, iss: httpSub, client_id: httpSub }),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /kid must use https/);
});
it('canonicalizes sub (case/default-port) before subject-identity check', async () => {
// JWT carries non-canonical sub/iss/client_id (uppercase scheme,
// explicit default port). Profile @id is canonical. After
// canonicalization, both should match and the returned webId is
// canonical (so downstream WAC ACL string matching works).
const noncanonical = 'HTTPS://Example.COM:443/profile/card.jsonld#me';
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(undefined, {
sub: noncanonical,
iss: noncanonical,
client_id: noncanonical,
}),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.strictEqual(r.error, null);
assert.strictEqual(r.webId, WEBID); // canonical form returned
});
it('canonicalizes kid (case/default-port) before matching VM ids', async () => {
// JWT carries a non-canonical kid (uppercase scheme + host,
// explicit default port); the profile's VM id is canonical.
// After URL-parse normalization both should match.
const nonCanonicalKid = 'HTTPS://Example.COM:443/profile/card.jsonld#nostr-key-1';
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: nonCanonicalKid },
payload: claims(),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.strictEqual(r.error, null);
assert.strictEqual(r.webId, WEBID);
});
it('handles comma-separated x-forwarded-host (multi-proxy chain)', async () => {
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(undefined, { aud: ['https://public.example'] }),
});
const req = {
headers: {
authorization: `Bearer ${token}`,
'x-forwarded-proto': 'https, http',
'x-forwarded-host': 'public.example, internal.lan',
},
};
const r = await verifyLwsCidAuth(req);
assert.strictEqual(r.error, null);
assert.strictEqual(r.webId, WEBID);
});
it('refuses cross-origin redirect during profile fetch', async () => {
urlResponses.set(DOC_URL, {
status: 302,
headers: { location: 'https://attacker.example/profile/card.jsonld' },
});
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /cross-origin redirect refused/);
});
it('rejects profile larger than the byte cap', async () => {
// 300 KB of JSON — over the 256 KB cap.
const huge = 'x'.repeat(300 * 1024);
urlResponses.set(DOC_URL, {
status: 200,
headers: { 'content-type': 'application/ld+json' },
body: JSON.stringify({ junk: huge }),
});
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /CID document too large/);
});
it('rejects when Content-Length header announces oversize body', async () => {
urlResponses.set(DOC_URL, {
status: 200,
headers: {
'content-type': 'application/ld+json',
'content-length': String(10 * 1024 * 1024), // 10 MB declared
},
body: JSON.stringify({}), // body is small but header lies
});
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: VM_ID },
payload: claims(),
});
const r = await verifyLwsCidAuth(makeRequest(token));
assert.match(r.error, /too large/);
});
it('SSRF: rejects kid pointing at localhost', async () => {
const localKid = 'https://localhost/profile/card.jsonld#me';
const token = makeJwt({
privKey: priv,
header: { alg: 'ES256K', kid: localKid },
payload: claims(undefined, {
sub: localKid, iss: localKid, client_id: localKid,
}),
});
const r = await verifyLwsCidAuth(makeRequest(token));
// SSRF guard fires inside fetchProfile and surfaces as "could not
// fetch CID document: SSRF protection: ...".
assert.match(r.error, /SSRF protection/);
});
// --- non-ES256K alg coverage (the jose-driven branch) -------------
describe('non-ES256K algorithms via jose', () => {
async function runHappyPath(alg) {
const kp = await jose.generateKeyPair(alg, { extractable: true });
const publicJwk = await jose.exportJWK(kp.publicKey);
publicJwk.alg = alg;
nextProfile = buildProfile(publicJwk);
const now = Math.floor(Date.now() / 1000);
const token = await new jose.SignJWT(claims(now))
.setProtectedHeader({ alg, kid: VM_ID, typ: 'JWT' })
.sign(kp.privateKey);
const r = await verifyLwsCidAuth(makeRequest(token));
assert.strictEqual(r.error, null, `unexpected error: ${r.error}`);
assert.strictEqual(r.webId, WEBID);
}
it('verifies ES256 (P-256)', async () => { await runHappyPath('ES256'); });
it('verifies EdDSA (Ed25519)', async () => { await runHappyPath('EdDSA'); });
it('verifies RS256 (RSA-2048)', async () => { await runHappyPath('RS256'); });
it('rejects RS256 with tampered payload', async () => {
const kp = await jose.generateKeyPair('RS256', { extractable: true, modulusLength: 2048 });
const publicJwk = await jose.exportJWK(kp.publicKey);
publicJwk.alg = 'RS256';
nextProfile = buildProfile(publicJwk);
const now = Math.floor(Date.now() / 1000);
const token = await new jose.SignJWT(claims(now))
.setProtectedHeader({ alg: 'RS256', kid: VM_ID })
.sign(kp.privateKey);
// Tamper with payload portion (middle section).
const parts = token.split('.');
const decoded = JSON.parse(Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString());
decoded.sub = 'https://attacker.example/#me';
parts[1] = b64u(Buffer.from(JSON.stringify(decoded)));
const tampered = parts.join('.');
const r = await verifyLwsCidAuth(makeRequest(tampered));
assert.notStrictEqual(r.error, null);
});
});
});