Skip to content

Commit

Permalink
[IoT] Adds baseline T2 Device Provisioning Service 2021-10-01 Datapla…
Browse files Browse the repository at this point in the history
…ne Service SDK (Azure#29729)
  • Loading branch information
c-ryan-k authored Jun 9, 2023
1 parent a1da00c commit b002b6e
Show file tree
Hide file tree
Showing 81 changed files with 39,810 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,9 @@
/sdk/datalake/ @ro-joowan
/sdk/datadatamigration/ @vchske

# PRLabel: %Device Provisioning
/sdk/iothub/azure-iot-deviceprovisioning @c-ryan-k @digimaun

# PRLabel: %Device Update
/sdk/deviceupdate/ @dpokluda @sedols

Expand Down
7 changes: 7 additions & 0 deletions .vscode/cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -1489,6 +1489,13 @@
"ctxt",
"wday"
]
},
{
"filename": "sdk/iothub/azure-iot-deviceprovisioning/azure/iot/deviceprovisioning/_serialization.py",
"words": [
"ctxt",
"wday"
]
}
],
"allowCompoundWords": true
Expand Down
5 changes: 5 additions & 0 deletions sdk/iothub/azure-iot-deviceprovisioning/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Release History

## 1.0.0b1 (2023-05-30)

- Initial Release
21 changes: 21 additions & 0 deletions sdk/iothub/azure-iot-deviceprovisioning/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Copyright (c) Microsoft Corporation.

MIT License

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.
7 changes: 7 additions & 0 deletions sdk/iothub/azure-iot-deviceprovisioning/MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
include *.md
recursive-include tests *.py
recursive-include samples *.py *.md
include LICENSE
include azure/__init__.py
include azure/iot/__init__.py
include azure/iot/deviceprovisioning/py.typed
351 changes: 351 additions & 0 deletions sdk/iothub/azure-iot-deviceprovisioning/README.md

Large diffs are not rendered by default.

8 changes: 8 additions & 0 deletions sdk/iothub/azure-iot-deviceprovisioning/azure/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# 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.
# --------------------------------------------------------------------------
__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore
8 changes: 8 additions & 0 deletions sdk/iothub/azure-iot-deviceprovisioning/azure/iot/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# 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.
# --------------------------------------------------------------------------
__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# 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 ._api_version import ApiVersion
from ._auth import generate_sas_token
from ._patch import DeviceProvisioningClient
from ._version import VERSION

__version__ = VERSION


from ._patch import patch_sdk as _patch_sdk

__all__ = ["DeviceProvisioningClient", "ApiVersion", "generate_sas_token"]


_patch_sdk()
Original file line number Diff line number Diff line change
@@ -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 enum import Enum

from azure.core import CaseInsensitiveEnumMeta


class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta):
V2021_10_01 = "2021-10-01"


DEFAULT_VERSION = ApiVersion.V2021_10_01
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# coding=utf-8
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------


from base64 import b64decode, b64encode
from hashlib import sha256
from hmac import HMAC
from time import time
from urllib.parse import quote_plus, urlencode

from azure.core.credentials import AzureSasCredential
from azure.core.pipeline import PipelineRequest
from azure.core.pipeline.policies import SansIOHTTPPolicy


def generate_sas_token(audience: str, policy: str, key: str, expiry: int = 3600) -> str:
"""
Generate a sas token according to the given audience, policy, key and expiry
:param str audience: The audience / endpoint to create the SAS token for
:param str policy: The policy this token represents
:param str key: The key used to sign this token
:param int expiry: Token expiry time in milliseconds
:returns: SAS token as a string literal
:rtype: str
"""

encoded_uri = quote_plus(audience)

ttl = int(time() + expiry)
sign_key = f"{encoded_uri}\n{ttl}"
signature = b64encode(
HMAC(b64decode(key), sign_key.encode("utf-8"), sha256).digest()
)
result = {"sr": audience, "sig": signature, "se": str(ttl)}
if policy:
result["skn"] = policy
return "SharedAccessSignature " + urlencode(result)


class SharedKeyCredentialPolicy(SansIOHTTPPolicy):
def __init__(self, endpoint: str, policy_name: str, key: str) -> None:
self.endpoint = endpoint
self.policy_name = policy_name
self.key = key
super(SharedKeyCredentialPolicy, self).__init__()

def _add_authorization_header(self, request: PipelineRequest) -> None:
try:
auth_string = generate_sas_token(
audience=self.endpoint, policy=self.policy_name, key=self.key
)
request.http_request.headers["Authorization"] = auth_string
except Exception as ex:
# TODO - Wrap error as a signing error?
raise ex

def on_request(self, request: PipelineRequest) -> None:
self._add_authorization_header(request=request)


class SasCredentialPolicy(SansIOHTTPPolicy):
"""Adds an authorization header for the provided credential.
:param credential: The credential used to authenticate requests.
:type credential: ~azure.core.credentials.AzureSasCredential
"""

def __init__(
self, credential: AzureSasCredential, **kwargs
): # pylint: disable=unused-argument
super(SasCredentialPolicy, self).__init__()
self._credential = credential

def on_request(self, request: PipelineRequest) -> None:
request.http_request.headers["Authorization"] = self._credential.signature
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# 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 copy import deepcopy
from typing import Any, TYPE_CHECKING

from azure.core import PipelineClient
from azure.core.rest import HttpRequest, HttpResponse

from ._configuration import DeviceProvisioningClientConfiguration
from ._serialization import Deserializer, Serializer
from .operations import DeviceRegistrationStateOperations, EnrollmentGroupOperations, EnrollmentOperations

if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import TokenCredential


class DeviceProvisioningClient: # pylint: disable=client-accepts-api-version-keyword
"""API for service operations with the Azure IoT Hub Device Provisioning Service.
:ivar enrollment: EnrollmentOperations operations
:vartype enrollment:
azure.iot.deviceprovisioning.operations.EnrollmentOperations
:ivar enrollment_group: EnrollmentGroupOperations operations
:vartype enrollment_group: azure.iot.deviceprovisioning.operations.EnrollmentGroupOperations
:ivar device_registration_state: DeviceRegistrationStateOperations operations
:vartype device_registration_state:
azure.iot.deviceprovisioning.operations.DeviceRegistrationStateOperations
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials.TokenCredential
:keyword endpoint: Service URL. Default value is
"https://your-dps.azure-devices-provisioning.net".
:paramtype endpoint: str
:keyword api_version: Api Version. Default value is "2021-10-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
"""

def __init__(
self,
credential: "TokenCredential",
*,
endpoint: str = "https://your-dps.azure-devices-provisioning.net",
**kwargs: Any
) -> None:
self._config = DeviceProvisioningClientConfiguration(credential=credential, **kwargs)
self._client: PipelineClient = PipelineClient(base_url=endpoint, config=self._config, **kwargs)

self._serialize = Serializer()
self._deserialize = Deserializer()
self._serialize.client_side_validation = False
self.enrollment = EnrollmentOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.enrollment_group = EnrollmentGroupOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.device_registration_state = DeviceRegistrationStateOperations(
self._client, self._config, self._serialize, self._deserialize
)

def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = client.send_request(request)
<HttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.HttpResponse
"""

request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)

def close(self) -> None:
self._client.close()

def __enter__(self) -> "DeviceProvisioningClient":
self._client.__enter__()
return self

def __exit__(self, *exc_details: Any) -> None:
self._client.__exit__(*exc_details)
Original file line number Diff line number Diff line change
@@ -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 Any, TYPE_CHECKING

from azure.core.configuration import Configuration
from azure.core.pipeline import policies

from ._version import VERSION

if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import TokenCredential


class DeviceProvisioningClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes
"""Configuration for DeviceProvisioningClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials.TokenCredential
:keyword api_version: Api Version. Default value is "2021-10-01". Note that overriding this
default value may result in unsupported behavior.
:paramtype api_version: str
"""

def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None:
super(DeviceProvisioningClientConfiguration, self).__init__(**kwargs)
api_version: str = kwargs.pop("api_version", "2021-10-01")

if credential is None:
raise ValueError("Parameter 'credential' must not be None.")

self.credential = credential
self.api_version = api_version
self.credential_scopes = kwargs.pop("credential_scopes", ["https://azure-devices-provisioning.net/.default"])
kwargs.setdefault("sdk_moniker", "iot-deviceprovisioning/{}".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.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")
if self.credential and not self.authentication_policy:
self.authentication_policy = policies.BearerTokenCredentialPolicy(
self.credential, *self.credential_scopes, **kwargs
)
Loading

0 comments on commit b002b6e

Please sign in to comment.