From d8a2169dd21b29b5891e858b1fd234b78f0e15cf Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Fri, 22 Jan 2021 16:44:36 -0800 Subject: [PATCH 01/40] Initial Azure Mixed Reality Authentication library from template --- .../CHANGELOG.md | 31 ++++++++ .../MANIFEST.in | 3 + .../README.md | 35 +++++++++ .../azure/__init__.py | 1 + .../azure/mixedreality/__init__.py | 1 + .../mixedreality/authentication/__init__.py | 5 ++ .../mixedreality/authentication/_version.py | 2 + .../authentication/template_code.py | 3 + .../dev_requirements.txt | 2 + .../sdk_packaging.toml | 2 + .../setup.cfg | 2 + .../setup.py | 74 +++++++++++++++++++ .../tests/test_simple.py | 15 ++++ 13 files changed, 176 insertions(+) create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/CHANGELOG.md create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/MANIFEST.in create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/README.md create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/__init__.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/__init__.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/__init__.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_version.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/template_code.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/dev_requirements.txt create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/sdk_packaging.toml create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/setup.cfg create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/setup.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/tests/test_simple.py diff --git a/sdk/mixedreality/azure-mixedreality-authentication/CHANGELOG.md b/sdk/mixedreality/azure-mixedreality-authentication/CHANGELOG.md new file mode 100644 index 000000000000..999dfa7dc075 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/CHANGELOG.md @@ -0,0 +1,31 @@ +# Release History + +## 0.0.18b3 (Unreleased) + + +## 0.0.18b2 (2020-09-04) +- Testing release tag version + +## 0.0.13b1 (2020-08-27) +- Testing out some alpha and beta versioning + +## 0.0.12 (Unreleased) +- Test a successful Release + +## 0.0.7 (2020-07-02) +- Test a successful Release + +## 0.0.6 (2020-05-20) +- Test a successful Release + +## 0.0.5 (2020-05-20) +- Test a successful Release + +## 0.0.3 (Unreleased) + +## 0.0.2 (2020-03-24) +- Test Release Pipeline + + +## 0.0.1 (2019-10-06) + - Template package diff --git a/sdk/mixedreality/azure-mixedreality-authentication/MANIFEST.in b/sdk/mixedreality/azure-mixedreality-authentication/MANIFEST.in new file mode 100644 index 000000000000..dd20dd67408b --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/MANIFEST.in @@ -0,0 +1,3 @@ +include *.md +include azure/__init__.py +recursive-include tests *.py \ No newline at end of file diff --git a/sdk/mixedreality/azure-mixedreality-authentication/README.md b/sdk/mixedreality/azure-mixedreality-authentication/README.md new file mode 100644 index 000000000000..92c7ca73c592 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/README.md @@ -0,0 +1,35 @@ +[![Build Status](https://dev.azure.com/azure-sdk/public/_apis/build/status/azure-sdk-for-python.client?branchName=master)](https://dev.azure.com/azure-sdk/public/_build/latest?definitionId=46?branchName=master) + +# Azure Template Package client library for Python + +This template package matches necessary patterns that the development team has established to create a unified sdk functional from Python 2.7 onwards. The packages contained herein can be installed singly or as part of the `azure` namespace. Any other introductory text should go here. + +This package has been tested with Python 2.7, 3.5, 3.6, 3.7 and 3.8 + +For a more complete set of Azure libraries, see https://aka.ms/azsdk/python/all + +# Getting started + +For a rich example of a well formatted readme, please check [here.](https://github.com/Azure/azure-sdk/blob/master/docs/policies/README-TEMPLATE.md) In addition, this is an [example readme](https://github.com/Azure/azure-sdk/blob/master/docs/policies/README-EXAMPLE.md) that should be emulated. Note that the top-level sections in this template align with that of the [template.](https://github.com/Azure/azure-sdk/blob/master/docs/policies/README-TEMPLATE.md) + +# Key concepts + +Bullet point list of your library's main concepts. + +# Examples + +Examples of some of the key concepts for your library. + +# Troubleshooting + +Running into issues? This section should contain details as to what to do there. + +# Next steps + +More sample code should go here, along with links out to the appropriate example tests. + +# Contributing + +If you encounter any bugs or have suggestions, please file an issue in the [Issues]() section of the project. + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python%2Fsdk%2Ftemplate%2Fazure-template%2FREADME.png) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/__init__.py new file mode 100644 index 000000000000..0260537a02bb --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__('pkgutil').extend_path(__path__, __name__) \ No newline at end of file diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/__init__.py new file mode 100644 index 000000000000..0260537a02bb --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/__init__.py @@ -0,0 +1 @@ +__path__ = __import__('pkgutil').extend_path(__path__, __name__) \ No newline at end of file diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/__init__.py new file mode 100644 index 000000000000..f60b32545925 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/__init__.py @@ -0,0 +1,5 @@ +from ._version import VERSION +from .template_code import template_main + +__all__ = ['template_main'] +__version__ = VERSION diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_version.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_version.py new file mode 100644 index 000000000000..e7ffbae43969 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_version.py @@ -0,0 +1,2 @@ +# matches SEMVER +VERSION = "0.0.1b1" \ No newline at end of file diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/template_code.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/template_code.py new file mode 100644 index 000000000000..f97c2985fde4 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/template_code.py @@ -0,0 +1,3 @@ +def template_main(): + print("Package code.") + return True diff --git a/sdk/mixedreality/azure-mixedreality-authentication/dev_requirements.txt b/sdk/mixedreality/azure-mixedreality-authentication/dev_requirements.txt new file mode 100644 index 000000000000..e8a0fc281e6f --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/dev_requirements.txt @@ -0,0 +1,2 @@ +-e ../../../tools/azure-sdk-tools +../../core/azure-core \ No newline at end of file diff --git a/sdk/mixedreality/azure-mixedreality-authentication/sdk_packaging.toml b/sdk/mixedreality/azure-mixedreality-authentication/sdk_packaging.toml new file mode 100644 index 000000000000..901bc8ccbfa6 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/sdk_packaging.toml @@ -0,0 +1,2 @@ +[packaging] +auto_update = false diff --git a/sdk/mixedreality/azure-mixedreality-authentication/setup.cfg b/sdk/mixedreality/azure-mixedreality-authentication/setup.cfg new file mode 100644 index 000000000000..3c6e79cf31da --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/setup.cfg @@ -0,0 +1,2 @@ +[bdist_wheel] +universal=1 diff --git a/sdk/mixedreality/azure-mixedreality-authentication/setup.py b/sdk/mixedreality/azure-mixedreality-authentication/setup.py new file mode 100644 index 000000000000..056741baf3a3 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/setup.py @@ -0,0 +1,74 @@ +from setuptools import setup, find_packages +import os +from io import open +import re + +# example setup.py Feel free to copy the entire "azure-template" folder into a package folder named +# with "azure-". Ensure that the below arguments to setup() are updated to reflect +# your package. + +# this setup.py is set up in a specific way to keep the azure* and azure-mgmt-* namespaces WORKING all the way +# up from python 2.7. Reference here: https://github.com/Azure/azure-sdk-for-python/wiki/Azure-packaging + +PACKAGE_NAME = "azure-mixedreality-authentication" +PACKAGE_PPRINT_NAME = "Mixed Reality Authentication" + +# a-b-c => a/b/c +package_folder_path = PACKAGE_NAME.replace('-', '/') +# a-b-c => a.b.c +namespace_name = PACKAGE_NAME.replace('-', '.') + +# Version extraction inspired from 'requests' +with open(os.path.join(package_folder_path, '_version.py'), 'r') as fd: + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', + fd.read(), re.MULTILINE).group(1) +if not version: + raise RuntimeError('Cannot find version information') + +with open('README.md', encoding='utf-8') as f: + long_description = f.read() + +setup( + name=PACKAGE_NAME, + version=version, + description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), + + # ensure that these are updated to reflect the package owners' information + long_description=long_description, + url='https://github.com/Azure/azure-sdk-for-python', + author='Microsoft Corporation', + author_email='azuresdkengsysadmins@microsoft.com', + + license='MIT License', + # ensure that the development status reflects the status of your package + classifiers=[ + "Development Status :: 4 - Beta", + + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'License :: OSI Approved :: MIT License', + ], + packages=find_packages(exclude=[ + 'tests', + # Exclude packages that will be covered by PEP420 or nspkg + 'azure' + ]), + install_requires=[ + #'msrest>=0.5.0', + #'msrestazure>=0.4.32,<2.0.0', + #'azure-common~=1.1', + ], + extras_require={ + ":python_version<'3.0'": ['azure-nspkg'], + }, + project_urls={ + 'Bug Reports': 'https://github.com/Azure/azure-sdk-for-python/issues', + 'Source': 'https://github.com/Azure/azure-sdk-python', + } +) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_simple.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_simple.py new file mode 100644 index 000000000000..50c0f99479e2 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_simple.py @@ -0,0 +1,15 @@ +# Testing Azure Packages has some additional complication/reading required. +# Reference https://github.com/Azure/azure-sdk-for-python/wiki/Contributing-to-the-tests +# Pytest should be leveraged to test your project. + +from devtools_testutils import AzureMgmtTestCase +from azure.template import template_main + +# this test case highlights that there are some additional Test capabilities present in devtools_testutils +# as a package owner you are not required to use these. Standard PyTest implementation will work. +class TemplateTest(AzureMgmtTestCase): + def setUp(self): + super(TemplateTest, self).setUp() + + def test_case_default(self): + self.assertEqual(template_main(), True) From 504fdbda975dff7f6cf999306a8e53cd015b5b8b Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Fri, 22 Jan 2021 17:27:01 -0800 Subject: [PATCH 02/40] Generated autorest service client --- .../authentication/_generated/__init__.py | 16 ++++ .../_generated/_configuration.py | 51 ++++++++++ .../_mixed_reality_sts_rest_client.py | 57 +++++++++++ .../authentication/_generated/aio/__init__.py | 10 ++ .../_generated/aio/_configuration.py | 45 +++++++++ .../aio/_mixed_reality_sts_rest_client.py | 49 ++++++++++ .../_generated/aio/operations/__init__.py | 13 +++ ...ixed_reality_sts_rest_client_operations.py | 89 ++++++++++++++++++ .../_generated/models/__init__.py | 19 ++++ .../_generated/models/_models.py | 54 +++++++++++ .../_generated/models/_models_py3.py | 60 ++++++++++++ .../_generated/operations/__init__.py | 13 +++ ...ixed_reality_sts_rest_client_operations.py | 94 +++++++++++++++++++ .../authentication/_generated/py.typed | 1 + .../swagger/README.md | 30 ++++++ .../swagger/update.ps1 | 6 ++ 16 files changed, 607 insertions(+) create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/__init__.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/_configuration.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/_mixed_reality_sts_rest_client.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/__init__.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/_configuration.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/_mixed_reality_sts_rest_client.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/operations/__init__.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/operations/_mixed_reality_sts_rest_client_operations.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/models/__init__.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/models/_models.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/models/_models_py3.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/operations/__init__.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/operations/_mixed_reality_sts_rest_client_operations.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/py.typed create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/swagger/README.md create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/swagger/update.ps1 diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/__init__.py new file mode 100644 index 000000000000..86838c6b621e --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/__init__.py @@ -0,0 +1,16 @@ +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._mixed_reality_sts_rest_client import MixedRealityStsRestClient +__all__ = ['MixedRealityStsRestClient'] + +try: + from ._patch import patch_sdk # type: ignore + patch_sdk() +except ImportError: + pass diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/_configuration.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/_configuration.py new file mode 100644 index 000000000000..9a762cc1fa5c --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/_configuration.py @@ -0,0 +1,51 @@ +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Optional + +VERSION = "unknown" + +class MixedRealityStsRestClientConfiguration(Configuration): + """Configuration for MixedRealityStsRestClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + """ + + def __init__( + self, + **kwargs # type: Any + ): + # type: (...) -> None + super(MixedRealityStsRestClientConfiguration, self).__init__(**kwargs) + + kwargs.setdefault('sdk_moniker', 'mixedrealitystsrestclient/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/_mixed_reality_sts_rest_client.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/_mixed_reality_sts_rest_client.py new file mode 100644 index 000000000000..53973ea0933f --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/_mixed_reality_sts_rest_client.py @@ -0,0 +1,57 @@ +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import TYPE_CHECKING + +from azure.core import PipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Optional + +from ._configuration import MixedRealityStsRestClientConfiguration +from .operations import MixedRealityStsRestClientOperationsMixin +from . import models + + +class MixedRealityStsRestClient(MixedRealityStsRestClientOperationsMixin): + """Definition for the Mixed Reality Cloud STS service APIs. + + :param str base_url: Service URL + """ + + def __init__( + self, + base_url=None, # type: Optional[str] + **kwargs # type: Any + ): + # type: (...) -> None + if not base_url: + base_url = 'https://sts.mixedreality.azure.com' + self._config = MixedRealityStsRestClientConfiguration(**kwargs) + self._client = PipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> MixedRealityStsRestClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/__init__.py new file mode 100644 index 000000000000..17251fcb2dbf --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/__init__.py @@ -0,0 +1,10 @@ +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._mixed_reality_sts_rest_client import MixedRealityStsRestClient +__all__ = ['MixedRealityStsRestClient'] diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/_configuration.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/_configuration.py new file mode 100644 index 000000000000..6045303ca6c1 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/_configuration.py @@ -0,0 +1,45 @@ +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies + +VERSION = "unknown" + +class MixedRealityStsRestClientConfiguration(Configuration): + """Configuration for MixedRealityStsRestClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + """ + + def __init__( + self, + **kwargs: Any + ) -> None: + super(MixedRealityStsRestClientConfiguration, self).__init__(**kwargs) + + kwargs.setdefault('sdk_moniker', 'mixedrealitystsrestclient/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get('authentication_policy') diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/_mixed_reality_sts_rest_client.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/_mixed_reality_sts_rest_client.py new file mode 100644 index 000000000000..593e47542967 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/_mixed_reality_sts_rest_client.py @@ -0,0 +1,49 @@ +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, Optional + +from azure.core import AsyncPipelineClient +from msrest import Deserializer, Serializer + +from ._configuration import MixedRealityStsRestClientConfiguration +from .operations import MixedRealityStsRestClientOperationsMixin +from .. import models + + +class MixedRealityStsRestClient(MixedRealityStsRestClientOperationsMixin): + """Definition for the Mixed Reality Cloud STS service APIs. + + :param str base_url: Service URL + """ + + def __init__( + self, + base_url: Optional[str] = None, + **kwargs: Any + ) -> None: + if not base_url: + base_url = 'https://sts.mixedreality.azure.com' + self._config = MixedRealityStsRestClientConfiguration(**kwargs) + self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._serialize.client_side_validation = False + self._deserialize = Deserializer(client_models) + + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "MixedRealityStsRestClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/operations/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/operations/__init__.py new file mode 100644 index 000000000000..56b55f918c06 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/operations/__init__.py @@ -0,0 +1,13 @@ +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._mixed_reality_sts_rest_client_operations import MixedRealityStsRestClientOperationsMixin + +__all__ = [ + 'MixedRealityStsRestClientOperationsMixin', +] diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/operations/_mixed_reality_sts_rest_client_operations.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/operations/_mixed_reality_sts_rest_client_operations.py new file mode 100644 index 000000000000..90031d443396 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/aio/operations/_mixed_reality_sts_rest_client_operations.py @@ -0,0 +1,89 @@ +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest + +from ... import models as _models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class MixedRealityStsRestClientOperationsMixin: + + async def get_token( + self, + account_id: str, + api_version: Optional[str] = "2019-02-28-preview", + token_request_options: Optional["_models.TokenRequestOptions"] = None, + **kwargs + ) -> "_models.StsTokenResponseMessage": + """Gets an access token to be used with Mixed Reality services. + + Gets an access token to be used with Mixed Reality services. + + :param account_id: The Mixed Reality account identifier. + :type account_id: str + :param api_version: Api Version. + :type api_version: str + :param token_request_options: Parameter group. + :type token_request_options: ~azure.mixedreality.authentication._generated.models.TokenRequestOptions + :keyword callable cls: A custom type or function that will be passed the direct response + :return: StsTokenResponseMessage, or the result of cls(response) + :rtype: ~azure.mixedreality.authentication._generated.models.StsTokenResponseMessage + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.StsTokenResponseMessage"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + _client_request_id = None + if token_request_options is not None: + _client_request_id = token_request_options.client_request_id + accept = "application/json" + + # Construct URL + url = self.get_token.metadata['url'] # type: ignore + path_format_arguments = { + 'accountId': self._serialize.url("account_id", account_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + if api_version is not None: + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + if _client_request_id is not None: + header_parameters['X-MRC-CV'] = self._serialize.header("client_request_id", _client_request_id, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers['MS-CV']=self._deserialize('str', response.headers.get('MS-CV')) + deserialized = self._deserialize('StsTokenResponseMessage', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + get_token.metadata = {'url': '/Accounts/{accountId}/token'} # type: ignore diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/models/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/models/__init__.py new file mode 100644 index 000000000000..6e706bc24cdc --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/models/__init__.py @@ -0,0 +1,19 @@ +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +try: + from ._models_py3 import StsTokenResponseMessage + from ._models_py3 import TokenRequestOptions +except (SyntaxError, ImportError): + from ._models import StsTokenResponseMessage # type: ignore + from ._models import TokenRequestOptions # type: ignore + +__all__ = [ + 'StsTokenResponseMessage', + 'TokenRequestOptions', +] diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/models/_models.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/models/_models.py new file mode 100644 index 000000000000..2b8d812be323 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/models/_models.py @@ -0,0 +1,54 @@ +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import msrest.serialization + + +class StsTokenResponseMessage(msrest.serialization.Model): + """Represents a token response message from the STS service. + + All required parameters must be populated in order to send to Azure. + + :param access_token: Required. An access token for the account. + :type access_token: str + """ + + _validation = { + 'access_token': {'required': True}, + } + + _attribute_map = { + 'access_token': {'key': 'AccessToken', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(StsTokenResponseMessage, self).__init__(**kwargs) + self.access_token = kwargs['access_token'] + + +class TokenRequestOptions(msrest.serialization.Model): + """Parameter group. + + :param client_request_id: The client request correlation vector, which should be set to a new + value for each request. Useful when debugging with Microsoft. + :type client_request_id: str + """ + + _attribute_map = { + 'client_request_id': {'key': 'clientRequestId', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(TokenRequestOptions, self).__init__(**kwargs) + self.client_request_id = kwargs.get('client_request_id', None) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/models/_models_py3.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/models/_models_py3.py new file mode 100644 index 000000000000..5ecff28c8992 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/models/_models_py3.py @@ -0,0 +1,60 @@ +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Optional + +import msrest.serialization + + +class StsTokenResponseMessage(msrest.serialization.Model): + """Represents a token response message from the STS service. + + All required parameters must be populated in order to send to Azure. + + :param access_token: Required. An access token for the account. + :type access_token: str + """ + + _validation = { + 'access_token': {'required': True}, + } + + _attribute_map = { + 'access_token': {'key': 'AccessToken', 'type': 'str'}, + } + + def __init__( + self, + *, + access_token: str, + **kwargs + ): + super(StsTokenResponseMessage, self).__init__(**kwargs) + self.access_token = access_token + + +class TokenRequestOptions(msrest.serialization.Model): + """Parameter group. + + :param client_request_id: The client request correlation vector, which should be set to a new + value for each request. Useful when debugging with Microsoft. + :type client_request_id: str + """ + + _attribute_map = { + 'client_request_id': {'key': 'clientRequestId', 'type': 'str'}, + } + + def __init__( + self, + *, + client_request_id: Optional[str] = None, + **kwargs + ): + super(TokenRequestOptions, self).__init__(**kwargs) + self.client_request_id = client_request_id diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/operations/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/operations/__init__.py new file mode 100644 index 000000000000..56b55f918c06 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/operations/__init__.py @@ -0,0 +1,13 @@ +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._mixed_reality_sts_rest_client_operations import MixedRealityStsRestClientOperationsMixin + +__all__ = [ + 'MixedRealityStsRestClientOperationsMixin', +] diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/operations/_mixed_reality_sts_rest_client_operations.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/operations/_mixed_reality_sts_rest_client_operations.py new file mode 100644 index 000000000000..8b8628e0c285 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/operations/_mixed_reality_sts_rest_client_operations.py @@ -0,0 +1,94 @@ +# 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. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse + +from .. import models as _models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class MixedRealityStsRestClientOperationsMixin(object): + + def get_token( + self, + account_id, # type: str + api_version="2019-02-28-preview", # type: Optional[str] + token_request_options=None, # type: Optional["_models.TokenRequestOptions"] + **kwargs # type: Any + ): + # type: (...) -> "_models.StsTokenResponseMessage" + """Gets an access token to be used with Mixed Reality services. + + Gets an access token to be used with Mixed Reality services. + + :param account_id: The Mixed Reality account identifier. + :type account_id: str + :param api_version: Api Version. + :type api_version: str + :param token_request_options: Parameter group. + :type token_request_options: ~azure.mixedreality.authentication._generated.models.TokenRequestOptions + :keyword callable cls: A custom type or function that will be passed the direct response + :return: StsTokenResponseMessage, or the result of cls(response) + :rtype: ~azure.mixedreality.authentication._generated.models.StsTokenResponseMessage + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["_models.StsTokenResponseMessage"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + + _client_request_id = None + if token_request_options is not None: + _client_request_id = token_request_options.client_request_id + accept = "application/json" + + # Construct URL + url = self.get_token.metadata['url'] # type: ignore + path_format_arguments = { + 'accountId': self._serialize.url("account_id", account_id, 'str'), + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} # type: Dict[str, Any] + if api_version is not None: + query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + if _client_request_id is not None: + header_parameters['X-MRC-CV'] = self._serialize.header("client_request_id", _client_request_id, 'str') + header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + + request = self._client.get(url, query_parameters, header_parameters) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers['MS-CV']=self._deserialize('str', response.headers.get('MS-CV')) + deserialized = self._deserialize('StsTokenResponseMessage', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, response_headers) + + return deserialized + get_token.metadata = {'url': '/Accounts/{accountId}/token'} # type: ignore diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/py.typed b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_generated/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/mixedreality/azure-mixedreality-authentication/swagger/README.md b/sdk/mixedreality/azure-mixedreality-authentication/swagger/README.md new file mode 100644 index 000000000000..db45991460b0 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/swagger/README.md @@ -0,0 +1,30 @@ +# Azure Mixed Reality Authentication Service client library for Python + +## Setup + +```ps +npm install -g autorest +``` + +## Generation + +```ps +cd +autorest README.md +``` + +### Code generation settings + +```yaml +title: MixedRealityStsRestClient +input-file: https://raw.githubusercontent.com/craigktreasure/azure-rest-api-specs/6938d23da2be2a20b9998e002ef8b79e8d83e509/specification/mixedreality/data-plane/Microsoft.MixedReality/preview/2019-02-28-preview/mr-sts.json +output-folder: ../azure/mixedreality/authentication/_generated +namespace: azure.mixedreality.authentication._generated +no-namespace-folders: true +license-header: MICROSOFT_MIT_NO_VERSION +enable-xml: false +clear-output-folder: true +python: true +v3: true +add-credentials: false +``` diff --git a/sdk/mixedreality/azure-mixedreality-authentication/swagger/update.ps1 b/sdk/mixedreality/azure-mixedreality-authentication/swagger/update.ps1 new file mode 100644 index 000000000000..d04e5660d16a --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/swagger/update.ps1 @@ -0,0 +1,6 @@ +Push-Location $PSScriptRoot +try { + & autorest README.md +} finally { + Pop-Location +} From 04abd30eed00afa16064639e29099efe0d78da4b Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Mon, 25 Jan 2021 17:19:04 -0800 Subject: [PATCH 03/40] Initial implementation --- .../mixedreality/authentication/__init__.py | 4 +- .../mixedreality/authentication/_client.py | 107 ++++++++++++++++++ .../mixedreality/authentication/_version.py | 10 +- .../authentication/aio/__init__.py | 11 ++ .../authentication/aio/_client_async.py | 107 ++++++++++++++++++ .../authentication/shared/__init__.py | 13 +++ .../shared/_authentication_endpoint.py | 9 ++ .../_mixedreality_account_key_credential.py | 41 +++++++ .../authentication/template_code.py | 3 - .../authentication/utils/__init__.py | 15 +++ .../mixedreality/authentication/utils/_cv.py | 28 +++++ .../mixedreality/authentication/utils/_jwt.py | 35 ++++++ .../authentication/utils/_utils.py | 22 ++++ .../dev_requirements.txt | 4 +- 14 files changed, 402 insertions(+), 7 deletions(-) create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/__init__.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/__init__.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_authentication_endpoint.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_mixedreality_account_key_credential.py delete mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/template_code.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/__init__.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_cv.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_jwt.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_utils.py diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/__init__.py index f60b32545925..508aee376b10 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/__init__.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/__init__.py @@ -1,5 +1,5 @@ from ._version import VERSION -from .template_code import template_main +from ._client import MixedRealityStsClient -__all__ = ['template_main'] __version__ = VERSION +__all__ = ['MixedRealityStsClient'] diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py new file mode 100644 index 000000000000..ff655499b1a9 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py @@ -0,0 +1,107 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING + +try: + from urllib.parse import urlparse +except ImportError: + from urlparse import urlparse # type: ignore + +from azure.core.credentials import AccessToken, AzureKeyCredential +from azure.core.tracing.decorator import distributed_trace +from azure.core.pipeline.policies import BearerTokenCredentialPolicy + +from ._generated import MixedRealityStsRestClient +from ._generated.models import TokenRequestOptions +from ._version import SDK_MONIKER +from .shared import _construct_endpoint_url, MixedRealityAccountKeyCredential +from .utils import _convert_to_access_token, _generate_cv_base + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Union + from azure.core.credentials import TokenCredential + + +class MixedRealityStsClient(object): + """ A client to interact with the Mixed Reality STS service. + + :param str account_id: + The Mixed Reality service account identifier. + :param str account_domain: + The Mixed Reality service account domain. + :param Union[TokenCredential, AzureKeyCredential] credential: + The credential used to access the Mixed Reality service. + """ + + def __init__(self, account_id, account_domain, credential, **kwargs): + # type: (str, str, Union[TokenCredential, AzureKeyCredential], Any) -> None + if not account_id: + raise ValueError("account_id can not be None") + + if not account_domain: + raise ValueError("account_domain can not be None") + + if not credential: + raise ValueError("credential can not be None") + + self._account_id = account_id + self._account_domain = account_domain + self._credential = credential + + endpoint_url = kwargs.pop('endpoint_url', _construct_endpoint_url(account_domain)) + + try: + if not endpoint_url.lower().startswith('http'): + endpoint_url = "https://" + endpoint_url + except AttributeError: + raise ValueError("Host URL must be a string") + + parsed_url = urlparse(endpoint_url.rstrip('/')) + if not parsed_url.netloc: + raise ValueError("Invalid URL: {}".format(endpoint_url)) + + self._endpoint_url = endpoint_url + + if isinstance(credential, AzureKeyCredential): + credential = MixedRealityAccountKeyCredential(account_id, credential) + + authentication_policy = BearerTokenCredentialPolicy(credential, [endpoint_url + '/.default']) + + self._client = MixedRealityStsRestClient( + base_url=endpoint_url, + authentication_policy=authentication_policy, + sdk_moniker=SDK_MONIKER, + **kwargs) + + @distributed_trace + def get_token(self, **kwargs): + # type: (Any) -> AccessToken + """ + Retrieve a token from the STS service for the specified account identifier asynchronously. + """ + token_request_options = TokenRequestOptions() + token_request_options.client_request_id = _generate_cv_base() + + response = self._client.get_token( + self._account_id, + api_version=None, + token_request_options=token_request_options, + **kwargs) + return _convert_to_access_token(response) + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> MixedRealityStsClient + self._client.__enter__() # pylint:disable=no-member + return self + + def __exit__(self, *args): + # type: (*Any) -> None + self._client.__exit__(*args) # pylint:disable=no-member diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_version.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_version.py index e7ffbae43969..f715dac0c388 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_version.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_version.py @@ -1,2 +1,10 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + # matches SEMVER -VERSION = "0.0.1b1" \ No newline at end of file +VERSION = "0.0.1b1" + +SDK_MONIKER = "mixedreality-authentication/{}".format(VERSION) # type: str \ No newline at end of file diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/__init__.py new file mode 100644 index 000000000000..736dc1c08fe4 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/__init__.py @@ -0,0 +1,11 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +from ._client_async import MixedRealityStsClient + +__all__ = [ + 'MixedRealityStsClient' +] diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py new file mode 100644 index 000000000000..bdf5aa03591e --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py @@ -0,0 +1,107 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING + +try: + from urllib.parse import urlparse +except ImportError: + from urlparse import urlparse # type: ignore + +# pylint: disable=unused-import,ungrouped-imports +from typing import Any, Union + +from azure.core.credentials import AccessToken, AzureKeyCredential +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.pipeline.policies import BearerTokenCredentialPolicy + +from .._generated.aio import MixedRealityStsRestClient +from .._generated.models import TokenRequestOptions +from .._version import SDK_MONIKER +from ..shared import _construct_endpoint_url, MixedRealityAccountKeyCredential +from ..utils import _convert_to_access_token, _generate_cv_base + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + + +class MixedRealityStsClient(object): + """ A client to interact with the Mixed Reality STS service. + + :param str account_id: + The Mixed Reality service account identifier. + :param str account_domain: + The Mixed Reality service account domain. + :param Union[TokenCredential, AzureKeyCredential] credential: + The credential used to access the Mixed Reality service. + """ + + def __init__(self, + account_id: str, + account_domain: str, + credential: Union[AzureKeyCredential, "AzureTokenCredential"], + **kwargs) -> None: + if not account_id: + raise ValueError("account_id can not be None") + + if not account_domain: + raise ValueError("account_domain can not be None") + + if not credential: + raise ValueError("credential can not be None") + + self._account_id = account_id + self._account_domain = account_domain + self._credential = credential + + endpoint_url = kwargs.pop('endpoint_url', _construct_endpoint_url(account_domain)) + + try: + if not endpoint_url.lower().startswith('http'): + endpoint_url = "https://" + endpoint_url + except AttributeError: + raise ValueError("Host URL must be a string") + + parsed_url = urlparse(endpoint_url.rstrip('/')) + if not parsed_url.netloc: + raise ValueError("Invalid URL: {}".format(endpoint_url)) + + self._endpoint_url = endpoint_url + + if isinstance(credential, AzureKeyCredential): + credential = MixedRealityAccountKeyCredential(account_id, credential) + + authentication_policy = BearerTokenCredentialPolicy(credential, [endpoint_url + '/.default']) + + self._client = MixedRealityStsRestClient( + base_url=endpoint_url, + authentication_policy=authentication_policy, + sdk_moniker=SDK_MONIKER, + **kwargs) + + @distributed_trace_async + async def get_token(self, **kwargs) -> AccessToken: + """ + Retrieve a token from the STS service for the specified account identifier asynchronously. + """ + token_request_options = TokenRequestOptions() + token_request_options.client_request_id=_generate_cv_base() + + response = await self._client.get_token( + self._account_id, + api_version=None, + token_request_options=token_request_options, + **kwargs) + return _convert_to_access_token(response) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "MixedRealityStsClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *args) -> None: + await self._client.__aexit__(*args) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/__init__.py new file mode 100644 index 000000000000..e95d3e1e89a7 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/__init__.py @@ -0,0 +1,13 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +from ._authentication_endpoint import _construct_endpoint_url +from ._mixedreality_account_key_credential import MixedRealityAccountKeyCredential + +__all__ = [ + '_construct_endpoint_url' + 'MixedRealityAccountKeyCredential' +] diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_authentication_endpoint.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_authentication_endpoint.py new file mode 100644 index 000000000000..0faae46a0e99 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_authentication_endpoint.py @@ -0,0 +1,9 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +def _construct_endpoint_url(account_domain): + # type: (str) -> str + return 'https://sts.' + account_domain diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_mixedreality_account_key_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_mixedreality_account_key_credential.py new file mode 100644 index 000000000000..599a4d921341 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_mixedreality_account_key_credential.py @@ -0,0 +1,41 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +from datetime import date, datetime + +from azure.core.credentials import AzureKeyCredential, AccessToken + +ACCOUNT_KEY_VALID_YEARS = 10 + +class MixedRealityAccountKeyCredential(object): + """ Represents an object used for Mixed Reality account key authentication. + + :param str account_id: The Mixed Reality service account identifier. + :param AzureKeyCredential account_key: The Mixed Reality service account primary or secondary key credential. + """ + + def __init__(self, account_id, account_key): + # type: (str, AzureKeyCredential) -> None + self.account_id = account_id + self.account_key = account_key + + def get_token(self, *scopes, **kwargs): + # type: (*str, **Any) -> AccessToken + + token = self.account_id + ":" + self.account_key.key + + # No way to know when an access token might expire, so we'll set it to be + # 10 years in the future. + expiration_date = _add_years(datetime.now(), ACCOUNT_KEY_VALID_YEARS) + expiration_timestamp = int(expiration_date.timestamp()) + + return AccessToken(token, expiration_timestamp) + +def _add_years(date_to_update, years): + try: + return date_to_update.replace(year = date_to_update.year + years) + except ValueError: + return date_to_update + (date(date_to_update.year + years, 1, 1) - date(date_to_update.year, 1, 1)) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/template_code.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/template_code.py deleted file mode 100644 index f97c2985fde4..000000000000 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/template_code.py +++ /dev/null @@ -1,3 +0,0 @@ -def template_main(): - print("Package code.") - return True diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/__init__.py new file mode 100644 index 000000000000..58bd0172a33c --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/__init__.py @@ -0,0 +1,15 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +from ._utils import _convert_to_access_token +from ._cv import _generate_cv_base +from ._jwt import _retrieve_jwt_expiration_timestamp + +__all__ = [ + '_convert_to_access_token', + '_generate_cv_base', + '_retrieve_jwt_expiration_timestamp' +] diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_cv.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_cv.py new file mode 100644 index 000000000000..ba7e75e2d573 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_cv.py @@ -0,0 +1,28 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +# This function is a minimal port borrowed from the JavaScript implementation at +# https://github.com/microsoft/CorrelationVector-JavaScript/blob/6da3f9e6150581756aba54b98dcd1e7329ef36bd/cV.js. +# License is MIT: https://github.com/microsoft/CorrelationVector-JavaScript/blob/6da3f9e6150581756aba54b98dcd1e7329ef36bd/LICENSE + +import random + +BASE_64_CHAR_SET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" +CV_BASE_LENGTH = 22 + +def _generate_cv_base(): + # type: () -> str + """ + Seed function to randomly generate a 16 character base64 encoded string for + the Correlation Vector's base value. + """ + result = '' + + for i in range(CV_BASE_LENGTH): + random_index = random.randint(0, len(BASE_64_CHAR_SET) - 1) + result += BASE_64_CHAR_SET[random_index] + + return result diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_jwt.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_jwt.py new file mode 100644 index 000000000000..fa8e50d30b0f --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_jwt.py @@ -0,0 +1,35 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import base64 +import json +import time +from datetime import datetime +from msrest.serialization import TZ_UTC + +def _retrieve_jwt_expiration_timestamp(jwt_value): + # type: (str) -> int + """ + Retrieves the expiration value from the JWT. + + :param str jwt_value: The JWT value. + :returns: int + """ + if not jwt_value: + raise ValueError("jwt_value can not be None") + + token_parse_err_msg = "Token is not formatted correctly" + parts = jwt_value.split(".") + + if len(parts) < 3: + raise ValueError(token_parse_err_msg) + + try: + padded_base64_payload = base64.b64decode(parts[1]) + payload = json.loads(padded_base64_payload) + return payload['exp'] + except ValueError: + raise ValueError(token_parse_err_msg) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_utils.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_utils.py new file mode 100644 index 000000000000..1c4eb5be3eb1 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_utils.py @@ -0,0 +1,22 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +from azure.core.credentials import AccessToken + +from ._jwt import _retrieve_jwt_expiration_timestamp +from .._generated.models import StsTokenResponseMessage + +def _convert_to_access_token(token_response_message): + # type: (StsTokenResponseMessage) -> AccessToken + """ + Converts the specified token response message to an AccessToken. + """ + if not StsTokenResponseMessage: + raise ValueError("token_response_message can not be None") + + expiration_timestamp = _retrieve_jwt_expiration_timestamp(token_response_message.access_token) + + return AccessToken(token_response_message.access_token, expiration_timestamp) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/dev_requirements.txt b/sdk/mixedreality/azure-mixedreality-authentication/dev_requirements.txt index e8a0fc281e6f..86370a2c4f21 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/dev_requirements.txt +++ b/sdk/mixedreality/azure-mixedreality-authentication/dev_requirements.txt @@ -1,2 +1,4 @@ +-e ../../../tools/azure-devtools -e ../../../tools/azure-sdk-tools -../../core/azure-core \ No newline at end of file +../../core/azure-core +aiohttp>=3.0; python_version >= '3.5' \ No newline at end of file From 0a972dfcddcbe8f7c0251914335c209ef4f6c045 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Mon, 25 Jan 2021 18:46:43 -0800 Subject: [PATCH 04/40] Added samples --- .../samples/client_sample async.py | 70 +++++++++++++++++++ .../samples/client_sample.py | 63 +++++++++++++++++ 2 files changed, 133 insertions(+) create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/samples/client_sample async.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/samples/client_sample.py diff --git a/sdk/mixedreality/azure-mixedreality-authentication/samples/client_sample async.py b/sdk/mixedreality/azure-mixedreality-authentication/samples/client_sample async.py new file mode 100644 index 000000000000..5dc595bc2f3e --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/samples/client_sample async.py @@ -0,0 +1,70 @@ + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: client_sample_async.py +DESCRIPTION: + These samples demonstrate creating a client and requesting a token. + +USAGE: + python client_sample_async.py + Set the environment variables with your own values before running the sample: + 1) MIXEDREALITY_ACCOUNT_DOMAIN - the Mixed Reality account domain. + 2) MIXEDREALITY_ACCOUNT_ID - the Mixed Reality account identifier. + 3) MIXEDREALITY_ACCOUNT_KEY - the Mixed Reality account primary or secondary key. +""" + + +import os +import asyncio + + +class ClientSamplesAsync(object): + from azure.core.credentials import AzureKeyCredential + + account_domain = os.environ.get("MIXEDREALITY_ACCOUNT_DOMAIN", None) + if not account_domain: + raise ValueError("Set MIXEDREALITY_ACCOUNT_DOMAIN env before run this sample.") + + account_id = os.environ.get("MIXEDREALITY_ACCOUNT_ID", None) + if not account_id: + raise ValueError("Set MIXEDREALITY_ACCOUNT_ID env before run this sample.") + + account_key = os.environ.get("MIXEDREALITY_ACCOUNT_KEY", None) + if not account_key: + raise ValueError("Set MIXEDREALITY_ACCOUNT_KEY env before run this sample.") + + key_credential = AzureKeyCredential(account_key) + + def create_client(self): + # [START create_client] + from azure.mixedreality.authentication.aio import MixedRealityStsClient + client = MixedRealityStsClient(self.account_id, self.account_domain, self.key_credential) + # [END create_client] + + print("client created") + + async def get_token(self): + from azure.mixedreality.authentication.aio import MixedRealityStsClient + client = MixedRealityStsClient(self.account_id, self.account_domain, self.key_credential) + + async with client: + # [START get_token] + access_token = await client.get_token() + # [END get_token] + + print("token retrieved: " + access_token.token) + + +async def main(): + sample = ClientSamplesAsync() + sample.create_client() + await sample.get_token() + +if __name__ == '__main__': + loop = asyncio.get_event_loop() + loop.run_until_complete(main()) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/samples/client_sample.py b/sdk/mixedreality/azure-mixedreality-authentication/samples/client_sample.py new file mode 100644 index 000000000000..0de0e21a39de --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/samples/client_sample.py @@ -0,0 +1,63 @@ + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +""" +FILE: client_sample.py +DESCRIPTION: + These samples demonstrate creating a client and requesting a token. + +USAGE: + python client_sample.py + Set the environment variables with your own values before running the sample: + 1) MIXEDREALITY_ACCOUNT_DOMAIN - the Mixed Reality account domain. + 2) MIXEDREALITY_ACCOUNT_ID - the Mixed Reality account identifier. + 3) MIXEDREALITY_ACCOUNT_KEY - the Mixed Reality account primary or secondary key. +""" + + +import os + + +class ClientSamples(object): + from azure.core.credentials import AzureKeyCredential + + account_domain = os.environ.get("MIXEDREALITY_ACCOUNT_DOMAIN", None) + if not account_domain: + raise ValueError("Set MIXEDREALITY_ACCOUNT_DOMAIN env before run this sample.") + + account_id = os.environ.get("MIXEDREALITY_ACCOUNT_ID", None) + if not account_id: + raise ValueError("Set MIXEDREALITY_ACCOUNT_ID env before run this sample.") + + account_key = os.environ.get("MIXEDREALITY_ACCOUNT_KEY", None) + if not account_key: + raise ValueError("Set MIXEDREALITY_ACCOUNT_KEY env before run this sample.") + + key_credential = AzureKeyCredential(account_key) + + def create_client(self): + # [START create_client] + from azure.mixedreality.authentication import MixedRealityStsClient + client = MixedRealityStsClient(self.account_id, self.account_domain, self.key_credential) + # [END create_client] + + print("client created") + + def get_token(self): + # [START get_token] + from azure.mixedreality.authentication import MixedRealityStsClient + client = MixedRealityStsClient(self.account_id, self.account_domain, self.key_credential) + access_token = client.get_token() + # [END get_token] + + print("token retrieved: " + access_token.token) + + +if __name__ == '__main__': + sample = ClientSamples() + sample.create_client() + sample.get_token() From 3a70b517a9c4db2a0246c5737af5ac03ba5668ff Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Tue, 26 Jan 2021 16:53:38 -0800 Subject: [PATCH 05/40] Added documentation --- .../README.md | 191 ++++++++++++++++-- 1 file changed, 178 insertions(+), 13 deletions(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/README.md b/sdk/mixedreality/azure-mixedreality-authentication/README.md index 92c7ca73c592..ec240c9e6490 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/README.md +++ b/sdk/mixedreality/azure-mixedreality-authentication/README.md @@ -1,35 +1,200 @@ [![Build Status](https://dev.azure.com/azure-sdk/public/_apis/build/status/azure-sdk-for-python.client?branchName=master)](https://dev.azure.com/azure-sdk/public/_build/latest?definitionId=46?branchName=master) -# Azure Template Package client library for Python +# Azure Mixed Reality Authentication Package client library for Python -This template package matches necessary patterns that the development team has established to create a unified sdk functional from Python 2.7 onwards. The packages contained herein can be installed singly or as part of the `azure` namespace. Any other introductory text should go here. +Mixed Reality services, like Azure Spatial Anchors, Azure Remote Rendering, and others, use the Mixed Reality security +token service (STS) for authentication. This package supports exchanging Mixed Reality account credentials for an access +token from the STS that can be used to access Mixed Reality services. -This package has been tested with Python 2.7, 3.5, 3.6, 3.7 and 3.8 - -For a more complete set of Azure libraries, see https://aka.ms/azsdk/python/all +![Mixed Reality service authentication diagram](https://docs.microsoft.com/azure/spatial-anchors/concepts/media/spatial-anchors-authentication-overview.png) # Getting started -For a rich example of a well formatted readme, please check [here.](https://github.com/Azure/azure-sdk/blob/master/docs/policies/README-TEMPLATE.md) In addition, this is an [example readme](https://github.com/Azure/azure-sdk/blob/master/docs/policies/README-EXAMPLE.md) that should be emulated. Note that the top-level sections in this template align with that of the [template.](https://github.com/Azure/azure-sdk/blob/master/docs/policies/README-TEMPLATE.md) +## Currently supported environments + +This package has been tested with Python 2.7, 3.5, 3.6, 3.7 and 3.8. + +## Prerequisites + +- An [Azure subscription][azure_sub]. +- You must have an account with an [Azure Mixed Reality service](https://azure.microsoft.com/topic/mixed-reality/): + - [Azure Remote Rendering](https://docs.microsoft.com/azure/remote-rendering/) + - [Azure Spatial Anchors](https://docs.microsoft.com/azure/spatial-anchors/) +- Familiarity with the authentication and credential concepts from the [Azure Identity library][azure_identity]. +- Python 2.7, or 3.5 or later is required to use this package. + +## Install the package + +Install the Azure Communication Service Chat SDK. + +```bash +pip install --pre azure-mixedreality-authentication +``` + +## Create and authenticate a `MixedRealityStsClient` + +To create a client object to request an access token for a Mixed Reality service, you will need the `account identifier` +and `account domain` of your Mixed Reality service resource and a `credential`. + +Mixed Reality services support a few different forms of authentication: + +- Account Key authentication + - Account keys enable you to get started quickly with using Mixed Reality services. But before you deploy your application + to production, we recommend that you update your app to use Azure AD authentication. +- Azure Active Directory (AD) token authentication + - If you're building an enterprise application and your company is using Azure AD as its identity system, you can use + user-based Azure AD authentication in your app. You then grant access to your Mixed Reality accounts by using your + existing Azure AD security groups. You can also grant access directly to users in your organization. + - Otherwise, we recommend that you obtain Azure AD tokens from a web service that supports your app. We recommend this + method for production applications because it allows you to avoid embedding the credentials for access to a Mixed + Reality service in your client application. + +See [here][register_aad_app] for detailed instructions and information. + +### Using account key authentication + +Use the [Azure Portal][azure_portal] to browse to your Mixed Reality service resource and retrieve an `account key`. + +Once you have an account key, you can use the `AzureKeyCredential` class to authenticate the client as follows: + +```python +from azure.core.credentials import AzureKeyCredential +from azure.mixedreality.authentication import MixedRealityStsClient + +account_id = "" +account_domain = "" +account_key = "" +key_credential = AzureKeyCredential(account_key) + +client = MixedRealityStsClient(account_id, account_domain, key_credential) +``` + +> Note: Account key authentication is **not recommended** for production applications. + +### Using an Azure Active Directory Credential + +Account key authentication is used in most of the examples, but you can also authenticate with Azure Active Directory +using the [Azure Identity library][azure_identity]. This is the recommended method for production applications. To use +the [DefaultAzureCredential][defaultazurecredential] provider shown below, or other credential providers provided with +the Azure SDK, please install the `@azure/identity` package: + +You will also need to [register a new AAD application][register_aad_app] and grant access to your Mixed Reality resource +by assigning the appropriate role for your Mixed Reality service to your service principal. + +```python +from azure.core.credentials import AzureKeyCredential +from azure.identity import DefaultAzureCredential +from azure.mixedreality.authentication import MixedRealityStsClient + +account_id = "" +account_domain = "" +default_credential = DefaultAzureCredential() + +client = MixedRealityStsClient(account_id, account_domain, default_credential) +``` # Key concepts -Bullet point list of your library's main concepts. +## MixedRealityStsClient + +The `MixedRealityStsClient` is the client library used to access the Mixed Reality STS to get an access token. An access +token can be retrieved by calling `get_token()` on an `MixedRealityStsClient` instance. + +Tokens obtained from the Mixed Reality STS have a lifetime of **24 hours**. + +### Token result value + +The return value for a successful call to `get_token` is an `azure.core.credentials.AccessToken`. + +See the authentication examples [above](#authenticate-the-client) or [Azure Identity][azure_identity] for more complex +authentication scenarios. + +## Retrieve an access token synchronously + +```python +from azure.core.credentials import AzureKeyCredential +from azure.mixedreality.authentication import MixedRealityStsClient + +account_id = "" +account_domain = "" +account_key = "" +key_credential = AzureKeyCredential(account_key) + +client = MixedRealityStsClient(account_id, account_domain, key_credential) + +token = client.get_token() +``` + +## Retrieve an access token asynchronously -# Examples +```python +from azure.core.credentials import AzureKeyCredential +from azure.mixedreality.authentication.aio import MixedRealityStsClient -Examples of some of the key concepts for your library. +account_id = "" +account_domain = "" +account_key = "" +key_credential = AzureKeyCredential(account_key) + +client = MixedRealityStsClient(account_id, account_domain, key_credential) + +token = await client.get_token() +``` + +## Sample Code + +These are code samples that show common scenario operations with the Azure Mixed Reality Authentication client library. +The async versions of the samples (the python sample files appended with `_async`) show asynchronous operations, +and require Python 3.5 or later. +Before running the sample code, refer to Prerequisites + +to create a resource, then set some Environment Variables + +```bash +set MIXEDREALITY_ACCOUNT_DOMAIN="" +set MIXEDREALITY_ACCOUNT_ID="" +set MIXEDREALITY_ACCOUNT_KEY="" + +pip install azure-mixedreality-authentication + +python samples\client_sample.py +python samples\client_sample_async.py +``` # Troubleshooting -Running into issues? This section should contain details as to what to do there. +The [troubleshooting](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity#troubleshooting) +section for Azure Identity can be helpful when troubleshooting authentication issues. # Next steps -More sample code should go here, along with links out to the appropriate example tests. +## Mixed Reality client libraries + +- Coming soon + +## Contributing -# Contributing +This project welcomes contributions and suggestions. Most contributions require you to agree to a +Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us +the rights to use your contribution. For details, visit https://cla.microsoft.com. -If you encounter any bugs or have suggestions, please file an issue in the [Issues]() section of the project. +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide +a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions +provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or +contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + +If you'd like to contribute to this library, please read the +[contributing guide](https://github.com/Azure/azure-sdk-for-python/blob/master/CONTRIBUTING.md) to learn more about how to +build and test the code. ![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python%2Fsdk%2Ftemplate%2Fazure-template%2FREADME.png) + +[azure_cli]: https://docs.microsoft.com/cli/azure +[azure_sub]: https://azure.microsoft.com/free/ +[azure_portal]: https://portal.azure.com +[azure_identity]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity +[register_aad_app]: https://docs.microsoft.com/azure/spatial-anchors/concepts/authentication +[defaultazurecredential]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity#defaultazurecredential From eaa1faa292612f28a89928761dfb391871e2ee8e Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Wed, 27 Jan 2021 17:41:44 -0800 Subject: [PATCH 06/40] Added some simple tests for utilities --- .../mixedreality/authentication/utils/_jwt.py | 16 ++++--- .../tests/test_cv.py | 22 +++++++++ .../tests/test_jwt.py | 45 +++++++++++++++++++ .../tests/test_simple.py | 15 ------- 4 files changed, 76 insertions(+), 22 deletions(-) create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/tests/test_cv.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/tests/test_jwt.py delete mode 100644 sdk/mixedreality/azure-mixedreality-authentication/tests/test_simple.py diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_jwt.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_jwt.py index fa8e50d30b0f..1176cb5be7ee 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_jwt.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_jwt.py @@ -6,9 +6,6 @@ import base64 import json -import time -from datetime import datetime -from msrest.serialization import TZ_UTC def _retrieve_jwt_expiration_timestamp(jwt_value): # type: (str) -> int @@ -21,15 +18,20 @@ def _retrieve_jwt_expiration_timestamp(jwt_value): if not jwt_value: raise ValueError("jwt_value can not be None") - token_parse_err_msg = "Token is not formatted correctly" parts = jwt_value.split(".") if len(parts) < 3: - raise ValueError(token_parse_err_msg) + raise ValueError("Invalid JWT structure.") try: padded_base64_payload = base64.b64decode(parts[1]) payload = json.loads(padded_base64_payload) - return payload['exp'] except ValueError: - raise ValueError(token_parse_err_msg) + raise ValueError("Unable to decode the JWT.") + + try: + exp = payload['exp'] + except KeyError: + raise ValueError("Invalid JWT payload structure. No expiration.") + + return int(exp) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_cv.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_cv.py new file mode 100644 index 000000000000..63eb0ba8d428 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_cv.py @@ -0,0 +1,22 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +from azure.mixedreality.authentication.utils._cv import _generate_cv_base + +class TestCv: + def test_generate_cv_base(self): + cv = _generate_cv_base() + + assert cv is not None + assert len(cv) == 22 + + def test_generate_cv_base_are_random(self): + cv1 = _generate_cv_base() + cv2 = _generate_cv_base() + + assert cv1 is not None + assert cv2 is not None + assert cv1 != cv2 diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_jwt.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_jwt.py new file mode 100644 index 000000000000..e6c8b6a5d566 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_jwt.py @@ -0,0 +1,45 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import pytest + +from azure.mixedreality.authentication.utils._jwt import _retrieve_jwt_expiration_timestamp + +class TestJwt: + def test_retrieve_jwt_expiration_timestamp(self): + # Note: The trailing "." on the end indicates an empty signature indicating that this JWT is not signed. + jwt_value = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYxMDgxMjI1MCIsIm5iZiI6IjE2MTA4MTI1NTAiLCJleHAiOiIxNjEwODk4NjUwIn0=." + expected_expiration_timestamp = 1610898650 # 1/17/2021 3:50:50 PM UTC + + actual = _retrieve_jwt_expiration_timestamp(jwt_value) + + assert actual is not None + assert actual == expected_expiration_timestamp + + def test_retrieve_jwt_expiration_timestamp_invalid_parameter(self): + with pytest.raises(ValueError): + _retrieve_jwt_expiration_timestamp(None) + + def test_retrieve_jwt_expiration_timestamp_invalid_structure(self): + # JWT value with missing signature section on the end. + jwt_value = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYxMDgxMjI1MCIsIm5iZiI6IjE2MTA4MTI1NTAiLCJleHAiOiIxNjEwODk4NjUwIn0=" + + with pytest.raises(ValueError): + _retrieve_jwt_expiration_timestamp(jwt_value) + + def test_retrieve_jwt_expiration_timestamp_invalid_payload(self): + # JWT value with missing payload. + jwt_value = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.." + + with pytest.raises(ValueError): + _retrieve_jwt_expiration_timestamp(jwt_value) + + def test_retrieve_jwt_expiration_timestamp_invalid_exp(self): + # JWT value with missing expiration field. + jwt_value = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYxMDgxMjI1MCIsIm5iZiI6IjE2MTA4MTI1NTAifQ==." + + with pytest.raises(ValueError): + _retrieve_jwt_expiration_timestamp(jwt_value) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_simple.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_simple.py deleted file mode 100644 index 50c0f99479e2..000000000000 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_simple.py +++ /dev/null @@ -1,15 +0,0 @@ -# Testing Azure Packages has some additional complication/reading required. -# Reference https://github.com/Azure/azure-sdk-for-python/wiki/Contributing-to-the-tests -# Pytest should be leveraged to test your project. - -from devtools_testutils import AzureMgmtTestCase -from azure.template import template_main - -# this test case highlights that there are some additional Test capabilities present in devtools_testutils -# as a package owner you are not required to use these. Standard PyTest implementation will work. -class TemplateTest(AzureMgmtTestCase): - def setUp(self): - super(TemplateTest, self).setUp() - - def test_case_default(self): - self.assertEqual(template_main(), True) From b64d4868cc9437c723bd76f6dc3ddd73cef5c08a Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Thu, 28 Jan 2021 10:33:31 -0800 Subject: [PATCH 07/40] Added client tests --- .../tests/_constants.py | 10 ++ .../tests/conftest.py | 11 ++ .../test_client.test_get_token.yaml | 38 ++++++ .../test_client_async.test_get_token.yaml | 28 +++++ .../tests/test_client.py | 106 +++++++++++++++++ .../tests/test_client_async.py | 108 ++++++++++++++++++ 6 files changed, 301 insertions(+) create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/tests/_constants.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/tests/conftest.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/tests/recordings/test_client.test_get_token.yaml create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/tests/recordings/test_client_async.test_get_token.yaml create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/_constants.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/_constants.py new file mode 100644 index 000000000000..9de02c451788 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/_constants.py @@ -0,0 +1,10 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +# Fake account details matching recordings. +MIXEDREALITY_ACCOUNT_DOMAIN="mixedreality.azure.com" +MIXEDREALITY_ACCOUNT_ID="68321d5a-7978-4ceb-b880-0f49751daae9" +MIXEDREALITY_ACCOUNT_KEY="NjgzMjFkNWEtNzk3OC00Y2ViLWI4ODAtMGY0OTc1MWRhYWU5" \ No newline at end of file diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/conftest.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/conftest.py new file mode 100644 index 000000000000..9f69fcac8bdc --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/conftest.py @@ -0,0 +1,11 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import sys + +# Ignore collection of async tests for Python 2 +collect_ignore_glob = [] +if sys.version_info < (3, 5): + collect_ignore_glob.append("*_async.py") diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/recordings/test_client.test_get_token.yaml b/sdk/mixedreality/azure-mixedreality-authentication/tests/recordings/test_client.test_get_token.yaml new file mode 100644 index 000000000000..d3dae59d3e85 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/recordings/test_client.test_get_token.yaml @@ -0,0 +1,38 @@ +interactions: +- request: + body: null + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + Connection: + - keep-alive + User-Agent: + - azsdk-python-mixedreality-authentication/0.0.1b1 Python/3.9.1 (Windows-10-10.0.19041-SP0) + X-MRC-CV: + - z2TH5gImRhQCZc4ubhqtRV + method: GET + uri: https://sts.mixedreality.azure.com/Accounts/68321d5a-7978-4ceb-b880-0f49751daae9/token + response: + body: + string: '{"AccessToken":"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0=."}' + headers: + cache-control: + - no-store,no-cache + content-length: + - '1264' + content-type: + - application/json; charset=utf-8 + date: + - Thu, 28 Jan 2021 01:56:10 GMT + ms-cv: + - gKXl1CkeG0mRb6HEtMUmHQ.0 + pragma: + - no-cache + x-content-type-options: + - nosniff + status: + code: 200 + message: OK +version: 1 diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/recordings/test_client_async.test_get_token.yaml b/sdk/mixedreality/azure-mixedreality-authentication/tests/recordings/test_client_async.test_get_token.yaml new file mode 100644 index 000000000000..d35fa806f550 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/recordings/test_client_async.test_get_token.yaml @@ -0,0 +1,28 @@ +interactions: +- request: + body: null + headers: + Accept: + - application/json + User-Agent: + - azsdk-python-mixedreality-authentication/0.0.1b1 Python/3.9.1 (Windows-10-10.0.19041-SP0) + X-MRC-CV: + - DOGUG9rex0lylvLZmhuJgR + method: GET + uri: https://sts.mixedreality.azure.com/Accounts/68321d5a-7978-4ceb-b880-0f49751daae9/token + response: + body: + string: '{"AccessToken":"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0=."}' + headers: + cache-control: no-store,no-cache + content-length: '1264' + content-type: application/json; charset=utf-8 + date: Thu, 28 Jan 2021 18:31:51 GMT + ms-cv: K89E7J8QQ0qfkjIiukWztw.0 + pragma: no-cache + x-content-type-options: nosniff + status: + code: 200 + message: OK + url: https://sts.mixedreality.azure.com/Accounts/68321d5a-7978-4ceb-b880-0f49751daae9/token +version: 1 diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py new file mode 100644 index 000000000000..fa0a9d7b18af --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py @@ -0,0 +1,106 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import os +import pytest + +from devtools_testutils import AzureTestCase + +from azure.core.credentials import AzureKeyCredential +from azure.mixedreality.authentication import MixedRealityStsClient +from azure.mixedreality.authentication.shared import MixedRealityAccountKeyCredential + +# Import fake account details matching recordings. +from _constants import ( + MIXEDREALITY_ACCOUNT_DOMAIN, + MIXEDREALITY_ACCOUNT_ID, + MIXEDREALITY_ACCOUNT_KEY +) + + +class ClientTests(AzureTestCase): + def __init__(self, *args, **kwargs): + super(ClientTests, self).__init__(*args, **kwargs) + self.account_domain = self.get_var('MIXEDREALITY_ACCOUNT_DOMAIN', MIXEDREALITY_ACCOUNT_DOMAIN) + self.account_id = self.get_var('MIXEDREALITY_ACCOUNT_ID', MIXEDREALITY_ACCOUNT_ID) + self.account_key = self.get_var('MIXEDREALITY_ACCOUNT_KEY', MIXEDREALITY_ACCOUNT_KEY) + self.key_credential = AzureKeyCredential(self.account_key) + + def setUp(self): + super(ClientTests, self).setUp() + + def tearDown(self): + super(ClientTests, self).tearDown() + + def get_var(self, variable_name, default_or_playback_value): + if self.is_live: + return os.environ.get(variable_name, default_or_playback_value) + + return default_or_playback_value + + def test_create_client(self): + client = MixedRealityStsClient( + account_id=self.account_id, + account_domain=self.account_domain, + credential=self.key_credential) + + assert client is not None + + def test_create_client_custom_with_endpoint(self): + custom_endpoint_url = "https://my.custom.endpoint" + client = MixedRealityStsClient( + account_id=self.account_id, + account_domain=self.account_domain, + credential=self.key_credential, + endpoint_url=custom_endpoint_url) + + assert client._endpoint_url == custom_endpoint_url + + def test_create_client_with_credential(self): + token_credential = MixedRealityAccountKeyCredential(self.account_id, self.key_credential) + client = MixedRealityStsClient( + account_id=self.account_id, + account_domain=self.account_domain, + credential=token_credential) + + assert client._credential == token_credential + + def test_create_client_with_invalid_arguments(self): + with pytest.raises(ValueError): + MixedRealityStsClient( + account_id=None, + account_domain=self.account_domain, + credential=self.key_credential) + + with pytest.raises(ValueError): + MixedRealityStsClient( + account_id=self.account_id, + account_domain=None, + credential=self.key_credential) + + with pytest.raises(ValueError): + MixedRealityStsClient( + account_id=self.account_id, + account_domain=self.account_domain, + credential=None) + + with pytest.raises(ValueError): + MixedRealityStsClient( + account_id=self.account_id, + account_domain=self.account_domain, + credential=self.key_credential, + endpoint_url="#") + + def test_get_token(self): + client = MixedRealityStsClient( + account_id=self.account_id, + account_domain=self.account_domain, + credential=self.key_credential) + + token = client.get_token() + + assert token is not None + assert token.token is not None + assert token.expires_on is not None diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py new file mode 100644 index 000000000000..fc6445d23002 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py @@ -0,0 +1,108 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import os +import pytest + +from devtools_testutils import AzureTestCase + +from azure.core.credentials import AzureKeyCredential +from azure.mixedreality.authentication.aio import MixedRealityStsClient +from azure.mixedreality.authentication.shared import MixedRealityAccountKeyCredential + +# Import fake account details matching recordings. +from _constants import ( + MIXEDREALITY_ACCOUNT_DOMAIN, + MIXEDREALITY_ACCOUNT_ID, + MIXEDREALITY_ACCOUNT_KEY +) + + +class ClientTests(AzureTestCase): + def __init__(self, *args, **kwargs): + super(ClientTests, self).__init__(*args, **kwargs) + self.account_domain = self.get_var('MIXEDREALITY_ACCOUNT_DOMAIN', MIXEDREALITY_ACCOUNT_DOMAIN) + self.account_id = self.get_var('MIXEDREALITY_ACCOUNT_ID', MIXEDREALITY_ACCOUNT_ID) + self.account_key = self.get_var('MIXEDREALITY_ACCOUNT_KEY', MIXEDREALITY_ACCOUNT_KEY) + self.key_credential = AzureKeyCredential(self.account_key) + + def setUp(self): + super(ClientTests, self).setUp() + + def tearDown(self): + super(ClientTests, self).tearDown() + + def get_var(self, variable_name, default_or_playback_value): + # type: (str, str) -> str + if self.is_live: + return os.environ.get(variable_name, default_or_playback_value) + + return default_or_playback_value + + def test_create_client(self): + client = MixedRealityStsClient( + account_id=self.account_id, + account_domain=self.account_domain, + credential=self.key_credential) + + assert client is not None + + def test_create_client_custom_with_endpoint(self): + custom_endpoint_url = "https://my.custom.endpoint" + client = MixedRealityStsClient( + account_id=self.account_id, + account_domain=self.account_domain, + credential=self.key_credential, + endpoint_url=custom_endpoint_url) + + assert client._endpoint_url == custom_endpoint_url + + def test_create_client_with_credential(self): + token_credential = MixedRealityAccountKeyCredential(self.account_id, self.key_credential) + client = MixedRealityStsClient( + account_id=self.account_id, + account_domain=self.account_domain, + credential=token_credential) + + assert client._credential == token_credential + + def test_create_client_with_invalid_arguments(self): + with pytest.raises(ValueError): + MixedRealityStsClient( + account_id=None, + account_domain=self.account_domain, + credential=self.key_credential) + + with pytest.raises(ValueError): + MixedRealityStsClient( + account_id=self.account_id, + account_domain=None, + credential=self.key_credential) + + with pytest.raises(ValueError): + MixedRealityStsClient( + account_id=self.account_id, + account_domain=self.account_domain, + credential=None) + + with pytest.raises(ValueError): + MixedRealityStsClient( + account_id=self.account_id, + account_domain=self.account_domain, + credential=self.key_credential, + endpoint_url="#") + + @AzureTestCase.await_prepared_test + async def test_get_token(self): + client = MixedRealityStsClient( + account_id=self.account_id, + account_domain=self.account_domain, + credential=self.key_credential) + + token = await client.get_token() + + assert token is not None + assert token.token is not None + assert token.expires_on is not None From 7255fc310a0242ed633c63eb0951cbb324e6217d Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Fri, 29 Jan 2021 16:29:34 -0800 Subject: [PATCH 08/40] Fix typing bug in async client --- .../azure/mixedreality/authentication/aio/_client_async.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py index bdf5aa03591e..f61e26182a4f 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py @@ -41,7 +41,7 @@ class MixedRealityStsClient(object): def __init__(self, account_id: str, account_domain: str, - credential: Union[AzureKeyCredential, "AzureTokenCredential"], + credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs) -> None: if not account_id: raise ValueError("account_id can not be None") From 3148c9a1b6533228939df18d71d2e38b8402302b Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Fri, 29 Jan 2021 16:31:14 -0800 Subject: [PATCH 09/40] Added MixedRealityTokenCredential and cleaned up shared Shared no longer contains a `__init__.py` file to prevent cyclic dependencies. --- .../mixedreality/authentication/_client.py | 5 +- .../authentication/aio/_client_async.py | 5 +- .../authentication/shared/__init__.py | 13 ----- .../shared/_authentication_endpoint.py | 2 +- .../shared/_mixed_reality_token_credential.py | 47 +++++++++++++++ .../shared/_static_access_token_credential.py | 29 ++++++++++ .../aio/_mixed_reality_token_credential.py | 58 +++++++++++++++++++ .../tests/test_client.py | 2 +- .../tests/test_client_async.py | 2 +- 9 files changed, 143 insertions(+), 20 deletions(-) delete mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/__init__.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_mixed_reality_token_credential.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_static_access_token_credential.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_mixed_reality_token_credential.py diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py index ff655499b1a9..2be522aa6eea 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py @@ -17,7 +17,8 @@ from ._generated import MixedRealityStsRestClient from ._generated.models import TokenRequestOptions from ._version import SDK_MONIKER -from .shared import _construct_endpoint_url, MixedRealityAccountKeyCredential +from .shared._authentication_endpoint import construct_endpoint_url +from .shared._mixedreality_account_key_credential import MixedRealityAccountKeyCredential from .utils import _convert_to_access_token, _generate_cv_base if TYPE_CHECKING: @@ -52,7 +53,7 @@ def __init__(self, account_id, account_domain, credential, **kwargs): self._account_domain = account_domain self._credential = credential - endpoint_url = kwargs.pop('endpoint_url', _construct_endpoint_url(account_domain)) + endpoint_url = kwargs.pop('endpoint_url', construct_endpoint_url(account_domain)) try: if not endpoint_url.lower().startswith('http'): diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py index f61e26182a4f..fa3c1d2d092d 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py @@ -20,7 +20,8 @@ from .._generated.aio import MixedRealityStsRestClient from .._generated.models import TokenRequestOptions from .._version import SDK_MONIKER -from ..shared import _construct_endpoint_url, MixedRealityAccountKeyCredential +from ..shared._authentication_endpoint import construct_endpoint_url +from ..shared._mixedreality_account_key_credential import MixedRealityAccountKeyCredential from ..utils import _convert_to_access_token, _generate_cv_base if TYPE_CHECKING: @@ -56,7 +57,7 @@ def __init__(self, self._account_domain = account_domain self._credential = credential - endpoint_url = kwargs.pop('endpoint_url', _construct_endpoint_url(account_domain)) + endpoint_url = kwargs.pop('endpoint_url', construct_endpoint_url(account_domain)) try: if not endpoint_url.lower().startswith('http'): diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/__init__.py deleted file mode 100644 index e95d3e1e89a7..000000000000 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from ._authentication_endpoint import _construct_endpoint_url -from ._mixedreality_account_key_credential import MixedRealityAccountKeyCredential - -__all__ = [ - '_construct_endpoint_url' - 'MixedRealityAccountKeyCredential' -] diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_authentication_endpoint.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_authentication_endpoint.py index 0faae46a0e99..72bdcc70fd96 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_authentication_endpoint.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_authentication_endpoint.py @@ -4,6 +4,6 @@ # license information. # -------------------------------------------------------------------------- -def _construct_endpoint_url(account_domain): +def construct_endpoint_url(account_domain): # type: (str) -> str return 'https://sts.' + account_domain diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_mixed_reality_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_mixed_reality_token_credential.py new file mode 100644 index 000000000000..775a6d6c8ff2 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_mixed_reality_token_credential.py @@ -0,0 +1,47 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Union + from azure.core.credentials import AccessToken, TokenCredential + +from ._static_access_token_credential import StaticAccessTokenCredential +from .._client import MixedRealityStsClient + +def get_mixedreality_credential(account_id, endpoint_url, credential, **kwargs): + # type: (str, str, TokenCredential, Any) -> TokenCredential + if isinstance(credential, StaticAccessTokenCredential): + return credential + + return MixedRealityTokenCredential( + account_id=account_id, + endpoint_url=endpoint_url, + credential=credential, + **kwargs) + + +class MixedRealityTokenCredential(object): + """ Represents a token credential that can be used to access a Mixed Reality service. + This implements the TokenCredential protocol. + + :param str account_id: The Mixed Reality service account identifier. + :param str endpoint_url: The Mixed Reality STS service endpoint. + :param TokenCredential credential: The credential used to access the Mixed Reality service. + """ + + def __init__(self, account_id, endpoint_url, credential, **kwargs): + # type: (str, str, TokenCredential, Any) -> None + self.stsClient = MixedRealityStsClient( + account_id=account_id, + endpoint_url=endpoint_url, + credential=credential, + **kwargs) + + def get_token(self, *scopes, **kwargs): + # type: (*str, **Any) -> AccessToken + return self.stsClient.get_token(**kwargs) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_static_access_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_static_access_token_credential.py new file mode 100644 index 000000000000..519a782de6f2 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_static_access_token_credential.py @@ -0,0 +1,29 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + +from azure.core.credentials import AccessToken + +class StaticAccessTokenCredential(object): + """ Represents a static access token credential. + This implements the TokenCredential protocol. + + :param str account_id: The Mixed Reality service account identifier. + :param str endpoint_url: The Mixed Reality STS service endpoint. + :param TokenCredential credential: The credential used to access the Mixed Reality service. + """ + + def __init__(self, access_token): + # type: (AccessToken) -> None + self._access_token = access_token + + def get_token(self, *scopes, **kwargs): + # type: (*str, **Any) -> AccessToken + return self._access_token diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_mixed_reality_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_mixed_reality_token_credential.py new file mode 100644 index 000000000000..7a0464c9e090 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_mixed_reality_token_credential.py @@ -0,0 +1,58 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing import Any + from azure.core.credentials import AccessToken + from azure.core.credentials_async import AsyncTokenCredential + +from .._static_access_token_credential import StaticAccessTokenCredential +from ...aio._client_async import MixedRealityStsClient + +def get_mixedreality_credential_async( + account_id: str, + endpoint_url: str, + credential: "AsyncTokenCredential", + **kwargs): + if isinstance(credential, StaticAccessTokenCredential): + return credential + + return MixedRealityTokenCredential( + account_id=account_id, + endpoint_url=endpoint_url, + credential=credential, + **kwargs) + + +class MixedRealityTokenCredential(object): + """ Represents a token credential that can be used to access a Mixed Reality service. + This implements the TokenCredential protocol. + + :param str account_id: The Mixed Reality service account identifier. + :param str endpoint_url: The Mixed Reality STS service endpoint. + :param TokenCredential credential: The credential used to access the Mixed Reality service. + """ + + def __init__(self, account_id, endpoint_url, credential, **kwargs): + self.stsClient = MixedRealityStsClient( + account_id=account_id, + endpoint_url=endpoint_url, + credential=credential, + **kwargs) + + async def get_token(self, *scopes: str, **kwargs: "Any") -> "AccessToken": + return await self.stsClient.get_token(**kwargs) + + async def close(self) -> None: + self.stsClient.close() + + async def __aenter__(self): + await self.stsClient.__aenter__() + return self + + async def __aexit__(self, exc_type, exc_value, traceback) -> None: + await self.stsClient.__aexit__() diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py index fa0a9d7b18af..31e5ec0aca79 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py @@ -10,7 +10,7 @@ from azure.core.credentials import AzureKeyCredential from azure.mixedreality.authentication import MixedRealityStsClient -from azure.mixedreality.authentication.shared import MixedRealityAccountKeyCredential +from azure.mixedreality.authentication.shared._mixedreality_account_key_credential import MixedRealityAccountKeyCredential # Import fake account details matching recordings. from _constants import ( diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py index fc6445d23002..7985d037a30d 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py @@ -10,7 +10,7 @@ from azure.core.credentials import AzureKeyCredential from azure.mixedreality.authentication.aio import MixedRealityStsClient -from azure.mixedreality.authentication.shared import MixedRealityAccountKeyCredential +from azure.mixedreality.authentication.shared._mixedreality_account_key_credential import MixedRealityAccountKeyCredential # Import fake account details matching recordings. from _constants import ( From c76debfc356009c404852cf8c12716155d9ac3c8 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Fri, 29 Jan 2021 18:29:25 -0800 Subject: [PATCH 10/40] Tests and bug fixes - Lots of bugs around the async stuff. We actually need async versions of all of the credential types :(. You also have to use the async version of the bearer token policy, which took me a while to figure out. --- .../mixedreality/authentication/_client.py | 7 +-- .../authentication/aio/_client_async.py | 13 ++--- .../shared/_mixed_reality_token_credential.py | 10 ++-- .../shared/_static_access_token_credential.py | 7 +-- .../aio/_mixed_reality_token_credential.py | 9 ++-- .../_mixedreality_account_key_credential.py | 54 +++++++++++++++++++ .../aio/_static_access_token_credential.py | 34 ++++++++++++ .../tests/test_client_async.py | 2 +- .../test_mixed_reality_token_credential.py | 37 +++++++++++++ ...st_mixed_reality_token_credential_async.py | 37 +++++++++++++ .../test_static_access_token_credential.py | 21 ++++++++ ...st_static_access_token_credential_async.py | 23 ++++++++ 12 files changed, 232 insertions(+), 22 deletions(-) create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_mixedreality_account_key_credential.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_static_access_token_credential.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/tests/test_mixed_reality_token_credential.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/tests/test_mixed_reality_token_credential_async.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/tests/test_static_access_token_credential.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/tests/test_static_access_token_credential_async.py diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py index 2be522aa6eea..9f2acce03614 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py @@ -51,6 +51,10 @@ def __init__(self, account_id, account_domain, credential, **kwargs): self._account_id = account_id self._account_domain = account_domain + + if isinstance(credential, AzureKeyCredential): + credential = MixedRealityAccountKeyCredential(account_id, credential) + self._credential = credential endpoint_url = kwargs.pop('endpoint_url', construct_endpoint_url(account_domain)) @@ -67,9 +71,6 @@ def __init__(self, account_id, account_domain, credential, **kwargs): self._endpoint_url = endpoint_url - if isinstance(credential, AzureKeyCredential): - credential = MixedRealityAccountKeyCredential(account_id, credential) - authentication_policy = BearerTokenCredentialPolicy(credential, [endpoint_url + '/.default']) self._client = MixedRealityStsRestClient( diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py index fa3c1d2d092d..e650c577368b 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py @@ -15,13 +15,13 @@ from azure.core.credentials import AccessToken, AzureKeyCredential from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.pipeline.policies import BearerTokenCredentialPolicy +from azure.core.pipeline.policies import AsyncBearerTokenCredentialPolicy from .._generated.aio import MixedRealityStsRestClient from .._generated.models import TokenRequestOptions from .._version import SDK_MONIKER from ..shared._authentication_endpoint import construct_endpoint_url -from ..shared._mixedreality_account_key_credential import MixedRealityAccountKeyCredential +from ..shared.aio._mixedreality_account_key_credential import MixedRealityAccountKeyCredential from ..utils import _convert_to_access_token, _generate_cv_base if TYPE_CHECKING: @@ -55,6 +55,10 @@ def __init__(self, self._account_id = account_id self._account_domain = account_domain + + if isinstance(credential, AzureKeyCredential): + credential = MixedRealityAccountKeyCredential(account_id, credential) + self._credential = credential endpoint_url = kwargs.pop('endpoint_url', construct_endpoint_url(account_domain)) @@ -71,10 +75,7 @@ def __init__(self, self._endpoint_url = endpoint_url - if isinstance(credential, AzureKeyCredential): - credential = MixedRealityAccountKeyCredential(account_id, credential) - - authentication_policy = BearerTokenCredentialPolicy(credential, [endpoint_url + '/.default']) + authentication_policy = AsyncBearerTokenCredentialPolicy(credential, [endpoint_url + '/.default']) self._client = MixedRealityStsRestClient( base_url=endpoint_url, diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_mixed_reality_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_mixed_reality_token_credential.py index 775a6d6c8ff2..e805e6de08ea 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_mixed_reality_token_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_mixed_reality_token_credential.py @@ -13,13 +13,14 @@ from ._static_access_token_credential import StaticAccessTokenCredential from .._client import MixedRealityStsClient -def get_mixedreality_credential(account_id, endpoint_url, credential, **kwargs): - # type: (str, str, TokenCredential, Any) -> TokenCredential +def get_mixedreality_credential(account_id, account_domain, endpoint_url, credential, **kwargs): + # type: (str, str, str, TokenCredential, Any) -> TokenCredential if isinstance(credential, StaticAccessTokenCredential): return credential return MixedRealityTokenCredential( account_id=account_id, + account_domain=account_domain, endpoint_url=endpoint_url, credential=credential, **kwargs) @@ -34,10 +35,11 @@ class MixedRealityTokenCredential(object): :param TokenCredential credential: The credential used to access the Mixed Reality service. """ - def __init__(self, account_id, endpoint_url, credential, **kwargs): - # type: (str, str, TokenCredential, Any) -> None + def __init__(self, account_id, account_domain, endpoint_url, credential, **kwargs): + # type: (str, str, str, TokenCredential, Any) -> None self.stsClient = MixedRealityStsClient( account_id=account_id, + account_domain=account_domain, endpoint_url=endpoint_url, credential=credential, **kwargs) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_static_access_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_static_access_token_credential.py index 519a782de6f2..3dd902553cce 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_static_access_token_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_static_access_token_credential.py @@ -8,16 +8,13 @@ if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential - -from azure.core.credentials import AccessToken + from azure.core.credentials import AccessToken class StaticAccessTokenCredential(object): """ Represents a static access token credential. This implements the TokenCredential protocol. - :param str account_id: The Mixed Reality service account identifier. - :param str endpoint_url: The Mixed Reality STS service endpoint. - :param TokenCredential credential: The credential used to access the Mixed Reality service. + :param AccessToken access_token: An access token. """ def __init__(self, access_token): diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_mixed_reality_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_mixed_reality_token_credential.py index 7a0464c9e090..14b4e81facf3 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_mixed_reality_token_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_mixed_reality_token_credential.py @@ -10,11 +10,12 @@ from azure.core.credentials import AccessToken from azure.core.credentials_async import AsyncTokenCredential -from .._static_access_token_credential import StaticAccessTokenCredential +from ._static_access_token_credential import StaticAccessTokenCredential from ...aio._client_async import MixedRealityStsClient -def get_mixedreality_credential_async( +def get_mixedreality_credential( account_id: str, + account_domain: str, endpoint_url: str, credential: "AsyncTokenCredential", **kwargs): @@ -23,6 +24,7 @@ def get_mixedreality_credential_async( return MixedRealityTokenCredential( account_id=account_id, + account_domain=account_domain, endpoint_url=endpoint_url, credential=credential, **kwargs) @@ -37,9 +39,10 @@ class MixedRealityTokenCredential(object): :param TokenCredential credential: The credential used to access the Mixed Reality service. """ - def __init__(self, account_id, endpoint_url, credential, **kwargs): + def __init__(self, account_id: str, account_domain: str, endpoint_url: str, credential: "AsyncTokenCredential", **kwargs): self.stsClient = MixedRealityStsClient( account_id=account_id, + account_domain=account_domain, endpoint_url=endpoint_url, credential=credential, **kwargs) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_mixedreality_account_key_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_mixedreality_account_key_credential.py new file mode 100644 index 000000000000..fb2adb3283af --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_mixedreality_account_key_credential.py @@ -0,0 +1,54 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +from typing import TYPE_CHECKING + +from datetime import date, datetime + +from azure.core.credentials import AccessToken + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + from azure.core.credentials import AzureKeyCredential + +ACCOUNT_KEY_VALID_YEARS = 10 + +class MixedRealityAccountKeyCredential(object): + """ Represents an object used for Mixed Reality account key authentication. + + :param str account_id: The Mixed Reality service account identifier. + :param AzureKeyCredential account_key: The Mixed Reality service account primary or secondary key credential. + """ + + def __init__(self, account_id, account_key): + # type: (str, AzureKeyCredential) -> None + self.account_id = account_id + self.account_key = account_key + + async def get_token(self, *scopes: str, **kwargs: "Any") -> "AccessToken": + token = self.account_id + ":" + self.account_key.key + + # No way to know when an access token might expire, so we'll set it to be + # 10 years in the future. + expiration_date = _add_years(datetime.now(), ACCOUNT_KEY_VALID_YEARS) + expiration_timestamp = int(expiration_date.timestamp()) + + return AccessToken(token, expiration_timestamp) + + async def close(self) -> None: + pass + + async def __aenter__(self): + pass + + async def __aexit__(self, exc_type, exc_value, traceback) -> None: + pass + +def _add_years(date_to_update, years): + try: + return date_to_update.replace(year = date_to_update.year + years) + except ValueError: + return date_to_update + (date(date_to_update.year + years, 1, 1) - date(date_to_update.year, 1, 1)) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_static_access_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_static_access_token_credential.py new file mode 100644 index 000000000000..a62618fc8c79 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_static_access_token_credential.py @@ -0,0 +1,34 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import asyncio +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials_async import AsyncTokenCredential + from azure.core.credentials import AccessToken + +class StaticAccessTokenCredential(object): + """ Represents a static access token credential. + This implements the AsyncTokenCredential protocol. + + :param AccessToken access_token: An access token. + """ + + def __init__(self, access_token: "AccessToken"): + self._access_token = access_token + + async def get_token(self, *scopes: str, **kwargs: "Any") -> "AccessToken": + return self._access_token + + async def close(self) -> None: + pass + + async def __aenter__(self): + pass + + async def __aexit__(self, exc_type, exc_value, traceback) -> None: + pass diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py index 7985d037a30d..c9b4a7968f58 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py @@ -10,7 +10,7 @@ from azure.core.credentials import AzureKeyCredential from azure.mixedreality.authentication.aio import MixedRealityStsClient -from azure.mixedreality.authentication.shared._mixedreality_account_key_credential import MixedRealityAccountKeyCredential +from azure.mixedreality.authentication.shared.aio._mixedreality_account_key_credential import MixedRealityAccountKeyCredential # Import fake account details matching recordings. from _constants import ( diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_mixed_reality_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_mixed_reality_token_credential.py new file mode 100644 index 000000000000..36e872a7866a --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_mixed_reality_token_credential.py @@ -0,0 +1,37 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +from azure.core.credentials import AccessToken, AzureKeyCredential + +from azure.mixedreality.authentication.shared._mixed_reality_token_credential import get_mixedreality_credential, MixedRealityTokenCredential +from azure.mixedreality.authentication.shared._static_access_token_credential import StaticAccessTokenCredential +from azure.mixedreality.authentication.shared._mixedreality_account_key_credential import MixedRealityAccountKeyCredential + +class TestMixedRealityTokenCredential: + def test_get_mixedreality_credential_static_credential(self): + access_token = AccessToken("My access token", 0) + credential = StaticAccessTokenCredential(access_token) + + actualCredential = get_mixedreality_credential( + account_id="account_id", + account_domain="account_domain", + endpoint_url="http://my.endpoint.url", + credential=credential) + + assert credential == actualCredential + + def test_get_mixedreality_credential_other_credential(self): + keyCredential = AzureKeyCredential("my_account_key") + credential = MixedRealityAccountKeyCredential("account_id", keyCredential) + + actualCredential = get_mixedreality_credential( + account_id="account_id", + account_domain="account_domain", + endpoint_url="http://my.endpoint.url", + credential=credential) + + assert credential != actualCredential + assert isinstance(actualCredential, MixedRealityTokenCredential) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_mixed_reality_token_credential_async.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_mixed_reality_token_credential_async.py new file mode 100644 index 000000000000..b8eafb039a0c --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_mixed_reality_token_credential_async.py @@ -0,0 +1,37 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +from azure.core.credentials import AccessToken, AzureKeyCredential + +from azure.mixedreality.authentication.shared.aio._mixed_reality_token_credential import get_mixedreality_credential, MixedRealityTokenCredential +from azure.mixedreality.authentication.shared.aio._static_access_token_credential import StaticAccessTokenCredential +from azure.mixedreality.authentication.shared.aio._mixedreality_account_key_credential import MixedRealityAccountKeyCredential + +class TestMixedRealityTokenCredential: + def test_get_mixedreality_credential_static_credential(self): + access_token = AccessToken("My access token", 0) + credential = StaticAccessTokenCredential(access_token) + + actualCredential = get_mixedreality_credential( + account_id="account_id", + account_domain="account_domain", + endpoint_url="http://my.endpoint.url", + credential=credential) + + assert credential == actualCredential + + def test_get_mixedreality_credential_other_credential(self): + keyCredential = AzureKeyCredential("my_account_key") + credential = MixedRealityAccountKeyCredential("account_id", keyCredential) + + actualCredential = get_mixedreality_credential( + account_id="account_id", + account_domain="account_domain", + endpoint_url="http://my.endpoint.url", + credential=credential) + + assert credential != actualCredential + assert isinstance(actualCredential, MixedRealityTokenCredential) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_static_access_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_static_access_token_credential.py new file mode 100644 index 000000000000..b8aced015c2f --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_static_access_token_credential.py @@ -0,0 +1,21 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +from azure.core.credentials import AccessToken + +from azure.mixedreality.authentication.shared._static_access_token_credential import StaticAccessTokenCredential + +class TestStaticAccessTokenCredential: + def test_get_token(self): + token = "My access token" + expiration = 0 + + access_token = AccessToken(token=token, expires_on=expiration) + staticAccessToken = StaticAccessTokenCredential(access_token) + + actual = staticAccessToken.get_token() + + assert access_token == actual diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_static_access_token_credential_async.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_static_access_token_credential_async.py new file mode 100644 index 000000000000..7c6ebb2951eb --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_static_access_token_credential_async.py @@ -0,0 +1,23 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +from azure.core.credentials import AccessToken +from devtools_testutils import AzureTestCase + +from azure.mixedreality.authentication.shared.aio._static_access_token_credential import StaticAccessTokenCredential + +class TestAsyncStaticAccessTokenCredential: + @AzureTestCase.await_prepared_test + async def test_get_token(self): + token = "My access token" + expiration = 0 + + access_token = AccessToken(token=token, expires_on=expiration) + staticAccessToken = StaticAccessTokenCredential(access_token) + + actual = await staticAccessToken.get_token() + + assert access_token == actual From 30a088377fe285b7fcb87e2735421a2d1e2f23a1 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Mon, 1 Feb 2021 16:00:24 -0800 Subject: [PATCH 11/40] Updated input file to updated spec file --- .../azure-mixedreality-authentication/swagger/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/swagger/README.md b/sdk/mixedreality/azure-mixedreality-authentication/swagger/README.md index db45991460b0..aa23b1d9c8bd 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/swagger/README.md +++ b/sdk/mixedreality/azure-mixedreality-authentication/swagger/README.md @@ -17,7 +17,7 @@ autorest README.md ```yaml title: MixedRealityStsRestClient -input-file: https://raw.githubusercontent.com/craigktreasure/azure-rest-api-specs/6938d23da2be2a20b9998e002ef8b79e8d83e509/specification/mixedreality/data-plane/Microsoft.MixedReality/preview/2019-02-28-preview/mr-sts.json +input-file: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/aa19725fe79aea2a9dc580f3c66f77f89cc34563/specification/mixedreality/data-plane/Microsoft.MixedReality/preview/2019-02-28-preview/mr-sts.json output-folder: ../azure/mixedreality/authentication/_generated namespace: azure.mixedreality.authentication._generated no-namespace-folders: true From 2f8449a7443d204892d3b1153444792969b05ffb Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Wed, 3 Feb 2021 18:14:24 -0800 Subject: [PATCH 12/40] Fixed the AccessToken type hint --- .../azure/mixedreality/authentication/_client.py | 4 +++- .../azure/mixedreality/authentication/aio/_client_async.py | 7 +++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py index 9f2acce03614..0cb934060c16 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py @@ -81,9 +81,11 @@ def __init__(self, account_id, account_domain, credential, **kwargs): @distributed_trace def get_token(self, **kwargs): - # type: (Any) -> AccessToken + # type: (Any) -> azure.core.credentials.AccessToken """ Retrieve a token from the STS service for the specified account identifier asynchronously. + :return: Instance of azure.core.credentials.AccessToken - token and expiry date of it + :rtype: ~azure.core.credentials.AccessToken """ token_request_options = TokenRequestOptions() token_request_options.client_request_id = _generate_cv_base() diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py index e650c577368b..ed39ca42a58a 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py @@ -13,7 +13,7 @@ # pylint: disable=unused-import,ungrouped-imports from typing import Any, Union -from azure.core.credentials import AccessToken, AzureKeyCredential +from azure.core.credentials import AzureKeyCredential from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.pipeline.policies import AsyncBearerTokenCredentialPolicy @@ -25,6 +25,7 @@ from ..utils import _convert_to_access_token, _generate_cv_base if TYPE_CHECKING: + from azure.core.credentials import AccessToken from azure.core.credentials_async import AsyncTokenCredential @@ -84,9 +85,11 @@ def __init__(self, **kwargs) @distributed_trace_async - async def get_token(self, **kwargs) -> AccessToken: + async def get_token(self, **kwargs) -> "AccessToken": """ Retrieve a token from the STS service for the specified account identifier asynchronously. + :return: Instance of azure.core.credentials.AccessToken - token and expiry date of it + :rtype: :class:`azure.core.credentials.AccessToken` """ token_request_options = TokenRequestOptions() token_request_options.client_request_id=_generate_cv_base() From 6d97bc5d676c3616d28492351879782fa49327fb Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Wed, 3 Feb 2021 18:45:51 -0800 Subject: [PATCH 13/40] Added custom_endpoint as an optional parameter --- .../mixedreality/authentication/_client.py | 17 ++++++++--------- .../authentication/aio/_client_async.py | 17 +++++++++-------- .../tests/test_client.py | 4 ++-- .../tests/test_client_async.py | 4 ++-- 4 files changed, 21 insertions(+), 21 deletions(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py index 0cb934060c16..2da2a5432fcd 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py @@ -36,10 +36,12 @@ class MixedRealityStsClient(object): The Mixed Reality service account domain. :param Union[TokenCredential, AzureKeyCredential] credential: The credential used to access the Mixed Reality service. + :param str custom_endpoint: + Override the Mixed Reality STS service endpoint. """ - def __init__(self, account_id, account_domain, credential, **kwargs): - # type: (str, str, Union[TokenCredential, AzureKeyCredential], Any) -> None + def __init__(self, account_id, account_domain, credential, custom_endpoint=None, **kwargs): + # type: (str, str, Union[TokenCredential, AzureKeyCredential], str, Any) -> None if not account_id: raise ValueError("account_id can not be None") @@ -57,13 +59,10 @@ def __init__(self, account_id, account_domain, credential, **kwargs): self._credential = credential - endpoint_url = kwargs.pop('endpoint_url', construct_endpoint_url(account_domain)) - - try: - if not endpoint_url.lower().startswith('http'): - endpoint_url = "https://" + endpoint_url - except AttributeError: - raise ValueError("Host URL must be a string") + if custom_endpoint: + endpoint_url = custom_endpoint + else: + endpoint_url = construct_endpoint_url(account_domain) parsed_url = urlparse(endpoint_url.rstrip('/')) if not parsed_url.netloc: diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py index ed39ca42a58a..8d92b15e4e21 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py @@ -3,7 +3,7 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Optional, TYPE_CHECKING try: from urllib.parse import urlparse @@ -38,12 +38,16 @@ class MixedRealityStsClient(object): The Mixed Reality service account domain. :param Union[TokenCredential, AzureKeyCredential] credential: The credential used to access the Mixed Reality service. + :param str custom_endpoint: + Override the Mixed Reality STS service endpoint. """ def __init__(self, account_id: str, account_domain: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], + *, + custom_endpoint: Optional[str] = None, **kwargs) -> None: if not account_id: raise ValueError("account_id can not be None") @@ -62,13 +66,10 @@ def __init__(self, self._credential = credential - endpoint_url = kwargs.pop('endpoint_url', construct_endpoint_url(account_domain)) - - try: - if not endpoint_url.lower().startswith('http'): - endpoint_url = "https://" + endpoint_url - except AttributeError: - raise ValueError("Host URL must be a string") + if custom_endpoint: + endpoint_url = custom_endpoint + else: + endpoint_url = construct_endpoint_url(account_domain) parsed_url = urlparse(endpoint_url.rstrip('/')) if not parsed_url.netloc: diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py index 31e5ec0aca79..f72835b08d62 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py @@ -54,7 +54,7 @@ def test_create_client_custom_with_endpoint(self): account_id=self.account_id, account_domain=self.account_domain, credential=self.key_credential, - endpoint_url=custom_endpoint_url) + custom_endpoint=custom_endpoint_url) assert client._endpoint_url == custom_endpoint_url @@ -91,7 +91,7 @@ def test_create_client_with_invalid_arguments(self): account_id=self.account_id, account_domain=self.account_domain, credential=self.key_credential, - endpoint_url="#") + custom_endpoint="#") def test_get_token(self): client = MixedRealityStsClient( diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py index c9b4a7968f58..051f98e1a950 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py @@ -55,7 +55,7 @@ def test_create_client_custom_with_endpoint(self): account_id=self.account_id, account_domain=self.account_domain, credential=self.key_credential, - endpoint_url=custom_endpoint_url) + custom_endpoint=custom_endpoint_url) assert client._endpoint_url == custom_endpoint_url @@ -92,7 +92,7 @@ def test_create_client_with_invalid_arguments(self): account_id=self.account_id, account_domain=self.account_domain, credential=self.key_credential, - endpoint_url="#") + custom_endpoint="#") @AzureTestCase.await_prepared_test async def test_get_token(self): From 8e959d4400231fbc3a3bcf4bde786272ba64ec0d Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Mon, 8 Feb 2021 09:58:17 -0800 Subject: [PATCH 14/40] Revert "Added custom_endpoint as an optional parameter" This reverts commit a2e77f40713c77390ea82433c50d2429a03a35e7. --- .../mixedreality/authentication/_client.py | 17 +++++++++-------- .../authentication/aio/_client_async.py | 17 ++++++++--------- .../tests/test_client.py | 4 ++-- .../tests/test_client_async.py | 4 ++-- 4 files changed, 21 insertions(+), 21 deletions(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py index 2da2a5432fcd..0cb934060c16 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py @@ -36,12 +36,10 @@ class MixedRealityStsClient(object): The Mixed Reality service account domain. :param Union[TokenCredential, AzureKeyCredential] credential: The credential used to access the Mixed Reality service. - :param str custom_endpoint: - Override the Mixed Reality STS service endpoint. """ - def __init__(self, account_id, account_domain, credential, custom_endpoint=None, **kwargs): - # type: (str, str, Union[TokenCredential, AzureKeyCredential], str, Any) -> None + def __init__(self, account_id, account_domain, credential, **kwargs): + # type: (str, str, Union[TokenCredential, AzureKeyCredential], Any) -> None if not account_id: raise ValueError("account_id can not be None") @@ -59,10 +57,13 @@ def __init__(self, account_id, account_domain, credential, custom_endpoint=None, self._credential = credential - if custom_endpoint: - endpoint_url = custom_endpoint - else: - endpoint_url = construct_endpoint_url(account_domain) + endpoint_url = kwargs.pop('endpoint_url', construct_endpoint_url(account_domain)) + + try: + if not endpoint_url.lower().startswith('http'): + endpoint_url = "https://" + endpoint_url + except AttributeError: + raise ValueError("Host URL must be a string") parsed_url = urlparse(endpoint_url.rstrip('/')) if not parsed_url.netloc: diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py index 8d92b15e4e21..ed39ca42a58a 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py @@ -3,7 +3,7 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- -from typing import Optional, TYPE_CHECKING +from typing import TYPE_CHECKING try: from urllib.parse import urlparse @@ -38,16 +38,12 @@ class MixedRealityStsClient(object): The Mixed Reality service account domain. :param Union[TokenCredential, AzureKeyCredential] credential: The credential used to access the Mixed Reality service. - :param str custom_endpoint: - Override the Mixed Reality STS service endpoint. """ def __init__(self, account_id: str, account_domain: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], - *, - custom_endpoint: Optional[str] = None, **kwargs) -> None: if not account_id: raise ValueError("account_id can not be None") @@ -66,10 +62,13 @@ def __init__(self, self._credential = credential - if custom_endpoint: - endpoint_url = custom_endpoint - else: - endpoint_url = construct_endpoint_url(account_domain) + endpoint_url = kwargs.pop('endpoint_url', construct_endpoint_url(account_domain)) + + try: + if not endpoint_url.lower().startswith('http'): + endpoint_url = "https://" + endpoint_url + except AttributeError: + raise ValueError("Host URL must be a string") parsed_url = urlparse(endpoint_url.rstrip('/')) if not parsed_url.netloc: diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py index f72835b08d62..31e5ec0aca79 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py @@ -54,7 +54,7 @@ def test_create_client_custom_with_endpoint(self): account_id=self.account_id, account_domain=self.account_domain, credential=self.key_credential, - custom_endpoint=custom_endpoint_url) + endpoint_url=custom_endpoint_url) assert client._endpoint_url == custom_endpoint_url @@ -91,7 +91,7 @@ def test_create_client_with_invalid_arguments(self): account_id=self.account_id, account_domain=self.account_domain, credential=self.key_credential, - custom_endpoint="#") + endpoint_url="#") def test_get_token(self): client = MixedRealityStsClient( diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py index 051f98e1a950..c9b4a7968f58 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py @@ -55,7 +55,7 @@ def test_create_client_custom_with_endpoint(self): account_id=self.account_id, account_domain=self.account_domain, credential=self.key_credential, - custom_endpoint=custom_endpoint_url) + endpoint_url=custom_endpoint_url) assert client._endpoint_url == custom_endpoint_url @@ -92,7 +92,7 @@ def test_create_client_with_invalid_arguments(self): account_id=self.account_id, account_domain=self.account_domain, credential=self.key_credential, - custom_endpoint="#") + endpoint_url="#") @AzureTestCase.await_prepared_test async def test_get_token(self): From 1b98cf2ead27ead29eec4e432fe8e2e7ef1dfe38 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Mon, 8 Feb 2021 10:09:57 -0800 Subject: [PATCH 15/40] Renamed endpoint_url to custom_endpoint_url with docstring --- .../azure/mixedreality/authentication/_client.py | 4 +++- .../azure/mixedreality/authentication/aio/_client_async.py | 4 +++- .../azure-mixedreality-authentication/tests/test_client.py | 4 ++-- .../tests/test_client_async.py | 4 ++-- 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py index 0cb934060c16..f10f36a107cc 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py @@ -36,6 +36,8 @@ class MixedRealityStsClient(object): The Mixed Reality service account domain. :param Union[TokenCredential, AzureKeyCredential] credential: The credential used to access the Mixed Reality service. + :keyword str custom_endpoint_url: + Override the Mixed Reality STS service endpoint. """ def __init__(self, account_id, account_domain, credential, **kwargs): @@ -57,7 +59,7 @@ def __init__(self, account_id, account_domain, credential, **kwargs): self._credential = credential - endpoint_url = kwargs.pop('endpoint_url', construct_endpoint_url(account_domain)) + endpoint_url = kwargs.pop('custom_endpoint_url', construct_endpoint_url(account_domain)) try: if not endpoint_url.lower().startswith('http'): diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py index ed39ca42a58a..f875d29bab45 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py @@ -38,6 +38,8 @@ class MixedRealityStsClient(object): The Mixed Reality service account domain. :param Union[TokenCredential, AzureKeyCredential] credential: The credential used to access the Mixed Reality service. + :keyword str custom_endpoint_url: + Override the Mixed Reality STS service endpoint. """ def __init__(self, @@ -62,7 +64,7 @@ def __init__(self, self._credential = credential - endpoint_url = kwargs.pop('endpoint_url', construct_endpoint_url(account_domain)) + endpoint_url = kwargs.pop('custom_endpoint_url', construct_endpoint_url(account_domain)) try: if not endpoint_url.lower().startswith('http'): diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py index 31e5ec0aca79..5829c45bd197 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py @@ -54,7 +54,7 @@ def test_create_client_custom_with_endpoint(self): account_id=self.account_id, account_domain=self.account_domain, credential=self.key_credential, - endpoint_url=custom_endpoint_url) + custom_endpoint_url=custom_endpoint_url) assert client._endpoint_url == custom_endpoint_url @@ -91,7 +91,7 @@ def test_create_client_with_invalid_arguments(self): account_id=self.account_id, account_domain=self.account_domain, credential=self.key_credential, - endpoint_url="#") + custom_endpoint_url="#") def test_get_token(self): client = MixedRealityStsClient( diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py index c9b4a7968f58..ced292db0c86 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py @@ -55,7 +55,7 @@ def test_create_client_custom_with_endpoint(self): account_id=self.account_id, account_domain=self.account_domain, credential=self.key_credential, - endpoint_url=custom_endpoint_url) + custom_endpoint_url=custom_endpoint_url) assert client._endpoint_url == custom_endpoint_url @@ -92,7 +92,7 @@ def test_create_client_with_invalid_arguments(self): account_id=self.account_id, account_domain=self.account_domain, credential=self.key_credential, - endpoint_url="#") + custom_endpoint_url="#") @AzureTestCase.await_prepared_test async def test_get_token(self): From a069dde37e20258db945fb227a38489c440ace57 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Mon, 8 Feb 2021 10:56:35 -0800 Subject: [PATCH 16/40] Get consistent on _ and use __init__ for shared modules --- .../azure/mixedreality/authentication/_client.py | 10 +++++----- .../mixedreality/authentication/_shared/__init__.py | 5 +++++ .../authentication/_shared/aio/__init__.py | 5 +++++ .../aio/mixed_reality_token_credential.py} | 2 +- .../aio/mixedreality_account_key_credential.py} | 0 .../aio/static_access_token_credential.py} | 0 .../authentication_endpoint.py} | 0 .../mixed_reality_token_credential.py} | 2 +- .../mixedreality_account_key_credential.py} | 0 .../static_access_token_credential.py} | 0 .../authentication/{utils => _utils}/__init__.py | 12 ++++++------ .../authentication/{utils/_cv.py => _utils/cv.py} | 2 +- .../authentication/{utils/_jwt.py => _utils/jwt.py} | 2 +- .../{utils/_utils.py => _utils/utils.py} | 6 +++--- .../mixedreality/authentication/aio/_client_async.py | 10 +++++----- .../tests/test_client.py | 2 +- .../tests/test_client_async.py | 2 +- .../tests/test_cv.py | 8 ++++---- .../tests/test_jwt.py | 12 ++++++------ .../tests/test_mixed_reality_token_credential.py | 6 +++--- .../test_mixed_reality_token_credential_async.py | 6 +++--- .../tests/test_static_access_token_credential.py | 2 +- .../test_static_access_token_credential_async.py | 2 +- 23 files changed, 53 insertions(+), 43 deletions(-) create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/__init__.py create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/__init__.py rename sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/{shared/aio/_mixed_reality_token_credential.py => _shared/aio/mixed_reality_token_credential.py} (96%) rename sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/{shared/aio/_mixedreality_account_key_credential.py => _shared/aio/mixedreality_account_key_credential.py} (100%) rename sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/{shared/aio/_static_access_token_credential.py => _shared/aio/static_access_token_credential.py} (100%) rename sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/{shared/_authentication_endpoint.py => _shared/authentication_endpoint.py} (100%) rename sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/{shared/_mixed_reality_token_credential.py => _shared/mixed_reality_token_credential.py} (96%) rename sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/{shared/_mixedreality_account_key_credential.py => _shared/mixedreality_account_key_credential.py} (100%) rename sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/{shared/_static_access_token_credential.py => _shared/static_access_token_credential.py} (100%) rename sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/{utils => _utils}/__init__.py (58%) rename sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/{utils/_cv.py => _utils/cv.py} (97%) rename sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/{utils/_jwt.py => _utils/jwt.py} (95%) rename sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/{utils/_utils.py => _utils/utils.py} (78%) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py index f10f36a107cc..1b900e273a8a 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py @@ -17,9 +17,9 @@ from ._generated import MixedRealityStsRestClient from ._generated.models import TokenRequestOptions from ._version import SDK_MONIKER -from .shared._authentication_endpoint import construct_endpoint_url -from .shared._mixedreality_account_key_credential import MixedRealityAccountKeyCredential -from .utils import _convert_to_access_token, _generate_cv_base +from ._shared.authentication_endpoint import construct_endpoint_url +from ._shared.mixedreality_account_key_credential import MixedRealityAccountKeyCredential +from ._utils import convert_to_access_token, generate_cv_base if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports @@ -90,14 +90,14 @@ def get_token(self, **kwargs): :rtype: ~azure.core.credentials.AccessToken """ token_request_options = TokenRequestOptions() - token_request_options.client_request_id = _generate_cv_base() + token_request_options.client_request_id = generate_cv_base() response = self._client.get_token( self._account_id, api_version=None, token_request_options=token_request_options, **kwargs) - return _convert_to_access_token(response) + return convert_to_access_token(response) def close(self): # type: () -> None diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/__init__.py new file mode 100644 index 000000000000..5b396cd202e8 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/__init__.py @@ -0,0 +1,5 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/__init__.py new file mode 100644 index 000000000000..5b396cd202e8 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/__init__.py @@ -0,0 +1,5 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_mixed_reality_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixed_reality_token_credential.py similarity index 96% rename from sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_mixed_reality_token_credential.py rename to sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixed_reality_token_credential.py index 14b4e81facf3..a83da8f6cfd8 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_mixed_reality_token_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixed_reality_token_credential.py @@ -10,7 +10,7 @@ from azure.core.credentials import AccessToken from azure.core.credentials_async import AsyncTokenCredential -from ._static_access_token_credential import StaticAccessTokenCredential +from .static_access_token_credential import StaticAccessTokenCredential from ...aio._client_async import MixedRealityStsClient def get_mixedreality_credential( diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_mixedreality_account_key_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixedreality_account_key_credential.py similarity index 100% rename from sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_mixedreality_account_key_credential.py rename to sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixedreality_account_key_credential.py diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_static_access_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/static_access_token_credential.py similarity index 100% rename from sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/aio/_static_access_token_credential.py rename to sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/static_access_token_credential.py diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_authentication_endpoint.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/authentication_endpoint.py similarity index 100% rename from sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_authentication_endpoint.py rename to sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/authentication_endpoint.py diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_mixed_reality_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixed_reality_token_credential.py similarity index 96% rename from sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_mixed_reality_token_credential.py rename to sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixed_reality_token_credential.py index e805e6de08ea..955816d8de6d 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_mixed_reality_token_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixed_reality_token_credential.py @@ -10,7 +10,7 @@ from typing import Any, Union from azure.core.credentials import AccessToken, TokenCredential -from ._static_access_token_credential import StaticAccessTokenCredential +from .static_access_token_credential import StaticAccessTokenCredential from .._client import MixedRealityStsClient def get_mixedreality_credential(account_id, account_domain, endpoint_url, credential, **kwargs): diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_mixedreality_account_key_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py similarity index 100% rename from sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_mixedreality_account_key_credential.py rename to sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_static_access_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/static_access_token_credential.py similarity index 100% rename from sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/shared/_static_access_token_credential.py rename to sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/static_access_token_credential.py diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/__init__.py similarity index 58% rename from sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/__init__.py rename to sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/__init__.py index 58bd0172a33c..77b48b43bb40 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/__init__.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/__init__.py @@ -4,12 +4,12 @@ # license information. # -------------------------------------------------------------------------- -from ._utils import _convert_to_access_token -from ._cv import _generate_cv_base -from ._jwt import _retrieve_jwt_expiration_timestamp +from .utils import convert_to_access_token +from .cv import generate_cv_base +from .jwt import retrieve_jwt_expiration_timestamp __all__ = [ - '_convert_to_access_token', - '_generate_cv_base', - '_retrieve_jwt_expiration_timestamp' + 'convert_to_access_token', + 'generate_cv_base', + 'retrieve_jwt_expiration_timestamp' ] diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_cv.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/cv.py similarity index 97% rename from sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_cv.py rename to sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/cv.py index ba7e75e2d573..c1001cd5c24c 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_cv.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/cv.py @@ -13,7 +13,7 @@ BASE_64_CHAR_SET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" CV_BASE_LENGTH = 22 -def _generate_cv_base(): +def generate_cv_base(): # type: () -> str """ Seed function to randomly generate a 16 character base64 encoded string for diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_jwt.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/jwt.py similarity index 95% rename from sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_jwt.py rename to sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/jwt.py index 1176cb5be7ee..244821c77853 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_jwt.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/jwt.py @@ -7,7 +7,7 @@ import base64 import json -def _retrieve_jwt_expiration_timestamp(jwt_value): +def retrieve_jwt_expiration_timestamp(jwt_value): # type: (str) -> int """ Retrieves the expiration value from the JWT. diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_utils.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/utils.py similarity index 78% rename from sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_utils.py rename to sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/utils.py index 1c4eb5be3eb1..d2005932de29 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/utils/_utils.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/utils.py @@ -6,10 +6,10 @@ from azure.core.credentials import AccessToken -from ._jwt import _retrieve_jwt_expiration_timestamp +from .jwt import retrieve_jwt_expiration_timestamp from .._generated.models import StsTokenResponseMessage -def _convert_to_access_token(token_response_message): +def convert_to_access_token(token_response_message): # type: (StsTokenResponseMessage) -> AccessToken """ Converts the specified token response message to an AccessToken. @@ -17,6 +17,6 @@ def _convert_to_access_token(token_response_message): if not StsTokenResponseMessage: raise ValueError("token_response_message can not be None") - expiration_timestamp = _retrieve_jwt_expiration_timestamp(token_response_message.access_token) + expiration_timestamp = retrieve_jwt_expiration_timestamp(token_response_message.access_token) return AccessToken(token_response_message.access_token, expiration_timestamp) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py index f875d29bab45..69e570ab5bd3 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py @@ -20,9 +20,9 @@ from .._generated.aio import MixedRealityStsRestClient from .._generated.models import TokenRequestOptions from .._version import SDK_MONIKER -from ..shared._authentication_endpoint import construct_endpoint_url -from ..shared.aio._mixedreality_account_key_credential import MixedRealityAccountKeyCredential -from ..utils import _convert_to_access_token, _generate_cv_base +from .._shared.authentication_endpoint import construct_endpoint_url +from .._shared.aio.mixedreality_account_key_credential import MixedRealityAccountKeyCredential +from .._utils import convert_to_access_token, generate_cv_base if TYPE_CHECKING: from azure.core.credentials import AccessToken @@ -94,14 +94,14 @@ async def get_token(self, **kwargs) -> "AccessToken": :rtype: :class:`azure.core.credentials.AccessToken` """ token_request_options = TokenRequestOptions() - token_request_options.client_request_id=_generate_cv_base() + token_request_options.client_request_id=generate_cv_base() response = await self._client.get_token( self._account_id, api_version=None, token_request_options=token_request_options, **kwargs) - return _convert_to_access_token(response) + return convert_to_access_token(response) async def close(self) -> None: await self._client.close() diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py index 5829c45bd197..33e4fee685df 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client.py @@ -10,7 +10,7 @@ from azure.core.credentials import AzureKeyCredential from azure.mixedreality.authentication import MixedRealityStsClient -from azure.mixedreality.authentication.shared._mixedreality_account_key_credential import MixedRealityAccountKeyCredential +from azure.mixedreality.authentication._shared.mixedreality_account_key_credential import MixedRealityAccountKeyCredential # Import fake account details matching recordings. from _constants import ( diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py index ced292db0c86..aeead54991fc 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_client_async.py @@ -10,7 +10,7 @@ from azure.core.credentials import AzureKeyCredential from azure.mixedreality.authentication.aio import MixedRealityStsClient -from azure.mixedreality.authentication.shared.aio._mixedreality_account_key_credential import MixedRealityAccountKeyCredential +from azure.mixedreality.authentication._shared.aio.mixedreality_account_key_credential import MixedRealityAccountKeyCredential # Import fake account details matching recordings. from _constants import ( diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_cv.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_cv.py index 63eb0ba8d428..1bd846d82f54 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_cv.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_cv.py @@ -4,18 +4,18 @@ # license information. # -------------------------------------------------------------------------- -from azure.mixedreality.authentication.utils._cv import _generate_cv_base +from azure.mixedreality.authentication._utils.cv import generate_cv_base class TestCv: def test_generate_cv_base(self): - cv = _generate_cv_base() + cv = generate_cv_base() assert cv is not None assert len(cv) == 22 def test_generate_cv_base_are_random(self): - cv1 = _generate_cv_base() - cv2 = _generate_cv_base() + cv1 = generate_cv_base() + cv2 = generate_cv_base() assert cv1 is not None assert cv2 is not None diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_jwt.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_jwt.py index e6c8b6a5d566..680b8ffdc1b6 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_jwt.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_jwt.py @@ -6,7 +6,7 @@ import pytest -from azure.mixedreality.authentication.utils._jwt import _retrieve_jwt_expiration_timestamp +from azure.mixedreality.authentication._utils.jwt import retrieve_jwt_expiration_timestamp class TestJwt: def test_retrieve_jwt_expiration_timestamp(self): @@ -14,32 +14,32 @@ def test_retrieve_jwt_expiration_timestamp(self): jwt_value = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYxMDgxMjI1MCIsIm5iZiI6IjE2MTA4MTI1NTAiLCJleHAiOiIxNjEwODk4NjUwIn0=." expected_expiration_timestamp = 1610898650 # 1/17/2021 3:50:50 PM UTC - actual = _retrieve_jwt_expiration_timestamp(jwt_value) + actual = retrieve_jwt_expiration_timestamp(jwt_value) assert actual is not None assert actual == expected_expiration_timestamp def test_retrieve_jwt_expiration_timestamp_invalid_parameter(self): with pytest.raises(ValueError): - _retrieve_jwt_expiration_timestamp(None) + retrieve_jwt_expiration_timestamp(None) def test_retrieve_jwt_expiration_timestamp_invalid_structure(self): # JWT value with missing signature section on the end. jwt_value = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYxMDgxMjI1MCIsIm5iZiI6IjE2MTA4MTI1NTAiLCJleHAiOiIxNjEwODk4NjUwIn0=" with pytest.raises(ValueError): - _retrieve_jwt_expiration_timestamp(jwt_value) + retrieve_jwt_expiration_timestamp(jwt_value) def test_retrieve_jwt_expiration_timestamp_invalid_payload(self): # JWT value with missing payload. jwt_value = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.." with pytest.raises(ValueError): - _retrieve_jwt_expiration_timestamp(jwt_value) + retrieve_jwt_expiration_timestamp(jwt_value) def test_retrieve_jwt_expiration_timestamp_invalid_exp(self): # JWT value with missing expiration field. jwt_value = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYxMDgxMjI1MCIsIm5iZiI6IjE2MTA4MTI1NTAifQ==." with pytest.raises(ValueError): - _retrieve_jwt_expiration_timestamp(jwt_value) + retrieve_jwt_expiration_timestamp(jwt_value) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_mixed_reality_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_mixed_reality_token_credential.py index 36e872a7866a..bb9b3b376c6a 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_mixed_reality_token_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_mixed_reality_token_credential.py @@ -6,9 +6,9 @@ from azure.core.credentials import AccessToken, AzureKeyCredential -from azure.mixedreality.authentication.shared._mixed_reality_token_credential import get_mixedreality_credential, MixedRealityTokenCredential -from azure.mixedreality.authentication.shared._static_access_token_credential import StaticAccessTokenCredential -from azure.mixedreality.authentication.shared._mixedreality_account_key_credential import MixedRealityAccountKeyCredential +from azure.mixedreality.authentication._shared.mixed_reality_token_credential import get_mixedreality_credential, MixedRealityTokenCredential +from azure.mixedreality.authentication._shared.static_access_token_credential import StaticAccessTokenCredential +from azure.mixedreality.authentication._shared.mixedreality_account_key_credential import MixedRealityAccountKeyCredential class TestMixedRealityTokenCredential: def test_get_mixedreality_credential_static_credential(self): diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_mixed_reality_token_credential_async.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_mixed_reality_token_credential_async.py index b8eafb039a0c..a7b2e02dc793 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_mixed_reality_token_credential_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_mixed_reality_token_credential_async.py @@ -6,9 +6,9 @@ from azure.core.credentials import AccessToken, AzureKeyCredential -from azure.mixedreality.authentication.shared.aio._mixed_reality_token_credential import get_mixedreality_credential, MixedRealityTokenCredential -from azure.mixedreality.authentication.shared.aio._static_access_token_credential import StaticAccessTokenCredential -from azure.mixedreality.authentication.shared.aio._mixedreality_account_key_credential import MixedRealityAccountKeyCredential +from azure.mixedreality.authentication._shared.aio.mixed_reality_token_credential import get_mixedreality_credential, MixedRealityTokenCredential +from azure.mixedreality.authentication._shared.aio.static_access_token_credential import StaticAccessTokenCredential +from azure.mixedreality.authentication._shared.aio.mixedreality_account_key_credential import MixedRealityAccountKeyCredential class TestMixedRealityTokenCredential: def test_get_mixedreality_credential_static_credential(self): diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_static_access_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_static_access_token_credential.py index b8aced015c2f..0511780951dd 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_static_access_token_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_static_access_token_credential.py @@ -6,7 +6,7 @@ from azure.core.credentials import AccessToken -from azure.mixedreality.authentication.shared._static_access_token_credential import StaticAccessTokenCredential +from azure.mixedreality.authentication._shared.static_access_token_credential import StaticAccessTokenCredential class TestStaticAccessTokenCredential: def test_get_token(self): diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_static_access_token_credential_async.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_static_access_token_credential_async.py index 7c6ebb2951eb..f9b7171460fd 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_static_access_token_credential_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_static_access_token_credential_async.py @@ -7,7 +7,7 @@ from azure.core.credentials import AccessToken from devtools_testutils import AzureTestCase -from azure.mixedreality.authentication.shared.aio._static_access_token_credential import StaticAccessTokenCredential +from azure.mixedreality.authentication._shared.aio.static_access_token_credential import StaticAccessTokenCredential class TestAsyncStaticAccessTokenCredential: @AzureTestCase.await_prepared_test From d192103b5b64ae047da74aaae378a54cbdc23da5 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Mon, 8 Feb 2021 14:58:25 -0800 Subject: [PATCH 17/40] Merge utils into single file per request --- .../{_utils/jwt.py => _utils.py} | 35 +++++++++++++++++++ .../authentication/_utils/__init__.py | 15 -------- .../mixedreality/authentication/_utils/cv.py | 28 --------------- .../authentication/_utils/utils.py | 22 ------------ .../tests/test_cv.py | 22 ------------ .../tests/{test_jwt.py => test_utils.py} | 19 ++++++++-- 6 files changed, 52 insertions(+), 89 deletions(-) rename sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/{_utils/jwt.py => _utils.py} (50%) delete mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/__init__.py delete mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/cv.py delete mode 100644 sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/utils.py delete mode 100644 sdk/mixedreality/azure-mixedreality-authentication/tests/test_cv.py rename sdk/mixedreality/azure-mixedreality-authentication/tests/{test_jwt.py => test_utils.py} (84%) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/jwt.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py similarity index 50% rename from sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/jwt.py rename to sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py index 244821c77853..708949ffbb72 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/jwt.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py @@ -6,6 +6,24 @@ import base64 import json +import random + +from azure.core.credentials import AccessToken + +from ._generated.models import StsTokenResponseMessage + + +def convert_to_access_token(token_response_message): + # type: (StsTokenResponseMessage) -> AccessToken + """ + Converts the specified token response message to an AccessToken. + """ + if not StsTokenResponseMessage: + raise ValueError("token_response_message can not be None") + + expiration_timestamp = retrieve_jwt_expiration_timestamp(token_response_message.access_token) + + return AccessToken(token_response_message.access_token, expiration_timestamp) def retrieve_jwt_expiration_timestamp(jwt_value): # type: (str) -> int @@ -35,3 +53,20 @@ def retrieve_jwt_expiration_timestamp(jwt_value): raise ValueError("Invalid JWT payload structure. No expiration.") return int(exp) + +BASE_64_CHAR_SET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" +CV_BASE_LENGTH = 22 + +def generate_cv_base(): + # type: () -> str + """ + Seed function to randomly generate a 16 character base64 encoded string for + the Correlation Vector's base value. + """ + result = '' + + for i in range(CV_BASE_LENGTH): + random_index = random.randint(0, len(BASE_64_CHAR_SET) - 1) + result += BASE_64_CHAR_SET[random_index] + + return result diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/__init__.py deleted file mode 100644 index 77b48b43bb40..000000000000 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from .utils import convert_to_access_token -from .cv import generate_cv_base -from .jwt import retrieve_jwt_expiration_timestamp - -__all__ = [ - 'convert_to_access_token', - 'generate_cv_base', - 'retrieve_jwt_expiration_timestamp' -] diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/cv.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/cv.py deleted file mode 100644 index c1001cd5c24c..000000000000 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/cv.py +++ /dev/null @@ -1,28 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -# This function is a minimal port borrowed from the JavaScript implementation at -# https://github.com/microsoft/CorrelationVector-JavaScript/blob/6da3f9e6150581756aba54b98dcd1e7329ef36bd/cV.js. -# License is MIT: https://github.com/microsoft/CorrelationVector-JavaScript/blob/6da3f9e6150581756aba54b98dcd1e7329ef36bd/LICENSE - -import random - -BASE_64_CHAR_SET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" -CV_BASE_LENGTH = 22 - -def generate_cv_base(): - # type: () -> str - """ - Seed function to randomly generate a 16 character base64 encoded string for - the Correlation Vector's base value. - """ - result = '' - - for i in range(CV_BASE_LENGTH): - random_index = random.randint(0, len(BASE_64_CHAR_SET) - 1) - result += BASE_64_CHAR_SET[random_index] - - return result diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/utils.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/utils.py deleted file mode 100644 index d2005932de29..000000000000 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils/utils.py +++ /dev/null @@ -1,22 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from azure.core.credentials import AccessToken - -from .jwt import retrieve_jwt_expiration_timestamp -from .._generated.models import StsTokenResponseMessage - -def convert_to_access_token(token_response_message): - # type: (StsTokenResponseMessage) -> AccessToken - """ - Converts the specified token response message to an AccessToken. - """ - if not StsTokenResponseMessage: - raise ValueError("token_response_message can not be None") - - expiration_timestamp = retrieve_jwt_expiration_timestamp(token_response_message.access_token) - - return AccessToken(token_response_message.access_token, expiration_timestamp) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_cv.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_cv.py deleted file mode 100644 index 1bd846d82f54..000000000000 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_cv.py +++ /dev/null @@ -1,22 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from azure.mixedreality.authentication._utils.cv import generate_cv_base - -class TestCv: - def test_generate_cv_base(self): - cv = generate_cv_base() - - assert cv is not None - assert len(cv) == 22 - - def test_generate_cv_base_are_random(self): - cv1 = generate_cv_base() - cv2 = generate_cv_base() - - assert cv1 is not None - assert cv2 is not None - assert cv1 != cv2 diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_jwt.py b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_utils.py similarity index 84% rename from sdk/mixedreality/azure-mixedreality-authentication/tests/test_jwt.py rename to sdk/mixedreality/azure-mixedreality-authentication/tests/test_utils.py index 680b8ffdc1b6..17b31bcb87fa 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/test_jwt.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/test_utils.py @@ -6,9 +6,24 @@ import pytest -from azure.mixedreality.authentication._utils.jwt import retrieve_jwt_expiration_timestamp +from azure.mixedreality.authentication._utils import generate_cv_base, retrieve_jwt_expiration_timestamp + + +class TestUtils: + def test_generate_cv_base(self): + cv = generate_cv_base() + + assert cv is not None + assert len(cv) == 22 + + def test_generate_cv_base_are_random(self): + cv1 = generate_cv_base() + cv2 = generate_cv_base() + + assert cv1 is not None + assert cv2 is not None + assert cv1 != cv2 -class TestJwt: def test_retrieve_jwt_expiration_timestamp(self): # Note: The trailing "." on the end indicates an empty signature indicating that this JWT is not signed. jwt_value = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYxMDgxMjI1MCIsIm5iZiI6IjE2MTA4MTI1NTAiLCJleHAiOiIxNjEwODk4NjUwIn0=." From df0270de81f347cd4cebf08f043064121b3f2639 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Thu, 11 Feb 2021 10:29:49 -0800 Subject: [PATCH 18/40] Added pipeline configuration for authentication library --- sdk/mixedreality/ci.yml | 2 + sdk/mixedreality/test-resources.json | 141 +++++++++++++++++++++++++++ sdk/mixedreality/tests.yml | 13 +++ 3 files changed, 156 insertions(+) create mode 100644 sdk/mixedreality/test-resources.json create mode 100644 sdk/mixedreality/tests.yml diff --git a/sdk/mixedreality/ci.yml b/sdk/mixedreality/ci.yml index 991d84a936a7..ef254485218c 100644 --- a/sdk/mixedreality/ci.yml +++ b/sdk/mixedreality/ci.yml @@ -30,3 +30,5 @@ extends: Artifacts: - name: azure_mgmt_mixedreality safeName: azuremgmtmixedreality + - name: azure_mixedreality_authentication + safeName: azuremixedrealityauthentication diff --git a/sdk/mixedreality/test-resources.json b/sdk/mixedreality/test-resources.json new file mode 100644 index 000000000000..30e81531cdfd --- /dev/null +++ b/sdk/mixedreality/test-resources.json @@ -0,0 +1,141 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "baseName": { + "type": "string", + "defaultValue": "[resourceGroup().name]", + "metadata": { + "description": "The base resource name." + } + }, + "tenantId": { + "type": "string", + "defaultValue": "72f988bf-86f1-41af-91ab-2d7cd011db47", + "metadata": { + "description": "The tenant ID to which the application and resources belong." + } + }, + "location": { + "type": "string", + "defaultValue": "[resourceGroup().location]", + "metadata": { + "description": "The location of the resource. By default, this is the same as the resource group." + } + }, + "baseTime": { + "type": "string", + "defaultValue": "[utcNow('u')]" + } + }, + "variables": { + "apiVersion": "2020-05-01", + "asaAccountName": "[concat(parameters('baseName'), '-asa-account')]", + "arrApiVersion": "2020-04-06-preview", + "arrAccountName": "[concat(parameters('baseName'), '-arr-account')]", + "storageApiVersion": "2019-06-01", + "storageAccountName": "[parameters('baseName')]", + "blobContainerName": "test", + "blobContainerResourceName": "[concat(variables('storageAccountName'), '/default/', variables('blobContainerName'))]", + "sasProperties": { + "signedPermission": "rwl", + "signedExpiry": "[dateTimeAdd(parameters('baseTime'), 'P1D')]", + "signedResource": "c", + "canonicalizedResource": "[concat('/blob/', variables('storageAccountName'), '/', variables('blobContainerName'))]" + } + }, + "resources": [ + { + "type": "Microsoft.MixedReality/spatialAnchorsAccounts", + "name": "[variables('asaAccountName')]", + "apiVersion": "[variables('apiVersion')]", + "location": "[parameters('location')]", + "properties": {} + }, + { + "type": "Microsoft.MixedReality/remoteRenderingAccounts", + "name": "[variables('arrAccountName')]", + "apiVersion": "[variables('arrApiVersion')]", + "location": "[parameters('location')]", + "properties": {}, + "identity": { "type": "systemAssigned" } + }, + { + "type": "Microsoft.Storage/storageAccounts", + "apiVersion": "[variables('storageApiVersion')]", + "name": "[variables('storageAccountName')]", + "location": "[parameters('location')]", + "sku": { + "name": "Standard_RAGRS", + "tier": "Standard" + }, + "kind": "StorageV2", + "properties": { + "supportsHttpsTrafficOnly": true, + "encryption": { + "keySource": "Microsoft.Storage", + "services": { + "blob": { + "enabled": true + } + }, + }, + "accessTier": "Hot" + } + }, + { + "type": "Microsoft.Storage/storageAccounts/blobServices/containers", + "apiVersion": "[variables('storageApiVersion')]", + "name": "[variables('blobContainerResourceName')]", + "dependsOn": [ + "[variables('storageAccountName')]" + ] + } + ], + "outputs": { + "MIXEDREALITY_ACCOUNT_ID": { + "type": "string", + "value": "[reference(variables('asaAccountName')).accountId]" + }, + "MIXEDREALITY_ACCOUNT_DOMAIN": { + "type": "string", + "value": "[reference(variables('asaAccountName')).accountDomain]" + }, + "MIXEDREALITY_ACCOUNT_KEY": { + "type": "string", + "value": "[listKeys(resourceId('Microsoft.MixedReality/spatialAnchorsAccounts', variables('asaAccountName')), variables('apiVersion')).primaryKey]" + }, + "MIXEDREALITY_ARR_ACCOUNT_ID": { + "type": "string", + "value": "[reference(variables('arrAccountName')).accountId]" + }, + "MIXEDREALITY_ARR_ACCOUNT_DOMAIN": { + "type": "string", + "value": "[reference(variables('arrAccountName')).accountDomain]" + }, + "MIXEDREALITY_ARR_ACCOUNT_KEY": { + "type": "string", + "value": "[listKeys(resourceId('Microsoft.MixedReality/remoteRenderingAccounts', variables('arrAccountName')), variables('arrApiVersion')).primaryKey]" + }, + "MIXEDREALITY_ARR_STORAGE_ACCOUNT_NAME": { + "type": "string", + "value": "[variables('storageAccountName')]" + }, + "MIXEDREALITY_ARR_STORAGE_ACCOUNT_KEY": { + "type": "string", + "value": "[listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName')), variables('storageApiVersion')).keys[0].value]" + }, + "MIXEDREALITY_ARR_BLOB_CONTAINER_NAME": { + "type": "string", + "value": "[variables('blobContainerName')]" + }, + "MIXEDREALITY_ARR_SAS_TOKEN": { + "type": "string", + "value": "[listServiceSas(variables('storageAccountName'), variables('storageApiVersion'), variables('sasProperties')).serviceSasToken]" + }, + "MIXEDREALITY_ARR_SERVICE_ENDPOINT": { + "type": "string", + "value": "[concat('https://remoterendering.', parameters('location'), '.mixedreality.azure.com')]" + } + } +} \ No newline at end of file diff --git a/sdk/mixedreality/tests.yml b/sdk/mixedreality/tests.yml new file mode 100644 index 000000000000..8755e0615f27 --- /dev/null +++ b/sdk/mixedreality/tests.yml @@ -0,0 +1,13 @@ +trigger: none + +stages: + - template: ../../eng/pipelines/templates/stages/archetype-sdk-tests.yml + parameters: + AllocateResourceGroup: false + ServiceDirectory: mixedreality + DeployArmTemplate: true + EnvVars: + AZURE_CLIENT_ID: $(aad-azure-sdk-test-client-id) + AZURE_CLIENT_SECRET: $(aad-azure-sdk-test-client-secret) + AZURE_TENANT_ID: $(aad-azure-sdk-test-tenant-id) + TEST_MODE: 'RunLiveNoRecord' \ No newline at end of file From b3de499493204080f7c32c75aa08f0eacd749f97 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Thu, 11 Feb 2021 12:38:39 -0800 Subject: [PATCH 19/40] Updated the name of the swagger config file - The swagger config file named as README gets picked up by some validation with certain assumptions, so I've renamed it. --- .../swagger/{README.md => SWAGGER.md} | 2 +- .../azure-mixedreality-authentication/swagger/update.ps1 | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename sdk/mixedreality/azure-mixedreality-authentication/swagger/{README.md => SWAGGER.md} (97%) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/swagger/README.md b/sdk/mixedreality/azure-mixedreality-authentication/swagger/SWAGGER.md similarity index 97% rename from sdk/mixedreality/azure-mixedreality-authentication/swagger/README.md rename to sdk/mixedreality/azure-mixedreality-authentication/swagger/SWAGGER.md index aa23b1d9c8bd..40af809e4840 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/swagger/README.md +++ b/sdk/mixedreality/azure-mixedreality-authentication/swagger/SWAGGER.md @@ -10,7 +10,7 @@ npm install -g autorest ```ps cd -autorest README.md +autorest SWAGGER.md ``` ### Code generation settings diff --git a/sdk/mixedreality/azure-mixedreality-authentication/swagger/update.ps1 b/sdk/mixedreality/azure-mixedreality-authentication/swagger/update.ps1 index d04e5660d16a..a7490a9848d1 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/swagger/update.ps1 +++ b/sdk/mixedreality/azure-mixedreality-authentication/swagger/update.ps1 @@ -1,6 +1,6 @@ Push-Location $PSScriptRoot try { - & autorest README.md + & autorest SWAGGER.md } finally { Pop-Location } From 22122a8696d842e53f8fcc0509f1d32992441888 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Thu, 11 Feb 2021 12:40:48 -0800 Subject: [PATCH 20/40] Fixed an issue with the README --- sdk/mixedreality/azure-mixedreality-authentication/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/README.md b/sdk/mixedreality/azure-mixedreality-authentication/README.md index ec240c9e6490..1c6d675c396b 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/README.md +++ b/sdk/mixedreality/azure-mixedreality-authentication/README.md @@ -141,7 +141,7 @@ client = MixedRealityStsClient(account_id, account_domain, key_credential) token = await client.get_token() ``` -## Sample Code +# Examples These are code samples that show common scenario operations with the Azure Mixed Reality Authentication client library. The async versions of the samples (the python sample files appended with `_async`) show asynchronous operations, From 3834295c35e92cca4699106b4ffbe0a76e38367f Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Thu, 11 Feb 2021 12:57:42 -0800 Subject: [PATCH 21/40] Fixed version and changelog - The version number now matches the other libraries. --- .../CHANGELOG.md | 30 ++----------------- .../mixedreality/authentication/_version.py | 2 +- 2 files changed, 3 insertions(+), 29 deletions(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/CHANGELOG.md b/sdk/mixedreality/azure-mixedreality-authentication/CHANGELOG.md index 999dfa7dc075..11533387e830 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/CHANGELOG.md +++ b/sdk/mixedreality/azure-mixedreality-authentication/CHANGELOG.md @@ -1,31 +1,5 @@ # Release History -## 0.0.18b3 (Unreleased) +## 1.0.0b1 (Unreleased) - -## 0.0.18b2 (2020-09-04) -- Testing release tag version - -## 0.0.13b1 (2020-08-27) -- Testing out some alpha and beta versioning - -## 0.0.12 (Unreleased) -- Test a successful Release - -## 0.0.7 (2020-07-02) -- Test a successful Release - -## 0.0.6 (2020-05-20) -- Test a successful Release - -## 0.0.5 (2020-05-20) -- Test a successful Release - -## 0.0.3 (Unreleased) - -## 0.0.2 (2020-03-24) -- Test Release Pipeline - - -## 0.0.1 (2019-10-06) - - Template package +- Initial release. diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_version.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_version.py index f715dac0c388..79ce8e42a972 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_version.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_version.py @@ -5,6 +5,6 @@ # -------------------------------------------------------------------------- # matches SEMVER -VERSION = "0.0.1b1" +VERSION = "1.0.0b1" SDK_MONIKER = "mixedreality-authentication/{}".format(VERSION) # type: str \ No newline at end of file From b3d6526cd7a55b4c35afe48a37a10e6225a49fc3 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Thu, 11 Feb 2021 16:13:38 -0800 Subject: [PATCH 22/40] Added missing doc content type to setup.py --- sdk/mixedreality/azure-mixedreality-authentication/setup.py | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/setup.py b/sdk/mixedreality/azure-mixedreality-authentication/setup.py index 056741baf3a3..b523fd604f22 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/setup.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/setup.py @@ -35,6 +35,7 @@ # ensure that these are updated to reflect the package owners' information long_description=long_description, + long_description_content_type='text/markdown', url='https://github.com/Azure/azure-sdk-for-python', author='Microsoft Corporation', author_email='azuresdkengsysadmins@microsoft.com', From f8b67ded973470a96699eb3c8dc6327d8194f58b Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Thu, 11 Feb 2021 18:26:09 -0800 Subject: [PATCH 23/40] Use a Python2 compatible method of converting to timestamp --- .../_shared/mixedreality_account_key_credential.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py index 599a4d921341..cfadee040131 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py @@ -5,6 +5,7 @@ # -------------------------------------------------------------------------- from datetime import date, datetime +import time from azure.core.credentials import AzureKeyCredential, AccessToken @@ -23,14 +24,14 @@ def __init__(self, account_id, account_key): self.account_key = account_key def get_token(self, *scopes, **kwargs): - # type: (*str, **Any) -> AccessToken + # type: (*str, **Any) -> azure.core.credentials.AccessToken token = self.account_id + ":" + self.account_key.key # No way to know when an access token might expire, so we'll set it to be # 10 years in the future. expiration_date = _add_years(datetime.now(), ACCOUNT_KEY_VALID_YEARS) - expiration_timestamp = int(expiration_date.timestamp()) + expiration_timestamp = int(time.mktime(expiration_date.timetuple())) return AccessToken(token, expiration_timestamp) From 61fdf829ce8468ffec010e05ed5e015ab4bcbeed Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Thu, 11 Feb 2021 19:23:24 -0800 Subject: [PATCH 24/40] Addressed pylint issues (lots of disabling) --- .../azure/__init__.py | 2 +- .../azure/mixedreality/__init__.py | 2 +- .../mixedreality/authentication/_client.py | 4 +-- .../aio/mixed_reality_token_credential.py | 32 +++++++++++-------- .../mixedreality_account_key_credential.py | 2 +- .../aio/static_access_token_credential.py | 7 ++-- .../_shared/mixed_reality_token_credential.py | 25 ++++++++------- .../mixedreality_account_key_credential.py | 2 +- .../_shared/static_access_token_credential.py | 2 +- .../mixedreality/authentication/_utils.py | 3 ++ .../mixedreality/authentication/_version.py | 2 +- .../authentication/aio/_client_async.py | 10 +++--- 12 files changed, 53 insertions(+), 40 deletions(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/__init__.py index 0260537a02bb..69e3be50dac4 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/__init__.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/__init__.py @@ -1 +1 @@ -__path__ = __import__('pkgutil').extend_path(__path__, __name__) \ No newline at end of file +__path__ = __import__('pkgutil').extend_path(__path__, __name__) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/__init__.py index 0260537a02bb..69e3be50dac4 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/__init__.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/__init__.py @@ -1 +1 @@ -__path__ = __import__('pkgutil').extend_path(__path__, __name__) \ No newline at end of file +__path__ = __import__('pkgutil').extend_path(__path__, __name__) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py index 1b900e273a8a..9ed5ee9c29d7 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py @@ -10,7 +10,7 @@ except ImportError: from urlparse import urlparse # type: ignore -from azure.core.credentials import AccessToken, AzureKeyCredential +from azure.core.credentials import AzureKeyCredential from azure.core.tracing.decorator import distributed_trace from azure.core.pipeline.policies import BearerTokenCredentialPolicy @@ -24,7 +24,6 @@ if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Union - from azure.core.credentials import TokenCredential class MixedRealityStsClient(object): @@ -65,6 +64,7 @@ def __init__(self, account_id, account_domain, credential, **kwargs): if not endpoint_url.lower().startswith('http'): endpoint_url = "https://" + endpoint_url except AttributeError: + #pylint: disable=raise-missing-from raise ValueError("Host URL must be a string") parsed_url = urlparse(endpoint_url.rstrip('/')) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixed_reality_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixed_reality_token_credential.py index a83da8f6cfd8..c102156d1419 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixed_reality_token_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixed_reality_token_credential.py @@ -5,29 +5,29 @@ # -------------------------------------------------------------------------- from typing import TYPE_CHECKING +from .static_access_token_credential import StaticAccessTokenCredential +from ...aio._client_async import MixedRealityStsClient + if TYPE_CHECKING: from typing import Any from azure.core.credentials import AccessToken from azure.core.credentials_async import AsyncTokenCredential -from .static_access_token_credential import StaticAccessTokenCredential -from ...aio._client_async import MixedRealityStsClient - def get_mixedreality_credential( account_id: str, account_domain: str, endpoint_url: str, credential: "AsyncTokenCredential", **kwargs): - if isinstance(credential, StaticAccessTokenCredential): - return credential + if isinstance(credential, StaticAccessTokenCredential): + return credential - return MixedRealityTokenCredential( - account_id=account_id, - account_domain=account_domain, - endpoint_url=endpoint_url, - credential=credential, - **kwargs) + return MixedRealityTokenCredential( + account_id=account_id, + account_domain=account_domain, + endpoint_url=endpoint_url, + credential=credential, + **kwargs) class MixedRealityTokenCredential(object): @@ -39,7 +39,13 @@ class MixedRealityTokenCredential(object): :param TokenCredential credential: The credential used to access the Mixed Reality service. """ - def __init__(self, account_id: str, account_domain: str, endpoint_url: str, credential: "AsyncTokenCredential", **kwargs): + def __init__( + self, + account_id: str, + account_domain: str, + endpoint_url: str, + credential: "AsyncTokenCredential", + **kwargs): self.stsClient = MixedRealityStsClient( account_id=account_id, account_domain=account_domain, @@ -47,7 +53,7 @@ def __init__(self, account_id: str, account_domain: str, endpoint_url: str, cred credential=credential, **kwargs) - async def get_token(self, *scopes: str, **kwargs: "Any") -> "AccessToken": + async def get_token(self, *scopes: str, **kwargs: "Any") -> "AccessToken": #pylint: disable=unused-argument return await self.stsClient.get_token(**kwargs) async def close(self) -> None: diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixedreality_account_key_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixedreality_account_key_credential.py index fb2adb3283af..814cab6e2082 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixedreality_account_key_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixedreality_account_key_credential.py @@ -28,7 +28,7 @@ def __init__(self, account_id, account_key): self.account_id = account_id self.account_key = account_key - async def get_token(self, *scopes: str, **kwargs: "Any") -> "AccessToken": + async def get_token(self, *scopes: str, **kwargs: "Any") -> "AccessToken": #pylint: disable=unused-argument token = self.account_id + ":" + self.account_key.key # No way to know when an access token might expire, so we'll set it to be diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/static_access_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/static_access_token_credential.py index a62618fc8c79..b4ba12f2a16e 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/static_access_token_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/static_access_token_credential.py @@ -3,7 +3,6 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- -import asyncio from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -21,7 +20,11 @@ class StaticAccessTokenCredential(object): def __init__(self, access_token: "AccessToken"): self._access_token = access_token - async def get_token(self, *scopes: str, **kwargs: "Any") -> "AccessToken": + async def get_token( + self, + #pylint: disable=unused-argument + *scopes: str, + **kwargs: "Any") -> "AccessToken": return self._access_token async def close(self) -> None: diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixed_reality_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixed_reality_token_credential.py index 955816d8de6d..a599edd0dd7e 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixed_reality_token_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixed_reality_token_credential.py @@ -5,25 +5,26 @@ # -------------------------------------------------------------------------- from typing import TYPE_CHECKING +from .static_access_token_credential import StaticAccessTokenCredential +from .._client import MixedRealityStsClient + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Union from azure.core.credentials import AccessToken, TokenCredential -from .static_access_token_credential import StaticAccessTokenCredential -from .._client import MixedRealityStsClient def get_mixedreality_credential(account_id, account_domain, endpoint_url, credential, **kwargs): - # type: (str, str, str, TokenCredential, Any) -> TokenCredential - if isinstance(credential, StaticAccessTokenCredential): - return credential + # type: (str, str, str, TokenCredential, Any) -> TokenCredential + if isinstance(credential, StaticAccessTokenCredential): + return credential - return MixedRealityTokenCredential( - account_id=account_id, - account_domain=account_domain, - endpoint_url=endpoint_url, - credential=credential, - **kwargs) + return MixedRealityTokenCredential( + account_id=account_id, + account_domain=account_domain, + endpoint_url=endpoint_url, + credential=credential, + **kwargs) class MixedRealityTokenCredential(object): @@ -44,6 +45,6 @@ def __init__(self, account_id, account_domain, endpoint_url, credential, **kwarg credential=credential, **kwargs) - def get_token(self, *scopes, **kwargs): + def get_token(self, *scopes, **kwargs): #pylint: disable=unused-argument # type: (*str, **Any) -> AccessToken return self.stsClient.get_token(**kwargs) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py index cfadee040131..0fa8566e6baf 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py @@ -23,7 +23,7 @@ def __init__(self, account_id, account_key): self.account_id = account_id self.account_key = account_key - def get_token(self, *scopes, **kwargs): + def get_token(self, *scopes, **kwargs): #pylint: disable=unused-argument # type: (*str, **Any) -> azure.core.credentials.AccessToken token = self.account_id + ":" + self.account_key.key diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/static_access_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/static_access_token_credential.py index 3dd902553cce..b2abd13af1e4 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/static_access_token_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/static_access_token_credential.py @@ -21,6 +21,6 @@ def __init__(self, access_token): # type: (AccessToken) -> None self._access_token = access_token - def get_token(self, *scopes, **kwargs): + def get_token(self, *scopes, **kwargs): #pylint: disable=unused-argument # type: (*str, **Any) -> AccessToken return self._access_token diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py index 708949ffbb72..96a2539a0bbc 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py @@ -45,11 +45,13 @@ def retrieve_jwt_expiration_timestamp(jwt_value): padded_base64_payload = base64.b64decode(parts[1]) payload = json.loads(padded_base64_payload) except ValueError: + #pylint: disable=raise-missing-from raise ValueError("Unable to decode the JWT.") try: exp = payload['exp'] except KeyError: + #pylint: disable=raise-missing-from raise ValueError("Invalid JWT payload structure. No expiration.") return int(exp) @@ -65,6 +67,7 @@ def generate_cv_base(): """ result = '' + #pylint: disable=unused-variable for i in range(CV_BASE_LENGTH): random_index = random.randint(0, len(BASE_64_CHAR_SET) - 1) result += BASE_64_CHAR_SET[random_index] diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_version.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_version.py index 79ce8e42a972..14cf0981d001 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_version.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_version.py @@ -7,4 +7,4 @@ # matches SEMVER VERSION = "1.0.0b1" -SDK_MONIKER = "mixedreality-authentication/{}".format(VERSION) # type: str \ No newline at end of file +SDK_MONIKER = "mixedreality-authentication/{}".format(VERSION) # type: str diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py index 69e570ab5bd3..d63475e1898c 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py @@ -3,16 +3,15 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING + +# pylint: disable=unused-import,ungrouped-imports +from typing import Any, TYPE_CHECKING, Union try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse # type: ignore -# pylint: disable=unused-import,ungrouped-imports -from typing import Any, Union - from azure.core.credentials import AzureKeyCredential from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.pipeline.policies import AsyncBearerTokenCredentialPolicy @@ -45,7 +44,7 @@ class MixedRealityStsClient(object): def __init__(self, account_id: str, account_domain: str, - credential: Union[AzureKeyCredential, "AsyncTokenCredential"], + credential: Union[AzureKeyCredential, "AsyncTokenCredential"], #pylint: disable=unsubscriptable-object **kwargs) -> None: if not account_id: raise ValueError("account_id can not be None") @@ -70,6 +69,7 @@ def __init__(self, if not endpoint_url.lower().startswith('http'): endpoint_url = "https://" + endpoint_url except AttributeError: + #pylint: disable=raise-missing-from raise ValueError("Host URL must be a string") parsed_url = urlparse(endpoint_url.rstrip('/')) From 0fb09439dfe27969b6e2a209ef02680811754663 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Fri, 12 Feb 2021 08:22:26 -0800 Subject: [PATCH 25/40] More pylint fixes --- .../_shared/aio/mixedreality_account_key_credential.py | 2 +- .../_shared/mixedreality_account_key_credential.py | 2 +- .../azure/mixedreality/authentication/aio/_client_async.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixedreality_account_key_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixedreality_account_key_credential.py index 814cab6e2082..ffc23fea396e 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixedreality_account_key_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixedreality_account_key_credential.py @@ -49,6 +49,6 @@ async def __aexit__(self, exc_type, exc_value, traceback) -> None: def _add_years(date_to_update, years): try: - return date_to_update.replace(year = date_to_update.year + years) + return date_to_update.replace(year=date_to_update.year + years) except ValueError: return date_to_update + (date(date_to_update.year + years, 1, 1) - date(date_to_update.year, 1, 1)) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py index 0fa8566e6baf..c5d175eb40dd 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py @@ -37,6 +37,6 @@ def get_token(self, *scopes, **kwargs): #pylint: disable=unused-argument def _add_years(date_to_update, years): try: - return date_to_update.replace(year = date_to_update.year + years) + return date_to_update.replace(year=date_to_update.year + years) except ValueError: return date_to_update + (date(date_to_update.year + years, 1, 1) - date(date_to_update.year, 1, 1)) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py index d63475e1898c..1a1577203511 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py @@ -94,7 +94,7 @@ async def get_token(self, **kwargs) -> "AccessToken": :rtype: :class:`azure.core.credentials.AccessToken` """ token_request_options = TokenRequestOptions() - token_request_options.client_request_id=generate_cv_base() + token_request_options.client_request_id = generate_cv_base() response = await self._client.get_token( self._account_id, From c0dfa8ab270facb89a89a9f5ba94f8cf13bc5c02 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Fri, 12 Feb 2021 10:43:43 -0800 Subject: [PATCH 26/40] Satisfy mypy --- .../azure-mixedreality-authentication/azure/__init__.py | 2 +- .../azure/mixedreality/__init__.py | 2 +- .../azure/mixedreality/authentication/_client.py | 6 ++++-- .../_shared/aio/static_access_token_credential.py | 1 + .../_shared/mixedreality_account_key_credential.py | 8 ++++++-- .../_shared/static_access_token_credential.py | 1 + 6 files changed, 14 insertions(+), 6 deletions(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/__init__.py index 69e3be50dac4..0c36c2076ba0 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/__init__.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/__init__.py @@ -1 +1 @@ -__path__ = __import__('pkgutil').extend_path(__path__, __name__) +__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/__init__.py index 69e3be50dac4..0c36c2076ba0 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/__init__.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/__init__.py @@ -1 +1 @@ -__path__ = __import__('pkgutil').extend_path(__path__, __name__) +__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py index 9ed5ee9c29d7..235bdfde1698 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py @@ -24,6 +24,8 @@ if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Union + from azure.core.credentials import TokenCredential + from azure.core.credentials import AccessToken class MixedRealityStsClient(object): @@ -73,7 +75,7 @@ def __init__(self, account_id, account_domain, credential, **kwargs): self._endpoint_url = endpoint_url - authentication_policy = BearerTokenCredentialPolicy(credential, [endpoint_url + '/.default']) + authentication_policy = BearerTokenCredentialPolicy(credential, endpoint_url + '/.default') self._client = MixedRealityStsRestClient( base_url=endpoint_url, @@ -83,7 +85,7 @@ def __init__(self, account_id, account_domain, credential, **kwargs): @distributed_trace def get_token(self, **kwargs): - # type: (Any) -> azure.core.credentials.AccessToken + # type: (Any) -> AccessToken """ Retrieve a token from the STS service for the specified account identifier asynchronously. :return: Instance of azure.core.credentials.AccessToken - token and expiry date of it diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/static_access_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/static_access_token_credential.py index b4ba12f2a16e..fccbd6f1a2b0 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/static_access_token_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/static_access_token_credential.py @@ -7,6 +7,7 @@ if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports + from typing import Any from azure.core.credentials_async import AsyncTokenCredential from azure.core.credentials import AccessToken diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py index c5d175eb40dd..82216fe5f457 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py @@ -3,12 +3,16 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- - +from typing import TYPE_CHECKING from datetime import date, datetime import time from azure.core.credentials import AzureKeyCredential, AccessToken +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + ACCOUNT_KEY_VALID_YEARS = 10 class MixedRealityAccountKeyCredential(object): @@ -24,7 +28,7 @@ def __init__(self, account_id, account_key): self.account_key = account_key def get_token(self, *scopes, **kwargs): #pylint: disable=unused-argument - # type: (*str, **Any) -> azure.core.credentials.AccessToken + # type: (*str, **Any) -> AccessToken token = self.account_id + ":" + self.account_key.key diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/static_access_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/static_access_token_credential.py index b2abd13af1e4..712f4e20738f 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/static_access_token_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/static_access_token_credential.py @@ -7,6 +7,7 @@ if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports + from typing import Any from azure.core.credentials import TokenCredential from azure.core.credentials import AccessToken From 9081b7cf7e7a23a0753b51bcd873ea8a9550f01d Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Fri, 12 Feb 2021 10:51:22 -0800 Subject: [PATCH 27/40] Satisfy pylint --- .../azure/mixedreality/authentication/_client.py | 5 ++--- .../azure/mixedreality/authentication/_utils.py | 10 ++++------ .../mixedreality/authentication/aio/_client_async.py | 5 ++--- 3 files changed, 8 insertions(+), 12 deletions(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py index 235bdfde1698..39b7b8c12c0a 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py @@ -65,9 +65,8 @@ def __init__(self, account_id, account_domain, credential, **kwargs): try: if not endpoint_url.lower().startswith('http'): endpoint_url = "https://" + endpoint_url - except AttributeError: - #pylint: disable=raise-missing-from - raise ValueError("Host URL must be a string") + except AttributeError as ex: + raise ValueError("Host URL must be a string") from ex parsed_url = urlparse(endpoint_url.rstrip('/')) if not parsed_url.netloc: diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py index 96a2539a0bbc..0390886ca520 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py @@ -44,15 +44,13 @@ def retrieve_jwt_expiration_timestamp(jwt_value): try: padded_base64_payload = base64.b64decode(parts[1]) payload = json.loads(padded_base64_payload) - except ValueError: - #pylint: disable=raise-missing-from - raise ValueError("Unable to decode the JWT.") + except ValueError as ex: + raise ValueError("Unable to decode the JWT.") from ex try: exp = payload['exp'] - except KeyError: - #pylint: disable=raise-missing-from - raise ValueError("Invalid JWT payload structure. No expiration.") + except KeyError as ex: + raise ValueError("Invalid JWT payload structure. No expiration.") from ex return int(exp) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py index 1a1577203511..112d6da3e60e 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py @@ -68,9 +68,8 @@ def __init__(self, try: if not endpoint_url.lower().startswith('http'): endpoint_url = "https://" + endpoint_url - except AttributeError: - #pylint: disable=raise-missing-from - raise ValueError("Host URL must be a string") + except AttributeError as ex: + raise ValueError("Host URL must be a string") from ex parsed_url = urlparse(endpoint_url.rstrip('/')) if not parsed_url.netloc: From 2cf45e67f6f3bc6701bc1b7ccdf9fc63d61502d7 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Fri, 12 Feb 2021 11:13:58 -0800 Subject: [PATCH 28/40] Addressed feedback from ARR's PR --- .../LICENSE.txt | 21 +++++++++++++++++++ .../MANIFEST.in | 5 ++++- .../dev_requirements.txt | 4 ++-- .../sdk_packaging.toml | 5 +++++ .../setup.py | 12 ++++++----- 5 files changed, 39 insertions(+), 8 deletions(-) create mode 100644 sdk/mixedreality/azure-mixedreality-authentication/LICENSE.txt diff --git a/sdk/mixedreality/azure-mixedreality-authentication/LICENSE.txt b/sdk/mixedreality/azure-mixedreality-authentication/LICENSE.txt new file mode 100644 index 000000000000..0313a903d76c --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-authentication/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Microsoft + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/sdk/mixedreality/azure-mixedreality-authentication/MANIFEST.in b/sdk/mixedreality/azure-mixedreality-authentication/MANIFEST.in index dd20dd67408b..3b4fef95fee1 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/MANIFEST.in +++ b/sdk/mixedreality/azure-mixedreality-authentication/MANIFEST.in @@ -1,3 +1,6 @@ include *.md include azure/__init__.py -recursive-include tests *.py \ No newline at end of file +include azure/mixedreality/__init__.py +include LICENSE.txt +recursive-include tests *.py *.yaml +recursive-include samples *.py *.md \ No newline at end of file diff --git a/sdk/mixedreality/azure-mixedreality-authentication/dev_requirements.txt b/sdk/mixedreality/azure-mixedreality-authentication/dev_requirements.txt index 86370a2c4f21..d9b5454b3434 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/dev_requirements.txt +++ b/sdk/mixedreality/azure-mixedreality-authentication/dev_requirements.txt @@ -1,4 +1,4 @@ --e ../../../tools/azure-devtools -e ../../../tools/azure-sdk-tools +../azure-mixedreality-nspkg ../../core/azure-core -aiohttp>=3.0; python_version >= '3.5' \ No newline at end of file +aiohttp>=3.0; python_version >= '3.5' diff --git a/sdk/mixedreality/azure-mixedreality-authentication/sdk_packaging.toml b/sdk/mixedreality/azure-mixedreality-authentication/sdk_packaging.toml index 901bc8ccbfa6..2684d587e162 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/sdk_packaging.toml +++ b/sdk/mixedreality/azure-mixedreality-authentication/sdk_packaging.toml @@ -1,2 +1,7 @@ [packaging] auto_update = false +package_name = "azure-mixedreality-authentication" +package_pprint_name = "Mixed Reality Authentication" +package_doc_id = "" +is_stable = false +is_arm = false diff --git a/sdk/mixedreality/azure-mixedreality-authentication/setup.py b/sdk/mixedreality/azure-mixedreality-authentication/setup.py index b523fd604f22..883ce987c6d9 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/setup.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/setup.py @@ -53,20 +53,22 @@ 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', 'License :: OSI Approved :: MIT License', ], packages=find_packages(exclude=[ 'tests', # Exclude packages that will be covered by PEP420 or nspkg - 'azure' + 'azure', + 'azure.mixedreality' ]), install_requires=[ - #'msrest>=0.5.0', - #'msrestazure>=0.4.32,<2.0.0', - #'azure-common~=1.1', + 'azure-core<2.0.0,>=1.9.0' ], extras_require={ - ":python_version<'3.0'": ['azure-nspkg'], + ":python_version<'3.0'": ['azure-mixedreality-nspkg'], + ":python_version<'3.5'": ["typing"] }, project_urls={ 'Bug Reports': 'https://github.com/Azure/azure-sdk-for-python/issues', From 9d0a681c89eae6f50914abec9a24f6bf410f43ab Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Fri, 12 Feb 2021 11:19:44 -0800 Subject: [PATCH 29/40] Added a Mixed Reality namespace package --- .../azure-mixedreality-nspkg/CHANGELOG.md | 5 +++ .../azure-mixedreality-nspkg/MANIFEST.in | 3 ++ .../azure-mixedreality-nspkg/README.md | 11 +++++ .../azure/__init__.py | 1 + .../azure/mixedreality/__init__.py | 0 .../azure-mixedreality-nspkg/setup.cfg | 2 + .../azure-mixedreality-nspkg/setup.py | 40 +++++++++++++++++++ sdk/mixedreality/ci.yml | 2 + 8 files changed, 64 insertions(+) create mode 100644 sdk/mixedreality/azure-mixedreality-nspkg/CHANGELOG.md create mode 100644 sdk/mixedreality/azure-mixedreality-nspkg/MANIFEST.in create mode 100644 sdk/mixedreality/azure-mixedreality-nspkg/README.md create mode 100644 sdk/mixedreality/azure-mixedreality-nspkg/azure/__init__.py create mode 100644 sdk/mixedreality/azure-mixedreality-nspkg/azure/mixedreality/__init__.py create mode 100644 sdk/mixedreality/azure-mixedreality-nspkg/setup.cfg create mode 100644 sdk/mixedreality/azure-mixedreality-nspkg/setup.py diff --git a/sdk/mixedreality/azure-mixedreality-nspkg/CHANGELOG.md b/sdk/mixedreality/azure-mixedreality-nspkg/CHANGELOG.md new file mode 100644 index 000000000000..6e1371575985 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-nspkg/CHANGELOG.md @@ -0,0 +1,5 @@ +# Release History + +## 0.0.0b1 (2021-02-12) + +- Test a successful Release diff --git a/sdk/mixedreality/azure-mixedreality-nspkg/MANIFEST.in b/sdk/mixedreality/azure-mixedreality-nspkg/MANIFEST.in new file mode 100644 index 000000000000..092b64f9159b --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-nspkg/MANIFEST.in @@ -0,0 +1,3 @@ +include *.md +include azure/__init__.py +include azure/mixedreality/__init__.py \ No newline at end of file diff --git a/sdk/mixedreality/azure-mixedreality-nspkg/README.md b/sdk/mixedreality/azure-mixedreality-nspkg/README.md new file mode 100644 index 000000000000..995038c70840 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-nspkg/README.md @@ -0,0 +1,11 @@ +# Microsoft Azure Mixed Reality SDK for Python + +This is the Microsoft Azure Mixed Reality namespace package. + +This package is not intended to be installed directly by the end user. + +It provides the necessary files for other packages to extend the +azure.mixedreality namespace. + +The complete list of available packages can be found at: +https://aka.ms/azsdk/python/all diff --git a/sdk/mixedreality/azure-mixedreality-nspkg/azure/__init__.py b/sdk/mixedreality/azure-mixedreality-nspkg/azure/__init__.py new file mode 100644 index 000000000000..69e3be50dac4 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-nspkg/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__('pkgutil').extend_path(__path__, __name__) diff --git a/sdk/mixedreality/azure-mixedreality-nspkg/azure/mixedreality/__init__.py b/sdk/mixedreality/azure-mixedreality-nspkg/azure/mixedreality/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/sdk/mixedreality/azure-mixedreality-nspkg/setup.cfg b/sdk/mixedreality/azure-mixedreality-nspkg/setup.cfg new file mode 100644 index 000000000000..3480374bc2f2 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-nspkg/setup.cfg @@ -0,0 +1,2 @@ +[bdist_wheel] +universal=1 \ No newline at end of file diff --git a/sdk/mixedreality/azure-mixedreality-nspkg/setup.py b/sdk/mixedreality/azure-mixedreality-nspkg/setup.py new file mode 100644 index 000000000000..106d5c897f67 --- /dev/null +++ b/sdk/mixedreality/azure-mixedreality-nspkg/setup.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +from setuptools import setup + +setup( + name='azure-mixedreality-nspkg', + version='0.0.0b1', + description='Microsoft Azure Mixed Reality Namespace Package [Internal]', + long_description=open('README.md', 'r').read(), + license='MIT License', + author='Microsoft Corporation', + author_email='azurepysdk@microsoft.com', + url='https://github.com/Azure/azure-sdk-for-python/', + classifiers=[ + 'Development Status :: 3 - Alpha', + + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'License :: OSI Approved :: MIT License', + ], + zip_safe=False, + packages=[ + 'azure.mixedreality', + ], + install_requires=[ + 'azure-nspkg>=2.0.0', + ] +) \ No newline at end of file diff --git a/sdk/mixedreality/ci.yml b/sdk/mixedreality/ci.yml index ef254485218c..f3ae04fd79eb 100644 --- a/sdk/mixedreality/ci.yml +++ b/sdk/mixedreality/ci.yml @@ -28,6 +28,8 @@ extends: parameters: ServiceDirectory: mixedreality Artifacts: + - name: azure_mixedreality_nspkg + safeName: azuremixedrealitynspkg - name: azure_mgmt_mixedreality safeName: azuremgmtmixedreality - name: azure_mixedreality_authentication From 9608950b98823d86bed01fafa4069b3ab62a6efb Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Fri, 12 Feb 2021 13:54:04 -0800 Subject: [PATCH 30/40] Revert some pylint changes to support Python 2.7 --- .../azure/mixedreality/authentication/_client.py | 4 ++-- .../azure/mixedreality/authentication/_utils.py | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py index 39b7b8c12c0a..8e56fd99fa5a 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py @@ -65,8 +65,8 @@ def __init__(self, account_id, account_domain, credential, **kwargs): try: if not endpoint_url.lower().startswith('http'): endpoint_url = "https://" + endpoint_url - except AttributeError as ex: - raise ValueError("Host URL must be a string") from ex + except AttributeError: + raise ValueError("Host URL must be a string") parsed_url = urlparse(endpoint_url.rstrip('/')) if not parsed_url.netloc: diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py index 0390886ca520..46852e0a3c91 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py @@ -44,13 +44,13 @@ def retrieve_jwt_expiration_timestamp(jwt_value): try: padded_base64_payload = base64.b64decode(parts[1]) payload = json.loads(padded_base64_payload) - except ValueError as ex: - raise ValueError("Unable to decode the JWT.") from ex + except ValueError: + raise ValueError("Unable to decode the JWT.") try: exp = payload['exp'] - except KeyError as ex: - raise ValueError("Invalid JWT payload structure. No expiration.") from ex + except KeyError: + raise ValueError("Invalid JWT payload structure. No expiration.") return int(exp) From 3e05a0587a3557608d201e9b4d9811c3c1106142 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Tue, 16 Feb 2021 10:14:55 -0800 Subject: [PATCH 31/40] Addressed feedback --- .../azure-mixedreality-authentication/MANIFEST.in | 2 +- .../azure-mixedreality-authentication/README.md | 4 ++-- .../azure/mixedreality/authentication/_client.py | 1 - .../aio/mixedreality_account_key_credential.py | 4 ++-- .../_shared/mixedreality_account_key_credential.py | 4 ++-- .../authentication/aio/_client_async.py | 1 - .../azure-mixedreality-authentication/setup.py | 14 ++++++++------ .../recordings/test_client.test_get_token.yaml | 4 ++-- .../test_client_async.test_get_token.yaml | 6 +++--- sdk/mixedreality/azure-mixedreality-nspkg/setup.py | 5 +++-- 10 files changed, 23 insertions(+), 22 deletions(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/MANIFEST.in b/sdk/mixedreality/azure-mixedreality-authentication/MANIFEST.in index 3b4fef95fee1..b69eaab9edd0 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/MANIFEST.in +++ b/sdk/mixedreality/azure-mixedreality-authentication/MANIFEST.in @@ -2,5 +2,5 @@ include *.md include azure/__init__.py include azure/mixedreality/__init__.py include LICENSE.txt -recursive-include tests *.py *.yaml +recursive-include tests *.py recursive-include samples *.py *.md \ No newline at end of file diff --git a/sdk/mixedreality/azure-mixedreality-authentication/README.md b/sdk/mixedreality/azure-mixedreality-authentication/README.md index 1c6d675c396b..05f159ef81fd 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/README.md +++ b/sdk/mixedreality/azure-mixedreality-authentication/README.md @@ -12,7 +12,7 @@ token from the STS that can be used to access Mixed Reality services. ## Currently supported environments -This package has been tested with Python 2.7, 3.5, 3.6, 3.7 and 3.8. +This package has been tested with Python 2.7, 3.5, 3.6, 3.7, 3.8, and 3.9. ## Prerequisites @@ -25,7 +25,7 @@ This package has been tested with Python 2.7, 3.5, 3.6, 3.7 and 3.8. ## Install the package -Install the Azure Communication Service Chat SDK. +Install the Azure Mixed Reality Authentication SDK. ```bash pip install --pre azure-mixedreality-authentication diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py index 8e56fd99fa5a..a5c6b618d160 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py @@ -95,7 +95,6 @@ def get_token(self, **kwargs): response = self._client.get_token( self._account_id, - api_version=None, token_request_options=token_request_options, **kwargs) return convert_to_access_token(response) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixedreality_account_key_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixedreality_account_key_credential.py index ffc23fea396e..2f9efb559a53 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixedreality_account_key_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixedreality_account_key_credential.py @@ -31,8 +31,8 @@ def __init__(self, account_id, account_key): async def get_token(self, *scopes: str, **kwargs: "Any") -> "AccessToken": #pylint: disable=unused-argument token = self.account_id + ":" + self.account_key.key - # No way to know when an access token might expire, so we'll set it to be - # 10 years in the future. + # No way to know when an account key might expire, so we'll set the + # access token wrapping it to expire 10 years in the future. expiration_date = _add_years(datetime.now(), ACCOUNT_KEY_VALID_YEARS) expiration_timestamp = int(expiration_date.timestamp()) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py index 82216fe5f457..a7ec1ca5db63 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixedreality_account_key_credential.py @@ -32,8 +32,8 @@ def get_token(self, *scopes, **kwargs): #pylint: disable=unused-argument token = self.account_id + ":" + self.account_key.key - # No way to know when an access token might expire, so we'll set it to be - # 10 years in the future. + # No way to know when an account key might expire, so we'll set the + # access token wrapping it to expire 10 years in the future. expiration_date = _add_years(datetime.now(), ACCOUNT_KEY_VALID_YEARS) expiration_timestamp = int(time.mktime(expiration_date.timetuple())) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py index 112d6da3e60e..9885907f76ab 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py @@ -97,7 +97,6 @@ async def get_token(self, **kwargs) -> "AccessToken": response = await self._client.get_token( self._account_id, - api_version=None, token_request_options=token_request_options, **kwargs) return convert_to_access_token(response) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/setup.py b/sdk/mixedreality/azure-mixedreality-authentication/setup.py index 883ce987c6d9..2d4057539f8a 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/setup.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/setup.py @@ -3,11 +3,11 @@ from io import open import re -# example setup.py Feel free to copy the entire "azure-template" folder into a package folder named -# with "azure-". Ensure that the below arguments to setup() are updated to reflect +# example setup.py Feel free to copy the entire "azure-template" folder into a package folder named +# with "azure-". Ensure that the below arguments to setup() are updated to reflect # your package. -# this setup.py is set up in a specific way to keep the azure* and azure-mgmt-* namespaces WORKING all the way +# this setup.py is set up in a specific way to keep the azure* and azure-mgmt-* namespaces WORKING all the way # up from python 2.7. Reference here: https://github.com/Azure/azure-sdk-for-python/wiki/Azure-packaging PACKAGE_NAME = "azure-mixedreality-authentication" @@ -26,7 +26,10 @@ raise RuntimeError('Cannot find version information') with open('README.md', encoding='utf-8') as f: - long_description = f.read() + readme = f.read() + +with open('CHANGELOG.md', encoding='utf-8') as f: + changelog = f.read() setup( name=PACKAGE_NAME, @@ -34,7 +37,7 @@ description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), # ensure that these are updated to reflect the package owners' information - long_description=long_description, + long_description=readme + "\n\n" + changelog, long_description_content_type='text/markdown', url='https://github.com/Azure/azure-sdk-for-python', author='Microsoft Corporation', @@ -49,7 +52,6 @@ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/recordings/test_client.test_get_token.yaml b/sdk/mixedreality/azure-mixedreality-authentication/tests/recordings/test_client.test_get_token.yaml index d3dae59d3e85..6be3baa36955 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/recordings/test_client.test_get_token.yaml +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/recordings/test_client.test_get_token.yaml @@ -9,11 +9,11 @@ interactions: Connection: - keep-alive User-Agent: - - azsdk-python-mixedreality-authentication/0.0.1b1 Python/3.9.1 (Windows-10-10.0.19041-SP0) + - azsdk-python-mixedreality-authentication/1.0.0b1 Python/3.9.1 (Windows-10-10.0.19041-SP0) X-MRC-CV: - z2TH5gImRhQCZc4ubhqtRV method: GET - uri: https://sts.mixedreality.azure.com/Accounts/68321d5a-7978-4ceb-b880-0f49751daae9/token + uri: https://sts.mixedreality.azure.com/Accounts/68321d5a-7978-4ceb-b880-0f49751daae9/token?api-version=2019-02-28-preview response: body: string: '{"AccessToken":"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0=."}' diff --git a/sdk/mixedreality/azure-mixedreality-authentication/tests/recordings/test_client_async.test_get_token.yaml b/sdk/mixedreality/azure-mixedreality-authentication/tests/recordings/test_client_async.test_get_token.yaml index d35fa806f550..32b3c3b0e66c 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/tests/recordings/test_client_async.test_get_token.yaml +++ b/sdk/mixedreality/azure-mixedreality-authentication/tests/recordings/test_client_async.test_get_token.yaml @@ -5,11 +5,11 @@ interactions: Accept: - application/json User-Agent: - - azsdk-python-mixedreality-authentication/0.0.1b1 Python/3.9.1 (Windows-10-10.0.19041-SP0) + - azsdk-python-mixedreality-authentication/1.0.0b1 Python/3.9.1 (Windows-10-10.0.19041-SP0) X-MRC-CV: - DOGUG9rex0lylvLZmhuJgR method: GET - uri: https://sts.mixedreality.azure.com/Accounts/68321d5a-7978-4ceb-b880-0f49751daae9/token + uri: https://sts.mixedreality.azure.com/Accounts/68321d5a-7978-4ceb-b880-0f49751daae9/token?api-version=2019-02-28-preview response: body: string: '{"AccessToken":"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6IkJvYkBjb250b3NvLmNvbSIsImdpdmVuX25hbWUiOiJCb2IiLCJpc3MiOiJodHRwOi8vRGVmYXVsdC5Jc3N1ZXIuY29tIiwiYXVkIjoiaHR0cDovL0RlZmF1bHQuQXVkaWVuY2UuY29tIiwiaWF0IjoiMTYwNzk3ODY4MyIsIm5iZiI6IjE2MDc5Nzg2ODMiLCJleHAiOiIxNjA3OTc4OTgzIn0=."}' @@ -24,5 +24,5 @@ interactions: status: code: 200 message: OK - url: https://sts.mixedreality.azure.com/Accounts/68321d5a-7978-4ceb-b880-0f49751daae9/token + url: https://sts.mixedreality.azure.com/Accounts/68321d5a-7978-4ceb-b880-0f49751daae9/token?api-version=2019-02-28-preview version: 1 diff --git a/sdk/mixedreality/azure-mixedreality-nspkg/setup.py b/sdk/mixedreality/azure-mixedreality-nspkg/setup.py index 106d5c897f67..a80cc7d1344c 100644 --- a/sdk/mixedreality/azure-mixedreality-nspkg/setup.py +++ b/sdk/mixedreality/azure-mixedreality-nspkg/setup.py @@ -10,7 +10,7 @@ setup( name='azure-mixedreality-nspkg', - version='0.0.0b1', + version='1.0.0', description='Microsoft Azure Mixed Reality Namespace Package [Internal]', long_description=open('README.md', 'r').read(), license='MIT License', @@ -18,7 +18,7 @@ author_email='azurepysdk@microsoft.com', url='https://github.com/Azure/azure-sdk-for-python/', classifiers=[ - 'Development Status :: 3 - Alpha', + 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python', 'Programming Language :: Python :: 2', @@ -28,6 +28,7 @@ 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', 'License :: OSI Approved :: MIT License', ], zip_safe=False, From 2174f3774183972d797e146409515e80b5817abe Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Tue, 16 Feb 2021 10:42:39 -0800 Subject: [PATCH 32/40] Ignore Mixed Reality nspkg README.md --- eng/.docsettings.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/eng/.docsettings.yml b/eng/.docsettings.yml index a732c246e727..d0dba16dd0bb 100644 --- a/eng/.docsettings.yml +++ b/eng/.docsettings.yml @@ -124,6 +124,7 @@ known_content_issues: - ['sdk/core/azure-mgmt-nspkg/README.rst', 'nspkg and common'] - ['sdk/core/azure-nspkg/README.rst', 'nspkg and common'] - ['sdk/keyvault/azure-keyvault-nspkg/README.md', 'nspkg and common'] + - ['sdk/mixedreality/azure-mixedreality-nspkg/README.md', 'nspkg and common'] - ['sdk/search/azure-search-nspkg/README.md', 'nspkg and common'] - ['sdk/storage/azure-storage-blob/samples/README.md', 'nspkg and common'] - ['sdk/storage/azure-storage-file-datalake/samples/README.md', 'nspkg and common'] From ce024201c3e31377f40e549790f95d2698eb6d2e Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Tue, 16 Feb 2021 10:45:32 -0800 Subject: [PATCH 33/40] Added msrest to required packages --- sdk/mixedreality/azure-mixedreality-authentication/setup.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/setup.py b/sdk/mixedreality/azure-mixedreality-authentication/setup.py index 2d4057539f8a..245b0d7e0801 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/setup.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/setup.py @@ -66,7 +66,8 @@ 'azure.mixedreality' ]), install_requires=[ - 'azure-core<2.0.0,>=1.9.0' + 'azure-core<2.0.0,>=1.9.0', + 'msrest>=0.6.21' ], extras_require={ ":python_version<'3.0'": ['azure-mixedreality-nspkg'], From 5d628b511033ad78346f7ea123489d0692646251 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Tue, 16 Feb 2021 12:07:40 -0800 Subject: [PATCH 34/40] Trying to resolve issues related to frozen libraries --- sdk/mixedreality/azure-mixedreality-authentication/setup.py | 4 ++-- shared_requirements.txt | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/setup.py b/sdk/mixedreality/azure-mixedreality-authentication/setup.py index 245b0d7e0801..0384e23bf7c8 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/setup.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/setup.py @@ -66,8 +66,8 @@ 'azure.mixedreality' ]), install_requires=[ - 'azure-core<2.0.0,>=1.9.0', - 'msrest>=0.6.21' + 'azure-core<2.0.0,>=1.2.2', + 'msrest>=0.5.0' ], extras_require={ ":python_version<'3.0'": ['azure-mixedreality-nspkg'], diff --git a/shared_requirements.txt b/shared_requirements.txt index 03d2819c522e..b05f18da2281 100644 --- a/shared_requirements.txt +++ b/shared_requirements.txt @@ -84,6 +84,7 @@ azure-mgmt-storage~=2.0 azure-mgmt-subscription~=0.2.0 azure-mgmt-trafficmanager~=0.50.0 azure-mgmt-web~=0.35.0 +azure-mixedreality-nspkg azure-nspkg azure-keyvault-nspkg azure-media-nspkg From ceb2859b6184efdafc6fbe1aa991a57829ed014a Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Wed, 17 Feb 2021 11:33:42 -0800 Subject: [PATCH 35/40] Added nspkg CHANGELOG --- sdk/mixedreality/azure-mixedreality-nspkg/CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/mixedreality/azure-mixedreality-nspkg/CHANGELOG.md b/sdk/mixedreality/azure-mixedreality-nspkg/CHANGELOG.md index 6e1371575985..627c355468b5 100644 --- a/sdk/mixedreality/azure-mixedreality-nspkg/CHANGELOG.md +++ b/sdk/mixedreality/azure-mixedreality-nspkg/CHANGELOG.md @@ -1,5 +1,5 @@ # Release History -## 0.0.0b1 (2021-02-12) +## 1.0.0 (Unreleased) -- Test a successful Release +- Initial release From 877d3bc93ff7e18da74f108213c73241dc8c9f8b Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Wed, 17 Feb 2021 17:45:41 -0800 Subject: [PATCH 36/40] Fix tests in Python 3.5 by converting bytes to str --- .../azure/mixedreality/authentication/_utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py index 46852e0a3c91..cd16657afe2f 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py @@ -42,7 +42,7 @@ def retrieve_jwt_expiration_timestamp(jwt_value): raise ValueError("Invalid JWT structure.") try: - padded_base64_payload = base64.b64decode(parts[1]) + padded_base64_payload = base64.b64decode(parts[1]).decode('utf-8') payload = json.loads(padded_base64_payload) except ValueError: raise ValueError("Unable to decode the JWT.") From 6d7ff6b249070b8f96b61b1e4ebd2bbf55d13de9 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Mon, 22 Feb 2021 09:11:54 -0800 Subject: [PATCH 37/40] Added license headers to __init__.py files --- .../azure-mixedreality-authentication/azure/__init__.py | 6 ++++++ .../azure/mixedreality/__init__.py | 6 ++++++ .../azure/mixedreality/authentication/__init__.py | 6 ++++++ 3 files changed, 18 insertions(+) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/__init__.py index 0c36c2076ba0..431ed648086a 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/__init__.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/__init__.py @@ -1 +1,7 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + __path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/__init__.py index 0c36c2076ba0..431ed648086a 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/__init__.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/__init__.py @@ -1 +1,7 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + __path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/__init__.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/__init__.py index 508aee376b10..2996cdaaeb4c 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/__init__.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/__init__.py @@ -1,3 +1,9 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + from ._version import VERSION from ._client import MixedRealityStsClient From 10ff17c56fc4a268be9e6767d7db2f0114ef6218 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Mon, 22 Feb 2021 09:13:31 -0800 Subject: [PATCH 38/40] Removed extra import from snippet --- sdk/mixedreality/azure-mixedreality-authentication/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/README.md b/sdk/mixedreality/azure-mixedreality-authentication/README.md index 05f159ef81fd..ca0845d344a6 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/README.md +++ b/sdk/mixedreality/azure-mixedreality-authentication/README.md @@ -82,7 +82,6 @@ You will also need to [register a new AAD application][register_aad_app] and gra by assigning the appropriate role for your Mixed Reality service to your service principal. ```python -from azure.core.credentials import AzureKeyCredential from azure.identity import DefaultAzureCredential from azure.mixedreality.authentication import MixedRealityStsClient From 0fc4ce2d7ae62dbf93a7f378272c3491caca0242 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Mon, 22 Feb 2021 11:49:12 -0800 Subject: [PATCH 39/40] Updated error messages --- .../azure/mixedreality/authentication/_client.py | 8 ++++---- .../azure/mixedreality/authentication/_utils.py | 8 ++++---- .../mixedreality/authentication/aio/_client_async.py | 8 ++++---- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py index a5c6b618d160..919a99cb55a1 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_client.py @@ -44,13 +44,13 @@ class MixedRealityStsClient(object): def __init__(self, account_id, account_domain, credential, **kwargs): # type: (str, str, Union[TokenCredential, AzureKeyCredential], Any) -> None if not account_id: - raise ValueError("account_id can not be None") + raise ValueError("account_id must be a non-empty string.") if not account_domain: - raise ValueError("account_domain can not be None") + raise ValueError("account_domain must be a non-empty string.") if not credential: - raise ValueError("credential can not be None") + raise ValueError("credential can not be None.") self._account_id = account_id self._account_domain = account_domain @@ -66,7 +66,7 @@ def __init__(self, account_id, account_domain, credential, **kwargs): if not endpoint_url.lower().startswith('http'): endpoint_url = "https://" + endpoint_url except AttributeError: - raise ValueError("Host URL must be a string") + raise ValueError("Host URL must be a string.") parsed_url = urlparse(endpoint_url.rstrip('/')) if not parsed_url.netloc: diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py index cd16657afe2f..9a016a0692a7 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_utils.py @@ -18,8 +18,8 @@ def convert_to_access_token(token_response_message): """ Converts the specified token response message to an AccessToken. """ - if not StsTokenResponseMessage: - raise ValueError("token_response_message can not be None") + if not token_response_message: + raise ValueError("token_response_message must be a non-empty string.") expiration_timestamp = retrieve_jwt_expiration_timestamp(token_response_message.access_token) @@ -34,12 +34,12 @@ def retrieve_jwt_expiration_timestamp(jwt_value): :returns: int """ if not jwt_value: - raise ValueError("jwt_value can not be None") + raise ValueError("jwt_value must be a non-empty string.") parts = jwt_value.split(".") if len(parts) < 3: - raise ValueError("Invalid JWT structure.") + raise ValueError("Invalid JWT structure. Expected a JWS Compact Serialization formatted value.") try: padded_base64_payload = base64.b64decode(parts[1]).decode('utf-8') diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py index 9885907f76ab..fedbacccf397 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/aio/_client_async.py @@ -47,13 +47,13 @@ def __init__(self, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], #pylint: disable=unsubscriptable-object **kwargs) -> None: if not account_id: - raise ValueError("account_id can not be None") + raise ValueError("account_id must be a non-empty string.") if not account_domain: - raise ValueError("account_domain can not be None") + raise ValueError("account_domain must be a non-empty string.") if not credential: - raise ValueError("credential can not be None") + raise ValueError("credential can not be None.") self._account_id = account_id self._account_domain = account_domain @@ -69,7 +69,7 @@ def __init__(self, if not endpoint_url.lower().startswith('http'): endpoint_url = "https://" + endpoint_url except AttributeError as ex: - raise ValueError("Host URL must be a string") from ex + raise ValueError("Host URL must be a string.") from ex parsed_url = urlparse(endpoint_url.rstrip('/')) if not parsed_url.netloc: From e2d0f6422006b2a7bccb8b3b72155064b62c8ee8 Mon Sep 17 00:00:00 2001 From: Craig Treasure Date: Mon, 22 Feb 2021 12:42:59 -0800 Subject: [PATCH 40/40] Fixed imports from _shared --- .../_shared/aio/mixed_reality_token_credential.py | 2 +- .../authentication/_shared/mixed_reality_token_credential.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixed_reality_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixed_reality_token_credential.py index c102156d1419..7cc4e98d8bc6 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixed_reality_token_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/aio/mixed_reality_token_credential.py @@ -5,8 +5,8 @@ # -------------------------------------------------------------------------- from typing import TYPE_CHECKING +from azure.mixedreality.authentication.aio import MixedRealityStsClient from .static_access_token_credential import StaticAccessTokenCredential -from ...aio._client_async import MixedRealityStsClient if TYPE_CHECKING: from typing import Any diff --git a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixed_reality_token_credential.py b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixed_reality_token_credential.py index a599edd0dd7e..e0bb1dda3627 100644 --- a/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixed_reality_token_credential.py +++ b/sdk/mixedreality/azure-mixedreality-authentication/azure/mixedreality/authentication/_shared/mixed_reality_token_credential.py @@ -5,8 +5,8 @@ # -------------------------------------------------------------------------- from typing import TYPE_CHECKING +from azure.mixedreality.authentication import MixedRealityStsClient from .static_access_token_credential import StaticAccessTokenCredential -from .._client import MixedRealityStsClient if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports