| 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 |
1×
1×
1×
1×
1×
20×
1×
1×
1×
14×
14×
10×
10×
14×
14×
1×
1×
1×
1×
1×
1×
1×
1×
3×
3×
3×
3×
3×
3×
3×
3×
1×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
1×
1×
3×
1×
1×
3×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
3×
5×
5×
3×
3×
5×
5×
5×
5×
5×
3×
3×
1×
12×
12×
4×
4×
4×
4×
1×
11×
6×
6×
11×
4×
4×
4×
7×
1×
1×
1×
1×
6×
6×
6×
6×
11×
1×
6×
6×
1×
5×
5×
1×
3×
3×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
1×
3×
3×
1×
1×
3×
3×
3×
3×
3×
1×
1×
1×
3×
2×
2×
3×
3×
3×
3×
3×
3×
3×
3×
3×
3×
1×
1×
1×
1×
1×
26×
26×
26×
26×
26×
26×
5×
21×
1×
20×
1×
6×
6×
1×
10×
10×
10×
10×
10×
10×
10×
10×
13×
13×
3×
10×
10×
10×
1×
9×
9×
9×
9×
9×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
9×
9×
2×
2×
1×
8×
8×
1×
1×
2×
2×
2×
2×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
| 'use strict'
const model = require("./model")
const sockets = require('./sockets')
const EventEmitter = require('events')
// when false, log output is suppressed
exports.showLog = false
// log to console
// @s string to log
function log(s) {
Iif (exports.showLog) {
console.log('grant> ', s)
}
}
// Event emitter for resource (create, update and delete)
class Emitter extends EventEmitter {}
const events = new Emitter()
exports.events = events
// This function fires a resource change event to interested parties.
// resource: the name of the resource
// operation: 'create', 'update' or 'delete'
// usersToNotify: a list of users to notify
//
// The event is called 'resource'
function emit(resource, operation, usersToNotify) {
// gather users (identities) of this resource
const users = usersToNotify?usersToNotify:[]
if (resources.hasOwnProperty(resource)) {
let perm = resources[resource].permissions
for (let user in perm) {
users.push(user)
}
}
// fire a 'resource' event
events.emit('resource', resource, operation, users)
}
// the resources data structure
let resources = {}
let dbStateSaveInterval = 1000
// determines how often the state is saved to the database
// i.e. the number of db operations / logs between saves.
exports.setDbStateSaveInterval = function(value) {
dbStateSaveInterval = value
}
// write the content of the db to the terminal
exports.dump = function (msg) {
let s = JSON.stringify(resources, null, 3)
const title = msg?msg:""
console.log('\n\nCLOUSDSIM GRANT DUMP\n',
title,
'\n',
' DB:', model.listName,
'\n',s,
'\n-----\n')
}
// Clear cache in memory without wiping data from database server
function clearCache() {
resources = {}
}
// Initialization
// @resources: dictionary of resource names and initial data
// @databaseName: the Redis list that contains the data
// @databaseUrl: the ip of the Redis db
// @server: the httpServer used to initialize socket.io
// @cb: callback
function init(initialResources, databaseName, databaseUrl, server, cb) {
log('cloudsim-grant init')
// set the name of the list where data is stored
model.init(databaseName)
model.setDatabaseUrl(databaseUrl)
log('loading redis list "' + databaseName + '" at url: ' + databaseUrl)
loadPermissions(initialResources, () =>{
sockets.init(server, events)
console.log('cloudsim-grant db "' + databaseName + '" loaded\n')
cb()
})
}
// read pemission from the database.
function loadPermissions(initialResources, cb) {
let t = new Date()
const callback = function() {
// make sure initial resources and permissions are set
setupInitialResources(initialResources)
return cb()
}
model.loadData('state', (err, data) => {
Iif (err) {
return cb(err)
}
Iif (!data) {
loadPermissionLogs((err) => {
if (err) {
return cb(err)
}
t = new Date()
model.saveData('state', resources, (err) => {
if (err) {
return cb(err)
}
console.log('State saved. Time taken: ' + (new Date() - t))
return callback()
})
})
}
else {
console.log('State loaded. Time taken: ' + (new Date() - t))
// set resources from state data
resources = data
// check for if there are any operations that are not saved in state
// res is the number of operations performed post saved state
model.loadData('state-backlog', (err, res) => {
Iif (err) {
return cb(err)
}
Eif (res && typeof (res == 'number') && res != 0) {
let offset = res*-1
model.readDbRange(offset, -1, (err, items) => {
Iif (err) {
return cb(err)
}
Eif (items && items.length > 0) {
reconstructResources(items, callback)
}
})
}
})
}
})
}
// read operation logs the database and reconstruct a cache of resources
// @initialResources: Resources to be saved if the database is empty
// @cb: function(err)
function loadPermissionLogs(cb) {
// callback for db operations
const callback = function(e, r) {
if (e) {
console.log('error loading permissions: ' + e)
cb(e)
return
}
log('cb ', r)
}
let t = new Date()
model.readDb((err, items)=>{
if(err) {
cb(err)
return
}
log('data loaded')
console.log('Data loaded from db. Time taken: ' + (new Date() - t) + 'ms')
t = new Date()
// if the datbase was not empty, reconstruct the resources
if (items.length > 0) {
reconstructResources(items, callback)
}
cb(null)
})
}
// Check if initial resources are in the database. If not, add them
function setupInitialResources(initialResources) {
const callback = function(e, r) {
Iif (e) {
console.log('error loading permissions: ' + e)
cb(e)
return
}
log('cb ', r)
}
for (let i in initialResources) {
const resource = initialResources[i]
// skip resource if already exists
// TODO verify resource data and permissions?
Iif (resources.hasOwnProperty(resource))
continue
const resourceName = resource.name
const data = resource.data
const permissions = resource.permissions
// we need to split users into a creator and grantees
let creator
// find first user that has non readonly pemission and promote him/her
// to the creator
const first = permissions.filter( e => {
return e.permissions.readOnly == false
})[0]
Iif (!first) {
throw new Error("Resource '" + resourceName +
"' has no read/write user!")
}
else {
creator = first.username
// create the resource now
setResource(creator, resourceName, data, callback)
}
// the resource has been created... now let's share it with the others
for (let j in permissions) {
const permission = permissions[j]
const grantee = permission.username
Eif (creator === grantee)
continue // skip the creator
const readOnly = permission.permissions.readOnly
// grant accesss to this resource for our grantee
grantPermission(creator, grantee, resourceName, readOnly, callback)
}
}
}
function reconstructResources(items, cb) {
// callback for db operations
const callback = function(e, r) {
Iif (e) {
console.log('error reconstructing resources: ' + e)
cb(e)
return
}
log('cb ', r)
}
let t = new Date()
// put the data back
for (let i=0; i < items.length; i++) {
const item = items[i]
// calling stringify repeatedly is computationally expensive
// so commented out for now
// log(' [' + i + '/' + items.length + '] ' + JSON.stringify(item, null, 2))
switch (item.operation) {
case 'set': {
log('set')
setResourceLocal(item.data.owner,
item.data.resource,
item.data.data,
callback)
break
}
case 'grant': {
log('grant ')
grantPermissionLocal(item.data.granter,
item.data.grantee,
item.data.resource,
item.data.readOnly,
callback)
break
}
case 'revoke': {
log('revoke')
revokePermissionLocal(item.data.granter,
item.data.grantee,
item.data.resource,
item.data.readOnly,
callback)
break
}
default: {
cb('Unknown operation "' + item.operation + '"')
return
}
}
}
console.log('Reconstructed cache. Time taken: ' + (new Date() - t) + 'ms')
cb(null)
}
// keep track of db operations and save the state
// when the backlog is full
function logDbWrite() {
model.incrData('state-backlog', (err, value) => {
if (value % dbStateSaveInterval === 0) {
model.saveData('state', resources, (err) => {
Iif (err) {
console.log('Error saving state')
return
}
model.saveData('state-backlog', 0, (err) => {
Iif (err) {
console.log('Error incr state-backlog')
return
}
})
})
}
})
}
// create update delete a resource.
// @me: user performing the operation
// @resource: resource name
// @data: resource data
// @local: if set to true, the operation will performed only on
// the resources in cache and not written back to database
function setResourceSync(me, resource, data, local) {
if (!local) {
model.setResource(me, resource, data)
logDbWrite()
}
if (!data) {
// NOTE: the same operation for gathering user data
// is done in the emit function so commented out for now
// const usersToNotify = []
// for (let user in resources[resource].permissions) {
// usersToNotify.push(user)
// }
// // data is null, signifying deletion
// delete resources[resource]
// // delete is a special case where users are collected before
// emit(resource, 'delete', usersToNotify)
Eif (resources.hasOwnProperty(resource)) {
delete resources[resource]
emit(resource, 'delete')
}
}
// adding or updating
else {
if(resources.hasOwnProperty(resource)) {
// resource update
let res = resources[resource];
Eif (res) {
res.data = data
emit(resource, 'update')
}
}
else {
// brand new resource
const permissions = {}
permissions[me] = {readOnly: false}
resources[resource] = {
data: data,
permissions: permissions
}
emit(resource, 'create')
}
}
return {error: null, result: resources[resource]}
}
// create update delete a resource.
function setResource(me, resource, data, cb) {
const result = setResourceSync(me, resource, data)
cb(result.error, result.result, resource)
}
// create update delete a resource without writing to db.
function setResourceLocal(me, resource, data, cb) {
const result = setResourceSync(me, resource, data, true)
cb(result.error, result.result, resource)
}
// create a new resource with an existing name
function createResource (me, resource, data, cb) {
Iif(resources[resource]) {
cb('"' + resource + '" already exists')
return
}
setResource(me, resource, data, cb)
}
// create a new resource, using a type to generate a new name
// @me the username creating the resource
// @resourceType the resource prefix name (ex "simulator")
// the resulting resource will have a name that is type with a number
// (ex "simulator-00X")
// @data JSON data for the resource
// @callback function(err, data, resourceName)
function createResourceWithType(me, resourceType, data, cb) {
model.getNextResourceId(resourceType, (err, resourceName) => {
if(err) {
cb(err)
return
}
createResource(me, resourceName, data, cb)
})
}
// function deleteResourceSync (me, resource) {
// if (resources[resource]) {
// return setResourceSync(me, resource, null)
// }
// return {error: 'resource "' + resource + '" does not exist', result: null}
// }
function deleteResource (me, resource, cb) {
Eif(resources[resource]) {
setResource(me, resource, null, cb)
return
}
cb('resource "' + resource + '" does not exist')
}
function updateResource(me, resource, data, cb) {
Iif(!resources[resource]) {
cb('resource "' + resource + '" does not exist')
return
}
isAuthorized(me, resource, false, (err, authorized) => {
Iif(err) {
cb(err)
return
}
Iif(!authorized) {
cb('not authorized')
return
}
else {
resources[resource].data = data
setResource(me, resource, data, cb)
}
})
}
// Grant permission on a resource
// @me: grantor
// @user: grantee
// @resource: resource name
// @readOnly: True to grant readOnly permission, otherwise write
// @local: if set to true, the operation will performed only on
// the resources in cache and not written back to database
function grantPermissionSync(me, user, resource, readOnly, local) {
const p = JSON.stringify(resources, null, 2)
log('Grant:', me, user, resource, '\n', p)
Iif (!resources[resource])
{
return {error: null, success: false, message: 'Resource "' + resource +
'" does not exist'}
}
let current = resources[resource].permissions[user]
let message
// If user already has some authorization
Iif (current)
{
// Is already read only
if ((readOnly == true) && (current.readOnly == true))
{
return {error: null, success: true, message: '"' + user +
'" is already authorized for "read only" for "'
+ resource + '"'}
}
// Is already write
if ((readOnly == false) && (current.readOnly == false))
{
return {error: null, success: true, message: '"' + user +
'" is already authorized for "write" for "' + resource + '"'}
}
// Is write and we want to downgrade
if ((readOnly == true) && (current.readOnly == false))
{
current.readOnly = true
message = '"' + user + '" access for "'
+ resource + '" has been downgraded to "read only"'
}
// Is read only and we want to upgrade
else if ((readOnly == false) && (current.readOnly == true))
{
current.readOnly = false
message = '"' + user + '" access for "'
+ resource + '" has been upgraded to "write"'
}
else {
return {error: 'something went wrong', success: false,
message: 'unknown error'}
}
}
else
{
// Grant brand new permission
let x = {
readOnly : readOnly,
authority : me
}
resources[resource].permissions[user] = x
const readOnlyTxt = readOnly? "read only" : "write"
message = '"' + user + '" now has "' + readOnlyTxt +
'" access for "' + resource + '"'
}
// write it to the db
Eif (!local) {
model.grant(me, user, resource, readOnly )
logDbWrite()
}
// console.trace('GRANT moment', resource)
emit(resource, 'grant')
return {error: null, success: true, message: message}
}
function grantPermission(me, user, resource, readOnly, cb) {
const result = grantPermissionSync(me, user, resource, readOnly)
cb(result.error, result.success, result.message)
}
function grantPermissionLocal(me, user, resource, readOnly, cb) {
const result = grantPermissionSync(me, user, resource, readOnly, true)
cb(result.error, result.success, result.message)
}
// Revoke permission on a resource
// @me: grantor
// @user: grantee
// @resource: resource name
// @readOnly: True to revoke readOnly permission, otherwise write
// @local: if set to true, the operation will performed only on
// the resources in cache and not written back to database
function revokePermissionSync (me, user, resource, readOnly, local) {
const innerRevoke = function(me, user, resource, readOnly, local) {
const current = resources[resource].permissions[user]
// If user has no authorization
Iif (!current)
{
const msg = '"' + user + '" has no authorization for "'
+ resource + '" so nothing changed.'
return {error: null, success: true, message: msg}
}
else
{
let result
// Is read only, revoking read only
if ((readOnly == true) && (current.readOnly == true))
{
delete resources[resource].permissions[user]
const msg = '"' + user
+ '" is no longer authorized for "read only" for "'
+ resource + '"'
result = {error: null, success: true, message: msg}
}
// Is write, revoking write
if ((readOnly == false) && (current.readOnly == false))
{
delete resources[resource].permissions[user]
result = {error: null, success: true, message: '"' + user +
'" is no longer authorized for "write" for "'
+ resource + '"'}
}
// Is write and we want to revoke read-only - not allowed
Iif ((readOnly == true) && (current.readOnly == false))
{
result = {error: null, success: false, message: '"' + user +
'" has "write" access for "' + resource +
'", so "read only" can\'t be revoked.'}
}
// Is read-only and want to revoke write - remove it all
Iif ((readOnly == false) && (current.readOnly == true))
{
delete resources[resource].permissions[user]
result = {error: null, success: true, message: '"' + user +
'" had "read only" access for "' + resource +
'" and now has nothing'}
}
// write it to the db
Eif (!local) {
model.revoke(me, user, resource, readOnly )
logDbWrite()
}
return result
}
}
const result = innerRevoke(me, user, resource, readOnly, local)
Eif (result.success)
events.emit('resource', resource, 'revoke', [user])
return result
}
function revokePermission (me, user, resource, readOnly, cb) {
const result = revokePermissionSync(me, user, resource, readOnly)
cb(result.error, result.success, result.message)
}
function revokePermissionLocal(me, user, resource, readOnly, cb) {
const result = revokePermissionSync(me, user, resource, readOnly, true)
cb(result.error, result.success, result.message)
}
// this is the synchronous version of isAuthorized. It returns
// true if the user has access to the specified resource
function isAuthorizedSync(user, resourceName, readOnly) {
Iif(!user)
return false
const resource = resources[resourceName]
Iif (!resource) {
return false
}
const permissions = resource.permissions
const current = permissions[user]
if (!current) {
return false
}
// not enough permission
if(current.readOnly && readOnly == false) {
return false
}
// user in the list, with enough permissions
return true
}
// Check if a user already has a given permission for a resource
function isAuthorized(user, resource, readOnly, cb) {
const r = isAuthorizedSync(user, resource, readOnly)
cb(null, r)
}
/// user: the requester... his permissions will be first
/// returns nothing if user has no access
function copyAndFormatResourceForOutput(user, resourceName) {
// check for permission (readOnly)
Iif (!isAuthorizedSync(user, resourceName, true)) {
return null
}
const dbInfo = resources[resourceName]
const data = dbInfo.data
const name = resourceName
const permissionDict = dbInfo.permissions
const requesterPermissions = dbInfo.permissions[user]
// by convention, the first permission is the requester's
const permissions = [{username: user, permissions: requesterPermissions}]
for (let username in permissionDict) {
const perms = permissionDict[username]
if (user != username)
permissions.push({username: username, permissions: perms})
}
const r = {
name: name,
data: data,
permissions: permissions,
}
// prevent modification of data by the caller
const clone = JSON.parse(JSON.stringify(r))
return clone
}
/// Get a single resource, including data and permissions
/// user The requester user.
function readResource(user, resourceName, cb) {
const resource = resources[resourceName]
Iif(!resource) {
cb('"' + resourceName + '" does not exist')
return
}
const data = copyAndFormatResourceForOutput(user, resourceName)
Iif (!data) {
cb("not authorized for resource")
return
}
cb(null, data)
}
function readAllResourcesForUser(identities, cb) {
const items =[]
for (let res in resources) {
Eif (resources.hasOwnProperty(res)) {
for (let i = 0; i < identities.length; ++i) {
const resource = copyAndFormatResourceForOutput(identities[i], res)
Eif (resource) {
items.push(resource)
break
}
}
}
}
cb(null, items)
}
// this returns a copy of the internal database.
// when resource is defined, it only gets the resource data
// and permission. When resource is null or undefined, the
// entire db is returned
function copyInternalDatabase(resource) {
let data = resources
if (resource) {
data = resources[resource]
if (!data) {
return {}
}
}
const res = JSON.parse(JSON.stringify(data))
return res
}
// Remove user from database and revoke the user permissions on all relevant
// resources
function deleteUser(user, cb) {
for (let res in resources) {
Eif (resources.hasOwnProperty(res)) {
Iif (!isAuthorizedSync(user, res, true)) {
continue
}
// revoke permission on resource
const result = revokePermissionSync(user, user, res,
resources[res].permissions[user].readOnly)
Iif (result.error) {
cb(result.error)
return
}
}
}
cb(null)
}
// database, setup
exports.init = init
exports.copyInternalDatabase = copyInternalDatabase
exports.clearCache = clearCache
// crud (create update read delete)
exports.createResource = createResource
exports.createResourceWithType = createResourceWithType
exports.getNextResourceId = model.getNextResourceId
exports.readResource = readResource
exports.updateResource = updateResource
exports.deleteResource = deleteResource
exports.deleteUser = deleteUser
// util
exports.isAuthorized = isAuthorized
exports.readAllResourcesForUser = readAllResourcesForUser
exports.grantPermission = grantPermission
exports.revokePermission = revokePermission
// inter module
exports.isAuthorizedSync = isAuthorizedSync
|