-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathcustom.py
More file actions
2163 lines (1764 loc) · 95.8 KB
/
custom.py
File metadata and controls
2163 lines (1764 loc) · 95.8 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
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) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
"""
`az ad` module has been migrated to use Microsoft Graph API: https://learn.microsoft.com/en-us/graph/api/overview
See:
Property differences between Azure AD Graph and Microsoft Graph
https://learn.microsoft.com/en-us/graph/migrate-azure-ad-graph-property-differences
"""
import base64
import datetime
import itertools
import json
import os
import re
import uuid
import dateutil.parser
from dateutil.relativedelta import relativedelta
from knack.log import get_logger
from knack.util import CLIError, todict
from azure.core.exceptions import HttpResponseError
from azure.cli.core.profiles import ResourceType, get_sdk
from azure.cli.core.util import get_file_json, shell_safe_json_parse, is_guid
from azure.cli.core.azclierror import ArgumentUsageError
from ._client_factory import _auth_client_factory, _graph_client_factory
from ._msgrpah import GraphError, set_object_properties
# ARM RBAC's principalType
USER = 'User'
SERVICE_PRINCIPAL = 'ServicePrincipal'
GROUP = 'Group'
# Map Graph '@odata.type' to ARM RBAC's principalType
ODATA_TYPE_TO_PRINCIPAL_TYPE = {
'#microsoft.graph.user': USER,
'#microsoft.graph.servicePrincipal': SERVICE_PRINCIPAL,
'#microsoft.graph.group': GROUP
}
# Object ID property name
ID = 'id'
CREDENTIAL_WARNING = (
"The output includes credentials that you must protect. Be sure that you do not include these credentials in "
"your code or check the credentials into your source control. For more information, see https://aka.ms/azadsp-cli")
logger = get_logger(__name__)
# pylint: disable=too-many-lines, protected-access
def list_role_definitions(cmd, name=None, resource_group_name=None, scope=None,
custom_role_only=False):
definitions_client = _auth_client_factory(cmd.cli_ctx, scope).role_definitions
scope = _build_role_scope(resource_group_name, scope,
definitions_client._config.subscription_id)
return _search_role_definitions(definitions_client, name, [scope], custom_role_only)
def show_role_definition(cmd, scope=None, name=None, role_id=None):
if not any((scope, name, role_id)):
raise CLIError('Usage error: Provide --scope and --name, or --id')
if not role_id and not (name and scope):
raise CLIError('Usage error: Provide both --scope and --name')
definitions_client = _auth_client_factory(cmd.cli_ctx, scope).role_definitions
# https://learn.microsoft.com/en-us/rest/api/authorization/role-definitions/get-by-id?view=rest-authorization-2022-04-01&tabs=HTTP
if role_id:
return definitions_client.get_by_id(role_id)
# https://learn.microsoft.com/en-us/rest/api/authorization/role-definitions/get?view=rest-authorization-2022-04-01&tabs=HTTP
return definitions_client.get(scope, name)
def create_role_definition(cmd, role_definition):
return _create_update_role_definition(cmd, role_definition, for_update=False)
def update_role_definition(cmd, role_definition):
return _create_update_role_definition(cmd, role_definition, for_update=True)
def _create_update_role_definition(cmd, role_definition, for_update):
if os.path.exists(role_definition):
role_definition = get_file_json(role_definition)
else:
role_definition = shell_safe_json_parse(role_definition)
if not isinstance(role_definition, dict):
raise CLIError('Invalid role definition. A valid dictionary JSON representation is expected.')
# to workaround service defects, ensure property names are camel case
# e.g. AssignableScopes -> assignableScopes
names = [p for p in role_definition if p[:1].isupper()]
for n in names:
new_name = n[:1].lower() + n[1:]
role_definition[new_name] = role_definition.pop(n)
worker = RoleApiHelper(cmd.cli_ctx)
if for_update: # for update, we need to use guid style unique name
role_resource_id = role_definition.get('id')
if not role_resource_id:
logger.warning('Role "id" is missing. Look for the role in the current subscription...')
definitions_client = _auth_client_factory(cmd.cli_ctx, scope=role_resource_id).role_definitions
scopes_in_definition = role_definition.get('assignableScopes', None)
scopes = (scopes_in_definition if scopes_in_definition else
['/subscriptions/' + definitions_client._config.subscription_id])
if role_resource_id:
from azure.mgmt.core.tools import parse_resource_id
role_id = parse_resource_id(role_resource_id)['name']
role_name = role_definition['roleName']
else:
matched = _search_role_definitions(definitions_client, role_definition['name'], scopes)
if len(matched) > 1:
raise CLIError('More than 2 definitions are found with the name of "{}"'.format(
role_definition['name']))
if not matched:
raise CLIError('No definition was found with the name of "{}"'.format(role_definition['name']))
role_id = role_definition['name'] = matched[0].name
role_name = matched[0].role_name
else: # for create
definitions_client = _auth_client_factory(cmd.cli_ctx).role_definitions
role_id = _gen_guid()
role_name = role_definition.get('name', None)
if not role_name:
raise CLIError("please provide role name")
if not for_update and not role_definition.get('assignableScopes', None):
raise CLIError("please provide 'assignableScopes'")
return worker.create_role_definition(definitions_client, role_name, role_id, role_definition)
def delete_role_definition(cmd, name, resource_group_name=None, scope=None,
custom_role_only=False):
definitions_client = _auth_client_factory(cmd.cli_ctx, scope).role_definitions
scope = _build_role_scope(resource_group_name, scope,
definitions_client._config.subscription_id)
roles = _search_role_definitions(definitions_client, name, [scope], custom_role_only)
for r in roles:
definitions_client.delete(role_definition_id=r.name, scope=scope)
def _search_role_definitions(definitions_client, name, scopes, custom_role_only=False):
for scope in scopes:
# name argument matches the role definition's name (GUID) or roleName (e.g. 'Reader') property.
# Only roleName can be used as a filter in Role Definitions - List API.
# If name is a GUID, the filtering is performed on the client side.
filter_query = f"roleName eq '{name}'" if name and not is_guid(name) else None
roles = list(definitions_client.list(scope, filter=filter_query))
if name:
roles = [rd for rd in roles if rd.name == name or rd.role_name == name]
if custom_role_only:
roles = [rd for rd in roles if rd.role_type == 'CustomRole']
if roles:
return roles
return []
def create_role_assignment(cmd, role, scope,
assignee=None, assignee_object_id=None,
assignee_principal_type=None, description=None,
condition=None, condition_version=None, assignment_name=None):
"""Check parameters are provided correctly, then call _create_role_assignment."""
if bool(assignee) == bool(assignee_object_id):
raise CLIError('usage error: --assignee STRING | --assignee-object-id GUID')
if assignee_principal_type and not assignee_object_id:
raise CLIError('usage error: --assignee-object-id GUID --assignee-principal-type TYPE')
# If condition is set and condition-version is empty, condition-version defaults to "2.0".
if condition and not condition_version:
condition_version = "2.0"
# If condition-version is set, condition must be set as well.
if condition_version and not condition:
raise CLIError('usage error: When --condition-version is set, --condition must be set as well.')
if assignee:
object_id, principal_type = _resolve_object_id_and_type(cmd.cli_ctx, assignee, fallback_to_object_id=True)
else:
object_id = assignee_object_id
if assignee_principal_type:
# If principal type is provided, nothing to resolve, do not call Graph
principal_type = assignee_principal_type
else:
# Try best to get principal type
logger.warning('RBAC service might reject creating role assignment without --assignee-principal-type '
'in the future. Better to specify --assignee-principal-type manually.')
principal_type = _get_principal_type_from_object_id(cmd.cli_ctx, assignee_object_id)
try:
return _create_role_assignment(cmd.cli_ctx, role, object_id, scope=scope, resolve_assignee=False,
assignee_principal_type=principal_type, description=description,
condition=condition, condition_version=condition_version,
assignment_name=assignment_name)
except Exception as ex: # pylint: disable=broad-except
if _error_caused_by_role_assignment_exists(ex): # for idempotent
return list_role_assignments(cmd, assignee_object_id=object_id, role=role, scope=scope)[0]
raise
def _create_role_assignment(cli_ctx, role, assignee, resource_group_name=None, scope=None,
resolve_assignee=True, assignee_principal_type=None, description=None,
condition=None, condition_version=None, assignment_name=None):
"""Prepare scope, role ID and resolve object ID from Graph API."""
assignment_name = assignment_name or _gen_guid()
factory = _auth_client_factory(cli_ctx, scope)
assignments_client = factory.role_assignments
definitions_client = factory.role_definitions
scope = _build_role_scope(resource_group_name, scope,
assignments_client._config.subscription_id)
role_id = _resolve_role_id(role, scope, definitions_client)
object_id = _resolve_object_id(cli_ctx, assignee) if resolve_assignee else assignee
worker = RoleApiHelper(cli_ctx)
return worker.create_role_assignment(assignments_client, assignment_name, role_id, object_id, scope,
assignee_principal_type, description=description,
condition=condition, condition_version=condition_version)
def list_role_assignments(cmd, # pylint: disable=too-many-locals, too-many-branches
assignee=None, assignee_object_id=None,
role=None,
resource_group_name=None, scope=None,
include_inherited=False,
show_all=False, include_groups=False,
fill_role_definition_name=True, fill_principal_name=True):
if assignee and assignee_object_id:
raise CLIError('Usage error: Provide only one of --assignee or --assignee-object-id.')
graph_client = _graph_client_factory(cmd.cli_ctx)
authorization_client = _auth_client_factory(cmd.cli_ctx, scope)
assignments_client = authorization_client.role_assignments
definitions_client = authorization_client.role_definitions
if show_all:
if resource_group_name or scope:
raise CLIError('group or scope are not required when --all is used')
scope = None
else:
scope = _build_role_scope(resource_group_name, scope,
definitions_client._config.subscription_id)
if assignee and not assignee_object_id:
assignee_object_id = _resolve_object_id(cmd.cli_ctx, assignee, fallback_to_object_id=True)
assignments = _search_role_assignments(assignments_client, definitions_client,
scope, assignee_object_id, role,
include_inherited, include_groups)
results = todict(assignments) if assignments else []
if not results:
return []
# Fill in role definition names
if fill_role_definition_name:
role_defs = list(definitions_client.list(
scope=scope or ('/subscriptions/' + definitions_client._config.subscription_id)))
role_dics = {rd.id: rd.role_name for rd in role_defs}
for ra in results:
ra['roleDefinitionName'] = role_dics.get(ra['roleDefinitionId'])
# Fill in principal names
if fill_principal_name:
principal_ids = set(ra['principalId'] for ra in results)
if principal_ids:
try:
principals = _get_object_stubs(graph_client, principal_ids)
principal_dics = {i[ID]: _get_displayable_name(i) for i in principals}
for ra in results:
ra['principalName'] = principal_dics.get(ra['principalId']) or ''
except (HttpResponseError, GraphError) as ex:
# failure on resolving principal due to graph permission should not fail the whole thing
logger.info("Failed to resolve graph object information per error '%s'", ex)
for r in results:
if not r.get('additionalProperties'): # remove the useless "additionalProperties"
r.pop('additionalProperties', None)
return results
def update_role_assignment(cmd, role_assignment):
# Try role_assignment as a file.
if os.path.exists(role_assignment):
role_assignment = get_file_json(role_assignment)
else:
role_assignment = shell_safe_json_parse(role_assignment)
RoleAssignment = get_sdk(cmd.cli_ctx, ResourceType.MGMT_AUTHORIZATION, 'RoleAssignment', mod='models',
operation_group='role_assignments')
assignment = RoleAssignment.from_dict(role_assignment)
scope = assignment.scope
name = assignment.name
auth_client = _auth_client_factory(cmd.cli_ctx, scope)
assignments_client = auth_client.role_assignments
# Get the existing assignment to do some checks.
original_assignment = assignments_client.get(scope, name)
# Forbid condition version downgrading.
# This should be implemented on the service-side in the future.
if (assignment.condition_version and original_assignment.condition_version and
original_assignment.condition_version.startswith('2.') and assignment.condition_version.startswith('1.')):
raise CLIError("Condition version cannot be downgraded to '1.X'.")
if not assignment.principal_type:
assignment.principal_type = original_assignment.principal_type
return assignments_client.create(scope, name, parameters=assignment)
def _get_assignment_events(cli_ctx, start_time=None, end_time=None):
from azure.mgmt.monitor import MonitorManagementClient
from azure.cli.core.commands.client_factory import get_mgmt_service_client
client = get_mgmt_service_client(cli_ctx, MonitorManagementClient)
DATE_TIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
if end_time:
try:
end_time = datetime.datetime.strptime(end_time, DATE_TIME_FORMAT)
except ValueError:
raise CLIError("Input '{}' is not valid datetime. Valid example: 2000-12-31T12:59:59Z".format(end_time))
else:
end_time = datetime.datetime.utcnow()
if start_time:
try:
start_time = datetime.datetime.strptime(start_time, DATE_TIME_FORMAT)
if start_time >= end_time:
raise CLIError("Start time cannot be later than end time.")
except ValueError:
raise CLIError("Input '{}' is not valid datetime. Valid example: 2000-12-31T12:59:59Z".format(start_time))
else:
start_time = end_time - datetime.timedelta(hours=1)
time_filter = 'eventTimestamp ge {} and eventTimestamp le {}'.format(_datetime_to_utc(start_time),
_datetime_to_utc(end_time))
# set time range filter
odata_filters = 'resourceProvider eq Microsoft.Authorization and {}'.format(time_filter)
activity_log = list(client.activity_logs.list(filter=odata_filters))
start_events, end_events = {}, {}
for item in activity_log:
if item.operation_name.value.startswith('Microsoft.Authorization/roleAssignments'):
if item.status.value == 'Started':
start_events[item.operation_id] = item
else:
end_events[item.operation_id] = item
return start_events, end_events
# A custom command around 'monitoring' events to produce understandable output for RBAC audit, a common scenario.
def list_role_assignment_change_logs(cmd, start_time=None, end_time=None): # pylint: disable=too-many-branches
# pylint: disable=too-many-nested-blocks, too-many-statements
result = []
start_events, end_events = _get_assignment_events(cmd.cli_ctx, start_time, end_time)
# Use the resource `name` of roleDefinitions as keys, instead of `id`, because `id` can be inherited.
# name: b24988ac-6180-42a0-ab88-20f7382dd24c
# id: /subscriptions/0b1f6471-1bf0-4dda-aec3-cb9272f09590/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c # pylint: disable=line-too-long
if start_events:
# Only query Role Definitions and Graph when there are events returned
role_defs = {rd.name: rd.role_name for rd in list_role_definitions(cmd)}
for k, v in start_events.items():
e = end_events.get(k, None)
if not e:
continue
entry = {}
if e.status.value == 'Succeeded':
s, payload = v, None
entry = dict.fromkeys(
['principalId', 'principalName', 'scope', 'scopeName', 'scopeType', 'roleDefinitionId', 'roleName'],
None)
entry['timestamp'], entry['caller'] = e.event_timestamp, s.caller
if s.http_request:
if s.http_request.method == 'PUT':
# 'requestbody' has a wrong camel-case. Should be 'requestBody'
payload = s.properties and s.properties.get('requestbody')
entry['action'] = 'Granted'
entry['scope'] = e.authorization.scope
elif s.http_request.method == 'DELETE':
payload = e.properties and e.properties.get('responseBody')
entry['action'] = 'Revoked'
if payload:
try:
payload = json.loads(payload)
except ValueError:
pass
if payload:
if payload.get('properties') is None:
continue
payload = payload['properties']
entry['principalId'] = payload['principalId']
if not entry['scope']:
entry['scope'] = payload['scope']
if entry['scope']:
index = entry['scope'].lower().find('/providers/microsoft.authorization')
if index != -1:
entry['scope'] = entry['scope'][:index]
parts = list(filter(None, entry['scope'].split('/')))
entry['scopeName'] = parts[-1]
if len(parts) < 3:
entry['scopeType'] = 'Subscription'
elif len(parts) < 5:
entry['scopeType'] = 'Resource group'
else:
entry['scopeType'] = 'Resource'
# Look up the resource `name`, like b24988ac-6180-42a0-ab88-20f7382dd24c
role_resource_name = payload['roleDefinitionId'].split('/')[-1]
entry['roleDefinitionId'] = role_resource_name
# In case the role definition has been deleted.
entry['roleName'] = role_defs.get(role_resource_name, "N/A")
result.append(entry)
# Fill in logical user/sp names as guid principal-id not readable
principal_ids = {x['principalId'] for x in result if x['principalId']}
if principal_ids:
graph_client = _graph_client_factory(cmd.cli_ctx)
stubs = _get_object_stubs(graph_client, principal_ids)
principal_dics = {i['id']: _get_displayable_name(i) for i in stubs}
if principal_dics:
for e in result:
e['principalName'] = principal_dics.get(e['principalId'], None)
return result
def _get_displayable_name(graph_object):
# user
if 'userPrincipalName' in graph_object:
return graph_object['userPrincipalName']
# service principal
if 'servicePrincipalNames' in graph_object:
return graph_object['servicePrincipalNames'][0]
# group
return graph_object['displayName'] or ''
def delete_role_assignments(cmd, ids=None,
assignee=None, assignee_object_id=None,
role=None,
resource_group_name=None, scope=None,
include_inherited=False,
yes=None): # pylint: disable=unused-argument
# yes is currently a no-op
if not any((ids, assignee, assignee_object_id, role, resource_group_name, scope)):
raise ArgumentUsageError('Please provide at least one of these arguments: '
'--ids, --assignee, --assignee-object-id, --role, --resource-group, --scope')
if assignee and assignee_object_id:
raise CLIError('Usage error: Provide only one of --assignee or --assignee-object-id.')
factory = _auth_client_factory(cmd.cli_ctx, scope)
assignments_client = factory.role_assignments
definitions_client = factory.role_definitions
ids = ids or []
if ids:
# Warn that other arguments are overriden.
# We can't reuse the logic of `azure.cli.core.commands.arm.register_ids_argument`, because in that function,
# `ids_metadata` is built by checking `id_part` of each argument.
# Commands like `az vm delete` require a resource ID with fixed parts, such as
# /subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/virtualMachines/{}
# But for `az role assignment delete`, `--id` can have variable parts:
# - subscription level: /subscriptions/{}
# - resource group level: /subscriptions/{}/resourceGroups/{}
# - resource level: /subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/virtualMachines/{}
# so it can't be parsed into pre-defined parts and is passed to SDK as is.
ids_override_args = ['assignee', 'role', 'resource_group_name', 'scope', 'include_inherited']
for arg in ids_override_args:
if locals()[arg]:
# This is different with `register_ids_argument`'s `--ids` handling.
# `register_ids_argument` doesn't show warning if `is_default` of an argument value is true,
# but we do here. I feel being explicit is better than being implicit.
logger.warning("option '%s' will be ignored due to use of '--ids'.",
cmd.arguments[arg].type.settings['options_list'][0])
for i in ids:
assignments_client.delete_by_id(i)
return
scope = _build_role_scope(resource_group_name, scope,
assignments_client._config.subscription_id)
# Delay resolving object ID, because if ids are provided, no need to resolve
if assignee and not assignee_object_id:
assignee_object_id = _resolve_object_id(cmd.cli_ctx, assignee, fallback_to_object_id=True)
assignments = _search_role_assignments(assignments_client, definitions_client,
scope, assignee_object_id, role, include_inherited,
include_groups=False)
if assignments:
for a in assignments:
assignments_client.delete_by_id(a.id)
else:
raise CLIError('No matched assignments were found to delete')
def _search_role_assignments(assignments_client, definitions_client,
scope, assignee_object_id, role, include_inherited, include_groups):
# https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-list-rest
# "atScope()" and "principalId eq '{value}'" query cannot be used together (API limitation).
# always use "scope" if provided, so we can get assignments beyond subscription e.g. management groups
if scope:
f = 'atScope()' # atScope() excludes role assignments at subscopes
if assignee_object_id and include_groups:
f = f + " and assignedTo('{}')".format(assignee_object_id)
assignments = list(assignments_client.list_for_scope(scope=scope, filter=f))
elif assignee_object_id:
if include_groups:
f = "assignedTo('{}')".format(assignee_object_id)
else:
f = "principalId eq '{}'".format(assignee_object_id)
assignments = list(assignments_client.list_for_subscription(filter=f))
else:
assignments = list(assignments_client.list_for_subscription())
if assignments:
assignments = [ra for ra in assignments if (
# If no scope, list all assignments
not scope or
# If scope is provided with include_inherited, list assignments at and above the scope.
# Note that assignments below the scope are already excluded by atScope()
include_inherited or
# If scope is provided, list assignments at the scope
ra.scope.lower() == scope.lower()
)]
if role:
role_id = _resolve_role_id(role, scope, definitions_client)
assignments = [ra for ra in assignments if ra.role_definition_id == role_id]
# filter the assignee if "include_groups" is not provided because service side
# does not accept filter "principalId eq and atScope()"
if assignee_object_id and not include_groups:
assignments = [ra for ra in assignments if ra.principal_id == assignee_object_id]
return assignments
def list_deny_assignments(cmd, scope=None, filter_str=None):
"""List deny assignments at a scope or for the entire subscription."""
authorization_client = _auth_client_factory(cmd.cli_ctx, scope)
deny_client = authorization_client.deny_assignments
if scope:
assignments = list(deny_client.list_for_scope(scope=scope, filter=filter_str))
else:
assignments = list(deny_client.list(filter=filter_str))
return todict(assignments) if assignments else []
def show_deny_assignment(cmd, deny_assignment_id=None, deny_assignment_name=None, scope=None):
"""Get a deny assignment by ID or name."""
authorization_client = _auth_client_factory(cmd.cli_ctx, scope)
deny_client = authorization_client.deny_assignments
if deny_assignment_id:
return deny_client.get_by_id(deny_assignment_id)
if deny_assignment_name and scope:
return deny_client.get(scope=scope, deny_assignment_id=deny_assignment_name)
raise CLIError('Please provide --id, or both --name and --scope.')
def create_deny_assignment(cmd, scope=None, deny_assignment_name=None,
actions=None, not_actions=None,
description=None,
principal_id=None, principal_type=None,
exclude_principal_ids=None, exclude_principal_types=None,
assignment_name=None):
"""Create a user-assigned deny assignment.
Two modes are supported:
- Everyone mode (default): Denies actions for all principals at the scope. Requires at least one
excluded principal via --exclude-principal-ids.
- Per-principal mode: Denies actions for a specific User or ServicePrincipal. Specify the target
with --principal-id and --principal-type. Excluded principals are optional in this mode.
Constraints:
- DataActions and NotDataActions are not supported
- DoNotApplyToChildScopes is not supported
- Read actions (*/read) are not permitted
- Group type principals are not permitted
"""
if not scope:
raise CLIError('--scope is required for creating a deny assignment.')
if not deny_assignment_name:
raise CLIError('--name is required for creating a deny assignment.')
authorization_client = _auth_client_factory(cmd.cli_ctx, scope)
deny_client = authorization_client.deny_assignments
if not actions:
raise CLIError('At least one action is required via --actions.')
# Validate no read actions
for action in actions:
if action.lower().endswith('/read'):
raise CLIError(f"Read actions are not permitted for user-assigned deny assignments: '{action}'. "
"Only write, delete, and action operations can be denied.")
# Build principals list
if principal_type and not principal_id:
raise CLIError('--principal-id is required when --principal-type is specified. '
'Provide both --principal-id and --principal-type together, '
'or omit both for Everyone mode.')
if principal_id:
if not principal_type:
raise CLIError('--principal-type is required when --principal-id is specified. '
'Accepted values: User, ServicePrincipal.')
if principal_type == 'Group':
raise CLIError('Group type principals are not permitted for user-assigned deny assignments. '
'Use User or ServicePrincipal instead.')
principals = [{'id': principal_id, 'type': principal_type}]
else:
# Everyone mode — deny applies to all principals at the scope
if not exclude_principal_ids:
raise CLIError('At least one excluded principal is required via --exclude-principal-ids '
'when using Everyone mode (no --principal-id specified). '
'User-assigned deny assignments that deny Everyone require at least one exclusion.')
principals = [{'id': '00000000-0000-0000-0000-000000000000', 'type': 'SystemDefined'}]
if not assignment_name:
assignment_name = str(uuid.uuid4())
# Build exclude principals list
exclude_principals = []
if exclude_principal_ids:
if exclude_principal_types and len(exclude_principal_types) != len(exclude_principal_ids):
raise CLIError('--exclude-principal-types must have the same number of entries as --exclude-principal-ids.')
for i, pid in enumerate(exclude_principal_ids):
principal = {
'id': pid,
'type': exclude_principal_types[i] if exclude_principal_types else 'ServicePrincipal'
}
exclude_principals.append(principal)
deny_assignment_params = {
'deny_assignment_name': deny_assignment_name,
'description': description or '',
'permissions': [{
'actions': actions or [],
'not_actions': not_actions or [],
'data_actions': [],
'not_data_actions': []
}],
'scope': scope,
'principals': principals,
'exclude_principals': exclude_principals,
'is_system_protected': False
}
return deny_client.create(scope=scope, deny_assignment_id=assignment_name,
parameters=deny_assignment_params)
def delete_deny_assignment(cmd, scope=None, deny_assignment_id=None, deny_assignment_name=None):
"""Delete a user-assigned deny assignment."""
authorization_client = _auth_client_factory(cmd.cli_ctx, scope)
deny_client = authorization_client.deny_assignments
if deny_assignment_id:
return deny_client.delete_by_id(deny_assignment_id)
if deny_assignment_name and scope:
return deny_client.delete(scope=scope, deny_assignment_id=deny_assignment_name)
raise CLIError('Please provide --id, or both --name and --scope.')
def _build_role_scope(resource_group_name, scope, subscription_id):
subscription_scope = '/subscriptions/' + subscription_id
if scope:
if resource_group_name:
err = 'Resource group "{}" is redundant because scope is supplied'
raise CLIError(err.format(resource_group_name))
from azure.mgmt.core.tools import is_valid_resource_id
if scope.startswith('/subscriptions/') and not is_valid_resource_id(scope):
raise CLIError('Invalid scope. Please use --help to view the valid format.')
elif resource_group_name:
scope = subscription_scope + '/resourceGroups/' + resource_group_name
else:
scope = subscription_scope
return scope
def _resolve_role_id(role, scope, definitions_client):
role_id = None
if re.match(r'/subscriptions/.+/providers/Microsoft.Authorization/roleDefinitions/',
role, re.I):
role_id = role
else:
if is_guid(role):
role_id = '/subscriptions/{}/providers/Microsoft.Authorization/roleDefinitions/{}'.format(
definitions_client._config.subscription_id, role)
if not role_id: # retrieve role id
role_defs = list(definitions_client.list(scope, "roleName eq '{}'".format(role)))
if not role_defs:
raise CLIError("Role '{}' doesn't exist.".format(role))
if len(role_defs) > 1:
ids = [r.id for r in role_defs]
err = "More than one role matches the given name '{}'. Please pick a value from '{}'"
raise CLIError(err.format(role, ids))
role_id = role_defs[0].id
return role_id
def create_application(cmd, client, display_name, identifier_uris=None,
is_fallback_public_client=None,
service_management_reference=None,
sign_in_audience=None,
# api
requested_access_token_version=None,
# keyCredentials
key_value=None, key_type=None, key_usage=None, start_date=None, end_date=None,
key_display_name=None,
# web
web_home_page_url=None, web_redirect_uris=None,
enable_id_token_issuance=None, enable_access_token_issuance=None,
# publicClient
public_client_redirect_uris=None,
# JSON properties
app_roles=None, optional_claims=None, required_resource_accesses=None):
# pylint:disable=too-many-locals
graph_client = _graph_client_factory(cmd.cli_ctx)
existing_apps = list_applications(cmd, client, display_name=display_name)
if existing_apps:
if identifier_uris:
existing_apps = [x for x in existing_apps if set(identifier_uris).issubset(set(x['identifierUris']))]
existing_apps = [x for x in existing_apps if x['displayName'] == display_name]
if len(existing_apps) > 1:
raise CLIError("More than one application have the same display name '{}': (id) {}, please remove "
'them first.'.format(display_name, ', '.join([x[ID] for x in existing_apps])))
if len(existing_apps) == 1:
logger.warning("Found an existing application instance: (id) %s. We will patch it.",
existing_apps[0][ID])
body = update_application(
existing_apps[0], display_name=display_name, identifier_uris=identifier_uris,
is_fallback_public_client=is_fallback_public_client,
service_management_reference=service_management_reference,
sign_in_audience=sign_in_audience,
# api
requested_access_token_version=requested_access_token_version,
# keyCredentials
key_value=key_value, key_type=key_type, key_usage=key_usage,
start_date=start_date, end_date=end_date,
key_display_name=key_display_name,
# web
web_home_page_url=web_home_page_url, web_redirect_uris=web_redirect_uris,
enable_id_token_issuance=enable_id_token_issuance,
enable_access_token_issuance=enable_access_token_issuance,
# publicClient
public_client_redirect_uris=public_client_redirect_uris,
# JSON properties
app_roles=app_roles,
optional_claims=optional_claims,
required_resource_accesses=required_resource_accesses)
# No need to resolve identifierUris or appId. Just use object id.
client.application_update(existing_apps[0][ID], body)
return client.application_get(existing_apps[0][ID])
# identifierUris is no longer required, compared to AD Graph
key_credentials = _build_key_credentials(
key_value=key_value, key_type=key_type, key_usage=key_usage,
start_date=start_date, end_date=end_date, display_name=key_display_name)
body = {}
_set_application_properties(
body, display_name=display_name, identifier_uris=identifier_uris,
is_fallback_public_client=is_fallback_public_client,
service_management_reference=service_management_reference,
sign_in_audience=sign_in_audience,
# api
requested_access_token_version=requested_access_token_version,
# keyCredentials
key_credentials=key_credentials,
# web
web_home_page_url=web_home_page_url, web_redirect_uris=web_redirect_uris,
enable_id_token_issuance=enable_id_token_issuance,
enable_access_token_issuance=enable_access_token_issuance,
# publicClient
public_client_redirect_uris=public_client_redirect_uris,
# JSON properties
app_roles=app_roles, optional_claims=optional_claims, required_resource_accesses=required_resource_accesses
)
try:
result = graph_client.application_create(body)
except GraphError as ex:
if 'insufficient privileges' in str(ex).lower():
link = 'https://learn.microsoft.com/azure/azure-resource-manager/resource-group-create-service-principal-portal' # pylint: disable=line-too-long
raise CLIError("Directory permission is needed for the current user to register the application. "
"For how to configure, please refer '{}'. Original error: {}".format(link, ex))
raise
return result
def update_application(instance, display_name=None, identifier_uris=None, # pylint: disable=unused-argument
is_fallback_public_client=None,
service_management_reference=None,
sign_in_audience=None,
# api
requested_access_token_version=None,
# keyCredentials
key_value=None, key_type=None, key_usage=None, start_date=None, end_date=None,
key_display_name=None,
# web
web_home_page_url=None, web_redirect_uris=None,
enable_id_token_issuance=None, enable_access_token_issuance=None,
# publicClient
public_client_redirect_uris=None,
# JSON properties
app_roles=None, optional_claims=None, required_resource_accesses=None):
body = {}
key_credentials = None
if key_value:
key_credentials = _build_key_credentials(
key_value=key_value, key_type=key_type, key_usage=key_usage,
start_date=start_date, end_date=end_date, display_name=key_display_name)
_set_application_properties(
body, display_name=display_name, identifier_uris=identifier_uris,
is_fallback_public_client=is_fallback_public_client,
service_management_reference=service_management_reference,
sign_in_audience=sign_in_audience,
# api
requested_access_token_version=requested_access_token_version,
# keyCredentials
key_credentials=key_credentials,
# web
web_home_page_url=web_home_page_url, web_redirect_uris=web_redirect_uris,
enable_id_token_issuance=enable_id_token_issuance,
enable_access_token_issuance=enable_access_token_issuance,
# publicClient
public_client_redirect_uris=public_client_redirect_uris,
# JSON properties
app_roles=app_roles, optional_claims=optional_claims, required_resource_accesses=required_resource_accesses
)
return body
def patch_application(cmd, identifier, parameters):
graph_client = _graph_client_factory(cmd.cli_ctx)
object_id = _resolve_application(graph_client, identifier)
return graph_client.application_update(object_id, parameters)
def show_application(client, identifier):
object_id = _resolve_application(client, identifier)
result = client.application_get(object_id)
return result
def delete_application(client, identifier):
object_id = _resolve_application(client, identifier)
client.application_delete(object_id)
def list_applications(cmd, client, app_id=None, # pylint: disable=unused-argument
display_name=None, identifier_uri=None, query_filter=None,
include_all=None, show_mine=None):
if show_mine:
return list_owned_objects(client, '#microsoft.graph.application')
sub_filters = []
if query_filter:
sub_filters.append(query_filter)
if app_id:
sub_filters.append("appId eq '{}'".format(app_id))
if display_name:
sub_filters.append("startswith(displayName,'{}')".format(display_name))
if identifier_uri:
sub_filters.append("identifierUris/any(s:s eq '{}')".format(identifier_uri))
result = client.application_list(filter=' and '.join(sub_filters) if sub_filters else None)
if sub_filters or include_all:
return list(result)
result = list(itertools.islice(result, 101))
if len(result) == 101:
logger.warning("The result is not complete. You can still use '--all' to get all of them with"
" long latency expected, or provide a filter through command arguments")
return result[:100]
def _resolve_application(client, identifier):
"""Resolve an application's id (previously known as objectId) from
- appId
- id (returned as-is)
- identifierUris
"""
if is_guid(identifier):
# it is either app id or object id, let us verify
result = client.application_list(filter="appId eq '{}'".format(identifier))
# If not found, this looks like an object id
return result[0][ID] if result else identifier
result = client.application_list(filter="identifierUris/any(s:s eq '{}')".format(identifier))
if not result:
error = CLIError("Application with identifier URI '{}' doesn't exist".format(identifier))
error.status_code = 404 # Make sure CLI returns 3
raise error
return result[0][ID]
def reset_application_credential(cmd, client, identifier, create_cert=False, cert=None, years=None,
end_date=None, keyvault=None, append=False, display_name=None):
app = show_application(client, identifier)
if not app:
raise CLIError("can't find an application matching '{}'".format(identifier))
result = _reset_credential(
cmd, app, client.application_add_password, client.application_remove_password,
client.application_update, create_cert=create_cert, cert=cert, years=years,
end_date=end_date, keyvault=keyvault, append=append, display_name=display_name)
result['tenant'] = client.tenant
return result
def delete_application_credential(cmd, client, identifier, key_id, cert=False): # pylint: disable=unused-argument
sp = show_application(client, identifier)
_delete_credential(sp, client.application_remove_password, client.application_update,
key_id=key_id, cert=cert)
def list_application_credentials(cmd, identifier, cert=False):
# Also see: list_service_principal_credentials
client = _graph_client_factory(cmd.cli_ctx)
app = show_application(client, identifier)
return _list_credentials(app, cert)
def add_application_owner(client, owner_object_id, identifier):
app_object_id = _resolve_application(client, identifier)
owners = client.application_owner_list(app_object_id)
# API not idempotent and fails with:
# One or more added object references already exist for the following modified properties: 'owners'
# We make it idempotent.
if not next((x for x in owners if x[ID] == owner_object_id), None):
body = _build_directory_object_json(client, owner_object_id)
client.application_owner_add(app_object_id, body)
def remove_application_owner(client, owner_object_id, identifier):
app_object_id = _resolve_application(client, identifier)
return client.application_owner_remove(app_object_id, owner_object_id)
def list_application_owners(client, identifier):
app_object_id = _resolve_application(client, identifier)
return client.application_owner_list(app_object_id)
def _get_grant_permissions(client, client_sp_object_id=None, query_filter=None):
query_filter = query_filter or ("clientId eq '{}'".format(client_sp_object_id) if client_sp_object_id else None)
grant_info = client.oauth2_permission_grant_list(filter=query_filter)
try:
# Make the REST request immediately so that errors can be raised and handled.
return list(grant_info)
except HttpResponseError as ex:
if ex.status_code == 404:
raise CLIError("Service principal with appId or objectId '{id}' doesn't exist. "
"If '{id}' is an appId, make sure an associated service principal is created "
"for the app. To create one, run `az ad sp create --id {id}`."
.format(id=client_sp_object_id))
raise
def add_permission(client, identifier, api, api_permissions):
# requiredResourceAccess property (requiredResourceAccess collection)
# requiredResourceAccess resource type
# resourceAppId <- api
# resourceAccess property (resourceAccess collection)
# resourceAccess resource type
# id <- api_permissions
# type
resource_access_list = []
for e in api_permissions:
try:
access_id, access_type = e.split('=')
except ValueError as ex:
raise ArgumentUsageError('Usage error: Please provide both permission id and type, such as '
'`--api-permissions e1fe6dd8-ba31-4d61-89e7-88639da4683d=Scope`') from ex