-
Notifications
You must be signed in to change notification settings - Fork 56
/
scimgateway.js
1790 lines (1685 loc) · 76.8 KB
/
scimgateway.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
// =================================================================================
// File: scimgateway.js
//
// Author: Jarle Elshaug
//
// Purpose: Started by endpoint plugin
// Listens and replies on incoming SCIM requests
// Communicates with plugin using event callback
// =================================================================================
'use strict'
const http = require('http')
const https = require('https')
const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const jwt = require('jsonwebtoken')
const passport = require('passport')
const OIDCBearerStrategy = require('passport-azure-ad').BearerStrategy
const dot = require('dot-object')
const nodemailer = require('nodemailer')
const fs = require('fs')
const path = require('path')
const callsite = require('callsite')
const utils = require('../lib/utils')
const endpointMap = require('../lib/endpointMap')
let scimDef = null
let isMailLock = false
/**
* @constructor
*/
const ScimGateway = function () {
let server = null
const stack = callsite()
const requester = stack[1].getFileName()
const pluginName = path.basename(requester, '.js')
const configDir = path.join(path.dirname(requester), '..', 'config')
const configFile = path.join(`${configDir}`, `${pluginName}.json`) // config name prefix same as pluging name prefix
let config = require(configFile).scimgateway
let extConfigErr = null
try {
config = ScimGateway.prototype.processExtConfig(pluginName, config, true) // external config support process.env and process.file
} catch (err) { extConfigErr = err }
const gwName = path.basename(__filename, '.js') // prefix of current file
const logDir = path.join(path.dirname(requester), '..', 'logs')
const Log = require('../lib/logger').Log
var log = new Log(utils.extendObj(utils.copyObj(config.log), { category: pluginName, colorize: process.stdout.isTTY || false, loglevel: { file: 'debug', console: 'debug' } }), path.join(`${logDir}`, `${pluginName}.log`))
const logger = log.logger
this.logger = logger // exposed to plugin-code
this.notValidAttributes = notValidAttributes // exposed to plugin-code
let pwErrCount = 0
let requestCounter = 0
const startTime = utils.timestamp()
if (extConfigErr) {
logger.error(`${gwName}[${pluginName}] ${extConfigErr.message}`)
logger.error(`${gwName}[${pluginName}] stopping...\n`)
throw (new Error('Using exception to stop further asynchronous code execution (ensure synchronous logger flush to logfile and exit program), please ignore this one...'))
}
if (!config.scim) config.scim = {}
if (!config.log) config.log = {}
if (!config.log.loglevel) config.log.loglevel = {}
if (!config.auth) config.auth = {}
if (!config.auth.basic) config.auth.basic = []
if (!config.auth.bearerToken) config.auth.bearerToken = []
if (!config.auth.bearerJwt) config.auth.bearerJwt = []
if (!config.auth.bearerJwtAzure) config.auth.bearerJwtAzure = []
if (!config.certificate) config.certificate = {}
if (!config.certificate.pfx) config.certificate.pfx = {}
if (!config.emailOnError) config.emailOnError = {}
if (!config.emailOnError.smtp) config.emailOnError.smtp = {}
const handler = {}
handler.Users = handler.users = {
description: 'User',
exploreMethod: 'exploreUsers',
getMethod: 'getUser',
inclusionMethod: 'getGroupUsers',
modifyMethod: 'modifyUser',
createMethod: 'createUser',
deleteMethod: 'deleteUser'
}
handler.Groups = handler.groups = {
description: 'Group',
exploreMethod: 'exploreGroups',
getMethod: 'getGroup',
inclusionMethod: 'getGroupMembers',
modifyMethod: 'modifyGroup',
createMethod: 'createGroup',
deleteMethod: 'deleteGroup'
}
handler.servicePlans = handler.serviceplans = { // plugin-azure using "CustomSCIM"
description: 'ServicePlan',
exploreMethod: 'exploreServicePlans',
getMethod: 'getServicePlan',
inclusionMethod: 'getServicePlanMembers',
modifyMethod: 'modifyServicePlanMembers',
createMethod: 'createServicePlan',
deleteMethod: null
}
let foundBasic = false
let foundBearerToken = false
let foundBearerJwtAzure = false
let foundBearerJwt = false
let pwPfxPassword
// if (config.auth.basic.password) pwBasicPassword = ScimGateway.prototype.getPassword('scimgateway.auth.basic.password', configFile)
if (Array.isArray(config.auth.basic)) {
const arr = config.auth.basic
for (let i = 0; i < arr.length; i++) {
if (arr[i].password) arr[i].password = ScimGateway.prototype.getPassword(`scimgateway.auth.basic[${i}].password`, configFile)
if (arr[i].password) foundBasic = true
}
if (!foundBasic) config.auth.basic = []
}
// if (config.auth.bearer.token) pwBearerToken = ScimGateway.prototype.getPassword('scimgateway.auth.bearer.token', configFile)
if (Array.isArray(config.auth.bearerToken)) {
const arr = config.auth.bearerToken
for (let i = 0; i < arr.length; i++) {
if (arr[i].token) {
arr[i].token = ScimGateway.prototype.getPassword(`scimgateway.auth.bearerToken[${i}].token`, configFile)
if (arr[i].token) foundBearerToken = true
}
}
if (!foundBearerToken) config.auth.bearerToken = []
}
if (Array.isArray(config.auth.bearerJwtAzure)) {
const issuers = []
const arr = config.auth.bearerJwtAzure
for (let i = 0; i < arr.length; i++) {
if (arr[i].tenantIdGUID) {
issuers.push(`https://sts.windows.net/${arr[i].tenantIdGUID}/`)
}
}
if (issuers.length > 0) {
foundBearerJwtAzure = true
const azureOptions = {
validateIssuer: true,
passReqToCallback: false,
loggingLevel: null,
// identityMetadata: `https://login.microsoftonline.com/${tenantIdGUID}/.well-known/openid-configuration`,
identityMetadata: 'https://login.microsoftonline.com/organizations/v2.0/.well-known/openid-configuration',
clientID: '00000014-0000-0000-c000-000000000000', // Well known appid: Microsoft.Azure.SyncFabric
audience: [
// Well known appid: Issued for accessing Windows Azure Active Directory Graph Webservice
'00000002-0000-0000-c000-000000000000',
// Appid used for SCIM provisioning for non-gallery applications. See changes introduced, in reverse cronological order:
// - https://github.com/MicrosoftDocs/azure-docs/commit/f6997c0952d2ad4f33ce7f5339eeb83c21b51f1e
// - https://github.com/MicrosoftDocs/azure-docs/commit/64525fea0675a73b2e6b8fe42fbd03ee568cadfc
'8adf8e6e-67b2-4cf2-a259-e3dc5476c621'
],
issuer: issuers // array => passport.authenticate supports more than one AAD tenant
}
passport.use(new OIDCBearerStrategy(azureOptions, (token, callback) => { // using named strategy = tenantIdGUID, passport.authenticate then using name
callback(null, token.sub, token) // Azure SyncFabric don't send user info claims, returning claim token.sub as user
}))
} else {
config.auth.bearerJwtAzure = []
}
}
if (Array.isArray(config.auth.bearerJwt)) {
const arr = config.auth.bearerJwt
for (let i = 0; i < arr.length; i++) {
if (arr[i].secret) {
arr[i].secret = ScimGateway.prototype.getPassword(`scimgateway.auth.bearerJwt[${i}].secret`, configFile)
if ((arr[i].options && arr[i].options.issuer) && (arr[i].secret || arr[i].publicKey)) {
foundBearerJwt = true
if (arr[i].publicKey) { // create publicKeyContent
try {
arr[i].publicKeyContent = fs.readFileSync(`${configDir}/certs/${arr[i].publicKey}`)
} catch (err) {
arr.splice(i, 1) // delete
foundBearerJwt = false
err.message = `failed reading file defined in configuration auth.bearerJwt: ${err.message}`
logger.error(err.message)
}
}
} else arr.splice(i, 1) // delete
}
}
if (!foundBearerJwt) config.auth.bearerJwt = []
}
if (config.certificate.pfx.password) pwPfxPassword = ScimGateway.prototype.getPassword('scimgateway.certificate.pfx.password', configFile)
if (config.emailOnError.smtp.password) config.emailOnError.smtp.password = ScimGateway.prototype.getPassword('scimgateway.emailOnError.smtp.password', configFile)
if (!foundBasic && !foundBearerToken && !foundBearerJwtAzure && !foundBearerJwt) {
logger.error(`${gwName}[${pluginName}] Scimgateway password decryption failed or no password defined`)
logger.error(`${gwName}[${pluginName}] stopping...\n`)
throw (new Error('Using exception to stop further asynchronous code execution (ensure synchronous logger flush to logfile and exit program), please ignore this one...'))
}
if (!fs.existsSync(logDir)) fs.mkdirSync(logDir)
if (!fs.existsSync(configDir + '/wsdls')) fs.mkdirSync(configDir + '/wsdls')
if (!fs.existsSync(configDir + '/certs')) fs.mkdirSync(configDir + '/certs')
if (!fs.existsSync(configDir + '/schemas')) fs.mkdirSync(configDir + '/schemas')
let isScimv2 = false
if (config.scim.version === '2.0' || config.scim.version === 2) {
isScimv2 = true
scimDef = require('../lib/scimdef-v2')
} else scimDef = require('../lib/scimdef-v1')
if (config.scim.customSchema) { // merge plugin custom schema extension into core schemas
let custom
try {
custom = JSON.parse(fs.readFileSync(`${configDir}/schemas/${config.scim.customSchema}`, 'utf8'))
} catch (err) {
throw new Error(`failed reading file defined in configuration "scim.customSchema": ${err.message}`)
}
if (!Array.isArray(custom)) custom = [custom]
const schemas = ['User', 'Group']
let customMerged = false
for (let i = 0; i < schemas.length; i++) {
const schema = scimDef.Schemas.Resources.find(el => el.name === schemas[i])
const customSchema = custom.find(el => el.name === schemas[i])
if (schema && customSchema && Array.isArray(customSchema.attributes)) {
const arr1 = schema.attributes // core:1.0/2.0 schema
const arr2 = customSchema.attributes
schema.attributes = arr2.filter(arr2Obj => { // only merge attributes (objects) having unique name into core schema
if (!arr1.some(arr1Obj => arr1Obj.name === arr2Obj.name)) {
customMerged = true
if (!isScimv2) arr2Obj.schema = 'urn:scim:schemas:core:1.0'
return arr2Obj
}
}).concat(arr1)
}
}
if (!customMerged) {
const err = [
'No custom SCIM schema attributes have been merged. Make sure using correct format e.g. ',
'[{"name": "User", "attributes" : [...]}]. ',
'Also make sure attribute names in attributes array do not conflict with core:1.0/2.0 SCIM attribute names'
].join()
throw new Error(err)
}
}
this.testmodeusers = scimDef.TestmodeUsers.Resources // exported and used by plugin-loki
this.testmodegroups = scimDef.TestmodeGroups.Resources // exported and used by plugin-loki
const logResult = async (ctx, next) => {
const started = Date.now()
await next() // once all middleware below completes, this continues
const ellapsed = (Date.now() - started) + 'ms' // ctx.set('X-ResponseTime', ellapsed)
const res = {
statusCode: ctx.response.status,
statusMessage: ctx.response.message,
body: ctx.response.body
}
let userName
const [authType, authToken] = (ctx.request.header.authorization || '').split(' ') // [0] = 'Basic' or 'Bearer'
if (authType === 'Basic') [userName] = (Buffer.from(authToken, 'base64').toString() || '').split(':')
if (!userName && authType === 'Bearer') userName = 'token'
if (ctx.request.url !== '/favicon.ico') {
if (ctx.response.status < 200 || ctx.response.status > 299) {
logger.error(`${gwName}[${pluginName}] ${ellapsed} ${ctx.request.ip} ${userName} ${ctx.request.method} ${ctx.request.href} Body = ${JSON.stringify(ctx.request.body)} Response = ${JSON.stringify(res)}${(config.log.loglevel.file === 'debug' && ctx.request.url !== '/ping') ? '\n' : ''}`)
} else logger.info(`${gwName}[${pluginName}] ${ellapsed} ${ctx.request.ip} ${userName} ${ctx.request.method} ${ctx.request.href} Body = ${JSON.stringify(ctx.request.body)} Response = ${JSON.stringify(res)}${(config.log.loglevel.file === 'debug' && ctx.request.url !== '/ping') ? '\n' : ''}`)
requestCounter += 1 // logged on exit (not win process termination)
}
}
// start auth methods - used by auth
const unauth = (ctx) => {
return new Promise((resolve, reject) => {
if (ctx.url === '/ping') resolve(true) // ping - no auth
else resolve(false)
})
}
const basic = (method, authType, authToken) => {
return new Promise((resolve, reject) => { // basic auth
if (authType !== 'Basic') resolve(false)
if (!foundBasic) resolve(false) // not configured
const [userName, userPassword] = (Buffer.from(authToken, 'base64').toString() || '').split(':')
if (!userName || !userPassword) {
reject(new Error(`authentication failed for user ${userName}`))
}
const arr = config.auth.basic
for (let i = 0; i < arr.length; i++) {
if (arr[i].username === userName && arr[i].password === userPassword) {
if (arr[i].readOnly === true && method !== 'GET') resolve(false)
resolve(true) // authentication OK
}
}
reject(new Error(`authentication failed for user ${userName}`))
})
}
const bearerToken = (method, authType, authToken) => {
return new Promise((resolve, reject) => { // bearer token
if (authType !== 'Bearer' || jwt.decode(authToken)) resolve(false) // bearer token auth not used
if (!foundBearerToken || !authToken) resolve(false)
const arr = config.auth.bearerToken
for (let i = 0; i < arr.length; i++) {
if (arr[i].token === authToken) {
if (arr[i].readOnly === true && method !== 'GET') resolve(false)
resolve(true) // authentication OK
}
}
reject(new Error('bearer token authentication failed'))
})
}
const bearerJwtAzure = (ctx, next, authType, authToken) => { // not supporting readOnly
return new Promise((resolve, reject) => {
if (authType !== 'Bearer' || !foundBearerJwtAzure) resolve(false) // no azure bearer token
const payload = jwt.decode(authToken)
if (!payload) resolve(false)
if (!payload.iss) resolve(false)
if (payload.iss.indexOf('https://sts.windows.net') !== 0) resolve(false)
passport.authenticate('oauth-bearer', { session: false }, (err, user, info) => {
if (err) { reject(err) }
if (user) resolve(true) // authentication OK
else reject(new Error(`Azure JWT authorization failed: ${info}`))
})(ctx, next)
})
}
const jwtVerify = (method, el, authToken) => { // used by bearerJwt
return new Promise((resolve, reject) => {
jwt.verify(authToken, (el.secret) ? el.secret : el.publicKeyContent, el.options, (err, decoded) => {
if (err) resolve(false)
else {
if (el.readOnly === true && method !== 'GET') resolve(false)
resolve(true) // authorization OK
}
})
})
}
const bearerJwt = async (method, authType, authToken) => {
if (authType !== 'Bearer' || !foundBearerJwt) return false // no standard jwt bearer token
const payload = jwt.decode(authToken)
if (!payload) return false
if (payload.iss && payload.iss.indexOf('https://sts.windows.net') === 0) return false // azure - handled by bearerJwtAzure
const promises = []
const arr = config.auth.bearerJwt
for (let i = 0; i < arr.length; i++) {
promises.push(jwtVerify(method, arr[i], authToken))
}
const arrResolve = await Promise.all(promises).catch((err) => { throw (err) })
for (const i in arrResolve) {
if (arrResolve[i]) return true
}
throw new Error('JWT authentication failed')
}
// end auth methods - used by auth
const auth = async (ctx, next) => { // authentication/authorization
const [authType, authToken] = (ctx.request.header.authorization || '').split(' ') // [0] = 'Basic' or 'Bearer'
try { // authenticate
const arrResolve = await Promise.all([unauth(ctx), basic(ctx.request.method, authType, authToken), bearerToken(ctx.request.method, authType, authToken), bearerJwtAzure(ctx, next, authType, authToken), bearerJwt(ctx.request.method, authType, authToken)]).catch((err) => { throw (err) })
for (const i in arrResolve) {
if (arrResolve[i]) {
ctx.set('Content-Type', 'application/scim+json; charset=utf-8') // IE don't support JSON content to be shown in browser, pre IE/Edge versions did not support 'application/scim+json'
return next() // auth OK - continue with routes
}
}
// all false - invalid auth method or missing pluging config
let err
if (authType.length < 1) err = new Error(`${ctx.url} request is missing authentication information`)
else {
err = new Error(`${ctx.url} request having unsupported authentication or plugin configuration is missing`)
logger.debug(`${gwName}[${pluginName}] request authToken = ${authToken}`)
logger.debug(`${gwName}[${pluginName}] request jwt.decode(authToken) = ${JSON.stringify(jwt.decode(authToken))}`)
}
ctx.set('WWW-Authenticate', 'Basic realm=""')
ctx.status = 401
ctx.body = 'Access denied'
if (ctx.url !== '/favicon.ico') logger.error(`${gwName}[${pluginName}] ${err.message}`)
} catch (err) {
ctx.set('WWW-Authenticate', 'Basic realm=""')
if (pwErrCount < 3) {
pwErrCount += 1
ctx.status = 401
ctx.body = 'Access denied'
logger.error(`${gwName}[${pluginName}] ${ctx.url} ${err.message}`)
} else { // delay brute force attempts
logger.error(`${gwName}[${pluginName}] ${ctx.url} ${err.message} => delaying response with 2 minutes to prevent brute force`)
return new Promise((resolve) => {
setTimeout(() => {
ctx.status = 401
ctx.body = 'Access denied'
resolve(ctx)
}, 1000 * 60 * 2)
})
}
}
} // authentication
const verifyContentType = (ctx, next) => {
return new Promise((resolve) => {
if (ctx.request.length) { // body is included - invalid content-type gives empty body (koa-bodyparser)
const contentType = ctx.request.type.toLowerCase()
if (contentType === 'application/json' || contentType === 'application/scim+json') {
return resolve(next())
}
ctx.status = 415
ctx.body = 'Content-Type header must be \'application/json\' or \'application/scim+json\''
return resolve(ctx)
}
resolve(next())
})
}
const app = new Koa()
const router = new Router()
// Middleware run in the order they are defined and communicates through ctx
// There is no return value, if there were it would be ignored
app.use(logResult)
app.use(bodyParser({ // parsed body store in ctx.request.body
enableTypes: ['json'],
extendTypes: { json: ['application/scim+json', 'text/plain'] }
}))
app.use(auth) // authentication before routes
app.use(verifyContentType)
app.use(router.routes())
app.use(router.allowedMethods())
app.on('error', (err, ctx) => { // catching none try/catch in app middleware, also bodyparser and body not json
logger.error(`${gwName}[${pluginName}] Koa method: ${ctx.method} url: ${ctx.origin + ctx.path} body: ${JSON.stringify(ctx.request.body)} error: ${err.message}`)
})
router.get('/ping', async (ctx) => { // auth not required
const tx = 'hello'
ctx.set('Content-Type', 'text/plain; charset=utf-8')
ctx.body = tx
})
// Initial connection, step #1: GET /ServiceProviderConfigs
// If not included => Provisioning will always use GET /Users without any paramenters
// scimv1 = ServiceProviderConfigs, scimv2 ServiceProviderConfig
router.get(['/(|scim/)(ServiceProviderConfigs|ServiceProviderConfig)',
'/:baseEntity/(|scim/)(ServiceProviderConfigs|ServiceProviderConfig)'], async (ctx) => {
const tx = scimDef.ServiceProviderConfigs // obfuscator friendly
const location = ctx.origin + ctx.path
if (tx.meta) tx.meta.location = location
else {
tx.meta = {}
tx.meta.location = location
}
ctx.body = tx
logger.debug(`${gwName}[${pluginName}] GET ${ctx.originalUrl} Response = ${JSON.stringify(tx)}`)
})
// Initial connection, step #2: GET /Schemas
router.get(['/(|scim/)Schemas', '/:baseEntity/(|scim/)Schemas'], async (ctx) => {
let tx = scimDef.Schemas
tx = addResources(tx)
tx = addSchemas(tx, null, isScimv2)
ctx.body = tx
})
router.get(['/(|scim/)Schemas/:id', '/:baseEntity/(|scim/)Schemas/:id'], async (ctx) => { // e.g /Schemas/Users | Groups | ServiceProviderConfigs
let schemaName = ctx.params.id
if (schemaName.substr(schemaName.length - 1) === 's') schemaName = schemaName.substr(0, schemaName.length - 1)
const tx = scimDef.Schemas.Resources.find(el => el.name === schemaName)
if (!tx) {
let err = new Error(`Schema '${schemaName}' not found`)
err = jsonErr(config.scim.version, pluginName, ctx.status, err)
ctx.status = 404
ctx.body = err
} else {
ctx.body = tx
}
})
router.get(['/(|scim/)(ResourceTypes|ResourceType)',
'/:baseEntity/(|scim/)(ResourceTypes|ResourceType)'], async (ctx) => { // ResourceTypes according to v2 specification
const tx = scimDef.ResourceType
ctx.body = tx
})
router.get([`/(|scim/)(!${undefined}|Users|Groups|servicePlans)/:id`,
`/:baseEntity/(|scim/)(!${undefined}|Users|Groups|servicePlans)/:id`], async (ctx) => {
let u = ctx.originalUrl.substr(0, ctx.originalUrl.lastIndexOf('/'))
u = u.substr(u.lastIndexOf('/') + 1) // u = Users, Groups
const handle = handler[u]
const id = require('path').basename(ctx.params.id, '.json') // supports <id>.json
const getObj = {
filter: 'id',
identifier: id
}
logger.debug(`${gwName}[${pluginName}] [Get ${handle.description}] ${getObj.filter}=${getObj.identifier}`)
logger.debug(`${gwName}[${pluginName}] calling "${handle.getMethod}" and awaiting result`)
if (Object.keys(ctx.query).length > 0) { // Users/bjensen?test=test
if (!ctx.query.excludedAttributes || Object.keys(ctx.query).length > 1) {
let err = 'incorrect syntax - using query only supports excludedAttributes'
err = jsonErr(config.scim.version, '', ctx.status, err)
ctx.status = 400
ctx.body = err
return null
}
}
try {
const data = await this[handle.getMethod](ctx.params.baseEntity, getObj, ctx.query.attributes ? ctx.query.attributes : '')
if (!data || JSON.stringify(data) === '{}') {
let err = new Error(`${handle.description} ${getObj.identifier} not found`)
err = jsonErr(config.scim.version, pluginName, ctx.status, err)
ctx.status = 404
ctx.body = err
} else {
for (const key in data) { // exclude null and empty object/array
if (data[key] === null) delete data[key]
else if (JSON.stringify(data[key]) === '{}') delete data[key]
else if (Array.isArray(data[key]) && data[key].length < 1) delete data[key]
}
if (ctx.query.excludedAttributes) { // e.g. Groups?excludedAttributes=members
const arrEx = ctx.query.excludedAttributes.split(',')
for (let i = 0; i < arrEx.length; i++) {
delete data[arrEx[i]]
}
}
delete data.password
let scimdata = data
const location = ctx.origin + ctx.path
scimdata = addSchemas(scimdata, handle.description, isScimv2)
if (scimdata.meta) scimdata.meta.location = location
else {
scimdata.meta = {}
scimdata.meta.location = location
}
ctx.body = scimdata
}
} catch (err) {
const e = jsonErr(config.scim.version, pluginName, ctx.status, err)
ctx.status = 404
ctx.body = e
}
})
router.get(['/(|scim/)(Users|Groups|servicePlans)',
'/:baseEntity/(|scim/)(Users|Groups|servicePlans)'], async (ctx) => {
let u = ctx.originalUrl.substr(ctx.originalUrl.lastIndexOf('/') + 1) // u = Users, Groups, servicePlans, ...
const ui = u.indexOf('?')
if (ui > 0) u = u.substr(0, ui)
const handle = handler[u]
if (ctx.query.filter) {
// ==========================================
// GET USER - getUser
// GET GROUP - getGroup
// ==========================================
//
// GET /Users?filter=userName eq "bjensen"&attributes=ims,locale,name.givenName,externalId,preferredLanguage,userType,id,title,timezone,name.middleName,name.familyName,nickName,name.formatted,meta.location,userName,name.honorificSuffix,meta.version,meta.lastModified,meta.created,name.honorificPrefix,emails,phoneNumbers,photos,x509Certificates.value,profileUrl,roles,active,addresses,displayName,entitlements
//
// Get user request before/after updating a user:
// GET = /Users?filter=userName eq "jsmith"&attributes=id,userName
//
// Get user request for retreving all attributes:
// GET = /Users?filter=userName eq "jsmith"&attributes=ims,locale,name.givenName,externalId,preferredLanguage,userType,id,title,timezone,name.middleName,name.familyName,nickName,name.formatted,meta.location,userName,name.honorificSuffix,meta.version,meta.lastModified,meta.created,name.honorificPrefix,emails,phoneNumbers,photos,x509Certificates.value,profileUrl,roles,active,addresses,displayName,entitlements
//
// ---- retreive all users for a spesific group ----
//
// "user member of group" => CA IM default scim endpoint config - Group having multivalue attribute members containing userName
// GET = /Users?filter=id eq "jsmith"&attributes=id,userName
//
// "group member of user" => User having multivalue attribute groups containing value=GroupName
// GET = /Users?filter=groups.value eq "UserGroup-1"&attributes=groups.value,userName
//
// ---- Azure AD to SCIM Users ----
//
// Default SCIM attribute mapping have:
// externalId mapped to mailNickname (matching precedence #1)
// userName mapped to userPrincipalName
//
// Precedence decides filter attribute sent to ScimGateway
// GET = /scim/Users?filter=externalId eq "jarle_elshaug"
//
// ScimGateway accepts externalId (as matching precedence) instead of userName, but userName and externalId must
// then be mapped to the same AD attribte e.g:
//
// externalId mapped to mailNickname (matching precedence #1)
// userName mapped to mailNickname
// or:
// externalId mapped to userPrincipalName (matching precedence #1)
// userName mapped to userPrincipalName
//
// ---- GROUP ----
//
// Get group:
// GET /Groups?filter=displayName eq "Employees"&attributes=externalId,id,members.value,displayName
//
// Azure AD:
// GET /scim/Groups?excludedAttributes=members&filter=externalId eq "MyGroup"
//
// Get group members:
// GET = /Groups?filter=members.value eq "<user-id>"&attributes=members.value,displayName&startIndex=1&count=100
//
// ---- Azure AD to SCIM Groups ----
//
// Default SCIM attribute for GROUP mapping have:
// externalId mapped to displayName (matching precedence #1)
// displayName mapped to mailNickname
//
// ScimGateway accepts externalId (as matching precedence) instead of displayName, but displayName and externalId must
// then be mapped to the same AD attribute e.g:
//
// externalId mapped to displayName (matching precedence #1)
// displayName mapped to displayName
//
// ---- servicePlans ----
// GET /servicePlans?filter=servicePlanName+eq+%22EXCHANGE_S_FOUNDATION%22&attributes=servicePlanName
//
const arrFilter = ctx.query.filter.split(' ') // userName eq "bjensen"
if (arrFilter.length > 2 && arrFilter[1] === 'eq') {
const identifier = ctx.query.filter.substring(ctx.query.filter.indexOf('"')).replace(/"/g, '') // bjensen / UserGroup-1
const getObj = {
filter: arrFilter[0], // e.g. userName
identifier: identifier // e.g. bjensen
}
if (getObj.filter === 'groups.value' || getObj.filter === 'members.value') {
// Using inclusionMethod
// User (groups.value) - get all users for a spesific group ("group member of user" - using groups attribute on user)
// User (manager.managerId) AAD
// Groups (members.value) - get users for a spesific groups
logger.debug(`${gwName}[${pluginName}] [Get ${handle.description} Inclusion] ${arrFilter[0]}=${identifier}`) // UserGroup-1
logger.debug(`${gwName}[${pluginName}] calling "${handle.inclusionMethod}" and awaiting result`)
try {
const data = await this[handle.inclusionMethod](ctx.params.baseEntity, identifier, ctx.query.attributes)
let scimdata = data
scimdata = addResources(scimdata, ctx.query.startIndex)
scimdata = addSchemas(scimdata, handle.description, isScimv2)
ctx.body = scimdata
return null
} catch (err) {
const e = jsonErr(config.scim.version, pluginName, ctx.status, err)
ctx.status = 500
ctx.body = e
return null
}
} else {
logger.debug(`${gwName}[${pluginName}] [Get ${handle.description}] ${getObj.filter}=${getObj.identifier}`) // bjensen or bjensen;<filter>
logger.debug(`${gwName}[${pluginName}] calling "${handle.getMethod}" and awaiting result`)
try {
let data = await this[handle.getMethod](ctx.params.baseEntity, getObj, ctx.query.attributes ? ctx.query.attributes : '')
if (!data) data = {}
if (!isScimv2 && JSON.stringify(data) === '{}') { // user/group not found, scim1.1 => http 404, scim2.0 http 200 and empty resource
let err
if (getObj.filter === 'userName' || getObj.filter === 'externalId' || getObj.filter === 'id') {
err = new Error(`${handle.description} ${getObj.identifier} not found`)
} else err = new Error(`${handle.description} having ${getObj.filter}=${getObj.identifier} not found`)
err = jsonErr(config.scim.version, pluginName, ctx.status, err)
ctx.status = 404
ctx.body = err
return null
} else {
for (const key in data) { // exclude null and empty object/array
if (data[key] === null) delete data[key]
else if (JSON.stringify(data[key]) === '{}') delete data[key]
else if (Array.isArray(data[key]) && data[key].length < 1) delete data[key]
}
if (ctx.query.excludedAttributes) { // e.g. Groups?excludedAttributes=members
const arrEx = ctx.query.excludedAttributes.split(',')
for (let i = 0; i < arrEx.length; i++) {
delete data[arrEx[i]]
}
}
delete data.password
let scimdata = data
scimdata = addResources(scimdata, ctx.query.startIndex)
scimdata = addSchemas(scimdata, handle.description, isScimv2)
ctx.body = scimdata
return null
}
} catch (err) {
const e = jsonErr(config.scim.version, pluginName, ctx.status, err)
ctx.status = 404
ctx.body = e
return null
}
}
} else {
let err = `GET /${handle.description} having incorrect filter query syntax - only supporting eq - example: ?filter=userName eq "bjensen"`
err = jsonErr(config.scim.version, '', ctx.status, err)
ctx.status = 400
ctx.body = err
return null
}
} else {
// ==========================================
// EXPLORE
// ==========================================
//
// GET /Users?attributes=userName&startIndex=1&count=100
// GET /Groups?attributes=displayName
// GET /servicePlans?attributes=servicePlanName
// GET /Users /Groups
//
logger.debug(`${gwName}[${pluginName}] [Explore ${handle.description}]`)
const queryNumbers = Object.keys(ctx.query).length
if (queryNumbers > 0 && !ctx.query.attributes) {
let err = 'attributes must be included when using query'
err = jsonErr(config.scim.version, '', ctx.status, err)
ctx.status = 400
ctx.body = err
return null
}
logger.debug(`${gwName}[${pluginName}] calling "${handle.exploreMethod}" and awaiting result`)
try {
const data = await this[handle.exploreMethod](ctx.params.baseEntity, ctx.query.attributes ? ctx.query.attributes : '', parseInt(ctx.query.startIndex), parseInt(ctx.query.count))
let scimdata = data
scimdata = addResources(scimdata, ctx.query.startIndex)
scimdata = addSchemas(scimdata, handle.description, isScimv2)
ctx.body = scimdata
return null
} catch (err) {
const e = jsonErr(config.scim.version, pluginName, ctx.status, err)
ctx.status = 500
ctx.body = e
return null
}
}
})
// ==========================================
// CREATE USER
// CREATE GROUP
// ==========================================
//
// POST = /Users
// Body contains user attributes including userName (userID)
// Body example:
// {"active":true,"name":{"familyName":"Elshaug","givenName":"Jarle"},"schemas":["urn:scim:schemas:core:1.0"],"userName":"jael01"}
//
// POST = /Groups
// Body contains group attributes including displayName (group name)
// Body example:
// {"displayName":"MyGroup","externalId":"MyExternal","schemas":["urn:scim:schemas:core:1.0"]}
//
router.post([`/(|scim/)(!${undefined}|Users|Groups)(|.json)(|.xml)`,
`/:baseEntity/(|scim/)(!${undefined}|Users|Groups)(|.json)(|.xml)`], async (ctx) => {
const u = ctx.originalUrl.substr(ctx.originalUrl.lastIndexOf('/') + 1) // u = Users<.json|.xml>, Groups<.json|.xml>
const handle = handler[u.split('.')[0]]
logger.debug(`${gwName}[${pluginName}] [Create ${handle.description}]`)
let jsonBody = ctx.request.body
const strBody = JSON.stringify(jsonBody)
if (strBody === '{}') {
let err = new Error('Not accepting empty or none JSON formatted POST requests')
err = jsonErr(config.scim.version, pluginName, ctx.status, err)
ctx.status = 500
ctx.body = err
return null
} else if (handle.createMethod === 'createUser' && !jsonBody.userName && !jsonBody.externalId) {
let err = new Error('userName or externalId is mandatory')
err = jsonErr(config.scim.version, pluginName, ctx.status, err)
ctx.status = 500
ctx.body = err
return null
} else if (handle.createMethod === 'createGroup' && !jsonBody.displayName && !jsonBody.externalId) {
let err = new Error('displayName or externalId is mandatory')
err = jsonErr(config.scim.version, pluginName, ctx.status, err)
ctx.status = 500
ctx.body = err
return null
}
logger.debug(`${gwName}[${pluginName}] POST ${ctx.originalUrl} body=${strBody}`)
jsonBody = JSON.parse(strBody) // using a copy
const scimdata = ScimGateway.prototype.convertedScim(jsonBody)
logger.debug(`${gwName}[${pluginName}] convertedBody=${JSON.stringify(scimdata)}`)
logger.debug(`${gwName}[${pluginName}] calling "${handle.createMethod}" and awaiting result`)
try {
const data = await this[handle.createMethod](ctx.params.baseEntity, scimdata)
const location = `${ctx.origin}${ctx.path}/${jsonBody.userName || jsonBody.displayName || jsonBody.externalId}`
if (!jsonBody.meta) jsonBody.meta = {}
jsonBody.meta.location = location
jsonBody.id = jsonBody.userName ? jsonBody.userName : jsonBody.displayName
for (const key in data) { // merge any result e.g: data = {'id': 'xxxx'} when endpoint id different than userName/displayName
jsonBody[key] = data[key]
}
delete jsonBody.password
ctx.set('Location', location)
ctx.status = 201
ctx.body = jsonBody
} catch (err) {
const e = jsonErr(config.scim.version, pluginName, ctx.status, err)
if (err.name && err.name === 'DuplicateKeyError') ctx.status = 409
else ctx.status = 500
ctx.body = e
}
}) // post
// ==========================================
// DELETE USER/GROUP
// ==========================================
//
// DELETE /Users/4aa37ddc-4985-4009-ab24-df42d37e2810
// DELETE /Groups/4aa37ddc-4985-4009-ab24-df42d37e2810
// Note user: using id (not userName). getUser should therefore set id = userName (userID) e.g. bjensen
// => We then have: DELETE /Users/bjensen
// Note groups: using id (not displayName). getGroup should therefore set id = displayName (groupID) e.g. Employees
// => We then have: DELETE /Groups/Employees
//
router.delete([`/(|scim/)(!${undefined}|Users|Groups)/:id`,
`/:baseEntity/(|scim/)(!${undefined}|Users|Groups)/:id`], async (ctx) => {
let u = ctx.originalUrl.substr(0, ctx.originalUrl.lastIndexOf('/'))
u = u.substr(u.lastIndexOf('/') + 1) // u = Users, Groups
const handle = handler[u]
const id = ctx.params.id
logger.debug(`${gwName}[${pluginName}] [Delete ${handle.description}] id=${id}`)
logger.debug(`${gwName}[${pluginName}] calling "${handle.deleteMethod}" and awaiting result`)
try {
await this[handle.deleteMethod](ctx.params.baseEntity, id)
ctx.status = 204
} catch (err) {
const e = jsonErr(config.scim.version, pluginName, ctx.status, err)
ctx.status = 500
ctx.body = e
}
}) // delete
// ==========================================
// MODIFY USER
// MODIFY GROUP MEMBERS
// ==========================================
//
// PATCH = /Users/<id>
// PATCH = /Users/4aa37ddc-4985-4009-ab24-df42d37e2810
// Note, using id (not userName). getUser should therefore set id = userName (userID)
// => We then have: PATCH /Users/bjensen
//
// Body contains user attributes to be updated
// example: {"active":true}
//
// Multi-value attributes excluding user attribute 'groups' are customized from array to object based on type
// This is done for simplifying plugin-code. For more information please see method convertedScim / convertedScim20
//
// MODIFY GROUP MEMBERS
//
// PATCH = /Groups/<id>
// PATCH = /Groups/4aa37ddc-4985-4009-ab24-df42d37e2810
// Note, using id (not displayName). getGroup should therefore set id = displayName
// => We then have: PATCH = /Groups/Employees
//
// Body contains user attributes to be updated
// example: {"members":[{"value":"bjensen"}],"schemas":["urn:scim:schemas:core:1.0"]}
//
router.patch([`/(|scim/)(!${undefined}|Users|Groups|servicePlans)/:id`,
`/:baseEntity/(|scim/)(!${undefined}|Users|Groups|servicePlans)/:id`], async (ctx) => {
let u = ctx.originalUrl.substr(0, ctx.originalUrl.lastIndexOf('/'))
u = u.substr(u.lastIndexOf('/') + 1) // u = Users, Groups
const handle = handler[u]
const id = ctx.params.id
let jsonBody = ctx.request.body
const strBody = JSON.stringify(jsonBody)
if (strBody === '{}') {
let err = new Error('Not accepting empty or none JSON formatted POST requests')
err = jsonErr(config.scim.version, pluginName, ctx.status, err)
ctx.status = 500
ctx.body = err
} else {
logger.debug(`${gwName}[${pluginName}] [Modify ${handle.description}] id=${id}`)
logger.debug(`${gwName}[${pluginName}] PATCH ${ctx.originalUrl} body=${strBody}`)
jsonBody = JSON.parse(strBody) // using a copy
let scimdata
if (isScimv2) scimdata = convertedScim20(jsonBody) // patch differences v1/v2
else scimdata = ScimGateway.prototype.convertedScim(jsonBody)
logger.debug(`${gwName}[${pluginName}] convertedBody=${JSON.stringify(scimdata)}`)
logger.debug(`${gwName}[${pluginName}] calling "${handle.modifyMethod}" and awaiting result`)
try {
await this[handle.modifyMethod](ctx.params.baseEntity, id, scimdata)
const location = ctx.origin + ctx.path
jsonBody.id = id
delete jsonBody.password
ctx.set('Location', location)
ctx.status = 200
ctx.body = jsonBody // using original body instead of retrieving actual data
} catch (err) {
const e = jsonErr(config.scim.version, pluginName, ctx.status, err)
ctx.status = 500
ctx.body = e
}
}
}) // patch
// ==========================================
// REPLACE USER
// REPLACE GROUP MEMBERS
// => Using same as patch, but no convertedScim20
// ==========================================
router.put([`/(|scim/)(!${undefined}|Users|Groups|servicePlans)/:id`,
`/:baseEntity/(|scim/)(!${undefined}|Users|Groups|servicePlans)/:id`], async (ctx) => {
let u = ctx.originalUrl.substr(0, ctx.originalUrl.lastIndexOf('/'))
u = u.substr(u.lastIndexOf('/') + 1) // u = Users, Groups
const handle = handler[u]
const id = ctx.params.id
let jsonBody = ctx.request.body
const strBody = JSON.stringify(jsonBody)
if (strBody === '{}') {
let err = new Error('Not accepting empty or none JSON formatted POST requests')
err = jsonErr(config.scim.version, pluginName, ctx.status, err)
ctx.status = 500
ctx.body = err
} else {
logger.debug(`${gwName}[${pluginName}] [Modify ${handle.description}] id=${id}`)
logger.debug(`${gwName}[${pluginName}] PUT ${ctx.originalUrl} body=${strBody}`)
jsonBody = JSON.parse(strBody) // using a copy
const scimdata = ScimGateway.prototype.convertedScim(jsonBody)
logger.debug(`${gwName}[${pluginName}] convertedBody=${JSON.stringify(scimdata)}`)
logger.debug(`${gwName}[${pluginName}] calling "${handle.modifyMethod}" and awaiting result`)
try {
await this[handle.modifyMethod](ctx.params.baseEntity, id, scimdata.members ? scimdata.members : scimdata)
const location = ctx.origin + ctx.path
jsonBody.id = id
delete jsonBody.password
ctx.set('Location', location)
ctx.status = 200
ctx.body = jsonBody // using original body instead of retrieving actual data
} catch (err) {
const e = jsonErr(config.scim.version, pluginName, ctx.status, err)
ctx.status = 500
ctx.body = e
}
}
}) // put
// ==========================================
// API POST (no SCIM)
// ==========================================
//
// POST = /api + body
// Send body "as is" to plugin-api
// Body example:
// {"eventName":"AsignAccessRoleEvent","subjectName":"RACF_System-B","userID":"peter01"}
//
router.post(['/api', '/:baseEntity/api'], async (ctx) => {
logger.debug(`${gwName}[${pluginName}] [POST api]`)
const apiObj = ctx.request.body
const strBody = JSON.stringify(apiObj)
if (strBody === '{}') {
const err = new Error('Not accepting empty or none JSON formatted POST requests')
ctx.status = 500
ctx.body = apiErr(pluginName, err)
} else {
logger.debug(`${gwName}[${pluginName}] POST ${ctx.originalUrl} body=${JSON.stringify(apiObj)}`)
logger.debug(`${gwName}[${pluginName}] calling "postApi" and awaiting result`)
try {
let result = await this.postApi(ctx.params.baseEntity, apiObj)
const location = ctx.origin + ctx.path
if (result) {
if (typeof result === 'object') result = { result: result }
else {
try {
result = { result: JSON.parse(result) }
} catch (err) {
result = { result: result }
}
}
} else result = {}
if (!result.meta) result.meta = {}
result.meta.result = 'success'
result.meta.location = location
ctx.status = 201
ctx.body = result
} catch (err) {
ctx.status = 500
ctx.body = apiErr(pluginName, err)
}
}
}) // post
// ==========================================
// API PUT (no SCIM)
// ==========================================
//
// PUT = /api/{id} + body
// Send body "as is" to plugin-api
// Body example:
// {"eventName":"AsignAccessRoleEvent","subjectName":"RACF_System-B","userID":"peter01"}
//
router.put(['/api/:id', '/:baseEntity/api/:id'], async (ctx) => {
const id = ctx.params.id
logger.debug(`${gwName}[${pluginName}] [PUT api ] id=${id}`)
const apiObj = ctx.request.body
const strBody = JSON.stringify(apiObj)
if (strBody === '{}') {
const err = new Error('Not accepting empty or none JSON formatted PUT requests')
ctx.status = 500
ctx.body = apiErr(pluginName, err)
} else {