Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_adapplication.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2020 Guopeng Lin, <[email protected]>
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 DOCUMENTATION = '''
12 ---
13 module: azure_rm_adapplication
14
15 version_added: "1.6.0"
16
17 short_description: Manage Azure Active Directory application
18
19 description:
20 - Manage Azure Active Directory application.
21
22 options:
23 app_id:
24 description:
25 - Application ID.
26 type: str
27
28 display_name:
29 description:
30 - The display name of the application.
31 required: true
32 type: str
33
34 app_roles:
35 description:
36 - Declare the roles you want to associate with your application.
37 type: list
38 elements: dict
39 suboptions:
40 allowed_member_types:
41 description:
42 - Specifies whether this app role can be assigned to users and groups I(allowed_member_types=User).
43 - To other application's I(allowed_member_types=Application).
44 - Or both C(User) and C(Appplication).
45 type: list
46 elements: str
47 required: True
48 description:
49 description:
50 - The description for the app role.
51 - This is displayed when the app role is being assigned.
52 - if the app role functions as an application permission, during consent experiences.
53 type: str
54 display_name:
55 description:
56 - Display name for the permission that appears in the app role assignment and consent experiences.
57 type: str
58 is_enabled:
59 description:
60 - When creating or updating an app role, this must be set to true (which is the default).
61 - To delete a role, this must first be set to false.
62 - At that point, in a subsequent call, this role may be removed.
63 type: bool
64 value:
65 description:
66 - Specifies the value to include in the roles claim in ID tokens and access tokens authenticating an assigned user or service principal.
67 - Must not exceed 120 characters in length.
68 - Allowed characters include ! # $ % & ' ( ) * + , - . / : ; < = > ? @ [ ] ^ + _ ` { | } ~, and characters in the ranges 0-9, A-Z and a-z.
69 - Any other character, including the space character, are not allowed.
70 type: str
71
72 sign_in_audience:
73 description:
74 - The application can be used from any Azure AD tenants.
75 - Microsoft Graph SDK deprecate I(available_to_other_tenants), replace by I(sign_in_audience).
76 - Refer to link U(https://learn.microsoft.com/en-us/graph/migrate-azure-ad-graph-property-differences#application-property-differences)
77 type: str
78 choices:
79 - AzureADMyOrg
80 - AzureADMultipleOrgs
81 - AzureADandPersonalMicrosoftAccount
82 - PersonalMicrosoftAccount
83
84 credential_description:
85 description:
86 - The description of the password.
87 type: str
88
89 end_date:
90 description:
91 - Date or datetime after which credentials expire(e.g. '2017-12-31').
92 - Default value is one year after current time.
93 type: str
94
95 homepage:
96 description:
97 - The url where users can sign in and use your app.
98 type: str
99
100 identifier_uris:
101 description:
102 - Space-separated unique URIs that Azure AD can use for this app.
103 elements: str
104 type: list
105
106 key_type:
107 description:
108 - The type of the key credentials associated with the application.
109 type: str
110 default: AsymmetricX509Cert
111 choices:
112 - AsymmetricX509Cert
113 - Password
114 - Symmetric
115
116 key_usage:
117 description:
118 - The usage of the key credentials associated with the application.
119 type: str
120 default: Verify
121 choices:
122 - Sign
123 - Verify
124
125 key_value:
126 description:
127 - The value for the key credentials associated with the application.
128 type: str
129
130 native_app:
131 description:
132 - An application which can be installed on a user's device or computer.
133 type: bool
134
135 notes:
136 description:
137 - Notes relevant for the management of the application.
138 type: str
139
140 oauth2_allow_implicit_flow:
141 description:
142 - Whether to allow implicit grant flow for OAuth2.
143 type: bool
144
145 optional_claims:
146 description:
147 - Declare the optional claims for the application.
148 type: dict
149 suboptions:
150 access_token_claims :
151 description:
152 - The optional claims returned in the JWT access token
153 type: list
154 elements: dict
155 suboptions:
156 name:
157 description:
158 - The name of the optional claim.
159 type: str
160 required: True
161 source:
162 description:
163 - The source (directory object) of the claim.
164 - There are predefined claims and user-defined claims from extension properties.
165 - If the source value is null, the claim is a predefined optional claim.
166 - If the source value is user, the value in the name property is the extension property from the user object.
167 type: str
168 essential:
169 description:
170 - If the value is true, the claim specified by the client is necessary to ensure a smooth authorization experience\
171 for the specific task requested by the end user.
172 - The default value is false.
173 default: false
174 type: bool
175 additional_properties:
176 description:
177 - Additional properties of the claim.
178 - If a property exists in this collection, it modifies the behavior of the optional claim specified in the name property.
179 type: list
180 elements: str
181 id_token_claims:
182 description:
183 - The optional claims returned in the JWT ID token
184 type: list
185 elements: dict
186 suboptions:
187 name:
188 description:
189 - The name of the optional claim.
190 type: str
191 required: True
192 source:
193 description:
194 - The source (directory object) of the claim.
195 - There are predefined claims and user-defined claims from extension properties.
196 - If the source value is null, the claim is a predefined optional claim.
197 - If the source value is user, the value in the name property is the extension property from the user object.
198 type: str
199 essential:
200 description:
201 - If the value is true, the claim specified by the client is necessary to ensure a smooth authorization experience\
202 for the specific task requested by the end user.
203 - The default value is false.
204 default: false
205 type: bool
206 additional_properties:
207 description:
208 - Additional properties of the claim.
209 - If a property exists in this collection, it modifies the behavior of the optional claim specified in the name property.
210 type: list
211 elements: str
212 saml2_token_claims:
213 description:
214 - The optional claims returned in the SAML token
215 type: list
216 elements: dict
217 suboptions:
218 name:
219 description:
220 - The name of the optional claim.
221 type: str
222 required: True
223 source:
224 description:
225 - The source (directory object) of the claim.
226 - There are predefined claims and user-defined claims from extension properties.
227 - If the source value is null, the claim is a predefined optional claim.
228 - If the source value is user, the value in the name property is the extension property rom the user object.
229 type: str
230 essential:
231 description:
232 - If the value is true, the claim specified by the client is necessary to ensure a smooth authorization experience\
233 for the specific task requested by the end user.
234 - The default value is false.
235 default: false
236 type: bool
237 additional_properties:
238 description:
239 - Additional properties of the claim.
240 - If a property exists in this collection, it modifies the behavior of the optional claim specified in the name property.
241 type: list
242 elements: str
243 password:
244 description:
245 - App password, aka 'client secret'.
246 type: str
247
248 web_reply_urls:
249 description:
250 - The web redirect urls.
251 - Space-separated URIs to which Azure AD will redirect in response to an OAuth 2.0 request.
252 - The value does not need to be a physical endpoint, but must be a valid URI.
253 type: list
254 elements: str
255 aliases:
256 - reply_urls
257
258 spa_reply_urls:
259 description:
260 - The spa redirect urls.
261 - Space-separated URIs to which Azure AD will redirect in response to an OAuth 2.0 request.
262 - The value does not need to be a physical endpoint, but must be a valid URI.
263 type: list
264 elements: str
265
266 public_client_reply_urls:
267 description:
268 - The public client redirect urls.
269 - Space-separated URIs to which Azure AD will redirect in response to an OAuth 2.0 request.
270 - The value does not need to be a physical endpoint, but must be a valid URI.
271 type: list
272 elements: str
273
274 required_resource_accesses:
275 description:
276 - Resource scopes and roles the application requires access to.
277 - Should be in manifest json format.
278 type: list
279 elements: dict
280 suboptions:
281 resource_app_id:
282 description:
283 - The unique identifier for the resource that the application requires access to.
284 - This should be equal to the appId declared on the target resource application.
285 type: str
286 resource_access:
287 description:
288 - The description of the app role.
289 type: list
290 elements: dict
291 suboptions:
292 id:
293 description:
294 - The unique identifier for one of the oauth2PermissionScopes or appRole instances that the resource application exposes.
295 type: str
296 type:
297 description:
298 - Specifies whether the id property references an oauth2PermissionScopes or an appRole.
299 - Possible values are Scope or Role.
300 type: str
301
302 start_date:
303 description:
304 - Date or datetime at which credentials become valid, such as '2017-01-01'.
305 - Default value is current time.
306 type: str
307 allow_guests_sign_in:
308 description:
309 - A property on the application to indicate if the application accepts other IDPs or not or partially accepts.
310 type: bool
311 state:
312 description:
313 - Assert the state of Active Dirctory service principal.
314 - Use C(present) to create or update a Password and use C(absent) to delete.
315 default: present
316 choices:
317 - absent
318 - present
319 type: str
320
321 extends_documentation_fragment:
322 - azure.azcollection.azure
323
324 author:
325 guopeng_lin (@guopenglin)
326 haiyuan_zhang (@haiyuazhang)
327 Fred-sun (@Fred-sun)
328 '''
329
330 EXAMPLES = '''
331 - name: Create ad application
332 azure_rm_adapplication:
333 display_name: "{{ display_name }}"
334
335 - name: Create ad application with multi redirect urls
336 azure_rm_adapplication:
337 display_name: "{{ display_name }}"
338 web_reply_urls:
339 - https://web01.com
340 spa_reply_urls:
341 - https://spa01.com
342 - https://spa02.com
343 public_client_reply_urls:
344 - https://public01.com
345 - https://public02.com
346
347 - name: Create application with more parameter
348 azure_rm_adapplication:
349 display_name: "{{ display_name }}"
350 sign_in_audience: AzureADandPersonalMicrosoftAccount
351 credential_description: "for test"
352 end_date: 2021-10-01
353 start_date: 2021-05-18
354 identifier_uris: fredtest02.com
355
356 - name: delete ad application
357 azure_rm_adapplication:
358 app_id: "{{ app_id }}"
359 state: absent
360
361 - name: Add certificate credential when creating ad application
362 azure_rm_adapplication:
363 display_name: "{{ display_name }}"
364 key_type: AsymmetricX509Cert
365 key_usage: Verify
366 key_value: "{{ cert_file.content }}" # slurp gives base64 of the file; module normalizes to DER bytes
367 tenant: "{{ tenant_id }}"
368 subscription_id: "{{ subscription_id }}"
369 '''
370
371 RETURN = '''
372 display_name:
373 description:
374 - Object's display name or its prefix.
375 type: str
376 returned: always
377 sample: fredAKSCluster
378 app_id:
379 description:
380 - The application ID.
381 returned: always
382 type: str
383 sample: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
384 object_id:
385 description:
386 - Object ID of the application
387 returned: always
388 type: str
389 sample: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
390 sign_in_audience:
391 description:
392 - The application can be used from any Azure AD tenants.
393 returned: always
394 type: str
395 sample: AzureADandPersonalMicrosoftAccount
396 homepage:
397 description:
398 - The url where users can sign in and use your app.
399 returned: always
400 type: str
401 sample: null
402 identifier_uris:
403 description:
404 - Space-separated unique URIs that Azure AD can use for this app.
405 returned: always
406 type: list
407 sample: []
408 oauth2_allow_implicit_flow:
409 description:
410 - Whether to allow implicit grant flow for OAuth2.
411 returned: always
412 type: bool
413 sample: false
414 public_client_reply_urls:
415 description:
416 - The public client redirect urls.
417 - Space-separated URIs to which Azure AD will redirect in response to an OAuth 2.0 request.
418 returned: always
419 type: list
420 sample: []
421 web_reply_urls:
422 description:
423 - The web redirect urls.
424 - Space-separated URIs to which Azure AD will redirect in response to an OAuth 2.0 request.
425 returned: always
426 type: list
427 sample: []
428 spa_reply_urls:
429 description:
430 - The spa redirect urls.
431 - Space-separated URIs to which Azure AD will redirect in response to an OAuth 2.0 request.
432 returned: always
433 type: list
434 sample: []
435 optional_claims:
436 description:
437 - Declare the optional claims for the application.
438 type: complex
439 returned: always
440 contains:
441 access_token_claims :
442 description:
443 - The optional claims returned in the JWT access token
444 type: list
445 returned: always
446 sample: ['name': 'aud', 'source': null, 'essential': false, 'additional_properties': []]
447 id_token_claims:
448 description:
449 - The optional claims returned in the JWT ID token
450 type: list
451 returned: always
452 sample: ['name': 'acct', 'source': null, 'essential': false, 'additional_properties': []]
453 saml2_token_claims:
454 description:
455 - The optional claims returned in the SAML token
456 type: list
457 returned: always
458 sample: ['name': 'acct', 'source': null, 'essential': false, 'additional_properties': []]
459 '''
460
461 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
462
463 try:
464 import datetime
465 import base64
466 import re
467 import dateutil.parser
468 import uuid
469 import asyncio
470 from dateutil.relativedelta import relativedelta
471 from msgraph.generated.applications.applications_request_builder import ApplicationsRequestBuilder
472 from msgraph.generated.models.application import Application
473 from msgraph.generated.models.password_credential import PasswordCredential
474 from msgraph.generated.models.key_credential import KeyCredential
475 from msgraph.generated.models.required_resource_access import RequiredResourceAccess
476 from msgraph.generated.models.resource_access import ResourceAccess
477 from msgraph.generated.models.app_role import AppRole
478 from msgraph.generated.models.web_application import WebApplication
479 from msgraph.generated.models.spa_application import SpaApplication
480 from msgraph.generated.models.public_client_application import PublicClientApplication
481 from msgraph.generated.models.implicit_grant_settings import ImplicitGrantSettings
482 from msgraph.generated.models.optional_claim import OptionalClaim
483 from msgraph.generated.models.optional_claims import OptionalClaims
484 except ImportError:
485 # This is handled in azure_rm_common
486 pass
487
488 app_role_spec = dict(
489 allowed_member_types=dict(
490 type='list',
491 elements='str',
492 required=True
493 ),
494 description=dict(
495 type='str'
496 ),
497 display_name=dict(
498 type='str'
499 ),
500 is_enabled=dict(
501 type='bool'
502 ),
503 value=dict(
504 type='str'
505 )
506 )
507
508 claims_spec = dict(
509 name=dict(
510 type='str',
511 required=True
512 ),
513 source=dict(
514 type='str'
515 ),
516 essential=dict(
517 type='bool',
518 default=False
519 ),
520 additional_properties=dict(
521 type='list',
522 elements='str'
523 )
524 )
525
526 required_resource_accesses_spec = dict(
527 resource_app_id=dict(
528 type='str'
529 ),
530 resource_access=dict(
531 type='list',
532 elements='dict',
533 options=dict(
534 id=dict(
535 type='str'
536 ),
537 type=dict(
538 type='str'
539 )
540 )
541 )
542 )
543
544
545 class AzureRMADApplication(AzureRMModuleBaseExt):
546 def __init__(self):
547
548 self.module_arg_spec = dict(
549 app_id=dict(type='str'),
550 display_name=dict(type='str', required=True),
551 app_roles=dict(type='list', elements='dict', options=app_role_spec),
552 sign_in_audience=dict(
553 type='str',
554 choices=['AzureADMyOrg', 'AzureADMultipleOrgs', 'AzureADandPersonalMicrosoftAccount', 'PersonalMicrosoftAccount']
555 ),
556 credential_description=dict(type='str'),
557 end_date=dict(type='str'),
558 homepage=dict(type='str'),
559 allow_guests_sign_in=dict(type='bool'),
560 identifier_uris=dict(type='list', elements='str'),
561 key_type=dict(type='str', default='AsymmetricX509Cert',
562 choices=['AsymmetricX509Cert', 'Password', 'Symmetric']),
563 key_usage=dict(type='str', default='Verify', choices=['Sign', 'Verify']),
564 key_value=dict(type='str', no_log=True),
565 native_app=dict(type='bool'),
566 notes=dict(type='str'),
567 oauth2_allow_implicit_flow=dict(type='bool'),
568 optional_claims=dict(
569 type='dict',
570 options=dict(
571 access_token_claims=dict(type='list', elements='dict', no_log=True, options=claims_spec),
572 id_token_claims=dict(type='list', elements='dict', no_log=True, options=claims_spec),
573 saml2_token_claims=dict(type='list', elements='dict', no_log=True, options=claims_spec),
574 )
575 ),
576 password=dict(type='str', no_log=True),
577 public_client_reply_urls=dict(type='list', elements='str'),
578 web_reply_urls=dict(type='list', elements='str', aliases=['reply_urls']),
579 spa_reply_urls=dict(type='list', elements='str'),
580 start_date=dict(type='str'),
581 required_resource_accesses=dict(type='list', elements='dict', options=required_resource_accesses_spec),
582 state=dict(type='str', default='present', choices=['present', 'absent']),
583 )
584
585 self.state = None
586 self.app_id = None
587 self.display_name = None
588 self.app_roles = None
589 self.credential_description = None
590 self.end_date = None
591 self.homepage = None
592 self.identifier_uris = None
593 self.key_type = None
594 self.key_usage = None
595 self.key_value = None
596 self.native_app = None
597 self.notes = None
598 self.oauth2_allow_implicit_flow = None
599 self.optional_claims = None
600 self.password = None
601 self.public_client_reply_urls = None
602 self.spa_reply_urls = None
603 self.web_reply_urls = None
604 self.start_date = None
605 self.required_resource_accesses = None
606 self.allow_guests_sign_in = None
607 self.results = dict(changed=False)
608 self._client = None
609 self.sign_in_audience = None
610
611 super(AzureRMADApplication, self).__init__(derived_arg_spec=self.module_arg_spec,
612 supports_check_mode=False,
613 supports_tags=False,
614 is_ad_resource=True)
615
616 def exec_module(self, **kwargs):
617 self._client = self.get_msgraph_client()
618 for key in list(self.module_arg_spec.keys()):
619 setattr(self, key, kwargs[key])
620
621 response = self.get_resource()
622 if response:
623 if self.state == 'present':
624 if self.check_update(response):
625 self.update_resource(response)
626 elif self.state == 'absent':
627 self.delete_resource(response)
628 else:
629 if self.state == 'present':
630 self.create_resource()
631 elif self.state == 'absent':
632 self.log("try to delete non exist resource")
633
634 return self.results
635
636 def create_resource(self):
637 try:
638 key_creds, password_creds, required_accesses, app_roles, optional_claims = None, None, None, None, None
639 if self.native_app:
640 if self.identifier_uris:
641 self.fail("'identifier_uris' is not required for creating a native application")
642 else:
643 password_creds, key_creds = self.build_application_creds(self.password, self.key_value, self.key_type,
644 self.key_usage,
645 self.start_date, self.end_date,
646 self.credential_description)
647 if self.required_resource_accesses:
648 required_accesses = self.build_application_accesses(self.required_resource_accesses)
649
650 if self.app_roles:
651 app_roles = self.build_app_roles(self.app_roles)
652
653 if self.optional_claims:
654 optional_claims = self.build_optional_claims(self.optional_claims)
655
656 create_app = Application(
657 sign_in_audience=self.sign_in_audience,
658 web=WebApplication(
659 home_page_url=self.homepage,
660 redirect_uris=self.web_reply_urls,
661 implicit_grant_settings=ImplicitGrantSettings(
662 enable_access_token_issuance=self.oauth2_allow_implicit_flow,
663 ),
664 ),
665 spa=SpaApplication(redirect_uris=self.spa_reply_urls),
666 public_client=PublicClientApplication(redirect_uris=self.public_client_reply_urls),
667 display_name=self.display_name,
668 identifier_uris=self.identifier_uris,
669 key_credentials=key_creds,
670 notes=self.notes,
671 password_credentials=password_creds,
672 required_resource_access=required_accesses,
673 app_roles=app_roles,
674 optional_claims=optional_claims
675 # allow_guests_sign_in=self.allow_guests_sign_in,
676 )
677 response = asyncio.get_event_loop().run_until_complete(self.create_application(create_app))
678 self.results['changed'] = True
679 self.results.update(self.to_dict(response))
680 return response
681 except Exception as ge:
682 self.fail("Error creating application, display_name: {0} - {1}".format(self.display_name, str(ge)))
683
684 def update_resource(self, old_response):
685 try:
686 key_creds, password_creds, required_accesses, app_roles, optional_claims = None, None, None, None, None
687 if self.native_app:
688 if self.identifier_uris:
689 self.fail("'identifier_uris' is not required for creating a native application")
690 else:
691 password_creds, key_creds = self.build_application_creds(self.password, self.key_value, self.key_type,
692 self.key_usage,
693 self.start_date, self.end_date,
694 self.credential_description)
695 if self.required_resource_accesses:
696 required_accesses = self.build_application_accesses(self.required_resource_accesses)
697
698 if self.app_roles:
699 app_roles = self.build_app_roles(self.app_roles)
700
701 if self.optional_claims:
702 optional_claims = self.build_optional_claims(self.optional_claims)
703
704 app_update_param = Application(
705 sign_in_audience=self.sign_in_audience,
706 web=WebApplication(
707 home_page_url=self.homepage,
708 redirect_uris=self.web_reply_urls,
709 implicit_grant_settings=ImplicitGrantSettings(
710 enable_access_token_issuance=self.oauth2_allow_implicit_flow,
711 ),
712 ),
713 spa=SpaApplication(redirect_uris=self.spa_reply_urls),
714 public_client=PublicClientApplication(redirect_uris=self.public_client_reply_urls),
715 display_name=self.display_name,
716 identifier_uris=self.identifier_uris,
717 key_credentials=key_creds,
718 notes=self.notes,
719 password_credentials=password_creds,
720 required_resource_access=required_accesses,
721 # allow_guests_sign_in=self.allow_guests_sign_in,
722 app_roles=app_roles,
723 optional_claims=optional_claims)
724 asyncio.get_event_loop().run_until_complete(self.update_application(
725 obj_id=old_response['object_id'], update_app=app_update_param))
726
727 self.results['changed'] = True
728 self.results.update(self.get_resource())
729
730 except Exception as ge:
731 self.fail("Error updating the application app_id {0} - {1}".format(self.app_id, str(ge)))
732
733 def delete_resource(self, response):
734 try:
735 asyncio.get_event_loop().run_until_complete(self.delete_application(response.get('object_id')))
736 self.results['changed'] = True
737 return True
738 except Exception as ge:
739 self.fail(
740 "Error deleting application app_id {0} display_name {1} - {2}".format(self.app_id, self.display_name,
741 str(ge)))
742
743 def get_resource(self):
744 try:
745 existing_apps = []
746 if self.app_id:
747 ret = asyncio.get_event_loop().run_until_complete(self.get_application_by_app_id(self.app_id))
748 existing_apps = ret.value
749
750 if not existing_apps:
751 return False
752 result = existing_apps[0]
753 return self.to_dict(result)
754 except Exception as ge:
755 self.fail(ge)
756 # self.log("Did not find the graph instance instance {0} - {1}".format(self.app_id, str(ge)))
757 # return False
758
759 def check_update(self, response):
760 for key in list(self.module_arg_spec.keys()):
761 attr = getattr(self, key)
762 if attr and key in response:
763 if (response and attr != response[key]) or response[key] is None:
764 return True
765 return False
766
767 def serialize_claims(self, claims):
768 if claims is None:
769 return None
770 return [{
771 "additional_properties": claim.additional_properties,
772 "essential": claim.essential,
773 "name": claim.name,
774 "source": claim.source} for claim in claims]
775
776 def to_dict(self, object):
777 app_roles = [{
778 'id': app_role.id,
779 'display_name': app_role.display_name,
780 'is_enabled': app_role.is_enabled,
781 'value': app_role.value,
782 "description": app_role.description
783 } for app_role in object.app_roles]
784 optional_claims = {
785 "access_token": self.serialize_claims(object.optional_claims.access_token),
786 "id_token": self.serialize_claims(object.optional_claims.id_token),
787 "saml2_token": self.serialize_claims(object.optional_claims.saml2_token)
788 } if object.optional_claims is not None else object.optional_claims
789 return dict(
790 app_id=object.app_id,
791 object_id=object.id,
792 display_name=object.display_name,
793 app_roles=app_roles,
794 sign_in_audience=object.sign_in_audience,
795 homepage=object.web.home_page_url,
796 identifier_uris=object.identifier_uris,
797 notes=object.notes,
798 oauth2_allow_implicit_flow=object.web.implicit_grant_settings.enable_access_token_issuance,
799 optional_claims=optional_claims,
800 # allow_guests_sign_in=object.allow_guests_sign_in,
801 web_reply_urls=object.web.redirect_uris,
802 spa_reply_urls=object.spa.redirect_uris,
803 public_client_reply_urls=object.public_client.redirect_uris
804 )
805
806 def build_application_creds(self, password=None, key_value=None, key_type=None, key_usage=None,
807 start_date=None, end_date=None, key_description=None):
808 if password and key_value:
809 self.fail('specify either password or key_value, but not both.')
810
811 if not start_date:
812 start_date = datetime.datetime.utcnow()
813 elif isinstance(start_date, str):
814 start_date = dateutil.parser.parse(start_date)
815
816 if not end_date:
817 end_date = start_date + relativedelta(years=1) - relativedelta(hours=24)
818 elif isinstance(end_date, str):
819 end_date = dateutil.parser.parse(end_date)
820
821 custom_key_id = None
822 if key_description and password:
823 custom_key_id = self.encode_custom_key_description(key_description)
824
825 key_type = key_type or 'AsymmetricX509Cert'
826 key_usage = key_usage or 'Verify'
827
828 password_creds = None
829 key_creds = None
830 if password:
831 password_creds = [PasswordCredential(start_date_time=start_date, end_date_time=end_date,
832 key_id=self.gen_guid(), secret_text=password,
833 custom_key_identifier=custom_key_id)] # value ? secret_text
834 elif key_value:
835 key_bytes = self._normalize_cert_key_value(key_value)
836 key_creds = [KeyCredential(start_date_time=start_date, end_date_time=end_date,
837 key_id=self.gen_guid(), key=key_bytes, usage=key_usage,
838 type=key_type, custom_key_identifier=custom_key_id)]
839
840 return password_creds, key_creds
841
842 def encode_custom_key_description(self, key_description):
843 # utf16 is used by AAD portal. Do not change it to other random encoding
844 # unless you know what you are doing.
845 return key_description.encode('utf-16')
846
847 def _normalize_cert_key_value(self, key_value):
848 """
849 Normalize a certificate to raw DER bytes suitable for KeyCredential.key.
850
851 Accepts:
852 - raw bytes: already DER, returned as-is
853 - str (PEM): strip headers and base64-decode to DER bytes
854 - str (base64 DER): base64-decode to DER bytes
855 - other types: best-effort bytes conversion
856
857 Returns:
858 DER bytes
859 """
860 if isinstance(key_value, bytes):
861 return key_value
862
863 if not isinstance(key_value, str):
864 try:
865 return bytes(key_value)
866 except Exception:
867 return str(key_value).encode("utf-8")
868
869 s = key_value.strip()
870
871 # PEM with BEGIN/END headers
872 m = re.search(r"-----BEGIN CERTIFICATE-----([\s\S]*?)-----END CERTIFICATE-----", s, re.S)
873 if m:
874 pem_b64 = re.sub(r"\s+", "", m.group(1))
875 return base64.b64decode(pem_b64)
876
877 # Base64 DER
878 try:
879 return base64.b64decode(s)
880 except Exception:
881 # Last resort: treat as UTF-8 bytes
882 return s.encode("utf-8")
883
884 def gen_guid(self):
885 return uuid.uuid4()
886
887 def build_application_accesses(self, required_resource_accesses):
888 if not required_resource_accesses:
889 return None
890 required_accesses = []
891 if isinstance(required_resource_accesses, dict):
892 self.log('Getting "requiredResourceAccess" from a full manifest')
893 required_resource_accesses = required_resource_accesses.get('required_resource_access', [])
894 for x in required_resource_accesses:
895 accesses = [ResourceAccess(id=y['id'], type=y['type']) for y in x['resource_access']]
896 required_accesses.append(RequiredResourceAccess(resource_app_id=x['resource_app_id'],
897 resource_access=accesses))
898 return required_accesses
899
900 def build_app_roles(self, app_roles):
901 if not app_roles:
902 return None
903 result = []
904 if isinstance(app_roles, dict):
905 self.log('Getting "appRoles" from a full manifest')
906 app_roles = app_roles.get('appRoles', [])
907 for x in app_roles:
908 role = AppRole(id=x.get('id', None) or self.gen_guid(),
909 allowed_member_types=x.get('allowed_member_types', None),
910 description=x.get('description', None), display_name=x.get('display_name', None),
911 is_enabled=x.get('is_enabled', None), value=x.get('value', None)) # value ? additional_data
912 result.append(role)
913 return result
914
915 def build_optional_claims(self, optional_claims):
916
917 def build_claims(claims_dict):
918 if claims_dict is None:
919 return None
920 return [OptionalClaim(
921 essential=claim.get("essential"),
922 name=claim.get("name"),
923 source=claim.get("source"),
924 additional_properties=claim.get("additional_properties")
925 ) for claim in claims_dict]
926
927 claims = OptionalClaims(
928 access_token=build_claims(optional_claims.get("access_token_claims")),
929 id_token=build_claims(optional_claims.get("id_token_claims")),
930 saml2_token=build_claims(optional_claims.get("saml2_token_claims"))
931 )
932 return claims
933
934 async def create_application(self, creat_app):
935 return await self._client.applications.post(body=creat_app)
936
937 async def update_application(self, obj_id, update_app):
938 return await self._client.applications.by_application_id(obj_id).patch(body=update_app)
939
940 async def get_application_by_app_id(self, app_id):
941 request_configuration = ApplicationsRequestBuilder.ApplicationsRequestBuilderGetRequestConfiguration(
942 query_parameters=ApplicationsRequestBuilder.ApplicationsRequestBuilderGetQueryParameters(
943 filter=(" appId eq '{0}'".format(app_id)), ),
944 )
945
946 return await self._client.applications.get(request_configuration=request_configuration)
947
948 async def delete_application(self, obj_id):
949 await self._client.applications.by_application_id(obj_id).delete()
950
951 async def get_applications(self, filters):
952 request_configuration = ApplicationsRequestBuilder.ApplicationsRequestBuilderGetRequestConfiguration(
953 query_parameters=ApplicationsRequestBuilder.ApplicationsRequestBuilderGetQueryParameters(
954 filter=(' and '.join(filters))
955 ))
956 return await self._client.applications.get(request_configuration=request_configuration)
957
958
959 def main():
960 AzureRMADApplication()
961
962
963 if __name__ == '__main__':
964 main()