-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcustom-endpoint-script.js
395 lines (347 loc) · 14.8 KB
/
custom-endpoint-script.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
/**
* @file Provide content for a script to be run at a ForgeRock Identity Management (IDM) custom endpoint
* responsible for validating user's answers to security questions.
* Hash plain-text answers with a custom (BCRYPT version 2a, cost 10) algorithm,
* and save the hash in a custom Array (Multivalued) Knowledge-Based Authentication (KBA) field.
* Update the standard KBA property field (kbaInfo) with correct answers.
*
* This can be used in a deployment on a customer's premises
* or during transition from an existing KBA implementation
* to a controlled environment, such as ForgeRock Identity Cloud (Identity Cloud).
*
* The user's answer for a security question will be checked against the hash saved in the custom KBA field.
* If the answer is valid, it is also saved in the kbaInfo field, hashed with the default algorithms.
* If there are other questions defined in the kbaInfo field, they will be preserved.
* When the kbaInfo field is populated, it could be used with the standard authentication means,
* such as the out of the box KBA nodes.
*
* The examples below could be run in the browser console during an active IDM administrator session,
* using the following URL template:
* {idm_base_url}/endpoint/{custom-kba-endpoint-name}/{user-id}
*
* PATCH to save a single plain-text answer as the custom hash in the custom KBA field,
* and save the answer hashed with the default algorithms in the kbaInfo field.
* @example
* var customEndpointName = '{custom-endpoint-name}';
* var userId = '{user-id}';
* var data = JSON.stringify([
* {
* operation: 'replace',
* field: '{custom-kba-field-name}',
* value: [
* {
* questionId: '{question-id}',
* answer: '{answer}'
* }
* ]
* }
* ]);
* await $.ajax({
* method: 'PATCH',
* url: '/openidm/endpoint/' + customEndpointName + '/' + userId,
* data: data,
* headers: {
* 'x-requested-with': 'XMLHttpRequest',
* 'Content-Type': 'application/json'
* }
* });
*
* POST to validate a single answer against the custom hash saved in the custom KBA field;
* if the answer is valid, save it hashed with the default algorithms in the kbaInfo field.
* @example
* var customEndpointName = '{custom-endpoint-name}';
* var userId = '{user-id}';
* var data = JSON.stringify({
* field: '{custom-kba-field-name}',
* input: [
* {
* questionId: '{question-id}',
* answer: '{answer}'
* }
* ]
* });
*
* await $.ajax({
* method: 'POST',
* url: '/openidm/endpoint/' + customEndpointName + '/' + userId,
* data: data,
* headers: {
* 'x-requested-with': 'XMLHttpRequest',
* 'Content-Type': 'application/json'
* }
* });
*
* @see {@link ../examples} for saving and verifying multiple answers examples.
*/
/**
* The result object to be returned in the response.
* @typedef {object} result
* @property {string} _id - The user identifier.
* @property {string} message - A message describing the outcome.
*/
/**
* @returns {result}
*/
(function () {
/**
* Import Java for handling the request and for custom hashing.
*/
const javaImports = JavaImporter(
java.security.SecureRandom,
org.bouncycastle.crypto.generators.OpenBSDBCrypt,
java.lang.String,
org.forgerock.json.resource.CreateRequest,
org.forgerock.json.resource.PatchRequest,
org.forgerock.json.resource.NotSupportedException
);
const userId = request.resourcePath;
const managedUserUri = 'managed/alpha_user/' + userId;
const kbaConfigurationUri = 'config/selfservice.kba';
const defaultKbaCustomField = 'frIndexedMultivalued3';
const successMessage = 'Success';
/**
* BCrypt defaults.
*/
const bcryptVersion = '2a';
const bcryptCost = 10;
/**
* Obtain the KBA configuration.
*/
const kbaConfiguration = openidm.read(kbaConfigurationUri, null, [
'kbaPropertyName',
'questions'
]);
/**
* Get the standard KBA property name from the configuration.
*/
const kbaPropertyName = kbaConfiguration.kbaPropertyName;
/**
* @type {result}
*/
const result = {
_id: userId
};
if (request instanceof javaImports.PatchRequest) {
/**
* PATCH to save question definitions with a plain-text answers as the custom hash in the custom KBA field,
* and save the answer hashed with the default algorithms in the kbaInfo field.
*/
result.message = saveQuestions();
} else if (request instanceof javaImports.CreateRequest) {
/**
* POST to validate user's answers against the custom KBA field, and if they match the hash,
* save the answers hashed with the default algorithms in the kbaInfo field.
*/
result.message = validateAnswers();
} else {
/**
* Throw if the request method is not supported.
*/
throw new javaImports.NotSupportedException(request.method);
}
return result;
/**
* Handle a PATCH request.
* @returns {string} A message describing the outcome of the request.
*/
function saveQuestions() {
function getKbaCustomValue(questions) {
function getKbaCustomQuestion(question) {
function hashAnswer(answer) {
const secureRandom = new javaImports.SecureRandom();
const salt = secureRandom.generateSeed(16);
const answerJava = new javaImports.String(answer);
return javaImports.OpenBSDBCrypt.generate(bcryptVersion, answerJava.toCharArray(), salt, bcryptCost);
}
const kbaCustomQuestion = JSON.stringify({
questionId: question.questionId,
answer: String(hashAnswer(question.answer))
});
return kbaCustomQuestion;
}
return questions.map(function (question) {
return getKbaCustomQuestion(question);
});
}
/**
* The global custom endpoint PATCH request object.
* @typedef {object} request
* @property {object[]} patchOperations - The PATCH operation definitions.
* @property {string} patchOperations[].operation - The PATCH operation name.
* @property {string} [patchOperations[].field=frIndexedMultivalued3] - The custom KBA field name.
* @property {object[]} patchOperations[].value - An array of answers with the corresponding question IDs.
* @property {string} patchOperations[].value.answer - Plain-text answer to a security question.
* @property {string} patchOperations[].value.questionId - The security question ID.
* @see {@link https://backstage.forgerock.com/docs/idm/7.1/scripting-guide/script-variables-custom-endpoints.html}.
* @see {@link https://backstage.forgerock.com/docs/ig/7.1/_attachments/apidocs/org/forgerock/json/resource/PatchRequest.html}.
*/
if (request.patchOperations.length !== 1) {
return 'Error: Exactly one patch operation is expected in the request; found: ' + request.patchOperations.length + '.';
}
if (!(kbaConfiguration && kbaConfiguration.questions && Object.keys(kbaConfiguration.questions).length)) {
return 'Error: No security questions found in KBA configuration.';
}
const patchOperation = request.patchOperations[0];
const operation = patchOperation.operation || 'replace';
if (operation !== 'replace') {
return 'Error: Only replace patch operation is currently supported.';
}
const requestQuestions = formatQuestions(patchOperation.value);
if (!(Array.isArray(requestQuestions) && requestQuestions.length)) {
return 'Error: No questions provided in the request.';
}
let invalidQuestions;
let invalidQuestionsIDs;
invalidQuestions = requestQuestions.filter(function (requestQuestion) {
if (!(requestQuestion.questionId && kbaConfiguration.questions[requestQuestion.questionId])) {
return true;
}
});
if (invalidQuestions.length) {
invalidQuestionsIDs = invalidQuestions.map((invalidQuestion) => {
return invalidQuestion.questionId;
}).join(', ');
return 'Error: Question ID(s) not found in the configuration: ' + invalidQuestionsIDs;
}
invalidQuestions = requestQuestions.filter(function (requestQuestion) {
if (!(requestQuestion.answer && requestQuestion.answer.length > 3)) {
return true;
}
});
if (invalidQuestions.length) {
const invalidAnswers = invalidQuestions.map((question) => {
return question.answer;
}).join(', ');
return 'Error: Answers not meeting minimum length requirements: ' + invalidAnswers;
}
const kbaCustomField = patchOperation.field || defaultKbaCustomField;
openidm.patch(managedUserUri, null, [
{
operation: operation,
field: kbaCustomField,
value: getKbaCustomValue(requestQuestions)
},
{
operation: operation,
field: kbaPropertyName,
value: getKbaInfoValue(requestQuestions)
}
]);
return successMessage;
}
/**
* @returns {string} A message describing the outcome of the request.
*/
function validateAnswers() {
/**
* The global custom endpoint POST request object.
* @typedef {object} request
* @property {object} content - The POST data.
* @property {string} [content.field=frIndexedMultivalued3] - The custom KBA field name.
* @property {object[]} content.input - An array of answers with the corresponding question IDs.
* @property {string} content.input[].answer - Plain-text answer to a security question.
* @property {string} content.input[].questionId - The security question ID.
* @see {@link https://backstage.forgerock.com/docs/idm/7.1/scripting-guide/script-variables-custom-endpoints.html}.
* @see {@link https://backstage.forgerock.com/docs/ig/7.1/_attachments/apidocs/org/forgerock/json/resource/CreateRequest.html}.
*/
const requestContent = JSON.parse(request.content);
if (!(Array.isArray(requestContent.input) && requestContent.input.length)) {
return 'Error: No input provided.';
}
const requestQuestions = formatQuestions(requestContent.input);
if (!(Array.isArray(requestQuestions) && requestQuestions.length)) {
return 'Error: No questions provided in the request.';
}
const kbaCustomField = requestContent.field || defaultKbaCustomField;
const userObject = openidm.read(managedUserUri, null, [kbaPropertyName, kbaCustomField]);
if (!userObject) {
return 'Error: User not found.';
}
if (!userObject[kbaCustomField]) {
return 'Error: The custom KBA field not found in the profile.';
}
const profileQuestions = userObject[kbaCustomField].map((questionJson) => {
return JSON.parse(questionJson);
});
let invalidQuestions;
let invalidQuestionsIDs;
invalidQuestions = requestQuestions.filter(function (question) {
const profileQuestionsIds = profileQuestions.map((question) => {
return question.questionId;
});
return !(question.questionId && profileQuestionsIds.indexOf(question.questionId) !== -1);
});
if (invalidQuestions.length) {
invalidQuestionsIDs = invalidQuestions.map((question) => {
return question.questionId;
}).join(', ');
return 'Error: Question ID(s) not found in the profile: ' + invalidQuestionsIDs;
}
invalidQuestions = requestQuestions.filter(function (requestQuestion) {
return !(requestQuestion.answer);
});
if (invalidQuestions.length) {
invalidQuestionsIDs = invalidQuestions.map((question) => {
return question.questionId;
}).join(', ');
return 'Error: Question ID(s) with no answer provided: ' + invalidQuestionsIDs;
}
const hasIncorrectAnswer = requestQuestions.some(function (requestQuestion) {
const requestAnswerJava = new javaImports.String(requestQuestion.answer);
const correctAnswer = profileQuestions.find(function (profileQuestion) {
return profileQuestion.questionId === requestQuestion.questionId;
}).answer;
return !javaImports.OpenBSDBCrypt.checkPassword(correctAnswer, requestAnswerJava.toCharArray());
});
if (hasIncorrectAnswer) {
return 'Failure';
}
let kbaInfoValue = getKbaInfoValue(requestQuestions);
kbaInfoValue = kbaInfoValue.concat(userObject[kbaPropertyName].filter((kbaInfoQuestion) => {
return !kbaInfoValue.map((kbaInfoValueQuestion) => {
return kbaInfoValueQuestion.questionId;
}).includes(kbaInfoQuestion.questionId);
}));
openidm.patch(managedUserUri, null, [
{
operation: 'replace',
field: kbaPropertyName,
value: kbaInfoValue
}
]);
return successMessage;
}
function formatQuestions(questions) {
function formatQuestionId(questionId) {
return String(questionId || '').replace(/^0+/, '');
}
function formatAnswer(answer) {
return String(answer || '').toLowerCase();
}
return questions.map((question) => {
return {
questionId: formatQuestionId(question.questionId),
answer: formatAnswer(question.answer)
};
});
}
function getKbaInfoValue(questions) {
/**
* Use the default hashing algorithms to create an individual answer hash
* for storing in the kbaInfo field.
* @param {object} question - The question definition.
* @param {string} question.questionId - The question ID.
* @param {string} question.answer - The answer.
* @returns {object} The individual value to store in the kbaInfo (Array) field.
*/
function getKbaInfoQuestion(question) {
return {
questionId: question.questionId,
answer: openidm.hash(question.answer, null)
};
}
return questions.map(function (question) {
return getKbaInfoQuestion(question);
});
}
}());