forked from sbweeden/fido2-node-clients
-
Notifications
You must be signed in to change notification settings - Fork 0
/
isvclient.js
379 lines (336 loc) · 13.5 KB
/
isvclient.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
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
// get configuration in place
require('dotenv').config();
const logger = require('./logging.js');
const tm = require('./oauthtokenmanager.js');
const fido2error = require('./fido2error.js');
const commonServices = require('./commonservices.js');
const fidoutils = require('./fidoutils.js');
// hack to use a supplied access token
if (process.env.OIDC_USER_ACCESS_TOKEN != null) {
// just set it as expiring in 2 hours
tm.setTokenResponse({
expires_at_ms: (new Date().getTime() + (120*60*1000)),
access_token: process.env.OIDC_USER_ACCESS_TOKEN
});
}
//
// Caching logic to reduce number of calls to ISV
//
// cache to map rpId to rpUuid
var rpIdMap = {};
// cache to map rpUuid to rpId
var rpUuidMap = {};
// cache to map user lookup filters to ISV user
var userFilterMap = {};
function lookupUserWithFilter(userFilter) {
let usingMeResource = false;
let url = process.env.ISV_TENANT_ENDPOINT + "/v2.0/Users?" + new URLSearchParams({filter: userFilter});
return tm.getAccessToken()
.then((access_token) => {
if (process.env.OIDC_USER_ACCESS_TOKEN != null) {
url = process.env.ISV_TENANT_ENDPOINT + "/v2.0/Me";
usingMeResource = true;
}
//logger.logWithTS("lookupUserWithFilter usingMeResource: " + usingMeResource + " url: " + url);
return commonServices.timedFetch(
url,
{
bucket: process.env.ISV_TENANT_ENDPOINT + "/v2.0/Users?filter=<userFilter>",
method: "GET",
headers: {
"Accept": "application/scim+json",
"Authorization": "Bearer " + access_token
},
returnAsJSON: true
}
);
}).then((scimResponse) => {
let scimResource = null;
if (usingMeResource) {
// the /Me resource returns the scim response as the entire result
scimResource = scimResponse;
} else {
// should be exactly one result - if so, add to cache
if (scimResponse && scimResponse.totalResults == 1) {
scimResource = scimResponse.Resources[0];
}
}
if (scimResource != null) {
userFilterMap[userFilter] = scimResource;
}
return scimResource;
}).catch((e) => {
logger.logWithTS("isvclient.lookupUserWithFilter e: " + e + " stringify(e): " + (e != null ? JSON.stringify(e): "null"));
});
}
function usernameToId(username) {
let result = null;
let userFilter = 'username eq "' + username + '"';
if (userFilterMap[userFilter] != null) {
return userFilterMap[userFilter].id;
} else {
return lookupUserWithFilter(userFilter)
.then((scimResult) => {
// userFilterMap should be updated
if (userFilterMap[userFilter] != null) {
return userFilterMap[userFilter].id;
} else {
// fatal
throw new fido2error.fido2Error("userId could not be resolved");
}
}).catch((e) => {
let fido2Error = commonServices.normaliseError("userIdToUsername", e, "Error resolving username: " + username);
logger.logWithTS("usernameToId: Unable to resolve id for username: " + username + " error: " + JSON.stringify(fido2Error));
});
}
}
function updateRPMaps() {
// reads all relying parties from discovery service updates local caches
return tm.getAccessToken()
.then((access_token) => {
return commonServices.timedFetch(
process.env.ISV_TENANT_ENDPOINT + "/v2.0/factors/discover/fido2",
{
method: "GET",
headers: {
"Accept": "application/json",
"Authorization": "Bearer " + access_token
},
returnAsJSON: true
}
);
}).then((discoverResponse) => {
rpUuidMap = {};
rpIdMap = {};
// there is a response message schema change happening - tolerate the old and new...
var rpWrapper = (discoverResponse.fido2 != null ? discoverResponse.fido2 : discoverResponse);
rpWrapper.relyingParties.forEach((rp) => {
rpUuidMap[rp.id] = rp.rpId;
rpIdMap[rp.rpId] = rp.id;
});
}).catch((e) => {
logger.logWithTS("isvclient.updateRPMaps e: " + e + " stringify(e): " + (e != null ? JSON.stringify(e): "null"));
});
}
function rpIdTorpUuid(rpId) {
if (rpIdMap[rpId] != null) {
return rpIdMap[rpId];
} else {
return updateRPMaps()
.then(() => {
if (rpIdMap[rpId] != null) {
return rpIdMap[rpId];
} else {
// hmm - no rpId, fatal at this point.
throw new fido2error.fido2Error("rpId: " + rpId + " could not be resolved");
}
});
}
}
//
// this debugging function just reformats what ISV accepts into the standardised toJSON
// format that many other tools use for decoding
//
function isvSPKCToStandardPublicKeyCredentialJSON (spkc) {
// these are only required for this debugging method
const cbor = require('cbor'); // https://www.npmjs.com/package/cbor
const jsrsasign = require('jsrsasign'); // https://www.npmjs.com/package/jsrsasign
//
// copy
//
let result = JSON.parse(JSON.stringify(spkc));
//
// modify
//
// Delete rawId
delete result.rawId;
// Delete nickname
delete result.nickname;
// Delete enabled
delete result.enabled;
// Delete type
delete result.type;
// Change getClientExtensionResults to clientExtensionResults
result.clientExtensionResults = result.getClientExtensionResults;
delete result.getClientExtensionResults;
// Change getTransports to transports
result.transports = result.getTransports;
delete result.getTransports;
// Convert attestationObject from b64url to b64
result.response.attestationObject = jsrsasign.b64utob64(result.response.attestationObject);
// Add response.publicKeyAlgorithm and response.publicKey
let attestationObjectBytes = jsrsasign.b64toBA(jsrsasign.b64utob64(result.response.attestationObject));
let decodedAttestationObject = cbor.decode((new Uint8Array(attestationObjectBytes)).buffer);
let unpackedAuthData = fidoutils.unpackAuthData(fidoutils.bytesFromArray(decodedAttestationObject.authData, 0, -1));
result.response.publicKeyAlgorithm = unpackedAuthData.attestedCredData.credentialPublicKey["3"];
if (result.response.publicKeyAlgorithm == -7) {
// this is a dirty hack since we know we really only support EC256 keys in this client,
// and this is what the ASN.1 of SubjectPublicKeyInfo of an EC key looks like
// Its this magic string followed by the bytes of the x and y coordinates
result.response.publicKey = jsrsasign.hextob64(
"3059301306072A8648CE3D020106082A8648CE3D03010703420004"+
jsrsasign.BAtohex(unpackedAuthData.attestedCredData.credentialPublicKey["-2"]) +
jsrsasign.BAtohex(unpackedAuthData.attestedCredData.credentialPublicKey["-3"])
);
} else {
console.log("isvSPKCToStandardPublicKeyCredentialJSON: Unexpected algorithm for public key: " +result.response.publicKeyAlgorithm);
}
return result;
}
function performAttestation(username, attestationFormat) {
let access_token = null;
let rpUuid = null;
let authenticatorSelection = {
"userVerification": "required",
"requireResidentKey": true
};
if (attestationFormat == "fido-u2f") {
authenticatorSelection = {
"userVerification": "discouraged",
"requireResidentKey": false
};
}
let bodyToSend = {
"userId": "TBD",
"authenticatorSelection": authenticatorSelection
};
let result = {
credentialCreationResult: null,
attestationResultResponse: null
}
return tm.getAccessToken()
.then((at) => {
access_token = at;
}).then(() => {
return usernameToId(username);
}).then((iui) => {
bodyToSend.userId = iui;
return rpIdTorpUuid(process.env.RPID);
}).then((rpuniqueIdentifier) => {
rpUuid = rpuniqueIdentifier;
logger.logWithTS("performAttestation sending attestation options to ISV: " + JSON.stringify(bodyToSend));
return commonServices.timedFetch(
process.env.ISV_TENANT_ENDPOINT + "/v2.0/factors/fido2/relyingparties/" + rpUuid + "/attestation/options",
{
method: "POST",
headers: {
"Content-type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + access_token
},
body: JSON.stringify(bodyToSend),
returnAsJSON: true
}
);
}).then((attestationOptionsResponse) => {
//logger.logWithTS("performAttestation: attestationOptionsResponse: " + JSON.stringify(attestationOptionsResponse));
let cco = fidoutils.attestationOptionsResponeToCredentialCreationOptions(attestationOptionsResponse);
//logger.logWithTS("performAttestation: CredentialCreationOptions: " + JSON.stringify(cco));
let credentialCreationResult = fidoutils.processCredentialCreationOptions(cco, attestationFormat);
// add stuff required (and optional) for ISV
credentialCreationResult.spkc["nickname"] = "NodeClient - " + attestationOptionsResponse.challenge;
credentialCreationResult.spkc["enabled"] = true;
credentialCreationResult.spkc["getTransports"] = ["node"];
//logger.logWithTS("Standard JSON format SPKC: " + JSON.stringify(isvSPKCToStandardPublicKeyCredentialJSON(credentialCreationResult.spkc)));
logger.logWithTS("performAttestation sending attestation result to ISV: " + JSON.stringify(credentialCreationResult.spkc));
result.credentialCreationResult = credentialCreationResult;
return commonServices.timedFetch(
process.env.ISV_TENANT_ENDPOINT + "/v2.0/factors/fido2/relyingparties/" + rpUuid + "/attestation/result",
{
method: "POST",
headers: {
"Content-type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + access_token
},
body: JSON.stringify(credentialCreationResult.spkc),
returnAsJSON: true
}
);
}).then((attestationResultResponse) => {
logger.logWithTS("performAttestation got attestationResultResponse: " + JSON.stringify(attestationResultResponse));
result.attestationResultResponse = attestationResultResponse;
return result;
}).catch((e) => {
let fido2Error = commonServices.normaliseError("performAttestation", e, "Unable to complete attestation");
//logger.logWithTS("performAttestation got exception: " + JSON.stringify(fido2Error));
throw fido2Error;
});
}
/**
*
* Perform an assertion flow.
* The userId parameter is optional, but if supplied it must be the unique identifier of an ISV user and
* will be used in the /attestation/options call, which will retrieve a set of allowCredentials for the user.
* If performing a completely usernameless flow, pass it as null.
*
* The authenticatorRecords is required, as this contains a list of private keys that may be used for
* login. The authenticatorRecords is a map of credentialID to "record". This parameter should come from the results
* of a previous performAttestation call.
*
* Take a look at isv_example1.js for a demonstration of how to use this in combination with performAttestation.
*/
function performAssertion(userId, authenticatorRecords) {
let access_token = null;
let rpUuid = null;
let bodyToSend = {
"userVerification": "required"
};
if (userId != null) {
bodyToSend["userId"] = userId;
}
return tm.getAccessToken()
.then((at) => {
access_token = at;
}).then(() => {
return rpIdTorpUuid(process.env.RPID);
}).then((rpuniqueIdentifier) => {
rpUuid = rpuniqueIdentifier;
logger.logWithTS("performAssertion sending assertion options to ISV: " + JSON.stringify(bodyToSend));
return commonServices.timedFetch(
process.env.ISV_TENANT_ENDPOINT + "/v2.0/factors/fido2/relyingparties/" + rpUuid + "/assertion/options",
{
method: "POST",
headers: {
"Content-type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + access_token
},
body: JSON.stringify(bodyToSend),
returnAsJSON: true
}
);
}).then((assertionOptionsResponse) => {
// if performing the usernameless flow, make sure there are no allowCredentials in the list
if (userId == null) {
delete assertionOptionsResponse.allowCredentials;
}
logger.logWithTS("performAssertion: assertionOptionsResponse: " + JSON.stringify(assertionOptionsResponse));
let cro = fidoutils.assertionOptionsResponeToCredentialRequestOptions(assertionOptionsResponse);
let spkc = fidoutils.processCredentialRequestOptions(cro, authenticatorRecords);
logger.logWithTS("performAssertion sending assertion result to ISV: " + JSON.stringify(spkc));
return commonServices.timedFetch(
process.env.ISV_TENANT_ENDPOINT + "/v2.0/factors/fido2/relyingparties/" + rpUuid + "/assertion/result",
{
method: "POST",
headers: {
"Content-type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + access_token
},
body: JSON.stringify(spkc),
returnAsJSON: true
}
);
}).then((assertionResultResponse) => {
logger.logWithTS("performAssertion got assertionResultResponse: " + JSON.stringify(assertionResultResponse));
return assertionResultResponse;
}).catch((e) => {
let fido2Error = commonServices.normaliseError("performAssertion", e, "Unable to complete assertion");
throw fido2Error;
});
}
module.exports = {
performAttestation: performAttestation,
performAssertion: performAssertion
};