diff --git a/msgraph/cli/__init__.py b/msgraph/cli/__init__.py index b74cfa3b..4a09d9ec 100644 --- a/msgraph/cli/__init__.py +++ b/msgraph/cli/__init__.py @@ -2,3 +2,5 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ + +from .core.profile import read_profile, write_profile diff --git a/msgraph/cli/core/authentication.py b/msgraph/cli/core/authentication.py index 72debca6..570264ac 100644 --- a/msgraph/cli/core/authentication.py +++ b/msgraph/cli/core/authentication.py @@ -2,19 +2,19 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -import sys + from os import path, remove from azure.identity import InteractiveBrowserCredential, AuthenticationRecord -import logging -from msgraph.cli.core.constants import AUTH_RECORD_LOCATION, CLIENT_ID +from msgraph.cli.core.constants import AUTH_RECORD_LOCATION, DEFAULT_CLIENT_ID, DEFAULT_AUTHORITY from msgraph.cli.core.exceptions import CLIException +from msgraph.cli.core.profile import read_profile class Authentication: - def login(self, scopes: [str]) -> bool: + def login(self, scopes: [str], client_id=None, tenant_id=None) -> bool: try: - credential = self.get_credential() + credential = self.get_credential(user_client_id=client_id, tenant_id=tenant_id) auth_record = credential.authenticate(scopes=scopes) if auth_record is None: @@ -36,18 +36,39 @@ def logout(self): # By deleting the authentication record, we logout the user self._delete_auth_record() - def get_credential(self, auth_record=None) -> InteractiveBrowserCredential: + def get_credential(self, + auth_record=None, + user_client_id=None, + tenant_id=None) -> InteractiveBrowserCredential: ''' Raises ------ ValueError If PyGObject is not installed in the host Linux OS. ''' + profile = read_profile() + user_cloud = profile.get('cloud', None) + cloud_authority = user_cloud.get('azure_ad_endpoint', None) + + authority = cloud_authority or DEFAULT_AUTHORITY + client_id = user_client_id or DEFAULT_CLIENT_ID + + # Once a user is authenticated they get an auth_record object which will have the authority and client_id + # therefore we don't need to pass authority and client_id to InteractiveBrowserCredential. + if auth_record: + return InteractiveBrowserCredential( + enable_persistent_cache=True, + allow_unencrypted_cache=False, + authentication_record=auth_record, + ) + + # Passes authority and client_id when the user doesn't have an auth record return InteractiveBrowserCredential( - client_id=CLIENT_ID, + authority=authority, + client_id=client_id, + tenant_id=tenant_id, enable_persistent_cache=True, allow_unencrypted_cache=False, - authentication_record=auth_record, ) def _save_auth_record(self, auth_record: AuthenticationRecord): diff --git a/msgraph/cli/core/commands/client_factory.py b/msgraph/cli/core/commands/client_factory.py index bcd0e1fd..5ade679f 100644 --- a/msgraph/cli/core/commands/client_factory.py +++ b/msgraph/cli/core/commands/client_factory.py @@ -7,7 +7,9 @@ from knack.util import CLIError from msgraph.cli.core.authentication import Authentication +from msgraph.cli.core.profile import read_profile from msgraph.core import GraphSession +from msgraph.cli.core.constants import DEFAULT_BASE_URL def resolve_client_arg_name(operation, kwargs): @@ -41,5 +43,13 @@ def get_mgmt_service_client(cli_ctx, client_type, **kwargs): credential = auth.get_credential(auth_record=record) graph_session = GraphSession(credential=credential) - client = client_type({}, session=graph_session) + base_url = None + cloud = read_profile().get('cloud', None) + + if cloud: + base_url = cloud.get('graph_endpoint') + else: + base_url = DEFAULT_BASE_URL + + client = client_type({}, session=graph_session, base_url=base_url) return client diff --git a/msgraph/cli/core/constants.py b/msgraph/cli/core/constants.py index fb1d6491..64105052 100644 --- a/msgraph/cli/core/constants.py +++ b/msgraph/cli/core/constants.py @@ -7,7 +7,10 @@ from os import path AUTH_RECORD_LOCATION = path.join(Path.home(), '.mg', 'record.txt') -CLIENT_ID = 'f7218512-c727-4138-9fb9-a0fe2500650c' +PROFILE_LOCATION = path.join(Path.home(), '.mg', 'profile.json') +DEFAULT_CLIENT_ID = '837b13ab-6d14-4dc7-837f-8954cc87fdc0' +DEFAULT_AUTHORITY = 'https://login.microsoftonline.com' +DEFAULT_BASE_URL = 'https://graph.microsoft.com/v1.0' CLI_COMMON_KWARGS = [ 'min_api', 'max_api', 'resource_type', 'operation_group', 'custom_command_type', 'command_type', @@ -24,3 +27,31 @@ 'self', 'raw', 'polling', 'custom_headers', 'operation_config', 'content_version', 'kwargs', 'client', 'no_wait' ] + +DEFAULT_CLOUDS = { + 'PUBLIC': { + 'name': 'PUBLIC', + 'graph_endpoint': 'https://graph.microsoft.com/v1.0', + 'azure_ad_endpoint': 'https://login.microsoftonline.com' + }, + 'US_GOV_L4': { + 'name': 'US_GOV_L4', + 'graph_endpoint': 'https://graph.microsoft.us/v1.0', + 'azure_ad_endpoint': 'https://login.microsoftonline.us' + }, + 'US_GOV_L5': { + 'name': 'US_GOV_L5', + 'graph_endpoint': 'https://dod-graph.microsoft.us/v1.0', + 'azure_ad_endpoint': 'https://login.microsoftonline.us' + }, + 'GERMANY': { + 'name': 'GERMANY', + 'graph_endpoint': 'https://graph.microsoft.de/v1.0', + 'azure_ad_endpoint': 'https://login.microsoftonline.de' + }, + 'CHINA': { + 'name': 'CHINA', + 'graph_endpoint': 'https://microsoftgraph.chinacloudapi.cn/v1.0', + 'azure_ad_endpoint': 'https://login.chinacloudapi.cn' + } +} \ No newline at end of file diff --git a/msgraph/cli/core/installed_extensions.py b/msgraph/cli/core/installed_extensions.py index f2a8af82..b1af9466 100644 --- a/msgraph/cli/core/installed_extensions.py +++ b/msgraph/cli/core/installed_extensions.py @@ -1,25 +1,25 @@ -installed_extensions = [ - 'azext_schemaextensions', - 'azext_cloudcommunications', - 'azext_calendar', - 'azext_usersfunctions', - 'azext_security', - 'azext_mail', - 'azext_planner', - 'azext_education', - 'azext_sites', - 'azext_changenotifications', - 'azext_notes', - 'azext_users', - 'azext_usersactions', - 'azext_people', - 'azext_teams', - 'azext_applications', - 'azext_files', - 'azext_identitydirectorymanagement', - 'azext_directoryobjects', - 'azext_crossdeviceexperiences', - 'azext_personalcontacts', - 'azext_identitysignins', - 'azext_reports', +installed_extensions = [ + 'azext_applications', + 'azext_calendar', + 'azext_changenotifications', + 'azext_cloudcommunications', + 'azext_crossdeviceexperiences', + 'azext_directoryobjects', + 'azext_education', + 'azext_files', + 'azext_identitydirectorymanagement', + 'azext_identitysignins', + 'azext_mail', + 'azext_notes', + 'azext_people', + 'azext_personalcontacts', + 'azext_planner', + 'azext_reports', + 'azext_schemaextensions', + 'azext_security', + 'azext_sites', + 'azext_teams', + 'azext_users', + 'azext_usersactions', + 'azext_usersfunctions', ] \ No newline at end of file diff --git a/msgraph/cli/core/profile.py b/msgraph/cli/core/profile.py new file mode 100644 index 00000000..b3491882 --- /dev/null +++ b/msgraph/cli/core/profile.py @@ -0,0 +1,26 @@ +import json +from msgraph.cli.core.constants import PROFILE_LOCATION +from msgraph.cli.core.exceptions import CLIException + + +def read_profile() -> dict: + result = None + + try: + with open(PROFILE_LOCATION, 'r') as file: + result = file.read() + return json.loads(result) + except IOError as ex: + # This error will be thrown if a user has not selected a cloud before. + # Returning an empty dictionary so that the result can be processed by json.loads() + return {} + + +def write_profile(profile: dict, error_msg: str): + #TODO: Parameterize the error message + + try: + with open(PROFILE_LOCATION, 'w') as file: + file.write(json.dumps(profile)) + except IOError as ex: + raise CLIException(error_msg) from ex \ No newline at end of file diff --git a/msgraph/command_modules/authentication/_help.py b/msgraph/command_modules/authentication/_help.py index b1dccb26..6395b278 100644 --- a/msgraph/command_modules/authentication/_help.py +++ b/msgraph/command_modules/authentication/_help.py @@ -8,11 +8,14 @@ helps['login'] = """ type: command short-summary: Log in to Microsoft Graph -long-summary: Logs in a user to Microsoft Graph with the specified scopes. You must specify the scopes before you use commands. You will need to log out and log back in to consent to additional scopes. +long-summary: Logs in a user to Microsoft Graph with the specified scopes. You must specify the scopes before you use commands. You will need to log out and log back in to consent to additional scopes. examples: - name: Login in interactively text: > - mg login --scopes "user.read, mail.read" + mg login --scopes "user.read, mail.read" + - name: Sign in to a specific tenant/client + text: > + mg login --scopes "user.read" --client-id --tenant-id """ helps['logout'] = """ diff --git a/msgraph/command_modules/authentication/custom.py b/msgraph/command_modules/authentication/custom.py index 99816533..b540cb69 100644 --- a/msgraph/command_modules/authentication/custom.py +++ b/msgraph/command_modules/authentication/custom.py @@ -9,11 +9,11 @@ authentication = Authentication() -def login(scopes): +def login(scopes: str, client_id=None, tenant_id=None): # Stripping whitespaces so that users don't have to worry about how # they enter scopes. ie "user.read, mail.read" or "user.read,mail.read" scopes = [scope.strip() for scope in scopes.split(',')] - logged_in = authentication.login(scopes) + logged_in = authentication.login(scopes, client_id, tenant_id) if not logged_in: raise CLIError('Login failed') diff --git a/msgraph/command_modules/profile/__init__.py b/msgraph/command_modules/profile/__init__.py new file mode 100644 index 00000000..d9b6d12d --- /dev/null +++ b/msgraph/command_modules/profile/__init__.py @@ -0,0 +1,32 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +from msgraph.cli.core import AzCommandsLoader +from msgraph.cli.core.commands import CliCommandType +from msgraph.command_modules.profile._exception_handler import profile_exception_handler +import msgraph.command_modules.profile._help + + +class ProfileCommandsLoader(AzCommandsLoader): + """Provides profile commands to msgraph-cli + """ + def __init__(self, cli_ctx, **kwargs): + super().__init__(cli_ctx, **kwargs) + + def load_command_table(self, args): + # operations_tmpl is the file that contains the implementation of the command + command_type = CliCommandType(operations_tmpl='msgraph.command_modules.profile.custom#{}', + exception_handler=profile_exception_handler) + with self.command_group('cloud', command_type) as group: + group.command('select', 'select_cloud') + group.command('add', 'add_cloud') + group.command('show-current', 'current_cloud') + group.command('update', 'update_cloud') + group.command('delete', 'delete_cloud') + + return self.command_table + + +COMMAND_LOADER_CLS = ProfileCommandsLoader diff --git a/msgraph/command_modules/profile/_cloud_manager.py b/msgraph/command_modules/profile/_cloud_manager.py new file mode 100644 index 00000000..f2e92969 --- /dev/null +++ b/msgraph/command_modules/profile/_cloud_manager.py @@ -0,0 +1,96 @@ +# coding=utf-8 +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from msgraph.cli import read_profile, write_profile +from msgraph.cli.core.constants import DEFAULT_CLOUDS +from msgraph.cli.core.exceptions import CLIError + + +class CloudManager: + '''This class adds support for managing MicrosoftGraph and user defined clouds + List of supported Microsoft Graph clouds: https://docs.microsoft.com/en-us/graph/deployments + ''' + def __init__(self): + self.profile = read_profile() + + def get_clouds(self) -> dict: + user_defined_clouds = self.profile.get('user_defined_clouds', {}) + supported_clouds = DEFAULT_CLOUDS + + for cloud in user_defined_clouds: + supported_clouds.update(cloud) + return supported_clouds + + def create_cloud(self, cloud_name, cloud_endpoints): + entry = {cloud_name: cloud_endpoints} + + try: + user_defined_clouds = self.profile['user_defined_clouds'] + user_defined_clouds.append(entry) + except KeyError: + self.profile['user_defined_clouds'] = [entry] + + write_profile(self.profile, 'An error occured while creating the cloud.') + + def get_current_cloud(self) -> dict: + return self.profile.get('cloud', None) + + def update_cloud(self, cloud_name: str, props: dict): + updated = False + user_defined_clouds = self.profile.get('user_defined_clouds') + + # Search for the cloud to update in user defined clouds + for index, cloud in enumerate(user_defined_clouds): + found = cloud.get(cloud_name, None) + + if found: + cloud_to_update = cloud[cloud_name] + cloud_to_update.update(props) + + # Remove the old cloud and replace it with the updated cloud + user_defined_clouds.pop(index) + user_defined_clouds.insert(index, {cloud_to_update['name']: cloud_to_update}) + + updated = True + self.profile['user_defined_clouds'] = user_defined_clouds + write_profile( + self.profile, + error_msg=f'An error occured while updating the "{cloud_name}" cloud') + + # No need to keep looking for the cloud + break + + return updated + + def delete_cloud(self, name: str): + result = [] + current_cloud = self.profile.get('cloud', None) + + # throw an error if a user attempts to delete a current cloud + if current_cloud and name == current_cloud['name']: + raise CLIError(f'''The cloud "{name}" could not be deleted because it is a current cloud + +To see the current cloud run mg cloud show-current +To change to a different cloud run mg cloud select +''') + + # throw an error if the cloud is not a user defined cloud + if name not in self.profile['user_defined_clouds']: + raise CLIError(f'The cloud "{name}" is not a user defined cloud') + + for cloud in self.profile['user_defined_clouds']: + if name not in cloud.keys(): + result.append(cloud) + + self.profile['user_defined_clouds'] = result + write_profile(self.profile, error_msg=f'An error occured while deleting the "{name}" cloud') + + def set_current_cloud(self, name: str): + self.profile['cloud'] = self.get_clouds().get(name) + write_profile( + self.profile, + error_msg= + 'An error occured while setting the selected cloud, the CLI will use the PUBLIC cloud') diff --git a/msgraph/command_modules/profile/_exception_handler.py b/msgraph/command_modules/profile/_exception_handler.py new file mode 100644 index 00000000..c341fa80 --- /dev/null +++ b/msgraph/command_modules/profile/_exception_handler.py @@ -0,0 +1,11 @@ +# coding=utf-8 +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +from knack.cli import CLIError + + +def profile_exception_handler(exception): + raise CLIError(exception) \ No newline at end of file diff --git a/msgraph/command_modules/profile/_help.py b/msgraph/command_modules/profile/_help.py new file mode 100644 index 00000000..00d76176 --- /dev/null +++ b/msgraph/command_modules/profile/_help.py @@ -0,0 +1,69 @@ +# coding=utf-8 +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +from knack.help_files import helps + +helps['cloud select'] = """ +type: command +short-summary: Select a cloud from supported clouds. +""" + +helps['cloud show-current'] = """ +type: command +short-summary: Show current cloud +""" + +helps['cloud delete'] = """ +type: command +short-summary: Deletes a user defined cloud +parameters: + - name: --name + type: string + short-summary: Cloud to delete +examples: + - name: Delete cloud + text: > + mg cloud delete --name CUSTOM_CLOUD +""" + +helps['cloud add'] = """ +type: command +short-summary: Add a custom cloud +parameters: + - name: --name + type: string + short-summary: Cloud's name + long-summary: The cloud's name is shown in the list of clouds when a user runs mg cloud select. + - name: --graph-endpoint + type: string + short-summary: Cloud's endpoint + - name: --azure-ad-endpoint + short-summary: Cloud's authentication endpoint +examples: + - name: Add a new cloud + text: > + mg cloud add --name CUSTOM_CLOUD --endpoint https://graph.microsoft.com --authority https://graph.microsoftonline.com +""" + +helps['cloud update'] = """ +type: command +short-summary: update a user defined cloud +parameters: + - name: --cloud + type: string + short-summary: Name of user defined cloud to update + - name: --name + type: string + short-summary: Cloud's name + - name: --graph-endpoint + type: string + short-summary: Cloud's endpoint + - name: --azure-ad-endpoint + short-summary: Cloud's authentication endpoint +examples: + - name: Update a user defined cloud + text: > + mg cloud update --cloud CUSTOM_CLOUD --name UPDATED_NAME +""" diff --git a/msgraph/command_modules/profile/custom.py b/msgraph/command_modules/profile/custom.py new file mode 100644 index 00000000..76721846 --- /dev/null +++ b/msgraph/command_modules/profile/custom.py @@ -0,0 +1,85 @@ +# coding=utf-8 +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- +''' +Update the _help.py file after changing the signature or behavior of functions in this file +''' +from knack.prompting import prompt_choice_list +from msgraph.cli.core.constants import DEFAULT_CLOUDS +from ._cloud_manager import CloudManager + +cloud_manager = CloudManager() + + +def current_cloud(): + return cloud_manager.get_current_cloud() or DEFAULT_CLOUDS['PUBLIC'] + + +def delete_cloud(name: str): + cloud_manager.delete_cloud(name) + print(f'Cloud "{name}" deleted successfully') + + +def add_cloud(name: str, graph_endpoint: str, azure_ad_endpoint: str): + _validate(graph_endpoint) + + properties = { + 'name': name, + 'graph_endpoint': graph_endpoint, + 'azure_ad_endpoint': azure_ad_endpoint + } + + cloud_manager.create_cloud(name, properties) + print(f'Cloud "{name}" added successfully') + + +def select_cloud(): + supported_clouds = cloud_manager.get_clouds() + formatted = [] + + for cloud_name in supported_clouds: + cloud = supported_clouds[cloud_name] + formatted.append({ + 'name': + cloud.get('name'), + 'desc': + f"""Graph Endpoint: {cloud.get('graph_endpoint')} - Azure AD Endpoint: {cloud.get('azure_ad_endpoint')} + """ + }) + + selected = prompt_choice_list('Select a cloud \n', formatted) + name = formatted[selected].get('name') + + cloud_manager.set_current_cloud(name) + print(f'{name} cloud selected') + + +def update_cloud(cloud: str, name=None, graph_endpoint=None, azure_ad_endpoint=None): + + update_props = {} + + if name: + update_props.update({'name': name}) + if graph_endpoint: + _validate(graph_endpoint) + update_props.update({'graph_endpoint': graph_endpoint}) + if azure_ad_endpoint: + update_props.update({'azure_ad_endpoint': azure_ad_endpoint}) + + updated = cloud_manager.update_cloud(cloud, update_props) + + if updated: + print(f'{cloud} updated successfully') + else: + print(f'{cloud} does not exist') + + +def _validate(url: str): + from urllib import request + + try: + request.urlopen(url) + except IOError as error: + raise Exception('Invalid endpoint')