forked from panva/openid-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathissuer.js
284 lines (244 loc) · 8.03 KB
/
issuer.js
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
/* eslint-disable max-classes-per-file */
const { inspect } = require('util');
const url = require('url');
const jose = require('jose');
const pAny = require('p-any');
const LRU = require('lru-cache');
const objectHash = require('object-hash');
const { RPError } = require('./errors');
const getClient = require('./client');
const registry = require('./issuer_registry');
const processResponse = require('./helpers/process_response');
const webfingerNormalize = require('./helpers/webfinger_normalize');
const instance = require('./helpers/weak_cache');
const request = require('./helpers/request');
const { assertIssuerConfiguration } = require('./helpers/assert');
const {
ISSUER_DEFAULTS, OIDC_DISCOVERY, OAUTH2_DISCOVERY, WEBFINGER, REL, AAD_MULTITENANT_DISCOVERY,
} = require('./helpers/consts');
const AAD_MULTITENANT = Symbol('AAD_MULTITENANT');
class Issuer {
/**
* @name constructor
* @api public
*/
constructor(meta = {}) {
const aadIssValidation = meta[AAD_MULTITENANT];
delete meta[AAD_MULTITENANT];
['introspection', 'revocation'].forEach((endpoint) => {
// if intro/revocation endpoint auth specific meta is missing use the token ones if they
// are defined
if (
meta[`${endpoint}_endpoint`]
&& meta[`${endpoint}_endpoint_auth_methods_supported`] === undefined
&& meta[`${endpoint}_endpoint_auth_signing_alg_values_supported`] === undefined
) {
if (meta.token_endpoint_auth_methods_supported) {
meta[`${endpoint}_endpoint_auth_methods_supported`] = meta.token_endpoint_auth_methods_supported;
}
if (meta.token_endpoint_auth_signing_alg_values_supported) {
meta[`${endpoint}_endpoint_auth_signing_alg_values_supported`] = meta.token_endpoint_auth_signing_alg_values_supported;
}
}
});
Object.entries(meta).forEach(([key, value]) => {
instance(this).get('metadata').set(key, value);
if (!this[key]) {
Object.defineProperty(this, key, {
get() { return instance(this).get('metadata').get(key); },
enumerable: true,
});
}
});
instance(this).set('cache', new LRU({ max: 100 }));
registry.set(this.issuer, this);
Object.defineProperty(this, 'Client', {
value: getClient(this, aadIssValidation),
});
Object.defineProperty(this, 'FAPIClient', {
enumerable: true,
configurable: true,
get() {
process.emitWarning(
"The FAPI API implements an OIDF implementer's draft. Breaking draft implementations are included as minor versions of the openid-client library, therefore, the ~ semver operator should be used and close attention be payed to library changelog as well as the drafts themselves.",
'DraftWarning',
);
Object.defineProperty(this, 'FAPIClient', {
enumerable: true,
configurable: true,
value: class FAPIClient extends this.Client {},
});
return this.FAPIClient;
},
});
}
/**
* @name keystore
* @api public
*/
async keystore(reload = false) {
assertIssuerConfiguration(this, 'jwks_uri');
const keystore = instance(this).get('keystore');
const cache = instance(this).get('cache');
if (reload || !keystore) {
cache.reset();
const response = await request.call(this, {
method: 'GET',
responseType: 'json',
url: this.jwks_uri,
});
const jwks = processResponse(response);
const joseKeyStore = jose.JWKS.asKeyStore(jwks, { ignoreErrors: true });
cache.set('throttle', true, 60 * 1000);
instance(this).set('keystore', joseKeyStore);
return joseKeyStore;
}
return keystore;
}
/**
* @name queryKeyStore
* @api private
*/
async queryKeyStore({
kid, kty, alg, use, key_ops: ops,
}, { allowMulti = false } = {}) {
const cache = instance(this).get('cache');
const def = {
kid, kty, alg, use, key_ops: ops,
};
const defHash = objectHash(def, {
algorithm: 'sha256',
ignoreUnknown: true,
unorderedArrays: true,
unorderedSets: true,
});
// refresh keystore on every unknown key but also only upto once every minute
const freshJwksUri = cache.get(defHash) || cache.get('throttle');
const keystore = await this.keystore(!freshJwksUri);
const keys = keystore.all(def);
if (keys.length === 0) {
throw new RPError({
printf: ["no valid key found in issuer's jwks_uri for key parameters %j", def],
jwks: keystore,
});
}
if (!allowMulti && keys.length > 1 && !kid) {
throw new RPError({
printf: ["multiple matching keys found in issuer's jwks_uri for key parameters %j, kid must be provided in this case", def],
jwks: keystore,
});
}
cache.set(defHash, true);
return new jose.JWKS.KeyStore(keys);
}
/**
* @name metadata
* @api public
*/
get metadata() {
const copy = {};
instance(this).get('metadata').forEach((value, key) => {
copy[key] = value;
});
return copy;
}
/**
* @name webfinger
* @api public
*/
static async webfinger(input) {
const resource = webfingerNormalize(input);
const { host } = url.parse(resource);
const webfingerUrl = `https://${host}${WEBFINGER}`;
const response = await request.call(this, {
method: 'GET',
url: webfingerUrl,
responseType: 'json',
searchParams: { resource, rel: REL },
followRedirect: true,
});
const body = processResponse(response);
const location = Array.isArray(body.links) && body.links.find((link) => typeof link === 'object' && link.rel === REL && link.href);
if (!location) {
throw new RPError({
message: 'no issuer found in webfinger response',
body,
});
}
if (typeof location.href !== 'string' || !location.href.startsWith('https://')) {
throw new RPError({
printf: ['invalid issuer location %s', location.href],
body,
});
}
const expectedIssuer = location.href;
if (registry.has(expectedIssuer)) {
return registry.get(expectedIssuer);
}
const issuer = await this.discover(expectedIssuer);
if (issuer.issuer !== expectedIssuer) {
registry.delete(issuer.issuer);
throw new RPError('discovered issuer mismatch, expected %s, got: %s', expectedIssuer, issuer.issuer);
}
return issuer;
}
/**
* @name discover
* @api public
*/
static async discover(uri) {
const parsed = url.parse(uri);
if (parsed.pathname.includes('/.well-known/')) {
const response = await request.call(this, {
method: 'GET',
responseType: 'json',
url: uri,
});
const body = processResponse(response);
return new Issuer({
...ISSUER_DEFAULTS,
...body,
[AAD_MULTITENANT]: !!AAD_MULTITENANT_DISCOVERY.find(
(discoveryURL) => uri.startsWith(discoveryURL),
),
});
}
const uris = [];
if (parsed.pathname === '/') {
uris.push(`${OAUTH2_DISCOVERY}`);
} else {
uris.push(`${OAUTH2_DISCOVERY}${parsed.pathname}`);
}
if (parsed.pathname.endsWith('/')) {
uris.push(`${parsed.pathname}${OIDC_DISCOVERY.substring(1)}`);
} else {
uris.push(`${parsed.pathname}${OIDC_DISCOVERY}`);
}
return pAny(uris.map(async (pathname) => {
const wellKnownUri = url.format({ ...parsed, pathname });
const response = await request.call(this, {
method: 'GET',
responseType: 'json',
url: wellKnownUri,
});
const body = processResponse(response);
return new Issuer({
...ISSUER_DEFAULTS,
...body,
[AAD_MULTITENANT]: !!AAD_MULTITENANT_DISCOVERY.find(
(discoveryURL) => wellKnownUri.startsWith(discoveryURL),
),
});
}));
}
/* istanbul ignore next */
[inspect.custom]() {
return `${this.constructor.name} ${inspect(this.metadata, {
depth: Infinity,
colors: process.stdout.isTTY,
compact: false,
sorted: true,
})}`;
}
}
module.exports = Issuer;