forked from demisto/content
/
GSuiteAdmin.py
1560 lines (1250 loc) · 66 KB
/
GSuiteAdmin.py
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
from CommonServerPython import *
''' IMPORTS '''
import urllib.parse
import urllib3
import hashlib
import copy
from typing import List, Dict, Any, Callable, NamedTuple
from GSuiteApiModule import * # noqa: E402
# Disable insecure warnings
urllib3.disable_warnings()
''' CONSTANTS '''
MAX_PAGE_SIZE = 100
DEFAULT_PAGE_SIZE = 50
DEFAULT_LIMIT = 50
MESSAGES: Dict[str, str] = {
'TEST_FAILED_ERROR': 'Test connectivity failed. Check the configuration parameters provided.',
'TEST_CONFIGURE_ERROR': ('In order for the test_module to run, an admin_email is required, '
'if it is not configured, then each command can receive an admin_email '
'argument as an optional argument.'),
'BOOLEAN_ERROR': 'The argument {} must be either true or false.',
'INTEGER_ERROR': 'The argument {} must be a positive integer.',
'REQUIRED_ARGS_CUSTOM_SCHEMA': 'Argument field_raw_json or field_json_entry_id is required.',
'CUSTOM_SCHEMA_UPDATE_REQUIRED_ARGS': 'Argument schema_id or schema_name is required.',
'UNEXPECTED_ERROR': 'An unexpected error occurred.',
'DATATRANSFER_MISSING_ARGUMENT': 'The argument application_id or applications_raw_json'
' or application_raw_json_entry_id is required.',
'DATATRANSFER_TRANSFER_PARAM_FORMAT_ERROR': 'application_transfer_params argument not in expected format. Please '
'provide a comma separated string of format "key1:val;key2:val1,val2"',
'INVALID_ADMIN_EMAIL': 'Invalid value of argument/parameter Admin Email.',
'INVALID_RESOURCE_CUSTOMER_ID_ERROR': 'Please check the resource_id and the customer_id arguments.',
'INVALID_RESOURCE_ID_ERROR': 'Please check the resource_id argument.',
'INVALID_ORG_UNIT_PATH': 'Please insert a valid organization unit path (org_unit_path)',
'INVALID_PAGINATION_ARGS_SUPPLIED': ('In order to use pagination, please supply either the argument limit,'
' or the argument page_token, or the arguments page_token and page_size together.'),
'EXCEEDED_MAX_PAGE_SIZE_ERROR': f'The maximum page size is {MAX_PAGE_SIZE}',
'LIMIT_ARG_INVALID_ERROR': 'The limit argument can\'t be negative or equal to zero.',
}
HR_MESSAGES: Dict[str, str] = {
'MOBILE_UPDATE_SUCCESS': 'Mobile device with resource id - {} updated.',
'MOBILE_DELETE_SUCCESS': 'Mobile device with resource id - {} deleted.',
'USER_CREATE': 'User Details',
'LIST_COMMAND_SUCCESS': 'Total Retrieved {}: {}',
'ALIAS_ADD_SUCCESS': 'Added alias "{}" to user key "{}".',
'GROUP_CREATE_SUCCESS': 'A new group named "{}" created.',
'GROUP_GET_SUCCESS': 'Found group named "{}" .',
'ROLE_ASSIGNMENT_CREATE': 'Role Assignment Details',
'ROLE_CREATE_PRIVILEGES_INCORRECT_FORMAT': 'role_privileges argument missing or not in expected format. Please '
'provide a comma separated string of form "PrivilegeName1:ServiceId1,'
'PrivilegeName2:ServiceId2".',
'ROLE_CREATE_SUCCESS': 'A new role created.',
'TOKEN_REVOKE_SUCCESS': 'All access tokens deleted for {}.',
'NO_RECORDS': 'No {} found for the given argument(s).',
'CUSTOM_USER_SCHEMA_CREATE': 'Custom User Schema Details',
'CUSTOM_USER_SCHEMA_FIELD_DETAILS': 'Field Details',
'CUSTOM_USER_SCHEMA_UPDATE': 'Updated Custom User Schema Details',
'DATATRANSFER_REQUEST_CREATE_SUCCESS': 'Data Transfer Details',
'NOT_FOUND': 'No {} found.',
'USER_DELETE': 'User with user key {} deleted successfully.',
'USER_UPDATE': 'Updated User Details',
'USER_GET': 'Retrieved details for user {}',
'MOBILE_DEVICES_LIST_SUCCESS': 'Google Workspace Admin - Mobile Devices List',
'CHROMEOS_DEVICES_LIST_SUCCESS': 'Google Workspace Admin - ChromeOS Devices List',
'CHROMEOS_DEVICE_ACTION_SUCCESS': 'ChromeOS device with resource id - {} updated.',
'USER_SIGNOUT_SESSIONS': 'Signs a {} out of all web and device sessions and reset their sign-in cookies.',
}
URL_SUFFIX: Dict[str, str] = {
'DATA_TRANSFER': 'admin/datatransfer/v1/transfers',
'USER': 'admin/directory/v1/users',
'MOBILE_UPDATE': 'admin/directory/v1/customer/{}/devices/mobile/{}/action',
'MOBILE_DELETE': 'admin/directory/v1/customer/{}/devices/mobile/{}',
'USER_ALIAS': 'admin/directory/v1/users/{}/aliases',
'GROUP_CREATE': 'admin/directory/v1/groups',
'GROUP_GET': 'admin/directory/v1/groups/{}',
'ROLE_ASSIGNMENT': 'admin/directory/v1/customer/{}/roleassignments',
'ROLE_CREATE': 'admin/directory/v1/customer/{}/roles',
'TOKEN_REVOKE': 'admin/directory/v1/users/{}/tokens/{}',
'CUSTOM_USER_SCHEMA': 'admin/directory/v1/customer/{}/schemas',
'DATA_TRANSFER_CREATE': 'admin/datatransfer/v1/transfers',
'MOBILE_DEVICES_LIST': 'admin/directory/v1/customer/{}/devices/mobile',
'CHROMEOS_DEVICE_ACTION': 'admin/directory/v1/customer/{}/devices/chromeos/{}/action',
'CHROMEOS_DEVICES_LIST': 'admin/directory/v1/customer/{}/devices/chromeos',
'USER_SIGN_OUT': 'admin/directory/v1/users/{}/signOut',
}
SCOPES: Dict[str, List[str]] = {
'DIRECTORY_USER': ['https://www.googleapis.com/auth/admin.directory.user'],
'DEVICE_MOBILE': ['https://www.googleapis.com/auth/admin.directory.device.mobile'],
'GROUP': ['https://www.googleapis.com/auth/admin.directory.group'],
'ROLE_MANAGEMENT': ['https://www.googleapis.com/auth/admin.directory.rolemanagement'],
'USER_SECURITY': ['https://www.googleapis.com/auth/admin.directory.user.security'],
'DATA_TRANSFER': ['https://www.googleapis.com/auth/admin.datatransfer'],
'CUSTOM_USER_SCHEMA': ['https://www.googleapis.com/auth/admin.directory.userschema']
}
COMMAND_SCOPES: Dict[str, List[str]] = {
'DATA_TRANSFER_LIST': ['https://www.googleapis.com/auth/admin.datatransfer.readonly', *SCOPES['DATA_TRANSFER']],
'MOBILE_UPDATE': ['https://www.googleapis.com/auth/admin.directory.device.mobile.action'],
'USER_ALIAS_ADD': ['https://www.googleapis.com/auth/admin.directory.user.alias',
'https://www.googleapis.com/auth/admin.directory.user'],
'ROLE_ASSIGNMENT': ['https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly',
*SCOPES['ROLE_MANAGEMENT']],
'MOBILE_DEVICES_LIST': ['https://www.googleapis.com/auth/admin.directory.device.mobile.readonly'],
'CHROMEOS_DEVICE_ACTION': ['https://www.googleapis.com/auth/admin.directory.device.chromeos'],
'CHROMEOS_DEVICES_LIST': ['https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly'],
}
OUTPUT_PREFIX: Dict[str, str] = {
'CREATE_USER': 'GSuite.User',
'ADD_ALIAS': 'GSuite.UserAlias',
'GROUP': 'GSuite.Group',
'ROLE_ASSIGNMENT_LIST': 'GSuite.RoleAssignment(val.roleAssignmentId == obj.roleAssignmentId)',
'ROLE_ASSIGNMENT_LIST_PAGE_TOKEN': 'GSuite.PageToken.RoleAssignment',
'ROLE_ASSIGNMENT_CREATE': 'GSuite.RoleAssignment',
'ROLE': 'GSuite.Role',
'DATA_TRANSFER_LIST': 'GSuite.DataTransfer(val.id == obj.id)',
'DATA_TRANSFER_REQUEST_CREATE': 'GSuite.DataTransfer',
'DATA_TRANSFER_LIST_PAGE_TOKEN': 'GSuite.PageToken.DataTransfer',
'CUSTOM_USER_SCHEMA': 'GSuite.UserSchema',
'MOBILE_DEVICES_LIST': 'GSuite.MobileDevices',
'CHROMEOS_DEVICES_LIST': 'GSuite.ChromeOSDevices'
}
# New Classes and Named Tuples
class DevicesCommandConfig(NamedTuple):
table_headers: list[str]
table_title: str
response_devices_list_key: str
outputs_prefix: str
MobileDevicesConfig = DevicesCommandConfig(table_headers=['Serial Number', 'User Names', 'Model Name', 'OS', 'Type', 'Status'],
table_title=HR_MESSAGES.get('MOBILE_DEVICES_LIST_SUCCESS', ''),
response_devices_list_key='mobiledevices',
outputs_prefix=OUTPUT_PREFIX.get('MOBILE_DEVICES_LIST', ''),
)
ChromeOSDevicesConfig = DevicesCommandConfig(table_headers=['Serial Number', 'User Name', 'Model Name', 'OS', 'Status'],
table_title=HR_MESSAGES.get('CHROMEOS_DEVICES_LIST_SUCCESS', ''),
response_devices_list_key='chromeosdevices',
outputs_prefix=OUTPUT_PREFIX.get('CHROMEOS_DEVICES_LIST', ''),
)
class Client(GSuiteClient):
'''
This class is in charge of calling the set_authorized_http function of the GSuiteClient with the required scopes
and subject (admin_email, which can be as a command argument or integration parameter)
'''
def __init__(self, service_account_dict: Dict[str, Any], proxy: bool, verify: bool, headers: Optional[Dict[str, str]] = None,
base_url: str = '', admin_email: str = ''):
super().__init__(service_account_dict=service_account_dict,
base_url=base_url, verify=verify, proxy=proxy,
headers=headers)
self.admin_email = admin_email
def set_authorized_http(self, scopes: List[str], subject: Optional[str] = None, timeout: int = 60) -> None:
if not subject:
subject = self.admin_email
super().set_authorized_http(scopes=scopes, subject=subject, timeout=timeout)
def prepare_output_user_alias_add(alias: Dict[str, Any]) -> List[Dict[str, Any]]:
"""
To create context output for gsuite-user-alias-add.
:param alias: dictionary containing alias information.
:return: context output list.
"""
return GSuiteClient.remove_empty_entities({
'kind': alias.get('kind', ''),
'id': alias.get('id', ''),
'etag': alias.get('etag', ''),
'alias': alias.get('alias', '')
})
def prepare_args_for_user(args: Dict[str, str]) -> Dict[str, Any]:
"""
Prepares and maps argument for gsuite-user-create and gsuite-user-update command.
:param args: Command arguments.
:return: Prepared argument dictionary for filter create API.
"""
GSuiteClient.validate_set_boolean_arg(args, 'is_address_primary')
GSuiteClient.validate_set_boolean_arg(args, 'is_phone_number_primary')
GSuiteClient.validate_set_boolean_arg(args, 'suspended')
GSuiteClient.validate_set_boolean_arg(args, 'archived')
GSuiteClient.validate_set_boolean_arg(args, 'is_ip_white_listed')
return GSuiteClient.remove_empty_entities({
'name': {'familyName': args.get('last_name'),
'givenName': args.get('first_name')
},
'password': hashlib.md5(args['password'].encode()).hexdigest() if args.get('password') else None, # nosec
'hashFunction': 'MD5' if args.get('password') else None,
'primaryEmail': args.get('primary_email'),
'addresses': [{
'country': args.get('country'),
'type': args.get('address_type'),
'postalCode': args.get('postal_code'),
'primary': args.get('is_address_primary'),
'extendedAddress': args.get('extended_address'),
'region': args.get('region', ''),
'streetAddress': args.get('street_address')
}],
'emails': [{
'address': args.get('secondary_email_address'),
'type': args.get('secondary_email_type')
}],
'gender': {
'type': args.get('gender')
},
'ipWhitelisted': args.get('is_ip_white_listed', ''),
'notes': {
'contentType': args.get('notes_content_type', ''),
'value': args.get('notes_value', ''),
},
'phones': [{
'value': args.get('phone_number'),
'type': args.get('phone_number_type'),
'primary': args.get('is_phone_number_primary'),
}],
'recoveryEmail': args.get('recovery_email'),
'recoveryPhone': args.get('recovery_phone'),
'suspended': args.get('suspended'),
'archived': args.get('archived'),
'orgUnitPath': args.get('org_unit_path')
})
def prepare_output_for_user_command(response: Dict[str, Any]) -> Dict[str, Any]:
"""
Prepares output for gsuite-user commands.
:param response: response from API.
:return: Prepared output dictionary.
"""
outputs = {
'firstName': response.get('name', {}).pop('givenName', ''),
'fullName': response.get('name', {}).pop('fullName', ''),
'lastName': response.get('name', {}).pop('familyName', ''),
'gender': response.pop('gender', {}).get('type', ''),
'notesValue': response.get('notes', {}).pop('value', ''),
'notesContentType': response.get('notes', {}).pop('contentType', '')
}
outputs.update(response)
return GSuiteClient.remove_empty_entities(outputs)
def prepare_markdown_from_dictionary(data: Dict[str, Any], ignore_fields: List[str] = []) -> str:
"""
Prepares markdown from dictionary.
:param data: data directory.
:param ignore_fields: fields to ignore while preparing mark-down from dictionary.
:return: data in markdown format.
"""
hr_cell_info: List[str] = []
for key, value in data.items():
if key not in ignore_fields:
hr_cell_info.append(
'{}: {}'.format(pascalToSpace(key), ', '.join(value) if isinstance(value, list) else value))
return '\n'.join(hr_cell_info)
def prepare_readable_output_for_user_command(outputs):
"""
Prepares readable output for gsuite-user commands.
:param outputs: output context.
:return: Prepared readable output dictionary.
"""
readable_outputs = {
'addressDetails': prepare_markdown_from_dictionary(
outputs.pop('addresses', [])[0] if outputs.get('addresses', []) else {}),
'secondaryEmailDetails': prepare_markdown_from_dictionary(
outputs.pop('emails', [])[0] if outputs.get('emails', []) else {}),
'phoneDetails': prepare_markdown_from_dictionary(
outputs.pop('phones', [])[0] if outputs.get('phones', []) else {}),
}
readable_outputs.update(outputs)
return readable_outputs
def prepare_args_for_role_assignment_list(args: Dict[str, str]) -> Dict[str, str]:
"""
Prepares arguments for gsuite-role-assignment-list command.
:param args: Command arguments.
:return: Prepared arguments.
"""
return GSuiteClient.remove_empty_entities({
'pageToken': args.get('page_token'),
'roleId': args.get('role_id'),
'userKey': args.get('user_key'),
'maxResults': GSuiteClient.validate_get_int(args.get('max_results'),
MESSAGES['INTEGER_ERROR'].format('max_results'))
})
def prepare_output_for_role_assignment_list(response: Dict[str, Any]) -> Dict[str, Any]:
"""
prepares context output for gsuite-role-assignment-list.
:param response: API response.
:return: output dictionary.
"""
return GSuiteClient.remove_empty_entities({
OUTPUT_PREFIX['ROLE_ASSIGNMENT_LIST']: response.get('items', []),
OUTPUT_PREFIX['ROLE_ASSIGNMENT_LIST_PAGE_TOKEN']: {
'nextPageToken': response['nextPageToken']
} if response.get('nextPageToken', '') else {}
})
def prepare_args_for_role_assignment_create(args: Dict[str, str]) -> Dict[str, str]:
"""
Prepares arguments for gsuite-role-assignment-create command.
:param args: Command arguments.
:return: Prepared arguments.
"""
return GSuiteClient.remove_empty_entities({
'orgUnitId': args.get('org_unit_id'),
'roleId': args.get('role_id'),
'assignedTo': args.get('assigned_to'),
'scopeType': args.get('scope_type'),
})
def get_privileges_list_from_string(privileges: str) -> List[Dict[str, str]]:
"""
Converts string of form privilegeName:serviceId to a list of object containing privilegeName and serviceId keys
:param privileges: privileges string
:return: list of privilege objects
:raises ValueError: if the passed string is empty or not in expected format.
"""
if privileges and len(privileges) > 2 and ':' in privileges:
privileges_list = []
for privilege in privileges.split(','):
privilege_items = privilege.split(':')
privileges_list.append({'privilegeName': privilege_items[0], 'serviceId': privilege_items[1]})
return privileges_list
else:
raise ValueError(HR_MESSAGES['ROLE_CREATE_PRIVILEGES_INCORRECT_FORMAT'])
def prepare_args_for_datatransfer_list(args: Dict[str, str]) -> Dict[str, str]:
"""
Prepares arguments for gsuite-datatransfer-list command.
:param args: Command arguments.
:return: Prepared arguments.
"""
return GSuiteClient.remove_empty_entities({
'customerId': args.get('customer_id'),
'maxResults': GSuiteClient.validate_get_int(args.get('max_results'),
MESSAGES['INTEGER_ERROR'].format('max_results')),
'newOwnerUserId': args.get('new_owner_user_id'),
'oldOwnerUserId': args.get('old_owner_user_id'),
'pageToken': args.get('page_token'),
'status': args.get('status'),
})
def prepare_output_for_datatransfer_list(response: Dict[str, Any]) -> Dict[str, Any]:
"""
prepares context output for gsuite-datatransfer-list.
:param response: API response.
:return: output dictionary.
"""
return GSuiteClient.remove_empty_entities({
OUTPUT_PREFIX['DATA_TRANSFER_LIST']: response.get('dataTransfers', []),
OUTPUT_PREFIX['DATA_TRANSFER_LIST_PAGE_TOKEN']: {
'nextPageToken': response['nextPageToken'],
} if response.get('nextPageToken', '') else {}
})
def prepare_readable_output_for_datatransfer_list(response: Dict[str, Any]) -> str:
"""
prepares readable output for gsuite-datatransfer-list.
:param response: API response.
:return: output markdown string.
"""
readable_output = f'### Next Page Token: {response["nextPageToken"]}\n\n' if response.get("nextPageToken") else ''
# Formatting applicationDataTransfers list.
for datatransfer in response.get('dataTransfers', []):
app_transfer_markdown = ''
for app_transfer in datatransfer.get('applicationDataTransfers', []):
app_transfer_markdown += prepare_markdown_from_dictionary(app_transfer,
['applicationTransferParams']) + '\n\n'
datatransfer['applicationDataTransfers'] = app_transfer_markdown
readable_output += tableToMarkdown(
HR_MESSAGES['LIST_COMMAND_SUCCESS'].format('Data Transfers',
len(response.get('dataTransfers', []))),
response.get('dataTransfers', []),
['id', 'oldOwnerUserId', 'newOwnerUserId', 'overallTransferStatusCode', 'requestTime',
'applicationDataTransfers'],
headerTransform=pascalToSpace,
removeNull=True)
return readable_output
def prepare_args_for_custom_user_schema(args: Dict[str, str]) -> Dict[str, str]:
"""
Prepares arguments for gsuite-custom-user-schema-create/update command.
:param args: Command arguments.
:return: Prepared arguments.
:raises ValueError: If required argument(s) are not provided.
"""
if args.get('field_raw_json'):
field_json = GSuiteClient.safe_load_non_strict_json(args['field_raw_json'])
elif args.get('field_json_entry_id'):
field_json = safe_load_json(args['field_json_entry_id'])
else:
raise ValueError(MESSAGES['REQUIRED_ARGS_CUSTOM_SCHEMA'])
return GSuiteClient.remove_empty_entities({
'displayName': args.get('schema_display_name'),
'schemaName': args.get('schema_name'),
'schemaId': args.get('schema_id'),
'fields': field_json.get('fields', [])
})
def prepare_output_for_custom_user_schema(context_output: Dict[str, Any], readable_output: Dict[str, Any]) -> None:
"""
Prepares outputs for custom user schema command.
:param context_output: Context output dictionary.
:param readable_output: readable output dictionary.
:return: None
"""
for field in readable_output.get('fields', []):
field['numericIndexingSpec'] = prepare_markdown_from_dictionary(field.pop('numericIndexingSpec', {}))
for field in context_output.get('fields', []):
numeric_indexing_spec = field.pop('numericIndexingSpec', {})
field['numericIndexingSpecMinValue'] = numeric_indexing_spec.get('minValue')
field['numericIndexingSpecMaxValue'] = numeric_indexing_spec.get('maxValue')
def get_transfer_params_list_from_str(transfer_params_str: str) -> List:
"""
Extract transfer parameter list from a string of format "key1:val;key2:val1,val2"
:param transfer_params_str: Transfer parameters string
:return: Application transfer parameters list.
:raises ValueError: If the provided string is not in expected format.
"""
transfer_params = []
if transfer_params_str:
try:
if len(transfer_params_str) < 2 or ':' not in transfer_params_str:
raise ValueError
for transfer_param in transfer_params_str.split(';'):
transfer_params.append({
'key': transfer_param.split(':')[0].strip(),
'value': transfer_param.split(':')[1].strip().split(',')
})
except Exception:
raise ValueError(MESSAGES['DATATRANSFER_TRANSFER_PARAM_FORMAT_ERROR'])
return transfer_params
def prepare_datatransfer_payload_from_arguments(args: Dict[str, str]) -> Dict[str, Any]:
"""
Prepares datatransfer payload from command arguments dictionary.
:param args: Command arguments
:return: Dictionary containing datatransfer request payload.
"""
transfer_params = get_transfer_params_list_from_str(args.get('application_transfer_params', ''))
return GSuiteClient.remove_empty_entities({
'oldOwnerUserId': args.get('old_owner_id'),
'newOwnerUserId': args.get('new_owner_id'),
'applicationDataTransfers': [{
'applicationId': args.get('application_id'),
'applicationTransferParams': transfer_params
}]
})
def is_email_valid(email: str) -> bool:
"""
Validates provided email is valid or not.
:param email: email string.
:return: True if email is in valid format.
"""
return True if re.match(emailRegex, email) else False
''' COMMAND FUNCTIONS '''
@logger
def test_module(client: Client) -> str:
"""
Performs test connectivity by valid http response
:param client: client object which is used to get response from api.
:return: raise ValueError if any error occurred during connection
:raises DemistoException: If there is any other issues while making the http call.
"""
with GSuiteClient.http_exception_handler():
client.set_authorized_http(scopes=SCOPES['DIRECTORY_USER'])
if client.admin_email:
client.http_request(url_suffix=f"{URL_SUFFIX['USER']}/{client.admin_email}", method='GET')
else:
return_results(MESSAGES.get('TEST_CONFIGURE_ERROR', ''))
return 'ok'
@logger
def mobile_update_command(client: Client, args: Dict[str, str]) -> CommandResults:
"""
Takes an action that affects a mobile device. For example, remotely wiping a device.
:param client: client object used to get response from api
:param args: command arguments
:return: CommandResults which returns detailed results to war room and sets the context data.
"""
client.set_authorized_http(scopes=COMMAND_SCOPES['MOBILE_UPDATE'])
args.pop('admin_email', '')
resource_id = urllib.parse.quote(args.pop('resource_id', ''))
try:
client.http_request(
url_suffix=URL_SUFFIX['MOBILE_UPDATE'].format(urllib.parse.quote(args.pop('customer_id', '')), resource_id),
method='POST', body=args)
return CommandResults(readable_output=HR_MESSAGES['MOBILE_UPDATE_SUCCESS'].format(resource_id))
except DemistoException as e:
error_message = str(e)
if ('Internal error encountered' in error_message or 'Bad Request' in error_message):
raise DemistoException(MESSAGES.get('INVALID_RESOURCE_CUSTOMER_ID_ERROR', ''))
raise DemistoException(error_message)
@logger
def mobile_delete_command(client: Client, args: Dict[str, str]) -> CommandResults:
"""
Removes a mobile device. Note that this does not break the device's sync, it simply removes it from the list of
devices connected to the domain. If the device still has a valid login/authentication, it will be added back on
it's next successful sync.
:param client: client object used to get response from api
:param args: command arguments
:return: CommandResults which returns detailed results to war room and sets the context data.
"""
client.set_authorized_http(scopes=SCOPES['DEVICE_MOBILE'])
resource_id = urllib.parse.quote(args.pop('resource_id', ''))
client.http_request(
url_suffix=URL_SUFFIX['MOBILE_DELETE'].format(urllib.parse.quote(args.pop('customer_id', '')), resource_id),
method='DELETE')
return CommandResults(readable_output=HR_MESSAGES['MOBILE_DELETE_SUCCESS'].format(resource_id))
@logger
def user_create_command(client: Client, args: Dict[str, str]) -> CommandResults:
"""
Creates a user.
:param client: Client object.
:param args: Command arguments.
:return: Command Result.
"""
prepared_args = prepare_args_for_user(args)
client.set_authorized_http(scopes=SCOPES['DIRECTORY_USER'])
response = client.http_request(url_suffix=URL_SUFFIX['USER'], body=prepared_args, method='POST')
# Context
outputs = prepare_output_for_user_command(copy.deepcopy(response))
# Readable Output
readable_output_dict = prepare_readable_output_for_user_command(copy.deepcopy(outputs))
readable_output = tableToMarkdown(HR_MESSAGES['USER_CREATE'], readable_output_dict,
['id', 'customerId', 'primaryEmail', 'firstName', 'lastName', 'gender',
'suspended', 'notesValue', 'notesContentType', 'isAdmin', 'creationTime',
'phoneDetails',
'addressDetails', 'secondaryEmailDetails', 'ipWhitelisted', 'recoveryEmail',
'recoveryPhone'],
headerTransform=pascalToSpace, removeNull=True)
return CommandResults(outputs_prefix=OUTPUT_PREFIX['CREATE_USER'],
outputs_key_field=['id'],
outputs=outputs, raw_response=response,
readable_output=readable_output)
@logger
def role_assignment_list_command(client: Client, args: Dict[str, Any]) -> CommandResults:
"""
Prints all admin role assignments in the G Suite instance.
:param client: client object which is used to get response from api
:param args: command arguments.
:return: CommandResults object with context and human-readable.
"""
arguments = prepare_args_for_role_assignment_list(args)
client.set_authorized_http(scopes=COMMAND_SCOPES['ROLE_ASSIGNMENT'])
response = client.http_request(
url_suffix=URL_SUFFIX['ROLE_ASSIGNMENT'].format(urllib.parse.quote(args.get('customer_id', ''))),
params=arguments)
# Context
outputs = prepare_output_for_role_assignment_list(response)
# Readable Output
readable_output = f'### Next Page Token: {response["nextPageToken"]}\n' if response.get("nextPageToken") else ''
readable_output += tableToMarkdown(
HR_MESSAGES['LIST_COMMAND_SUCCESS'].format('Role Assignment(s)', len(response.get('items', []))),
response.get('items', []),
['roleAssignmentId', 'roleId', 'assignedTo', 'scopeType', 'orgUnitId'],
headerTransform=pascalToSpace,
removeNull=True) if response.get(
'items') else HR_MESSAGES['NO_RECORDS'].format('role assignment details')
return CommandResults(
outputs=outputs,
readable_output=readable_output,
raw_response=response
)
@logger
def role_assignment_create_command(client: Client, args: Dict[str, Any]) -> CommandResults:
"""
Assigns a role to the customer.
:param client: client object which is used to get response from api
:param args: command arguments.
:return: CommandResults object with context and human-readable.
"""
arguments = prepare_args_for_role_assignment_create(args)
client.set_authorized_http(scopes=SCOPES['ROLE_MANAGEMENT'])
response = client.http_request(
url_suffix=URL_SUFFIX['ROLE_ASSIGNMENT'].format(urllib.parse.quote(args.get('customer_id', ''))),
body=arguments, method='POST')
# Readable Output
readable_output = tableToMarkdown(
HR_MESSAGES['ROLE_ASSIGNMENT_CREATE'],
response,
['roleAssignmentId', 'roleId', 'assignedTo', 'scopeType', 'orgUnitId'],
headerTransform=pascalToSpace,
removeNull=True)
return CommandResults(
outputs_prefix=OUTPUT_PREFIX['ROLE_ASSIGNMENT_CREATE'],
outputs_key_field='roleAssignmentId',
outputs=GSuiteClient.remove_empty_entities(response),
readable_output=readable_output,
raw_response=response
)
@logger
def user_alias_add_command(client: Client, args: Dict[str, Any]) -> CommandResults:
"""
Adds an alias.
:param client: client object which is used to get response from api
:param args: command arguments.
:return: CommandResults object with context and human-readable.
"""
user_key = args.get('user_key', '')
user_key = urllib.parse.quote(user_key) # type: ignore
alias = args.get('alias', '')
# admin_email = ADMIN_EMAIL
body = {'alias': alias}
body = GSuiteClient.remove_empty_entities(body)
client.set_authorized_http(scopes=COMMAND_SCOPES['USER_ALIAS_ADD'])
response = client.http_request(url_suffix=URL_SUFFIX['USER_ALIAS'].format(user_key), body=body, method='POST')
outputs = prepare_output_user_alias_add(response)
readable_output = HR_MESSAGES['ALIAS_ADD_SUCCESS'].format(alias, args.get('user_key', ''))
return CommandResults(
outputs_prefix=OUTPUT_PREFIX['ADD_ALIAS'],
outputs_key_field=['id', 'alias'],
outputs=outputs,
readable_output=readable_output,
raw_response=response
)
@logger
def group_create_command(client: Client, args: Dict[str, str]) -> CommandResults:
"""
Creates a group with a group name and its description.
:param client: Client object.
:param args: Command arguments.
:return: CommandResults.
"""
client.set_authorized_http(scopes=SCOPES['GROUP'])
args.pop('admin_email', '')
args = {key.replace('group_', ''): value for (key, value) in args.items()}
response = client.http_request(url_suffix=URL_SUFFIX['GROUP_CREATE'], body=args, method='POST')
response = GSuiteClient.remove_empty_entities(response)
hr_output_fields = ['id', 'email', 'description', 'adminCreated']
readable_output = tableToMarkdown(HR_MESSAGES['GROUP_CREATE_SUCCESS'].format(response['name']),
response, headerTransform=pascalToSpace, removeNull=True,
headers=hr_output_fields)
return CommandResults(
outputs_prefix=OUTPUT_PREFIX['GROUP'],
outputs_key_field='id',
outputs=response,
readable_output=readable_output,
raw_response=response
)
@logger
def group_get_command(client: Client, args: Dict[str, str]) -> CommandResults:
"""
Get a group information with a group key
:param client: Client object.
:param args: Command arguments.
:return: CommandResults.
"""
client.set_authorized_http(scopes=SCOPES['GROUP'])
group_key_suffix = URL_SUFFIX['GROUP_GET'].format(args.pop('group', ''))
response = client.http_request(
url_suffix=group_key_suffix, method='GET')
response = GSuiteClient.remove_empty_entities(response)
hr_output_fields = ['id', 'email', 'description', 'adminCreated']
readable_output = tableToMarkdown(HR_MESSAGES['GROUP_GET_SUCCESS'].format(response['name']),
response, headerTransform=pascalToSpace, removeNull=True,
headers=hr_output_fields)
return CommandResults(
outputs_prefix=OUTPUT_PREFIX['GROUP'],
outputs_key_field='id',
outputs=response,
readable_output=readable_output,
raw_response=response
)
@logger
def role_create_command(client: Client, args: Dict[str, str]) -> CommandResults:
"""
Creates a role with a role name and its description.
:param client: Client object.
:param args: Command arguments.
:return: CommandResults.
"""
client.set_authorized_http(scopes=SCOPES['ROLE_MANAGEMENT'])
params = {
'rolePrivileges': get_privileges_list_from_string(args.pop('role_privileges', '')),
'roleName': args.get('role_name', ''),
'roleDescription': args.get('role_description', '')
}
response = client.http_request(
url_suffix=URL_SUFFIX['ROLE_CREATE'].format(urllib.parse.quote(args.get('customer_id', ''))), body=params,
method='POST')
response = GSuiteClient.remove_empty_entities(response)
hr_output = {key.replace('role', ''): value for (key, value) in response.items()}
hr_output['Privileges'] = ",\n".join(
[privilege['privilegeName'] + ': ' + privilege['serviceId'] for privilege in hr_output.get('Privileges', [])])
hr_output_fields = ['Id', 'Name', 'Description', 'Privileges']
readable_output = tableToMarkdown(HR_MESSAGES['ROLE_CREATE_SUCCESS'], hr_output, headerTransform=pascalToSpace,
removeNull=True, headers=hr_output_fields)
return CommandResults(
outputs_prefix=OUTPUT_PREFIX['ROLE'],
outputs_key_field='roleId',
outputs=response,
readable_output=readable_output,
raw_response=response
)
@logger
def token_revoke_command(client: Client, args: Dict[str, str]) -> CommandResults:
"""
Delete all access tokens issued by a user for an application.
:param client: Client object.
:param args: Command arguments.
:return: CommandResults.
"""
client.set_authorized_http(scopes=SCOPES['USER_SECURITY'])
user_key = urllib.parse.quote(args.get('user_key', ''))
client_id = urllib.parse.quote(args.get('client_id', ''))
client.http_request(url_suffix=URL_SUFFIX['TOKEN_REVOKE'].format(user_key, client_id), method='DELETE')
return CommandResults(readable_output=HR_MESSAGES['TOKEN_REVOKE_SUCCESS'].format(args.get('client_id', '')))
@logger
def user_signout_command(client: Client, args: Dict[str, str]) -> CommandResults:
"""
Signs a user out of all web and device sessions and reset their sign-in cookies.
:param client: Client object.
:param args: Command arguments.
:return: CommandResults.
"""
client.set_authorized_http(scopes=SCOPES['USER_SECURITY'])
user_key = urllib.parse.quote(args.get('user_key', ''))
client.http_request(url_suffix=URL_SUFFIX['USER_SIGN_OUT'].format(user_key), method='POST')
return CommandResults(readable_output=HR_MESSAGES['USER_SIGNOUT_SESSIONS'].format(args.get('user_key', '')))
@logger
def datatransfer_list_command(client: Client, args: Dict[str, str]) -> CommandResults:
"""
Lists the transfers for a customer by source user, destination user, or status.
:param client: Client object.
:param args: Command arguments.
:return: CommandResults.
"""
params = prepare_args_for_datatransfer_list(args)
client.set_authorized_http(scopes=COMMAND_SCOPES['DATA_TRANSFER_LIST'])
response = client.http_request(url_suffix=URL_SUFFIX['DATA_TRANSFER'], params=params)
# Context
outputs = prepare_output_for_datatransfer_list(response)
# Readable Output
readable_output = prepare_readable_output_for_datatransfer_list(copy.deepcopy(response)) if response.get(
'dataTransfers') else HR_MESSAGES['NO_RECORDS'].format('data transfer details')
return CommandResults(
outputs=outputs,
readable_output=readable_output,
raw_response=response
)
@logger
def custom_user_schema_create_command(client: Client, args: Dict[str, Any]) -> CommandResults:
"""
Creates a custom user schema to add custom fields to user profiles.
:param client: client object which is used to get response from api
:param args: command arguments.
:return: CommandResults object with context and human-readable.
"""
body = prepare_args_for_custom_user_schema(args)
client.set_authorized_http(scopes=SCOPES['CUSTOM_USER_SCHEMA'])
response = client.http_request(method='POST',
url_suffix=URL_SUFFIX['CUSTOM_USER_SCHEMA'].format(
urllib.parse.quote(args.get('customer_id', ''))),
body=body)
outputs = copy.deepcopy(response)
readable_output_dict = copy.deepcopy(response)
prepare_output_for_custom_user_schema(outputs, readable_output_dict)
readable_output = f"### {HR_MESSAGES['CUSTOM_USER_SCHEMA_CREATE']}\n"
readable_output += f"Schema Id: {readable_output_dict.get('schemaId', '')}\n"
readable_output += f"Schema Name: {readable_output_dict.get('schemaName', '')}\n"
readable_output += f"Schema Display Name: {readable_output_dict.get('displayName', '')}\n"
readable_output += tableToMarkdown(
HR_MESSAGES['CUSTOM_USER_SCHEMA_FIELD_DETAILS'],
readable_output_dict.get('fields', []),
['fieldId', 'fieldName', 'displayName', 'fieldType',
'readAccessType', 'multiValued', 'indexed', 'numericIndexingSpec'],
headerTransform=pascalToSpace,
removeNull=True)
return CommandResults(
outputs_prefix=OUTPUT_PREFIX['CUSTOM_USER_SCHEMA'],
outputs_key_field='schemaId',
outputs=GSuiteClient.remove_empty_entities(outputs),
readable_output=readable_output,
raw_response=GSuiteClient.remove_empty_entities(response)
)
@logger
def custom_user_schema_update_command(client: Client, args: Dict[str, Any]) -> CommandResults:
"""
Updates a custom user schema.
:param client: client object which is used to get response from api
:param args: command arguments.
:return: CommandResults object with context and human-readable.
:raise ValueError: If required arguments are not provided.
"""
if not args.get('schema_id') and not args.get('schema_name'):
raise ValueError(MESSAGES['CUSTOM_SCHEMA_UPDATE_REQUIRED_ARGS'])
body = prepare_args_for_custom_user_schema(args)
schema_key = args['schema_id'] if args.get('schema_id') else args.get('schema_name', '')
url_suffix = f"{URL_SUFFIX['CUSTOM_USER_SCHEMA'].format(urllib.parse.quote(args.get('customer_id', '')))}" \
f"/{urllib.parse.quote(schema_key)}"
client.set_authorized_http(scopes=SCOPES['CUSTOM_USER_SCHEMA'])
response = client.http_request(method='PUT',
url_suffix=url_suffix,
body=body)
outputs = copy.deepcopy(response)
readable_output_dict = copy.deepcopy(response)
prepare_output_for_custom_user_schema(outputs, readable_output_dict)
readable_output = f"### {HR_MESSAGES['CUSTOM_USER_SCHEMA_UPDATE']}\n"
readable_output += f"Schema Id: {readable_output_dict['schemaId']}\n" if readable_output_dict.get(
'schemaId', '') else ''
readable_output += f"Schema Name: {readable_output_dict['schemaName']}\n" if readable_output_dict.get(
'schemaName', '') else ''
readable_output += f"Schema Display Name: {readable_output_dict['displayName']}\n" if readable_output_dict.get(
'displayName', '') else ''
readable_output += tableToMarkdown(
HR_MESSAGES['CUSTOM_USER_SCHEMA_FIELD_DETAILS'],
readable_output_dict.get('fields', []),
['fieldId', 'fieldName', 'displayName', 'fieldType',
'readAccessType', 'multiValued', 'indexed', 'numericIndexingSpec'],
headerTransform=pascalToSpace,
removeNull=True)