-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsolid-oidc.js
More file actions
344 lines (286 loc) · 10.4 KB
/
solid-oidc.js
File metadata and controls
344 lines (286 loc) · 10.4 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
/**
* Solid-OIDC Resource Server
* Verifies DPoP-bound access tokens from external Identity Providers
*
* Flow:
* 1. User authenticates at external IdP (e.g., solidcommunity.net)
* 2. User gets DPoP-bound access token
* 3. User sends request with Authorization: DPoP <token> and DPoP: <proof>
* 4. We verify the token and DPoP proof
* 5. Extract WebID from token
*/
import * as jose from 'jose';
import { validateExternalUrl } from '../utils/ssrf.js';
// Cache for OIDC configurations and JWKS
const oidcConfigCache = new Map();
const jwksCache = new Map();
// Cache for DPoP jti values to prevent replay attacks
// Stores { jti: timestamp } entries, cleaned periodically
const dpopJtiCache = new Map();
const JTI_CACHE_CLEANUP_INTERVAL = 60 * 1000; // Clean every minute
// Cache TTL (15 minutes)
const CACHE_TTL = 15 * 60 * 1000;
// Trusted issuers (skip SSRF check) - populated by server config
const trustedIssuers = new Set();
/**
* Add a trusted issuer (e.g., the server's own issuer)
* Trusted issuers bypass SSRF validation since they're configured by admin
*/
export function addTrustedIssuer(issuer) {
const normalized = issuer.replace(/\/$/, '');
trustedIssuers.add(normalized);
trustedIssuers.add(normalized + '/');
}
// DPoP proof max age (5 minutes)
const DPOP_MAX_AGE = 5 * 60;
/**
* Clean expired jti entries from cache
* Called periodically to prevent memory growth
*/
function cleanupJtiCache() {
const now = Math.floor(Date.now() / 1000);
const expiredBefore = now - DPOP_MAX_AGE;
for (const [jti, timestamp] of dpopJtiCache.entries()) {
if (timestamp < expiredBefore) {
dpopJtiCache.delete(jti);
}
}
}
// Start periodic cleanup (unref so it doesn't keep process alive during tests)
setInterval(cleanupJtiCache, JTI_CACHE_CLEANUP_INTERVAL).unref();
/**
* Check if a jti has been used (replay attack prevention)
* @param {string} jti - The jti claim from DPoP proof
* @returns {boolean} - true if jti was already used
*/
function isJtiUsed(jti) {
return dpopJtiCache.has(jti);
}
/**
* Record a jti as used
* @param {string} jti - The jti claim from DPoP proof
* @param {number} iat - The issued-at timestamp
*/
function recordJti(jti, iat) {
dpopJtiCache.set(jti, iat);
}
/**
* Verify a Solid-OIDC request and extract WebID
* @param {object} request - Fastify request object
* @returns {Promise<{webId: string|null, error: string|null}>}
*/
export async function verifySolidOidc(request) {
const authHeader = request.headers.authorization;
const dpopHeader = request.headers.dpop;
// Check for DPoP authorization scheme
if (!authHeader || !authHeader.startsWith('DPoP ')) {
return { webId: null, error: null }; // Not a Solid-OIDC request
}
if (!dpopHeader) {
return { webId: null, error: 'Missing DPoP proof header' };
}
const accessToken = authHeader.slice(5); // Remove 'DPoP ' prefix
try {
// Step 1: Decode access token (without verification) to get issuer
const tokenPayload = jose.decodeJwt(accessToken);
const issuer = tokenPayload.iss;
if (!issuer) {
return { webId: null, error: 'Access token missing issuer' };
}
// Step 2: Verify DPoP proof
const dpopResult = await verifyDpopProof(dpopHeader, request, accessToken);
if (dpopResult.error) {
return { webId: null, error: dpopResult.error };
}
// Step 3: Fetch JWKS and verify access token
const jwks = await getJwks(issuer);
const { payload } = await jose.jwtVerify(accessToken, jwks, {
issuer,
clockTolerance: 30 // 30 seconds clock skew tolerance
});
// Step 4: Verify DPoP binding (cnf.jkt must match DPoP key thumbprint)
if (payload.cnf?.jkt) {
if (payload.cnf.jkt !== dpopResult.thumbprint) {
return { webId: null, error: 'DPoP key does not match token binding' };
}
}
// Step 5: Extract WebID
const webId = payload.webid || payload.sub;
if (!webId) {
return { webId: null, error: 'Token missing WebID claim' };
}
// Validate WebID is a valid URL
try {
new URL(webId);
} catch {
return { webId: null, error: 'Invalid WebID URL' };
}
return { webId, error: null };
} catch (err) {
// Handle specific JWT errors
if (err.code === 'ERR_JWT_EXPIRED') {
console.error('Solid-OIDC: Access token expired');
return { webId: null, error: 'Access token expired' };
}
if (err.code === 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED') {
console.error('Solid-OIDC: Invalid token signature');
return { webId: null, error: 'Invalid token signature' };
}
if (err.code === 'ERR_JWKS_NO_MATCHING_KEY') {
console.error('Solid-OIDC: No matching key found in JWKS');
return { webId: null, error: 'No matching key found in JWKS' };
}
console.error('Solid-OIDC verification error:', err.code, err.message);
return { webId: null, error: 'Token verification failed' };
}
}
/**
* Verify DPoP proof JWT
* @param {string} dpopProof - The DPoP proof JWT
* @param {object} request - Fastify request
* @param {string} accessToken - The access token (for ath claim verification)
* @returns {Promise<{thumbprint: string|null, error: string|null}>}
*/
async function verifyDpopProof(dpopProof, request, accessToken) {
try {
// Decode header to get the public key
const protectedHeader = jose.decodeProtectedHeader(dpopProof);
if (protectedHeader.typ !== 'dpop+jwt') {
return { thumbprint: null, error: 'Invalid DPoP proof type' };
}
if (!protectedHeader.jwk) {
return { thumbprint: null, error: 'DPoP proof missing jwk header' };
}
// Import the public key from the JWK in the header
const publicKey = await jose.importJWK(protectedHeader.jwk, protectedHeader.alg);
// Verify the DPoP proof signature
const { payload } = await jose.jwtVerify(dpopProof, publicKey, {
clockTolerance: 30
});
// Verify required claims
// htm: HTTP method
const expectedMethod = request.method.toUpperCase();
if (payload.htm !== expectedMethod) {
return { thumbprint: null, error: `DPoP htm mismatch: expected ${expectedMethod}` };
}
// htu: HTTP URI (without query string and fragment)
const requestUrl = `${request.protocol}://${request.hostname}${request.url.split('?')[0]}`;
// Normalize both URLs for comparison
const payloadHtu = payload.htu?.replace(/\/$/, '');
const expectedHtu = requestUrl.replace(/\/$/, '');
if (payloadHtu !== expectedHtu) {
// Also try without port for localhost
const altHtu = requestUrl.replace(/:(\d+)/, '').replace(/\/$/, '');
if (payloadHtu !== altHtu) {
return { thumbprint: null, error: `DPoP htu mismatch: expected ${expectedHtu}` };
}
}
// iat: Issued at (must be recent)
const now = Math.floor(Date.now() / 1000);
if (!payload.iat || Math.abs(now - payload.iat) > DPOP_MAX_AGE) {
return { thumbprint: null, error: 'DPoP proof expired or invalid iat' };
}
// jti: Unique identifier - track to prevent replay attacks
if (!payload.jti) {
return { thumbprint: null, error: 'DPoP proof missing jti' };
}
// Check for replay attack
if (isJtiUsed(payload.jti)) {
return { thumbprint: null, error: 'DPoP proof jti already used (replay attack prevented)' };
}
// Record jti to prevent future replay
recordJti(payload.jti, payload.iat);
// ath: Access token hash (optional but recommended)
if (payload.ath) {
const expectedAth = await calculateAth(accessToken);
if (payload.ath !== expectedAth) {
return { thumbprint: null, error: 'DPoP ath mismatch' };
}
}
// Calculate JWK thumbprint for binding verification
const thumbprint = await jose.calculateJwkThumbprint(protectedHeader.jwk, 'sha256');
return { thumbprint, error: null };
} catch (err) {
console.error('DPoP verification error:', err.code, err.message);
return { thumbprint: null, error: 'Invalid DPoP proof: ' + err.message };
}
}
/**
* Calculate access token hash (ath) for DPoP binding
*/
async function calculateAth(accessToken) {
const encoder = new TextEncoder();
const data = encoder.encode(accessToken);
const hash = await crypto.subtle.digest('SHA-256', data);
return jose.base64url.encode(new Uint8Array(hash));
}
/**
* Fetch and cache OIDC configuration
* SECURITY: Validates issuer URL to prevent SSRF attacks
*/
async function getOidcConfig(issuer) {
const cached = oidcConfigCache.get(issuer);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return cached.config;
}
// Check if this is a trusted issuer (e.g., our own server)
const normalizedIssuer = issuer.replace(/\/$/, '');
const isTrusted = trustedIssuers.has(normalizedIssuer) || trustedIssuers.has(normalizedIssuer + '/');
// SSRF Protection: Validate issuer URL before fetching (skip for trusted issuers)
if (!isTrusted) {
const validation = await validateExternalUrl(issuer, {
requireHttps: true,
blockPrivateIPs: true,
resolveDNS: true
});
if (!validation.valid) {
throw new Error(`Invalid OIDC issuer: ${validation.error}`);
}
}
const configUrl = `${issuer.replace(/\/$/, '')}/.well-known/openid-configuration`;
try {
const response = await fetch(configUrl);
if (!response.ok) {
throw new Error(`Failed to fetch OIDC config: ${response.status}`);
}
const config = await response.json();
oidcConfigCache.set(issuer, { config, timestamp: Date.now() });
return config;
} catch (err) {
console.error(`Failed to fetch OIDC config from ${issuer}:`, err.message);
throw err;
}
}
/**
* Get JWKS for an issuer (with caching)
*/
async function getJwks(issuer) {
const cached = jwksCache.get(issuer);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return cached.jwks;
}
// Get OIDC config to find JWKS URI
const config = await getOidcConfig(issuer);
const jwksUri = config.jwks_uri;
if (!jwksUri) {
throw new Error('OIDC config missing jwks_uri');
}
// Create a remote JWKS set
const jwks = jose.createRemoteJWKSet(new URL(jwksUri));
jwksCache.set(issuer, { jwks, timestamp: Date.now() });
return jwks;
}
/**
* Clear caches (useful for testing)
*/
export function clearCaches() {
oidcConfigCache.clear();
jwksCache.clear();
}
/**
* Check if request has Solid-OIDC authorization
*/
export function hasSolidOidcAuth(request) {
const authHeader = request.headers.authorization;
return authHeader && authHeader.startsWith('DPoP ');
}