-
-
Notifications
You must be signed in to change notification settings - Fork 410
Expand file tree
/
Copy pathauthorization.js
More file actions
756 lines (645 loc) · 26 KB
/
Copy pathauthorization.js
File metadata and controls
756 lines (645 loc) · 26 KB
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
const db = require('../../db');
const auth = require('../../auth');
const _ = require('lodash');
const config = require('../../config');
const viewMapUtils = require('@medic/view-map-utils');
const registrationUtils = require('@medic/registration-utils');
const request = require('@medic/couch-request');
const environment = require('@medic/environment');
const nouveau = require('@medic/nouveau');
const { DOC_IDS, PREFIXES, DOC_TYPES } = require('@medic/constants');
const { ReplicationLimitError } = require('../../errors');
const REPLICATION_LIMITS = {
SUBJECTS_COUNT: 100 * 1000,
SUBJECT_HITS: 500 * 1000,
UNPURGED_DOCS_COUNT: 50 * 1000
};
const ALL_KEY = '_all'; // key in the docs_by_replication_key view for records everyone can access
const UNASSIGNED_KEY = '_unassigned'; // key in the docs_by_replication_key view for unassigned records
const MEDIC_CLIENT_DDOC = '_design/medic-client';
const DEFAULT_DDOCS = [
MEDIC_CLIENT_DDOC,
DOC_IDS.SERVICE_WORKER_META,
DOC_IDS.SETTINGS,
];
/**
* @typedef {Object} userCtx
* @property {string} name
* @property {Array.<string>} roles
* @property {string} contact_id
* @property {Array.<string>} facility_id
* @property {Object} contact
* @property {Array.<Object>} facility
*/
/**
* @typedef {Object} AuthorizationContext
* @property {userCtx} userCtx
* @property {Array} contactsByDepthKeys,
* @property {string[]} subjectIds,
* @property {number} contactDepth.
* @property {number} reportDepth.
* @property {Object.<string, number>} subjectsDepth,
* @property {boolean} replicatePrimaryContacts,
*/
/**
* @typedef {Object} DocByReplicationKey
* @property {string|Array.<string>} key
* @property {string} [type]
* @property {string} [submitter]
* @property {string} [subject]
* @property {string} [private]
* @property {string} [needed_signoff]
*/
// fake view map, to store whether doc is a medic.user-settings doc
const couchDbUser = doc => doc.type === 'user-settings';
const getUserSettingsId = username => `${PREFIXES.COUCH_USER}${username}`;
const getDefaultDocs = (userCtx) => [ ...DEFAULT_DDOCS, getUserSettingsId(userCtx?.name)];
/**
* Returns maximum allowed contact and report replication depth and most permissive
* replicatePrimaryContacts setting for the highest depth based on user's roles
* @param {userCtx} userCtx
* @returns {{contactDepth: number, reportDepth: number, replicatePrimaryContacts:boolean}}
*/
const getDepth = (userCtx) => {
const NO_VAL = -1;
const depth = {
contactDepth: NO_VAL,
reportDepth: NO_VAL,
replicatePrimaryContacts: false,
};
const getReportDepth = (value) => {
value = Number.parseInt(value, 10);
return Number.isNaN(value) ? NO_VAL : value;
};
if (!userCtx.roles || !userCtx.roles.length) {
return depth;
}
const settings = config.get('replication_depth');
if (!settings) {
return depth;
}
userCtx.roles.forEach((role) => {
// find the role with the highest depth
const setting = settings.find(setting => setting.role === role);
if (!setting) {
return;
}
const settingDepth = Number.parseInt(setting.depth, 10);
if (Number.isNaN(setting.depth)) {
return;
}
if (settingDepth > depth.contactDepth) {
depth.contactDepth = settingDepth;
depth.replicatePrimaryContacts = !!setting.replicate_primary_contacts;
depth.reportDepth = getReportDepth(setting.report_depth);
return;
}
if (settingDepth === depth.contactDepth) {
depth.replicatePrimaryContacts = depth.replicatePrimaryContacts || !!setting.replicate_primary_contacts;
const settingsReportDepth = getReportDepth(setting.report_depth);
depth.reportDepth = Math.max(depth.reportDepth, settingsReportDepth);
}
});
return depth;
};
const usesReportDepth = (authorizationContext) => authorizationContext.reportDepth >= 0;
const hasAccessToUnassignedDocs = (userCtx) => {
return config.get('district_admins_access_unallocated_messages') &&
auth.hasAllPermissions(userCtx, 'can_view_unallocated_data_records');
};
const lowestSubjectDepth = (subjects, subjectsDepth, depth) => {
const depths = [Number.MAX_VALUE, depth, ...subjects.map(subject => subjectsDepth[subject])];
return Math.min(...depths.filter(d => !isNaN(d)));
};
const includeSubjects = (authorizationContext, newSubjects, depth) => {
const initialSubjectsCount = authorizationContext.subjectIds.length;
depth = lowestSubjectDepth(newSubjects, authorizationContext.subjectsDepth, depth);
newSubjects.forEach(subject => {
if (!subject || authorizationContext.subjectIds.includes(subject)) {
return;
}
authorizationContext.subjectsDepth[subject] = depth;
authorizationContext.subjectIds.push(subject);
});
return authorizationContext.subjectIds.length !== initialSubjectsCount;
};
const excludeSubjects = (authorizationContext, ...subjectIds) => {
authorizationContext.subjectIds = _.without(authorizationContext.subjectIds, ...subjectIds);
};
// gets the depth of a contact, relative to the user's facilities
const getContactDepth = (authorizationContext, contactsByDepth) => {
const depthEntry = contactsByDepth.find(entry => {
return entry.key.length === 2 && authorizationContext.userCtx.facility_id.includes(entry.key[0]);
});
return depthEntry?.key[1];
};
/**
* Updates authorizationContext.subjectIds, including or excluding tested contact `subjectId` and `docId`
* @param {Boolean} allowed - whether subjects should be included or excluded
* @param {AuthorizationContext} authorizationContext
* @param {Array} contactsByDepth - results of `medic/contacts_by_depth` view against doc
* @returns {Boolean} whether new subjectIds were added to authorizationContext
**/
const updateContext = (allowed, authorizationContext, { contactsByDepth }) => {
if (!contactsByDepth || !contactsByDepth.length) {
return false;
}
// first element of `contactsByDepth` contains both `subjectId` and `docID`
const [{ key: [ docId ], value: { shortcode: subjectId, primary_contact: primaryContact } }] = contactsByDepth;
if (allowed) {
const newSubjects = [subjectId, docId];
if (authorizationContext.replicatePrimaryContacts) {
newSubjects.push(primaryContact);
}
const contactDepth = getContactDepth(authorizationContext, contactsByDepth);
return includeSubjects(authorizationContext, newSubjects, contactDepth);
}
excludeSubjects(authorizationContext, subjectId, docId);
return false;
};
/**
* Returns whether an authenticated user has access to a document
* @param {String} docId - CouchDB document ID
* @param {AuthorizationContext} authorizationContext
* @param {DocByReplicationKey} docsByReplicationKey - result of `medic/_nouveau/docs_by_replication_key` index
* @param {Array} contactsByDepth - results of `medic/contacts_by_depth` view against doc
* @returns {Boolean}
*/
const allowedDoc = (docId, authorizationContext, { docsByReplicationKey, contactsByDepth }) => {
if ([MEDIC_CLIENT_DDOC, getUserSettingsId(authorizationContext.userCtx.name)].includes(docId)) {
return true;
}
const replicationKeys = docsByReplicationKey?.key;
if (replicationKeys?.includes(ALL_KEY)) {
return true;
}
if (contactsByDepth?.length) {
// it's a contact
return allowedContact(docId, contactsByDepth, authorizationContext);
}
return allowedReport(authorizationContext, docsByReplicationKey);
};
/**
* Returns whether an authenticated user has access to a document
* @param {String} docId document id
* @param {Array.<{ key: Array.<string>, value: {_id: string, shortcode: string} }>} docContactsByDepth
* @param {AuthorizationContext} authorizationContext
* @param {Boolean} authorizationContext.replicatePrimaryContacts - whether to allow replication of primary contacts
*
* @returns {Boolean}
*/
const allowedContact = (docId, docContactsByDepth, authorizationContext) => {
const viewResultKeys = docContactsByDepth.map(result => result.key);
const contactsByDepthKeys = authorizationContext.contactsByDepthKeys;
const matchedView = viewResultKeys.some(
viewResult => contactsByDepthKeys.some(generated => _.isEqual(viewResult, generated))
);
if (matchedView) {
return true;
}
if (!authorizationContext.replicatePrimaryContacts) {
return false;
}
// this doc isn't allowed through its direct lineage, but can be a primary contact of a place that is.
return authorizationContext.subjectIds.includes(docId);
};
/**
* Returns whether an authenticated user has access to a report document
* @param {AuthorizationContext} authorizationContext
* @param {DocByReplicationKey} docsByReplicationKey - result of `medic/_nouveau/docs_by_replication_key` index
*
* @returns {Boolean}
*/
const allowedReport = (authorizationContext, docsByReplicationKey) => {
if (!docsByReplicationKey) {
return false;
}
const replicationKeys = docsByReplicationKey?.key || [];
// it's a report, task or target
const allowedDepth = isAllowedDepth(authorizationContext, docsByReplicationKey);
const { subject: subjectId, submitter: submitterId, private: priv } = docsByReplicationKey;
const allowedSubmitter = submitterId && authorizationContext.subjectIds.includes(submitterId);
if (!subjectId && allowedSubmitter) {
return true;
}
return replicationKeys.some(subjectId => {
const allowedSubject = subjectId && authorizationContext.subjectIds.includes(subjectId);
return allowedSubject &&
!isSensitive(authorizationContext.userCtx, subjectId, submitterId, priv, allowedSubmitter) &&
allowedDepth;
});
};
/**
* Returns filtered list of docs the offline user is allowed to see
* @param {AuthorizationContext} authorizationContext
* @param {Object[]} docObjs - the list of docObjs to be filtered
* @param {String} docObjs[].id - the docId
* @param {Boolean} docObjs[].allowed - when true, the doc is considered as allowed without being checked
* @param {Object} docObjs[].viewResults - results of authorization views against the doc
* @returns {Object[]} filtered list of docs the offline user is allowed to see
* If authorizationContext was updating during an iteration, the remaining docs are rechecked against the
* updated context.
*/
const filterAllowedDocs = (authorizationContext, docObjs) => {
const allowedDocs = [];
let shouldIterate = true;
const checkDoc = (docObj) => {
const allowed = docObj.allowed || allowedDoc(docObj.id, authorizationContext, docObj.viewResults);
shouldIterate = updateContext(allowed, authorizationContext, docObj.viewResults) || shouldIterate;
if (!allowed) {
return;
}
allowedDocs.push(docObj);
docObjs = _.without(docObjs, docObj);
};
while (docObjs.length && shouldIterate) {
shouldIterate = false;
docObjs.forEach(checkDoc);
}
return allowedDocs;
};
const getContactsByDepthKeys = (userCtx, depth) => {
const keys = [];
for (const facilityId of userCtx.facility_id) {
if (depth >= 0) {
keys.push(...Array.from({ length: depth + 1 }).map((_, i) => [facilityId, i]));
} else {
// no configured depth limit
keys.push([ facilityId ]);
}
}
return keys;
};
/**
* Returns authorization user context object for an offline user
* @param {{ name:string, roles:string[] }} userCtx
* @returns {AuthorizationContext}
*/
const getContextObject = (userCtx) => {
const { contactDepth, reportDepth, replicatePrimaryContacts } = getDepth(userCtx);
const subjectsDepth = {};
return {
userCtx,
contactsByDepthKeys: getContactsByDepthKeys(userCtx, contactDepth),
subjectIds: [ ALL_KEY, getUserSettingsId(userCtx.name) ],
contactDepth,
reportDepth,
subjectsDepth,
replicatePrimaryContacts,
};
};
const getContactSubjects = (row) => {
const subjects = [];
subjects.push(row.id);
if (row.value?.shortcode) {
subjects.push(row.value.shortcode);
}
return subjects;
};
/**
* Returns the authorization context for an offline user.
* @param {{ name:string, roles:string[] }} userCtx
* @returns* {Promise<AuthorizationContext>}
*/
const getAuthorizationContext = async (userCtx) => {
const authCtx = getContextObject(userCtx);
const contactsSubjects = {};
const results = await db.medic.query('medic/contacts_by_depth', { keys: authCtx.contactsByDepthKeys });
results.rows.forEach(row => {
const subjects = getContactSubjects(row);
contactsSubjects[row.id] = { subjects, primaryContact: row.value?.primary_contact };
authCtx.subjectIds.push(...subjects);
if (usesReportDepth(authCtx)) {
const depth = lowestSubjectDepth(subjects, authCtx.subjectsDepth, row.key[1]);
subjects.forEach(subject => authCtx.subjectsDepth[subject] = depth);
}
});
if (authCtx.replicatePrimaryContacts) {
await addPrimaryContactsSubjects(authCtx, contactsSubjects);
}
authCtx.subjectIds = _.uniq(authCtx.subjectIds);
if (hasAccessToUnassignedDocs(userCtx)) {
authCtx.subjectIds.push(UNASSIGNED_KEY);
authCtx.subjectsDepth[UNASSIGNED_KEY] = 0;
}
return authCtx;
};
/**
* Retrieves unknown primary contacts from the database.
* Iterates over all primary contacts and includes them in the subjects lists and assigns correct depth.
* @param {AuthorizationContext} authCtx
* @param {Object.<string, {primaryContact: string, subjects: Array.<string>}>} contacts - map of contacts and their
* subject
* ids and primary contact
* @returns {Promise<void>}
*/
const addPrimaryContactsSubjects = async (authCtx, contacts) => {
const primaryContactIds = Object
.values(contacts)
.map(({ primaryContact }) => primaryContact)
.filter(id => !!id);
const unknownPrimaryContacts = _.uniq(primaryContactIds.filter(id => !contacts[id]));
if (unknownPrimaryContacts.length) {
const result = await db.medic.query('medic/contacts_by_depth', { keys: unknownPrimaryContacts.map(id => [id] ) });
result.rows.forEach(row => {
const subjects = getContactSubjects(row);
authCtx.subjectIds.push(...subjects);
contacts[row.id] = { subjects };
});
}
if (usesReportDepth(authCtx)) {
primaryContactIds.forEach(primaryContactId => {
const parents = Object.entries(contacts)
.filter(([, { primaryContact } ]) => primaryContact === primaryContactId)
.map(([id]) => id);
const depth = lowestSubjectDepth(parents, authCtx.subjectsDepth);
contacts[primaryContactId].subjects.forEach(subject => authCtx.subjectsDepth[subject] = depth);
});
}
};
const getReplicationKeys = (viewResults) => {
if (!viewResults || !viewResults.docsByReplicationKey) {
return [];
}
const replicationKeys = [...viewResults.docsByReplicationKey.key];
replicationKeys.push(viewResults.docsByReplicationKey.submitter);
return replicationKeys.filter(key => !!key);
};
/**
* returns a list of corresponding contact docs
* @param {string[]} replicationKeys - either contact shortcodes (`patient_id` or `place_id`) or doc ids
* @returns {Promise<Object[]>}
*/
const findContactsByReplicationKeys = (replicationKeys) => {
replicationKeys = _.without(replicationKeys, UNASSIGNED_KEY);
if (!replicationKeys || !replicationKeys.length) {
return Promise.resolve([]);
}
replicationKeys = _.uniq(replicationKeys);
const keys = replicationKeys.map(id => ['shortcode', id]);
return db.medic
.query('medic-client/contacts_by_reference', { keys })
.then(result => {
const docIds = new Set();
for (const replicationKey of replicationKeys) {
const keys = result.rows.filter(row => row.key[1] === replicationKey).map(row => row.id);
if (keys.length) {
keys.forEach(key => docIds.add(key));
} else {
docIds.add(replicationKey);
}
}
return db.medic.allDocs({ keys: [...docIds], include_docs: true });
})
.then(results => results.rows.map(row => row.doc).filter(doc => doc));
};
/**
* Returns a list of places for which the passed contacts are assigned as primary contacts.
* @param {Array.<{_id: string}>} docs
* @returns {Promise<Object[]>}
*/
const getPrimaryPlaces = async (docs) => {
const docIds = docs.map(doc => doc._id);
const queryResult = await db.medic.query('medic/contacts_by_primary_contact', { keys: docIds, include_docs: true });
return queryResult.rows.map(row => row.doc).filter(doc => doc);
};
/**
* Iterates over list of contacts and populates list of allowed subject ids. Returns whether new subjects were added.
* @param {{ subjectIds: string[], replicatePrimaryContacts: Boolean }} authorizationCtx
* @param {Object[]} contacts - contact docs to be evaluated
*/
const populateAllowedSubjectIds = (authorizationCtx, contacts) => {
const initialSubjectIdsCount = authorizationCtx.subjectIds.length;
contacts.forEach(contact => {
const viewResults = getViewResults(contact);
if (!allowedDoc(contact._id, authorizationCtx, viewResults)) {
return;
}
const contactsByDepthResults = viewResults.contactsByDepth?.[0]?.value;
if (!contactsByDepthResults) {
return;
}
const subjectIds = [contact._id, contactsByDepthResults.shortcode];
if (authorizationCtx.replicatePrimaryContacts) {
subjectIds.push(contactsByDepthResults.primary_contact);
}
const contactDepth = getContactDepth(authorizationCtx, viewResults.contactsByDepth);
includeSubjects(authorizationCtx, subjectIds, contactDepth);
});
return authorizationCtx.subjectIds.length !== initialSubjectIdsCount;
};
/**
* To determine whether a user has access to a small set of docs (for example, during a GET attachment
* request), instead of querying `medic/contacts_by_depth` to get all allowed subjectIds, runs the view queries
* over the provided docs, gets all contacts that the docs emit for in `medic/docs_by_replication_key`,
* if primary contacts are replicated, we also include the docs' lineage, and creates a reduced set of
* relevant allowed subject ids.
*
* @param {userCtx} userCtx
* @param {Array.<{doc: Object, viewResults: Object}>} scopeDocsCtx
* @returns { Promise<AuthorizationContext> }
*/
const getScopedAuthorizationContext = async (userCtx, scopeDocsCtx = []) => {
const authorizationCtx = getContextObject(userCtx);
scopeDocsCtx = scopeDocsCtx.filter(docCtx => docCtx && docCtx.doc);
if (!scopeDocsCtx.length) {
return authorizationCtx;
}
// collect all values that the docs would emit in `medic/docs_by_replication_key`
const replicationKeys = [];
scopeDocsCtx.forEach(docCtx => {
const viewResults = docCtx.viewResults || getViewResults(docCtx.doc);
replicationKeys.push(...getReplicationKeys(viewResults));
docCtx.viewResults = viewResults;
});
const contacts = await findContactsByReplicationKeys(replicationKeys);
if (authorizationCtx.replicatePrimaryContacts) {
const primaryPlaces = await getPrimaryPlaces(contacts);
contacts.push(...primaryPlaces);
}
// we simulate a `medic/contacts_by_depth` filter over the list contacts
// reiterate because primary contacts are only included in subjects lists
// after we initially populate it with all other contacts
let newSubjects;
do {
newSubjects = populateAllowedSubjectIds(authorizationCtx, contacts);
} while (newSubjects && authorizationCtx.replicatePrimaryContacts);
if (hasAccessToUnassignedDocs(userCtx)) {
authorizationCtx.subjectIds.push(UNASSIGNED_KEY);
}
return authorizationCtx;
};
/**
* Method to ensure users don't see private reports submitted by their boss about the user's contact
* @param {userCtx} userCtx User context object
* @param {string|undefined} subject report's subject
* @param {string|undefined} submitter report's submitter
* @param {boolean} isPrivate whether the report is private
* @param {boolean|function} allowedSubmitter boolean or function that returns a boolean representing whether the user
* can see the submitter of the report
* @returns {boolean}
*/
const isSensitive = (userCtx, subject, submitter, isPrivate, allowedSubmitter) => {
if (!subject || !submitter || !isPrivate) {
return false;
}
const sensitiveSubjects = [
...(userCtx.facility?.map(facility => registrationUtils.getSubjectIds(facility)) || []).flat(),
...registrationUtils.getSubjectIds(userCtx.contact),
...userCtx.facility_id,
userCtx.contact_id,
];
if (!sensitiveSubjects.includes(subject)) {
return false;
}
return typeof allowedSubmitter === 'function' ? !allowedSubmitter() : !allowedSubmitter;
};
/**
* Returns whether a doc should be visible, depending on configured replication_depth.report_depth.
* We're receiving all relevant replication keys to check whether at least one is of valid depth.
* In cases of reports with `needs_signoff`, the replication key of valid depth might be at facility level, but that
* key would be marked as sensitive.
* @param {AuthorizationContext} authorizationContext
* @param {DocByReplicationKey} docByReplicationKey
* @returns {boolean}
*/
const isAllowedDepth = (authorizationContext, docByReplicationKey) => {
if (!usesReportDepth(authorizationContext)) {
// no depth limitation
return true;
}
if (docByReplicationKey.type !== DOC_TYPES.DATA_RECORD) {
// allow everything that's not a data_record through (f.e. targets)
return true;
}
if (docByReplicationKey.submitter === authorizationContext.userCtx.contact_id) {
// current user is the submitter
return true;
}
const replicationKeys = Array.isArray(docByReplicationKey.key) ?
docByReplicationKey.key : [docByReplicationKey.key];
return replicationKeys.some(replicationKey => {
return authorizationContext.subjectsDepth[replicationKey] <= authorizationContext.reportDepth;
});
};
// casting everything to string to insure that comparisons are against the same type to avoid 5 > 'a' || 5 < 'a'
const prepareForSortedSearch = array => array.map(element => String(element)).sort();
const sortedIncludes = (sortedArray, element) => _.sortedIndexOf(sortedArray, String(element)) !== -1;
/**
* Returns a list of document ids that the user is allowed to see and edit
* @param authorizationContext
* @returns {Promise.<Array.<{id: string, fields: DocByReplicationKey}>>}
*/
const getDocsByReplicationKeyNouveau = async (authorizationContext) => {
const allKeys = [...authorizationContext.subjectIds];
const hits = [];
while (allKeys.length) {
const chunk = allKeys.splice(0, nouveau.BATCH_LIMIT);
const response = await request.post({
uri: `${environment.couchUrl}/_design/medic/_nouveau/docs_by_replication_key`,
body: {
q: `key:(${chunk.map(nouveau.escapeKeys).join(' OR ')})`,
limit: REPLICATION_LIMITS.SUBJECT_HITS,
}
});
if (!response.hits || !response.hits.length) {
continue;
}
// A single doc can have multiple hits (for different subjects), so this is not a strict "doc limit", but
// it is our "give up" limit
if ((hits.length + response.hits) > REPLICATION_LIMITS.SUBJECT_HITS) {
authorizationContext.userCtx.replicationLimitExceeded = true;
throw new ReplicationLimitError(
`User "${authorizationContext.userCtx.name}" exceeds the subject hits limit with at least [${
hits.length + response.hits
}] subject hits.`,
);
}
for (const hit of response.hits) {
hits.push({
id: hit.id,
fields: {
...hit.fields,
key: Array.isArray(hit.fields.key) ? hit.fields.key : [hit.fields.key],
},
});
}
}
return hits;
};
/**
* Returns a list of document ids that the user is allowed to see and edit
* @param {AuthorizationContext} authorizationContext
* @returns {Promise.<Array.<{id: string, fields: DocByReplicationKey}>>}
*/
const getDocsByReplicationKey = async (authorizationContext) => {
return getDocsByReplicationKeyNouveau(authorizationContext).then(hits => {
// leverage binary search when looking up subjects
const sortedSubjects = prepareForSortedSearch(authorizationContext.subjectIds);
const docsByReplicationKey = [];
for (const hit of hits) {
const { submitter, subject } = hit.fields;
const allowedSubmitter = () => sortedIncludes(sortedSubjects, submitter);
const sensitive = isSensitive(
authorizationContext.userCtx,
subject,
submitter,
hit.fields.private,
allowedSubmitter
);
if (!sensitive && isAllowedDepth(authorizationContext, hit.fields)) {
docsByReplicationKey.push(hit);
}
}
return docsByReplicationKey;
});
};
/**
* Returns a list of document ids that the user is allowed to see and edit
* @param {AuthorizationContext} authCtx
* @param {Array.<{id: string, fields: DocByReplicationKey}>} docsByReplicationKey
* @param {boolean} includeTasks - whether task documents should be included
* @returns {string[]}
*/
const filterAllowedDocIds = (authCtx, docsByReplicationKey, { includeTasks = true } = {}) => {
const validatedIds = [MEDIC_CLIENT_DDOC, getUserSettingsId(authCtx.userCtx.name)];
if (!docsByReplicationKey || !docsByReplicationKey.length) {
return validatedIds;
}
for (const hit of docsByReplicationKey) {
if (hit.fields.type !== 'task' || includeTasks) {
validatedIds.push(hit.id);
}
}
return _.uniq(validatedIds);
};
/**
* Evaluates medic/contacts_by_depth and medic/docs_by_replication_key view map functions over the document and
* returns results, and whether the document is a user-settings document or not
* @param {Object} doc - CouchDb document
* @returns {{contactsByDepth: Array, docsByReplicationKey: Array, couchDbUser: boolean}}
*/
const getViewResults = (doc) => {
const docsByReplicationKey = viewMapUtils.getNouveauViewMapFn('medic', 'docs_by_replication_key')(doc) || {};
return {
contactsByDepth: viewMapUtils.getViewMapFn('medic', 'contacts_by_depth')(doc),
docsByReplicationKey: {
...docsByReplicationKey,
key: Array.isArray(docsByReplicationKey.key) ? docsByReplicationKey.key : [docsByReplicationKey.key],
},
couchDbUser: couchDbUser(doc)
};
};
module.exports = {
REPLICATION_LIMITS,
DEFAULT_DDOCS,
updateContext,
getDefaultDocs,
allowedDoc,
getViewResults,
getAuthorizationContext,
getDocsByReplicationKey,
filterAllowedDocIds,
filterAllowedDocs,
getScopedAuthorizationContext,
};