-
Notifications
You must be signed in to change notification settings - Fork 77
/
account_server.js
1424 lines (1269 loc) · 51.6 KB
/
account_server.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
/* Copyright (C) 2016 NooBaa */
'use strict';
/** @typedef {import('azure-storage').BlobService} BlobService */
const P = require('../../util/promise');
const _ = require('lodash');
const net = require('net');
const AWS = require('aws-sdk');
const chance = require('chance')();
const GoogleStorage = require('../../util/google_storage_wrap');
const bcrypt = require('bcrypt');
const server_rpc = require('../server_rpc');
const config = require('../../../config');
const dbg = require('../../util/debug_module')(__filename);
const { RpcError } = require('../../rpc');
const Dispatcher = require('../notifications/dispatcher');
const http_utils = require('../../util/http_utils');
const SensitiveString = require('../../util/sensitive_string');
const cloud_utils = require('../../util/cloud_utils');
const auth_server = require('../common_services/auth_server');
const system_store = require('../system_services/system_store').get_instance();
const bucket_server = require('../system_services/bucket_server');
const pool_server = require('../system_services/pool_server');
const azure_storage = require('../../util/new_azure_storage_wrap');
const NetStorage = require('../../util/NetStorageKit-Node-master/lib/netstorage');
const usage_aggregator = require('../bg_services/usage_aggregator');
const { OP_NAME_TO_ACTION } = require('../../endpoint/sts/sts_rest');
const demo_access_keys = Object.freeze({
access_key: new SensitiveString('123'),
secret_key: new SensitiveString('abc')
});
const check_connection_timeout = 15 * 1000;
const check_new_azure_connection_timeout = 20 * 1000;
/**
*
* CREATE_ACCOUNT
*
*/
async function create_account(req) {
const account = {
_id: (
req.rpc_params.new_system_parameters ?
system_store.parse_system_store_id(req.rpc_params.new_system_parameters.account_id) :
system_store.new_system_store_id()
),
name: req.rpc_params.name,
email: req.rpc_params.email,
has_login: req.rpc_params.has_login,
is_external: req.rpc_params.is_external,
nsfs_account_config: req.rpc_params.nsfs_account_config
};
const { roles: account_roles = ['admin'] } = req.rpc_params;
validate_create_account_permissions(req);
validate_create_account_params(req);
if (account.name.unwrap() === 'demo' && account.email.unwrap() === 'demo@noobaa.com') {
account.access_keys = [demo_access_keys];
} else {
const access_keys = req.rpc_params.access_keys || [cloud_utils.generate_access_keys()];
if (!access_keys.length) throw new RpcError('FORBIDDEN', 'cannot create account without access_keys');
account.access_keys = access_keys;
}
if (req.rpc_params.must_change_password) {
account.next_password_change = new Date();
}
const sys_id = req.rpc_params.new_system_parameters ?
system_store.parse_system_store_id(req.rpc_params.new_system_parameters.new_system_id) :
req.system._id;
if (req.rpc_params.has_login) {
account.password = req.rpc_params.password;
const password_hash = await bcrypt_password(account.password.unwrap());
account.password = password_hash;
}
if (req.rpc_params.s3_access) {
if (req.rpc_params.new_system_parameters) {
account.default_resource = system_store.parse_system_store_id(req.rpc_params.new_system_parameters.default_resource);
account.allow_bucket_creation = true;
} else {
const resource = req.rpc_params.default_resource ? req.system.pools_by_name[req.rpc_params.default_resource] ||
(req.system.namespace_resources_by_name && req.system.namespace_resources_by_name[req.rpc_params.default_resource]) :
pool_server.get_internal_mongo_pool(req.system); //Internal
if (!resource) throw new RpcError('BAD_REQUEST', 'default resource doesn\'t exist');
if (resource.nsfs_config && resource.nsfs_config.fs_root_path && !req.rpc_params.nsfs_account_config) {
throw new RpcError('Invalid account configuration - must specify nsfs_account_config when default resource is a namespace resource');
}
account.default_resource = resource._id;
account.allow_bucket_creation = _.isUndefined(req.rpc_params.allow_bucket_creation) ?
true : req.rpc_params.allow_bucket_creation;
const bucket_claim_owner = req.rpc_params.bucket_claim_owner;
if (bucket_claim_owner) {
const creator_roles = req.account.roles_by_system[req.system._id];
if (creator_roles.includes('operator')) { // Not allowed to create claim owner outside of the operator
account.bucket_claim_owner = req.system.buckets_by_name[bucket_claim_owner.unwrap()]._id;
} else {
dbg.warn('None operator user was trying to set a bucket-claim-owner for account', req.account);
}
}
}
}
const roles = account_roles.map(role => ({
_id: system_store.new_system_store_id(),
account: account._id,
system: sys_id,
role
}));
// Suppress audit entry for creation of operator account.
if (!account_roles.includes('operator')) {
Dispatcher.instance().activity({
event: 'account.create',
level: 'info',
system: (req.system && req.system._id) || sys_id,
actor: req.account && req.account._id,
account: account._id,
desc: `${account.email.unwrap()} was created ` + (req.account ? `by ${req.account.email.unwrap()}` : ``),
});
}
const account_mkey = system_store.master_key_manager.new_master_key({
description: `master key of ${account._id} account`,
cipher_type: system_store.data.systems[0].master_key_id.cipher_type,
master_key_id: system_store.data.systems[0].master_key_id._id
});
account.master_key_id = account_mkey._id;
const decrypted_access_keys = _.cloneDeep(account.access_keys);
account.access_keys[0] = {
access_key: account.access_keys[0].access_key,
secret_key: system_store.master_key_manager.encrypt_sensitive_string_with_master_key_id(
account.access_keys[0].secret_key, account_mkey._id)
};
if (req.rpc_params.role_config) {
validate_assume_role_policy(req.rpc_params.role_config.assume_role_policy);
account.role_config = req.rpc_params.role_config;
}
await system_store.make_changes({
insert: {
accounts: [account],
roles,
master_keys: [account_mkey]
}
});
const created_account = system_store.data.get_by_id(account._id);
const auth = {
account_id: created_account._id
};
// since we created the first system for this account
// we expect just one system, but use _.each to get it from the map
const current_system = (req.system && req.system._id) || sys_id;
_.each(created_account.roles_by_system, (sys_roles, system_id) => {
//we cannot assume only one system.
if (current_system.toString() === system_id) {
auth.system_id = system_id;
auth.role = sys_roles[0];
}
});
return {
token: auth_server.make_auth_token(auth),
access_keys: decrypted_access_keys
};
}
function validate_assume_role_policy(policy) {
const all_op_names = Object.values(OP_NAME_TO_ACTION);
for (const statement of policy.statement) {
for (const principal of statement.principal) {
if (principal.unwrap() !== '*') {
const account = system_store.get_account_by_email(principal);
if (!account) {
throw new RpcError('MALFORMED_POLICY', 'Invalid principal in policy', { detail: principal });
}
}
}
for (const action of statement.action) {
if (action !== 'sts:*' && !all_op_names.includes(action)) {
throw new RpcError('MALFORMED_POLICY', 'Policy has invalid action', { detail: action });
}
}
}
}
function create_external_user_account(req) {
const {
HOST: hostPools = [],
CLOUD: cloudResource = [],
INTERNAL: internalStorage = []
} = _.groupBy(system_store.data.pools, pool => pool.resource_type);
const default_resource =
cloudResource[0] ||
hostPools[0] ||
internalStorage[0];
// TODO: check if need here to add namespace resource as default resource
Object.assign(req.rpc_params, {
is_external: true,
password: new SensitiveString(chance.string({ length: 16 })),
must_change_password: false,
has_login: true,
s3_access: true,
allow_bucket_creation: true,
default_resource: default_resource.name
});
return create_account(req);
}
/**
*
* READ_ACCOUNT
*
*/
function read_account(req) {
const email = req.rpc_params.email || req.account.email;
const account = system_store.get_account_by_email(email);
if (!account) {
throw new RpcError('NO_SUCH_ACCOUNT', 'No such account email: ' + email);
}
const is_self = req.account === account;
const self_roles = req.account.roles_by_system[req.system._id];
const is_operator = self_roles && self_roles.includes('operator');
return get_account_info(
account,
is_self || is_operator
);
}
function read_account_by_access_key(req) {
const { access_key } = req.rpc_params;
const account = _.find(system_store.data.accounts, acc =>
acc.access_keys && acc.access_keys[0].access_key.unwrap() === access_key.unwrap()
);
if (!account) throw new RpcError('NO_SUCH_ACCOUNT', 'No such account with credentials: ' + access_key);
return get_account_info(account);
}
/**
*
* GENERATE_ACCOUNT_KEYS
*
*/
async function generate_account_keys(req) {
const account = system_store.get_account_by_email(req.rpc_params.email);
if (!account) {
throw new RpcError('NO_SUCH_ACCOUNT', 'No such account email: ' + req.rpc_params.email);
}
if (req.system && req.account) {
if (!is_support_or_admin_or_me(req.system, req.account, account)) {
throw new RpcError('UNAUTHORIZED', 'Cannot update account');
}
}
if (account.is_support) {
throw new RpcError('FORBIDDEN', 'Cannot update support account');
}
const access_keys = cloud_utils.generate_access_keys();
access_keys.secret_key = system_store.master_key_manager.encrypt_sensitive_string_with_master_key_id(
access_keys.secret_key, account.master_key_id._id);
await system_store.make_changes({
update: {
accounts: [{
_id: account._id,
access_keys: [
access_keys
]
}]
}
});
Dispatcher.instance().activity({
event: 'account.generate_credentials',
level: 'info',
system: req.system && req.system._id,
actor: req.account && req.account._id,
account: account._id,
desc: `Credentials for ${account.email.unwrap()} were regenerated ${req.account && 'by ' + req.account.email.unwrap()}`,
});
}
/**
*
* update_account_s3_access
*
*/
function update_account_s3_access(req) {
const account = _.cloneDeep(system_store.get_account_by_email(req.rpc_params.email));
if (!account) {
throw new RpcError('NO_SUCH_ACCOUNT', 'No such account email: ' + req.rpc_params.email);
}
let system = req.system;
if (req.system && req.account) {
if (!is_support_or_admin_or_me(req.system, req.account, account)) {
throw new RpcError('UNAUTHORIZED', 'Cannot update account');
}
} else if (!req.system) {
system = system_store.data.systems_by_name[req.rpc_params.name];
}
if (account.is_support) {
throw new RpcError('FORBIDDEN', 'Cannot update support account');
}
const update = {
_id: account._id
};
//If s3_access is on, update allowed buckets and default_resource
if (req.rpc_params.s3_access) {
if (!req.rpc_params.default_resource) {
const pools = _.filter(req.system.pools_by_name, p => (!_.get(p, 'mongo_pool_info'))); // find none-internal pools
if (pools.length) { // has resources which is not internal - must supply resource
throw new RpcError('BAD_REQUEST', 'Enabling S3 requires providing default_resource');
}
}
if (req.rpc_params.default_resource) {
const resource = system.pools_by_name[req.rpc_params.default_resource] ||
(system.namespace_resources_by_name &&
system.namespace_resources_by_name[req.rpc_params.default_resource]);
if (!resource) throw new RpcError('BAD_REQUEST', 'default resource doesn\'t exist');
update.default_resource = resource._id;
} else {
update.default_resource = (Object.values(req.system.pools_by_name)[0])._id;
}
if (!_.isUndefined(req.rpc_params.allow_bucket_creation)) {
update.allow_bucket_creation = req.rpc_params.allow_bucket_creation;
}
if (req.rpc_params.nsfs_account_config) {
if (_.isUndefined(req.rpc_params.nsfs_account_config.uid) &&
_.isUndefined(req.rpc_params.nsfs_account_config.gid) && !req.rpc_params.nsfs_account_config.new_buckets_path &&
_.isUndefined(req.rpc_params.nsfs_account_config.nsfs_only)) {
throw new RpcError('FORBIDDEN', 'Invalid nsfs_account_config');
}
update.nsfs_account_config = {
...account.nsfs_account_config,
...req.rpc_params.nsfs_account_config
};
}
} else {
update.$unset = {
default_resource: true,
allow_bucket_creation: true
};
}
return system_store.make_changes({
update: {
accounts: [update]
}
})
.then(() => {
const pool = system.pools_by_name[req.rpc_params.default_resource] ||
(system.namespace_resources_by_name && system.namespace_resources_by_name[req.rpc_params.default_resource]);
const original_pool = pool && pool.name;
const desc_string = [];
const added_buckets = [];
const removed_buckets = [];
desc_string.push(`${account.email.unwrap()} S3 access was updated by ${req.account && req.account.email.unwrap()}`);
if (req.rpc_params.s3_access) {
if (original_pool !== req.rpc_params.default_resource) {
desc_string.push(`default pool changed to`, req.rpc_params.default_resource ? req.rpc_params.default_resource : `None`);
}
if (added_buckets.length) {
desc_string.push(`added buckets: ${added_buckets}`);
}
if (removed_buckets.length) {
desc_string.push(`removed buckets: ${removed_buckets}`);
}
if (account.allow_bucket_creation !== req.rpc_params.allow_bucket_creation) {
if (req.rpc_params.allow_bucket_creation) {
desc_string.push('future bucket creation was enabled');
} else {
desc_string.push('future bucket creation was disabled');
}
}
} else {
desc_string.push(`S3 permissions was changed to disabled`);
}
Dispatcher.instance().activity({
event: 'account.s3_access_updated',
level: 'info',
system: req.system && req.system._id,
actor: req.account && req.account._id,
account: account._id,
desc: desc_string.join('\n'),
});
if (removed_buckets.length) {
_.forEach(removed_buckets, bucket_name => {
const bucket = req.system.buckets_by_name[bucket_name.unwrap()];
bucket_server.check_for_lambda_permission_issue(req, bucket, [account]);
});
}
});
}
/**
*
* UPDATE_ACCOUNT
*
*/
function update_account(req) {
const params = req.rpc_params;
const account = system_store.get_account_by_email(req.rpc_params.email);
if (!account) {
throw new RpcError('NO_SUCH_ACCOUNT', 'No such account email: ' + params.email);
}
if (!is_support_or_admin_or_me(req.system, req.account, account)) {
throw new RpcError('UNAUTHORIZED', 'Cannot update account');
}
if (account.is_support) {
throw new RpcError('FORBIDDEN', 'Cannot update support account');
}
if (params.ips && !_.every(params.ips, ip_range => (net.isIP(ip_range.start) && net.isIP(ip_range.end)))) {
throw new RpcError('FORBIDDEN', 'Non valid IPs');
}
const updates = {
name: params.name,
email: params.new_email,
next_password_change: params.must_change_password === true ? new Date() : undefined,
allowed_ips: (!_.isUndefined(params.ips) && params.ips !== null) ? params.ips : undefined,
preferences: _.isUndefined(params.preferences) ? undefined : params.preferences,
};
if (req.rpc_params.role_config) {
validate_assume_role_policy(req.rpc_params.role_config.assume_role_policy);
updates.role_config = req.rpc_params.role_config;
}
const removals = {
next_password_change: params.must_change_password === false ? true : undefined,
allowed_ips: params.ips === null ? true : undefined
};
//Create the event description according to the changes performed
let event_desc = '';
if (params.new_email && params.new_email !== params.email) {
event_desc += `Email address changed from ${params.email} to ${params.new_email}. `;
}
if (!_.isUndefined(params.ips) && account.allowed_ips !== params.ips) {
if (params.ips === null) {
event_desc += `Restriction for IPs were removed`;
} else {
event_desc += `Allowed IPs were changed to ` + params.ips.map(ip_range => ip_range.start + ' - ' + ip_range.end).join(', ');
}
}
return system_store.make_changes({
update: {
accounts: [{
_id: account._id,
$set: _.omitBy(updates, _.isUndefined),
$unset: _.omitBy(removals, _.isUndefined)
}]
}
})
.then(() => Dispatcher.instance().activity({
event: 'account.update',
level: 'info',
system: req.system && req.system._id,
actor: req.account && req.account._id,
account: account._id,
desc: `${account.email.unwrap()} was updated by ${req.account && req.account.email.unwrap()}` +
(event_desc ? '. ' + event_desc : ''),
}));
}
/**
*
* RESET PASSWORD
*
*/
async function reset_password(req) {
const is_authorized_account = await verify_authorized_account(req);
if (!is_authorized_account) {
throw new RpcError('UNAUTHORIZED', 'Invalid verification password');
}
const account = system_store.data.accounts_by_email[req.rpc_params.email.unwrap()];
if (!account) {
throw new RpcError('NO_SUCH_ACCOUNT', 'No such account email: ' + req.rpc_params.email);
}
if (!is_support_or_admin_or_me(req.system, req.account, account)) {
throw new RpcError('UNAUTHORIZED', 'Cannot change password');
}
if (account.is_support) {
throw new RpcError('FORBIDDEN', 'Cannot change support password');
}
if (!account.has_login) {
throw new RpcError('FORBIDDEN', 'Cannot change non management password');
}
const params = req.rpc_params;
const password = await bcrypt_password(params.password.unwrap());
const changes = {
password: new SensitiveString(password),
next_password_change: params.must_change_password === true ? new Date() : undefined
};
const removals = {
next_password_change: params.must_change_password === false ? true : undefined
};
await system_store.make_changes({
update: {
accounts: [{
_id: account._id,
$set: _.omitBy(changes, _.isUndefined),
$unset: _.omitBy(removals, _.isUndefined)
}]
}
});
await Dispatcher.instance().activity({
event: 'account.update',
level: 'info',
system: req.system && req.system._id,
actor: req.account && req.account._id,
account: account._id,
desc: `${account.email.unwrap()} was updated by ${req.account.email.unwrap()}: reset password`,
});
}
async function get_account_usage(req) {
const { since, till, accounts, endpoint_groups } = req.rpc_params;
const account_ids = accounts && accounts.map(acc =>
_.get(system_store.data.accounts_by_email[acc.unwrap()], '_id')
);
return usage_aggregator.get_accounts_bandwidth_usage({
accounts: account_ids,
endpoint_groups,
since,
till
});
}
/**
*
* DELETE_ACCOUNT
*
*/
function delete_account(req) {
const account_to_delete = system_store.get_account_by_email(req.rpc_params.email);
_verify_can_delete_account(req, account_to_delete);
const roles_to_delete = system_store.data.roles
.filter(
role => String(role.account._id) === String(account_to_delete._id)
)
.map(
role => role._id
);
return system_store.make_changes({
remove: {
accounts: [account_to_delete._id],
roles: roles_to_delete
}
})
.then(
val => {
Dispatcher.instance().activity({
event: 'account.delete',
level: 'info',
system: req.system && req.system._id,
actor: req.account && req.account._id,
account: account_to_delete._id,
desc: `${account_to_delete.email.unwrap()} was deleted by ${req.account && req.account.email.unwrap()}`,
});
return val;
},
err => {
Dispatcher.instance().activity({
event: 'account.delete',
level: 'alert',
system: req.system && req.system._id,
actor: req.account && req.account._id,
account: account_to_delete._id,
desc: `Error: ${account_to_delete.email.unwrap()} failed to delete by ${req.account && req.account.email.unwrap()}`,
});
throw err;
}
);
}
/**
*
* DELETE_ACCOUNT BY PROPERTY
*
*/
function delete_account_by_property(req) {
let roles_to_delete = [];
const accounts_to_delete = system_store.get_accounts_by_nsfs_account_config(req.rpc_params.nsfs_account_config)
.map(account_to_delete => {
_verify_can_delete_account(req, account_to_delete);
roles_to_delete = roles_to_delete.concat(system_store.data.roles
.filter(
role => String(role.account._id) === String(account_to_delete._id)
)
.map(
role => role._id
));
return account_to_delete._id;
});
if (!accounts_to_delete.length) {
throw new RpcError('NO_SUCH_ACCOUNT', 'No account with provided uid/gid: ' +
req.rpc_params.nsfs_account_config.uid + '/' + req.rpc_params.nsfs_account_config.gid);
}
return system_store.make_changes({
remove: {
accounts: accounts_to_delete,
roles: roles_to_delete
}
});
}
/**
*
* LIST_ACCOUNTS
*
*/
function list_accounts(req) {
// list system accounts is supported only for admin / operator / support
const is_support = req.account.is_support;
const roles = !is_support && req.account.roles_by_system[req.system._id];
if (!is_support && roles && !roles.includes('admin') && !roles.includes('operator')) {
throw new RpcError('UNAUTHORIZED', 'Must be system admin or operator');
}
const accounts = system_store.data.accounts
// for support account - list all accounts
.filter(account => is_support || !account.is_support)
// filter list, UID and GID together
.filter(account => !req.rpc_params.filter ||
(req.rpc_params.filter &&
req.rpc_params.filter.fs_identity &&
req.rpc_params.filter.fs_identity.uid === (account.nsfs_account_config && account.nsfs_account_config.uid) &&
req.rpc_params.filter.fs_identity.gid === (account.nsfs_account_config && account.nsfs_account_config.gid))
)
.map(account => get_account_info(account, req.account === account));
return { accounts };
}
/**
*
* ACCOUNTS_STATUS
*
*/
function accounts_status(req) {
const any_non_support_account = _.find(system_store.data.accounts, function(account) {
return !account.is_support;
});
return {
has_accounts: Boolean(any_non_support_account)
};
}
// called only from stats_aggregator,
// we can remove here and access directly from there
function get_system_roles(req) {
return req.system.roles_by_account;
}
/**
*
* manage account external connections cache.
*
*/
async function add_external_connection(req) {
dbg.log0('add_external_connection:', req.rpc_params);
const res = await server_rpc.client.account.check_external_connection(req.rpc_params, {
auth_token: req.auth_token
});
if (res.status !== 'SUCCESS') {
throw new RpcError(res.error.code, res.error.message);
}
let info = _.pick(req.rpc_params, 'name', 'endpoint', 'endpoint_type', 'aws_sts_arn');
if (!info.endpoint_type) info.endpoint_type = 'AWS';
info.access_key = req.rpc_params.identity;
info.secret_key = system_store.master_key_manager.encrypt_sensitive_string_with_master_key_id(
req.rpc_params.secret, req.account.master_key_id._id);
info.cp_code = req.rpc_params.cp_code || undefined;
info.auth_method = req.rpc_params.auth_method || config.DEFAULT_S3_AUTH_METHOD[info.endpoint_type] || undefined;
info = _.omitBy(info, _.isUndefined);
if ((info.endpoint_type === 'AWS' || info.endpoint_type === 'S3_COMPATIBLE') &&
(!info.endpoint.startsWith('http://') && !info.endpoint.startsWith('https://'))) {
info.endpoint = 'http://' + info.endpoint;
}
// TODO: Maybe we should check differently regarding NET_STORAGE connections
//Verify the exact connection does not exist
const conn = _.find(req.account.sync_credentials_cache, function(cred) {
return cred.endpoint === info.endpoint &&
cred.endpoint_type === info.endpoint_type &&
cred.access_key.unwrap() === info.access_key.unwrap();
});
if (conn) {
throw new RpcError('External Connection Already Exists');
}
await system_store.make_changes({
update: {
accounts: [{
_id: req.account._id,
$push: { sync_credentials_cache: info }
}]
}
});
Dispatcher.instance().activity({
event: 'account.connection_create',
level: 'info',
system: req.system && req.system._id,
actor: req.account && req.account._id,
account: req.account && req.account._id,
desc: `Connection "${info.name}" was created by ${req.account && req.account.email.unwrap()}.
\nEndpoint: ${req.rpc_params.endpoint}
\nAccess key: ${req.rpc_params.identity}`,
});
}
async function update_external_connection(req) {
const connection = cloud_utils.find_cloud_connection(req.account, req.rpc_params.name);
const {
name,
identity = connection.access_key,
secret
} = req.rpc_params;
const encrypted_secret = system_store.master_key_manager.encrypt_sensitive_string_with_master_key_id(
secret, req.account.master_key_id._id);
let check_failed = false;
try {
const { status } = await _check_external_connection_internal({
name,
identity,
secret,
endpoint_type: connection.endpoint_type,
endpoint: connection.endpoint,
cp_code: connection.cp_code,
auth_method: connection.auth_method
});
check_failed = status !== 'SUCCESS';
} catch (error) {
dbg.error('update_external_connection: _check_external_connection_internal had error', error);
check_failed = true;
}
if (check_failed) {
throw new RpcError('INVALID_CREDENTIALS', `Credentials are not valid ${name}`);
}
const accounts_updates = [{
$find: {
_id: req.account._id,
"sync_credentials_cache.name": name
},
$set: {
"sync_credentials_cache.$.access_key": identity,
"sync_credentials_cache.$.secret_key": encrypted_secret
}
}];
const pools_updates = system_store.data.pools
.filter(pool =>
pool.cloud_pool_info &&
pool.cloud_pool_info.endpoint_type === connection.endpoint_type &&
pool.cloud_pool_info.endpoint === connection.endpoint &&
pool.cloud_pool_info.access_keys.account_id._id === req.account._id &&
pool.cloud_pool_info.access_keys.access_key.unwrap() === connection.access_key.unwrap()
)
.map(pool => ({
_id: pool._id,
'cloud_pool_info.access_keys.access_key': identity,
'cloud_pool_info.access_keys.secret_key': encrypted_secret,
}));
const ns_resources_updates = system_store.data.namespace_resources
.filter(ns_resource =>
ns_resource.connection &&
ns_resource.connection.endpoint_type === connection.endpoint_type &&
ns_resource.connection.endpoint === connection.endpoint &&
ns_resource.account._id === req.account._id &&
ns_resource.connection.access_key.unwrap() === connection.access_key.unwrap()
)
.map(ns_resource => ({
_id: ns_resource._id,
'connection.access_key': identity,
'connection.secret_key': encrypted_secret
}));
await system_store.make_changes({
update: {
accounts: accounts_updates,
pools: pools_updates,
namespace_resources: ns_resources_updates
}
});
if (pools_updates.length > 0) {
await server_rpc.client.hosted_agents.update_credentials({
pool_ids: pools_updates.map(update => String(update._id)),
credentials: {
access_key: identity.unwrap(),
secret_key: secret.unwrap(),
}
}, {
auth_token: req.auth_token
});
}
}
async function check_external_connection(req) {
dbg.log0('check_external_connection:', req.rpc_params);
const params = req.rpc_params;
const account = req.account;
const connection = req.rpc_params.name && _.find(account.sync_credentials_cache, sync_conn =>
sync_conn.name === req.rpc_params.name);
if (connection && !req.rpc_params.ignore_name_already_exist) {
throw new RpcError('CONNECTION_ALREADY_EXIST', 'Connection name already exists: ' + req.rpc_params.name);
}
return _check_external_connection_internal(params);
}
async function _check_external_connection_internal(connection) {
const { endpoint_type } = connection;
switch (endpoint_type) {
case 'AZURE': {
return check_azure_connection(connection);
}
case 'AWSSTS': {
return check_aws_sts_connection(connection);
}
case 'AWS':
case 'S3_COMPATIBLE':
case 'FLASHBLADE':
case 'IBM_COS': {
return check_aws_connection(connection);
}
case 'NET_STORAGE': {
return check_net_storage_connection(connection);
}
case 'GOOGLE': {
return check_google_connection(connection);
}
default: {
throw new Error('Unknown endpoint type');
}
}
}
async function check_azure_connection(params) {
try {
// set a timeout for the entire flow
const res = await P.timeout(
check_new_azure_connection_timeout,
_check_azure_connection_internal(params),
() => new Error('TIMEOUT')
);
return res;
} catch (err) {
dbg.warn(`check_azure_connection: params`, _.omit(params, 'secret'), ` error: ${err}`);
return {
status: err.message,
error: {
code: err.err_code,
message: err.err_message
}
};
}
}
async function _check_azure_connection_internal(params) {
const conn_str = cloud_utils.get_azure_new_connection_string({
endpoint: params.endpoint,
access_key: params.identity,
secret_key: params.secret
});
function err_to_status(err, status) {
return Object.assign(new Error(status), {
err_code: err.code || 'Error',
err_message: err.message || 'Unknown Error',
});
}
/** @type {azure_storage.BlobServiceClient} */
let blob;
try {
blob = azure_storage.BlobServiceClient.fromConnectionString(conn_str);
} catch (err) {
dbg.warn(`got error on createBlobService with params`, _.omit(params, 'secret'), ` error: ${err}`);
throw err_to_status(err, 'INVALID_CONNECTION_STRING');
}
try {
const iterator = blob.listContainers().byPage({ maxPageSize: 100 });
const response = (await iterator.next()).value;
dbg.log1('_check_azure_connection_internal: got response: ', response);
} catch (err) {
dbg.warn(`got error on listContainers with params`, _.omit(params, 'secret'), ` error: ${err}`);
if (err.code === 'AuthenticationFailed' &&
err.authenticationerrordetail && err.authenticationerrordetail.indexOf('Request date header too old') > -1) {
throw err_to_status(err, 'TIME_SKEW');
} else if (err.code === 'ENOTFOUND') {
throw err_to_status(err, 'UNKNOWN_FAILURE');
} else {
throw err_to_status(err, err.code === 'AuthenticationFailed' ? 'INVALID_CREDENTIALS' : 'INVALID_ENDPOINT');
}
}
let service_properties;
try {
service_properties = await blob.getProperties();
} catch (err) {
dbg.warn(`got error on getServiceProperties with params`, _.omit(params, 'secret'), ` error: ${err}`);
err.code = err.code || (err.details && err.details.errorCode);
throw err_to_status(err, 'NOT_SUPPORTED');
}
if (!service_properties.blobAnalyticsLogging) {
dbg.warn(`Error - connection for Premium account with params`, _.omit(params, 'secret'));
throw err_to_status({}, 'NOT_SUPPORTED');
}
return { status: 'SUCCESS' };
}
const aws_error_mapping = Object.freeze({
OperationTimeout: 'TIMEOUT',
UnknownEndpoint: 'INVALID_ENDPOINT',
NetworkingError: 'INVALID_ENDPOINT',
XMLParserError: 'INVALID_ENDPOINT',
InvalidAccessKeyId: 'INVALID_CREDENTIALS',
SignatureDoesNotMatch: 'INVALID_CREDENTIALS',
RequestTimeTooSkewed: 'TIME_SKEW'
});
const net_storage_error_mapping = Object.freeze({
OperationTimeout: 'TIMEOUT',
UnknownEndpoint: 'INVALID_ENDPOINT',
NetworkingError: 'INVALID_ENDPOINT',
XMLParserError: 'INVALID_ENDPOINT',
InvalidAccessKeyId: 'INVALID_CREDENTIALS',
SignatureDoesNotMatch: 'INVALID_CREDENTIALS',
RequestTimeTooSkewed: 'TIME_SKEW'
});
async function check_google_connection(params) {
try {
const key_file = JSON.parse(params.secret.unwrap());
const credentials = _.pick(key_file, 'client_email', 'private_key');
const storage = new GoogleStorage({ credentials, projectId: key_file.project_id });
await storage.getBuckets();
return { status: 'SUCCESS' };