-
Notifications
You must be signed in to change notification settings - Fork 2
/
ciservices.js
1527 lines (1400 loc) · 44.8 KB
/
ciservices.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
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ciservices - performs user and FIDO2 operations against IBM Cloud Identity
//
const KJUR = require('jsrsasign');
const logger = require('./logging.js');
const tm = require('./oauthtokenmanager.js');
const fido2error = require('./fido2error.js');
const fidoutils = require('./fidoutils.js');
const tokenIntrospection = require('token-introspection')({
endpoint: process.env.CI_TENANT_ENDPOINT + '/v1.0/endpoint/default/introspect',
client_id: process.env.OAUTH_CLIENT_ID,
client_secret: process.env.OAUTH_CLIENT_SECRET
});
const txnprocessing = require('./txnprocessing.js');
//
// Caching logic to reduce number of calls to CI
//
// cache to map rpUuid to rpId
var rpUuidMap = {};
// cache to map rpId to rpUuid
var rpIdMap = {};
function handleErrorResponse(methodName, rsp, e, genericError) {
// log what we can about this error case
logger.logWithTS("ciservices." + methodName + " e: " +
e + " stringify(e): " + (e != null ? JSON.stringify(e): "null"));
var fidoError = null;
// if e is already a fido2Error, return it, otherwise try to perform discovery of
// the error message, otherwise return a generic error message
if (e != null && e.status == "failed") {
// seems to already be a fido2Error
fidoError = e;
} else if (e != null && e.error != null && e.error.messageId != null && e.error.messageDescription != null) {
// this looks like one of the typical CI error messages
fidoError = new fido2error.fido2Error(e.error.messageId + ": " + e.error.messageDescription);
} else {
// fallback to the generic error
fidoError = new fido2error.fido2Error(genericError);
}
logger.logWithTS("handleErrorResponse sending error response: " + JSON.stringify(fidoError));
rsp.json(fidoError);
}
/**
* Just calls fetch, but then does some standardized result/error handling for JSON-based API calls
*/
function myfetch(url, fetchOptions) {
let returnAsJSON = false;
if (fetchOptions["returnAsJSON"] != null) {
returnAsJSON = fetchOptions.returnAsJSON;
delete fetchOptions.returnAsJSON;
}
return fetch(
url,
fetchOptions
).then((result) => {
if (returnAsJSON) {
if (!result.ok) {
logger.logWithTS("myfetch unexpected result. status: " + result.status);
return result.text().then((txt) => {
throw new fido2error.fido2Error("Unexpected HTTP response code: " + result.status + (txt != null ? (" body: " + txt) : ""));
});
} else {
return result.json();
}
} else {
return result;
}
});
}
/**
* Ensure the request contains a "username" attribute, and make sure it's either the
* empty string (if allowed), or is the username of the currently authenticated user.
*/
function validateSelf(fidoRequest, username, allowEmptyUsername) {
if (username != null) {
if (!((fidoRequest.username == username) || (allowEmptyUsername && fidoRequest.username == ""))) {
throw new fido2error.fido2Error("Invalid username in request");
}
} else {
// no currently authenticated user
// only permitted if fidoRequest.username is the empty string and allowEmptyUsername
if (!(fidoRequest.username == "" && allowEmptyUsername)) {
throw new fido2error.fido2Error("Not authenticated");
}
}
return fidoRequest;
}
/**
* Proxies what is expected to be a valid FIDO2 server request to one of:
* /attestation/options
* /attestation/result
* /assertion/options
* /assertion/result
*
* to the CI server. There is little validation done other than to ensure
* that the client is not sending a request for a user other than the user
* who is currently logged in.
*/
function proxyFIDO2ServerRequest(req, rsp, validateUsername, allowEmptyUsername) {
var bodyToSend = validateUsername ? validateSelf(req.body, req.session.username, allowEmptyUsername) : req.body;
// the CI body is slightly different from the FIDO server spec.
// instead of username (validity of which has already been checked above),
// we need to provide userId which is the CI IUI for the user.
if (bodyToSend.username != null) {
delete bodyToSend.username;
if (req.session.userSCIMId) {
bodyToSend.userId = req.session.userSCIMId;
}
}
// when performing registrations, I want the registration
// enabled immediately so insert this additional option
if (req.url.endsWith("/attestation/result")) {
bodyToSend.enabled = true;
}
var access_token = null;
tm.getAccessToken(req)
.then( (at) => {
access_token = at;
return rpIdTorpUuid(process.env.RPID);
}).then((rpUuid) => {
var options = {
method: "POST",
headers: {
"Content-type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + access_token
},
returnAsJSON: true,
body: JSON.stringify(bodyToSend)
};
logger.logWithTS("proxyFIDO2ServerRequest.options: " + JSON.stringify(options));
return myfetch(
process.env.CI_TENANT_ENDPOINT + "/v2.0/factors/fido2/relyingparties/" + rpUuid + req.url,
options
);
}).then((proxyResponse) => {
// worked - add server spec status and error message fields
var rspBody = proxyResponse;
rspBody.status = "ok";
rspBody.errorMessage = "";
logger.logWithTS("proxyFIDO2ServerRequest.success: " + JSON.stringify(rspBody));
rsp.json(rspBody);
}).catch((e) => {
handleErrorResponse("proxyFIDO2ServerRequest", rsp, e, "Unable to proxy FIDO2 request");
});
}
/**
* Lookup RP's rpUuid from an rpId
*/
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");
}
});
}
}
/**
* Performs an assertion result to the FIDO2 server, and if successful, completes
* the login process.
*/
function validateFIDO2Login(req, rsp) {
var bodyToSend = req.body;
var access_token = null;
tm.getAccessToken(req).then((at) => {
access_token = at;
return rpIdTorpUuid(process.env.RPID);
}).then((rpUuid) => {
return myfetch(
process.env.CI_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(bodyToSend),
returnAsJSON: true
}
);
}).then((assertionResult) => {
// FIDO2 login worked
logger.logWithTS("validateFIDO2Login.assertionResult: " + JSON.stringify(assertionResult));
// lookup user from id to make sure they are real and still active
return myfetch(
process.env.CI_TENANT_ENDPOINT + "/v2.0/Users?" + new URLSearchParams({ "filter" : 'id eq "' + assertionResult.userId + '"' }),
{
method: "GET",
headers: {
"Accept": "application/scim+json",
"Authorization": "Bearer " + access_token
},
returnAsJSON: true
}
);
}).then((scimResponse) => {
if (scimResponse && scimResponse.totalResults == 1) {
if (scimResponse.Resources[0].active) {
// ok to login
req.session.userSCIMId = scimResponse.Resources[0].id;
req.session.username = scimResponse.Resources[0].userName;
req.session.userDisplayName = getDisplayNameFromSCIMResponse(scimResponse.Resources[0]);
return getUserResponse(req);
} else {
throw new fido2error.fido2Error("User disabled");
}
} else {
throw new fido2error.fido2Error("User record not found");
}
}).then((userResponse) => {
rsp.json(userResponse);
}).catch((e) => {
handleErrorResponse("validateFIDO2Login", rsp, e, "Unable to perform FIDO2 login");
});
}
/**
* First checks that the registration identified by the provided id is owned by the currently
* logged in user, then Uses a DELETE operation to delete it.
* Returns the remaining registered credentials in the same format as sendUserResponse.
*/
function deleteRegistration(req, rsp) {
if (req.session.username) {
var regId = req.body.id;
if (regId != null) {
var access_token = null;
tm.getAccessToken(req).then((at) => {
access_token = at;
// first search for the suggested registration
return myfetch(
process.env.CI_TENANT_ENDPOINT + "/v2.0/factors/fido2/registrations/" + regId,
{
method: "GET",
headers: {
"Accept": "application/json",
"Authorization": "Bearer " + access_token
},
returnAsJSON: true
}
);
}).then((regToDelete) => {
// is it owned by the currenty authenticated user
if (regToDelete.userId == req.session.userSCIMId) {
return myfetch(
process.env.CI_TENANT_ENDPOINT + "/v2.0/factors/fido2/registrations/" + regId,
{
method: "DELETE",
headers: {
"Accept": "application/json",
"Authorization": "Bearer " + access_token
}
}
).then(() => {
logger.logWithTS("Registration deleted: " + regId);
});
} else {
throw new fido2error.fido2Error("Not owner of registration");
}
}).then((deleteResult) => {
// we care not about the deleteRequest - just build and send the user response
sendUserResponse(req, rsp);
}).catch((e) => {
handleErrorResponse("deleteRegistration", rsp, e, "Unable to delete registration");
});
} else {
rsp.json(new fido2error.fido2Error("Invalid id in request"));
}
} else {
rsp.json(new fido2error.fido2Error("Not logged in"));
}
}
/**
* Returns the details of the indicated registration, provided it is owned by the currently
* logged in user.
*/
function registrationDetails(req, rsp) {
if (req.session.username) {
var regId = req.query.id;
if (regId != null) {
var access_token = null;
tm.getAccessToken(req).then((at) => {
access_token = at;
// first retrieve the suggested registration
return myfetch(
process.env.CI_TENANT_ENDPOINT + "/v2.0/factors/fido2/registrations/" + regId,
{
method: "GET",
headers: {
"Accept": "application/json",
"Authorization": "Bearer " + access_token
},
returnAsJSON: true
}
);
}).then((reg) => {
logger.logWithTS("registrationDetails." + regId + " received: " + JSON.stringify(reg));
// check it is owned by the currenty authenticated user
if (reg.userId == req.session.userSCIMId) {
// if there are any transactions associated with this registration, add them in for display
let txns = txnprocessing.getTransactionsForCredentialID(reg.attributes.credentialId);
reg.attributes.transactions = txns;
rsp.json(reg);
} else {
throw new fido2error.fido2Error("Not owner of registration");
}
}).catch((e) => {
handleErrorResponse("registrationDetails", rsp, e, "Unable to retrieve registration");
});
} else {
rsp.json(new fido2error.fido2Error("Invalid id in request"));
}
} else {
rsp.json(new fido2error.fido2Error("Not logged in"));
}
}
function getDisplayNameFromSCIMResponse(scimResponse) {
var result = scimResponse.userName;
if (scimResponse.name != null && scimResponse.name.formatted != null) {
result = scimResponse.name.formatted;
}
return result;
}
function validateUsernamePassword(req, rsp) {
var username = req.body.username;
var password = req.body.password;
var access_token = null;
return tm.getAccessToken(req)
.then((at) => {
access_token = at;
return myfetch(
process.env.CI_TENANT_ENDPOINT + "/v2.0/Users/authentication",
{
method: "POST",
headers: {
"Authorization": "Bearer " + access_token,
"Content-type": "application/scim+json",
"Accept": "application/scim+json"
},
body: JSON.stringify({
"userName" : username,
"password": password,
"schemas": ["urn:ietf:params:scim:schemas:ibm:core:2.0:AuthenticateUser"]
}),
returnAsJSON: true
}
);
}).then((authenticationResponse) => {
// username/password ok
// get full user profile so that we can check user active and get display name
return myfetch(
process.env.CI_TENANT_ENDPOINT + "/v2.0/Users?" + new URLSearchParams({ "filter" : 'id eq "' + authenticationResponse.id + '"' }),
{
method: "GET",
headers: {
"Accept": "application/scim+json",
"Authorization": "Bearer " + access_token
},
returnAsJSON: true
}
);
}).then((scimResponse) => {
//logger.logWithTS("ciservices.validateUsernamePassword got scimResponse: " + JSON.stringify(scimResponse));
if (scimResponse && scimResponse.totalResults == 1) {
if (scimResponse.Resources[0].active) {
// ok to login
req.session.userSCIMId = scimResponse.Resources[0].id;
req.session.username = scimResponse.Resources[0].userName;
req.session.userDisplayName = getDisplayNameFromSCIMResponse(scimResponse.Resources[0]);
return getUserResponse(req);
} else {
throw new fido2error.fido2Error("User disabled");
}
} else {
throw new fido2error.fido2Error("User record not found");
}
}).then((userResponse) => {
rsp.json(userResponse);
}).catch((e) => {
logger.logWithTS("ciservices.validateUsernamePassword inside catch block with e: " + (e != null ? JSON.stringify(e): "null"));
rsp.json(e);
});
}
function updateRPMaps() {
// reads all relying parties from discovery service updates local caches
return tm.getAccessToken(null)
.then((access_token) => {
return myfetch(
process.env.CI_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("ciservices.updateRPMaps e: " + e + " stringify(e): " + (e != null ? JSON.stringify(e): "null"));
});
}
function updateRegistrationsFromMaps(registrationsResponse) {
registrationsResponse.fido2.forEach((reg) => {
reg.rpId = (rpUuidMap[reg.references.rpUuid] ? rpUuidMap[reg.references.rpUuid] : "UNKNOWN");
});
return registrationsResponse;
}
function coerceCIRegistrationsToClientFormat(registrationsResponse) {
return new Promise((resolve, reject) => {
// Do this check so we only lookup each unknown rpUuid all at once
var anyUnresolvedRpUuids = false;
for (var i = 0; i < registrationsResponse.fido2.length && !anyUnresolvedRpUuids; i++) {
if (rpUuidMap[registrationsResponse.fido2[i].references.rpUuid] == null) {
anyUnresolvedRpUuids = true;
}
}
// if we need to, refresh the rpUuidMap
if (anyUnresolvedRpUuids) {
updateRPMaps()
.then(() => {
resolve(updateRegistrationsFromMaps(registrationsResponse));
});
} else {
resolve(updateRegistrationsFromMaps(registrationsResponse));
}
});
}
function getUserResponse(req) {
var username = req.session.username;
var userId = req.session.userSCIMId;
var displayName = req.session.userDisplayName;
var result = { "authenticated": true, "username": username, "displayName": displayName, "credentials": []};
var search = 'userId="' + userId + '"';
// to futher filter results for just my rpId, add this
search += '&attributes/rpId="'+process.env.RPID+'"';
return tm.getAccessToken(req)
.then((access_token) => {
// This includes an example of how to measure the response time for a call
var start = (new Date()).getTime();
return myfetch(
process.env.CI_TENANT_ENDPOINT + "/v2.0/factors/fido2/registrations?" + new URLSearchParams({ "search" : search}),
{
method: "GET",
headers: {
"Accept": "application/json",
"Authorization": "Bearer " + access_token
},
returnAsJSON: true
}
).then((r) => {
var now = (new Date()).getTime();
console.log("getUserResponse: call to get user registrations took(msec): " + (now-start));
return r;
});
}).then((registrationsResponse) => {
return coerceCIRegistrationsToClientFormat(registrationsResponse);
}).then((registrationsResponse) => {
result.credentials = registrationsResponse.fido2;
// for each credential add any transactions if present
if (result.credentials != null) {
for (let i = 0; i < result.credentials.length; i++) {
let txns = txnprocessing.getTransactionsForCredentialID(result.credentials[i].attributes.credentialId);
result.credentials[i].attributes.transactions = txns;
}
}
return result;
});
}
/**
* Determines if the user is logged in.
* If so, returns their username and list of currently registered FIDO2 credentials as determined from a CI API.
* If not returns {"authenticated":false}
*/
function sendUserResponse(req, rsp) {
if (req.session.username) {
var access_token = null;
getUserResponse(req)
.then((userResponse) => {
rsp.json(userResponse);
}).catch((e) => {
handleErrorResponse("sendUserResponse", rsp, e, "Unable to get user registrations");
});
} else {
rsp.json({"authenticated": false});
}
}
/**
* Start of section dedicated to APIs used by the android app
*/
// Debugging utility
function logRequest(api, req) {
console.log("API: " + api);
console.log("req keys: " + Object.keys(req));
console.log("req query: " + (req.query == null ? "" : JSON.stringify(req.query)));
console.log("req params: " + (req.params == null ? "" : JSON.stringify(req.params)));
console.log("req body: " + (req.body == null ? "" : JSON.stringify(req.body)));
console.log("req cookies: " + (req.cookies == null ? "" : JSON.stringify(req.cookies)));
}
/**
* Promise-based function to return username and credentials response
*/
function getUsernameAndCredentialsResponse(req, username, requireSignedInCookie) {
var result = {};
// For this simple app, username is determined if two cookies exist
// signed-in=yes
// username=<value>
// in a real app that should be replaced with oauth access tokens....
if (username == null) {
username = req.cookies["username"];
}
if (username != null && (!requireSignedInCookie || req.cookies["signed-in"] == "yes")) {
result["username"] = req.cookies["username"];
var access_token = null;
var rpUuid = null;
var userId = null;
return tm.getAccessToken(req)
.then((at) => {
access_token = at;
return rpIdTorpUuid(process.env.RPID);
}).then((ruu) => {
rpUuid = ruu;
// now resolve username to userId
return myfetch(
process.env.CI_TENANT_ENDPOINT + "/v2.0/Users?" + new URLSearchParams({ "filter" : 'userName eq "' + username + '"' }),
{
method: "GET",
headers: {
"Accept": "application/scim+json",
"Authorization": "Bearer " + access_token
},
returnAsJSON: true
}
);
}).then((scimResponse) => {
if (scimResponse && scimResponse.totalResults == 1) {
if (scimResponse.Resources[0].active) {
// ok to proceed
userId = scimResponse.Resources[0].id;
result["id"] = userId;
//
// Search based on userId and filter on the rpUuid as well
//
var search = 'userId="' + userId + '"';
search += '&references/rpUuid="'+rpUuid+'"';
var url = process.env.CI_TENANT_ENDPOINT + "/v2.0/factors/fido2/registrations?" + new URLSearchParams({ "search" : search});
var options = {
method: "GET",
headers: {
"Accept": "application/json",
"Authorization": "Bearer " + access_token
},
returnAsJSON: true
};
var start = (new Date()).getTime();
return myfetch(
url,
options
).then((r) => {
var now = (new Date()).getTime();
console.log("getUsernameAndCredentialsResponse: call to get user registrations with options: " + JSON.stringify(options) + " took(msec): " + (now-start));
return r;
});
} else {
throw "user not active";
}
} else {
throw "user not found";
}
}).then((registrationsResponse) => {
// populate result credentials - filter to only include those for our rpID
result["credentials"] = [];
registrationsResponse.fido2.forEach((reg) => {
if (reg.attributes.rpId == process.env.RPID) {
// determine aaguidStr and publicKeyPEM
var aaguidStr = reg.attributes.aaGuid;
if (aaguidStr == null) {
aaguidStr = "00000000-0000-0000-0000-000000000000";
}
var coseKey = fidoutils.publicKeyStringToCOSEKey(reg.attributes.credentialPublicKey);
var pk = fidoutils.coseKeyToPublicKey(coseKey);
var publicKeyPEM = fidoutils.publicKeyToPEM(pk);
result.credentials.push({
"credId": reg.attributes.credentialId,
"aaguid": KJUR.hextob64u(aaguidStr.replace(/-/g,"")),
"publicKey": publicKeyPEM,
"prevCounter": (reg.attributes.counter != null ? reg.attributes.counter : 0)
});
}
});
// done
return result;
}).catch((e) => {
console.log("getUsernameAndCredentialsResponse exception: " + e);
result = {};
return result;
});
} else {
debugLog("getUsernameAndCredentialsResponse: It doesn't appear there is any user signed in!");
}
return result;
}
function androidAssetLinks(req, rsp) {
rsp.json(
[
{
"relation": [
"delegate_permission/common.handle_all_urls",
"delegate_permission/common.get_login_creds"
],
"target": {
"namespace": "web",
"site": "https://" + process.env.RPID
}
},
{
"relation": [
"delegate_permission/common.handle_all_urls",
"delegate_permission/common.get_login_creds"
],
"target": {
"namespace": "android_app",
"package_name": "com.example.android.fido2",
"sha256_cert_fingerprints": [
process.env.ANDROID_CERT_FINGERPRINT
]
}
}
]
);
}
function sendAndroidResponse(rsp, result) {
//console.log("sendAndroidResponse: called with result: " + JSON.stringify(result));
if (result.cookies) {
result.cookies.forEach((c) => {
//rsp.set('set-cookie', c);
rsp.cookie(c.name, c.value, c.options);
});
}
if (result.status != "ok") {
rsp.status(400);
}
rsp.json(result.body);
}
function androidUsername(req, rsp) {
//logRequest("androidUsername", req);
var result = {
"status": "ok",
"body": {},
"cookies": []
};
var username = req.body.username;
if (username != null) {
getUsernameAndCredentialsResponse(req, username, false)
.then((ucr) => {
result.body = ucr;
result.cookies.push({"name": "username", "value": username, "options": { "path": "/"}});
sendAndroidResponse(rsp, result);
}).catch((e) => {
result.status = "failed";
result.body = {"error": "androidUsername unexpected error"};
sendAndroidResponse(rsp, result);
});
} else {
result.status = "failed";
result.body = { "error": "no username supplied" };
sendAndroidResponse(rsp, result);
}
}
function androidPassword(req, rsp) {
logRequest("androidPassword", req);
var result = {
"status": "ok",
"body": {},
"cookies": []
};
var username = req.cookies["username"];
var password = req.body.password;
if (username != null && password != null) {
// validate username and password against CI
tm.getAccessToken(req)
.then((access_token) => {
return myfetch(
process.env.CI_TENANT_ENDPOINT + "/v2.0/Users/authentication",
{
method: "POST",
headers: {
"Authorization": "Bearer " + access_token,
"Content-type": "application/scim+json",
"Accept": "application/scim+json"
},
body: JSON.stringify({
"userName" : username,
"password": password,
"schemas": ["urn:ietf:params:scim:schemas:ibm:core:2.0:AuthenticateUser"]
}),
returnAsJSON: true
}
);
}).then((scimResponse) => {
// logged in ok
return getUsernameAndCredentialsResponse(req, username, false);
}).then((ucr) => {
result.body = ucr;
result.cookies.push({"name": "signed-in", "value": "yes", "options": {"path": "/"}});
sendAndroidResponse(rsp, result);
}).catch((e) => {
console.log(e);
result.status = "failed";
result.body = {"error": "androidPassword authentication failed"};
sendAndroidResponse(rsp, result);
});
} else {
result.status = "failed";
result.body = { "error": "no username and password available" };
sendAndroidResponse(rsp, result);
}
}
function androidGetKeys(req, rsp) {
logRequest("androidGetKeys", req);
var result = {
"status": "ok",
"body": {
},
"cookies" : [
]
};
getUsernameAndCredentialsResponse(req, null, false)
.then((ucr) => {
result.body = ucr;
sendAndroidResponse(rsp, result);
}).catch((e) => {
console.log(e);
result.status = "failed";
result.body = {"error": "androidGetKeys unexpected error"};
sendAndroidResponse(rsp, result);
});
}
function androidRegisterRequest(req, rsp) {
logRequest("androidRegisterRequest", req);
var result = {
"status": "ok",
"body": {
},
"cookies" : [
]
};
var username = req.cookies["username"];
if (username != null) {
tm.getAccessToken(req)
.then((at) => {
access_token = at;
return rpIdTorpUuid(process.env.RPID);
}).then((ruu) => {
rpUuid = ruu;
// now resolve username to check it's legit, and get display name
return myfetch(
process.env.CI_TENANT_ENDPOINT + "/v2.0/Users?" + new URLSearchParams({ "filter" : 'userName eq "' + username + '"' }),
{
method: "GET",
headers: {
"Accept": "application/scim+json",
"Authorization": "Bearer " + access_token
},
returnAsJSON: true
}
);
}).then((scimResponse) => {
if (scimResponse && scimResponse.totalResults == 1) {
if (scimResponse.Resources[0].active) {
// ok to proceed
var user = scimResponse.Resources[0];
var displayName = username;
if (user.name != null && user.name.formatted != null && user.name.formatted.length > 0) {
displayName = user.name.formatted;
}
// prepare attestation options body for CI
var reqBody = {
"userId": user.id,
"displayName": displayName
};
if (req.body.attestation != null) {
reqBody["attestation"] = req.body.attestation;
}
if (req.body.authenticatorSelection != null) {
reqBody["authenticatorSelection"] = req.body.authenticatorSelection;
}
// call CI
return myfetch(
process.env.CI_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(reqBody),
returnAsJSON: true
}
);
} else {
throw "user not active";
}
} else {
throw "user not found";
}
}).then((rspBody) => {
// remove these - the android app doesn't understand them
delete rspBody["status"];
delete rspBody["errorMessage"];
delete rspBody["extensions"];
// also the androidapp only understands one algorithm, and if you pass it others, it fails
rspBody.pubKeyCredParams = [ { "alg": -7, "type": "public-key" } ];
result.body = rspBody;
sendAndroidResponse(rsp, result);
}).catch((e) => {
console.log(e);
result.status = "failed";
result.body = {"error": "androidRegisterRequest unexpected error"};
sendAndroidResponse(rsp, result);
});
} else {
result.status = "failed";
result.body = { "error": "no username supplied" };
sendAndroidResponse(rsp, result);
}
}
function androidRegisterResponse(req, rsp) {
logRequest("androidRegisterResponse", req);
var result = {
"status": "ok",
"body": {
},
"cookies" : [
]
};
// we require these to be present
var id = req.body.id;
var rawId = req.body.rawId;
var type = req.body.type;
var response = req.body.response;
var getClientExtensionResults = {};
if (req.body.getClientExtensionResults != null) {
getClientExtensionResults = req.body.getClientExtensionResults
}
if (id != null && rawId != null && type != null && response != null) {
// if friendlyName is provided, use it, otherwise call it "android-<datestr>"
var nickname = req.body.nickname;
if (nickname == null) {
nickname = "androidapp-" + (new Date()).toISOString();
}
// validate the registration via the FIDO2 server
tm.getAccessToken(req)
.then((at) => {
access_token = at;
return rpIdTorpUuid(process.env.RPID);
}).then((ruu) => {
rpUuid = ruu;
reqBody = {
"nickname": nickname,
"id": id,
"rawId": rawId,
"type": type,
"response": response,
"getClientExtensionResults": getClientExtensionResults,
"enabled": true
};
return myfetch(
process.env.CI_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(reqBody),
returnAsJSON: true
}
);
}).then((rspBody) => {
// worked
return getUsernameAndCredentialsResponse(req, null, false);
}).then((ucr) => {
result.body = ucr;
sendAndroidResponse(rsp, result);
}).catch((e) => {
console.log(e);
result.status = "failed";
result.body = {"error": "androidRegisterResponse unexpected error"};
sendAndroidResponse(rsp, result);
});
} else {
result.status = "failed";
result.body = { "error":"required parameters not present"};
sendAndroidResponse(rsp, result);
}