1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
|
# 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.
# --------------------------------------------------------------------------
# TEST SCENARIO COVERAGE
# ----------------------
# Methods Total : 7
# Methods Covered : 7
# Examples Total : 7
# Examples Tested : 7
# Coverage % : 100
# ----------------------
from cryptography.hazmat.primitives import hashes
from devtools_testutils import AzureRecordedTestCase
from devtools_testutils.aio import recorded_by_proxy_async
from cryptography.hazmat.backends import default_backend
import base64
import pytest
from helpers import pem_from_base64
from preparers_async import AllAttestationTypes, AllInstanceTypes
from attestation_preparer import AttestationPreparer
from azure.security.attestation.aio import AttestationAdministrationClient
from azure.security.attestation import (
AttestationType,
AttestationPolicyToken,
PolicyModification,
CertificateModification,
)
from dotenv import find_dotenv, load_dotenv
load_dotenv(find_dotenv())
class TestAsyncPolicyGetSet(AzureRecordedTestCase):
@AttestationPreparer()
@AllAttestationTypes
@AllInstanceTypes
@recorded_by_proxy_async
async def test_get_policy_async(self, **kwargs):
attest_client = self.create_admin_client(
kwargs.pop("instance_url", kwargs.pop("attestation_aad_url"))
)
policy, token = await attest_client.get_policy(
kwargs.pop("attestation_type", AttestationType.SGX_ENCLAVE)
)
assert policy.startswith("version") or len(policy) == 0
print("Token: ", token)
await attest_client.close()
@AttestationPreparer()
@AllAttestationTypes
@recorded_by_proxy_async
async def test_aad_set_policy_unsecured(self, attestation_aad_url, **kwargs):
attestation_policy = (
u"version=1.0; authorizationrules{=> permit();}; issuancerules{};"
)
attestation_type = kwargs.pop("attestation_type")
attest_client = self.create_admin_client(attestation_aad_url, **kwargs)
policy_set_response, _ = await attest_client.set_policy(
attestation_type, attestation_policy
)
new_policy, _ = await attest_client.get_policy(attestation_type)
assert new_policy == attestation_policy
expected_policy = AttestationPolicyToken(attestation_policy)
hasher = hashes.Hash(hashes.SHA256(), backend=default_backend())
hasher.update(expected_policy.to_jwt_string().encode("utf-8"))
expected_hash = hasher.finalize()
assert expected_hash == policy_set_response.policy_token_hash
@AttestationPreparer()
@AllAttestationTypes
@recorded_by_proxy_async
async def test_aad_reset_policy_unsecured(self, attestation_aad_url, **kwargs):
attest_client = self.create_admin_client(attestation_aad_url)
policy_set_response, _ = await attest_client.reset_policy(
kwargs.pop("attestation_type")
)
assert None == policy_set_response.policy_token_hash
assert policy_set_response.policy_resolution == PolicyModification.REMOVED
@pytest.mark.live_test_only
@AttestationPreparer()
@AllAttestationTypes
async def test_aad_reset_policy_secured(
self,
attestation_aad_url,
attestation_policy_signing_key0,
attestation_policy_signing_certificate0,
**kwargs
):
signing_certificate = pem_from_base64(
attestation_policy_signing_certificate0, "CERTIFICATE"
)
key = pem_from_base64(attestation_policy_signing_key0, "PRIVATE KEY")
attestation_type = kwargs.pop("attestation_type", AttestationType.SGX_ENCLAVE)
attest_client = self.create_admin_client(attestation_aad_url)
policy_set_response, _ = await attest_client.reset_policy(
attestation_type,
signing_key=key,
signing_certificate=signing_certificate,
)
assert None == policy_set_response.policy_token_hash
assert policy_set_response.policy_resolution == PolicyModification.REMOVED
@pytest.mark.live_test_only
@AttestationPreparer()
@AllAttestationTypes
async def test_aad_set_policy_secured(
self,
attestation_aad_url,
attestation_policy_signing_key0,
attestation_policy_signing_certificate0,
**kwargs
):
attestation_policy = (
u"version=1.0; authorizationrules{=> permit();}; issuancerules{};"
)
signing_certificate = pem_from_base64(
attestation_policy_signing_certificate0, "CERTIFICATE"
)
key = pem_from_base64(attestation_policy_signing_key0, "PRIVATE KEY")
attest_client = self.create_admin_client(attestation_aad_url)
attestation_type = kwargs.pop("attestation_type")
policy_set_response, _ = await attest_client.set_policy(
attestation_type,
attestation_policy,
signing_key=key,
signing_certificate=signing_certificate,
)
policy, _ = await attest_client.get_policy(attestation_type)
assert policy == attestation_policy
expected_policy = AttestationPolicyToken(
attestation_policy,
signing_key=key,
signing_certificate=signing_certificate,
)
hasher = hashes.Hash(hashes.SHA256(), backend=default_backend())
hasher.update(expected_policy.to_jwt_string().encode("utf-8"))
expected_hash = hasher.finalize()
assert expected_hash == policy_set_response.policy_token_hash
@pytest.mark.live_test_only
@AttestationPreparer()
@AllAttestationTypes
async def test_isolated_set_policy_secured(
self,
attestation_isolated_url,
attestation_isolated_signing_key,
attestation_isolated_signing_certificate,
**kwargs
):
attestation_policy = (
u"version=1.0; authorizationrules{=> permit();}; issuancerules{};"
)
decoded_cert = pem_from_base64(
attestation_isolated_signing_certificate, "CERTIFICATE"
)
key = pem_from_base64(attestation_isolated_signing_key, "PRIVATE KEY")
attestation_type = kwargs.pop("attestation_type")
attest_client = self.create_admin_client(attestation_isolated_url)
policy_set_response, _ = await attest_client.set_policy(
attestation_type,
attestation_policy,
signing_key=key,
signing_certificate=decoded_cert,
)
policy, _ = await attest_client.get_policy(attestation_type)
assert policy == attestation_policy
expected_policy = AttestationPolicyToken(
attestation_policy,
signing_key=key,
signing_certificate=decoded_cert,
)
hasher = hashes.Hash(hashes.SHA256(), backend=default_backend())
hasher.update(expected_policy.to_jwt_string().encode("utf-8"))
expected_hash = hasher.finalize()
assert expected_hash == policy_set_response.policy_token_hash
@pytest.mark.live_test_only
@AttestationPreparer()
@AllAttestationTypes
async def test_isolated_reset_policy_secured(
self,
attestation_aad_url,
attestation_isolated_signing_key,
attestation_isolated_signing_certificate,
**kwargs
):
signing_certificate = pem_from_base64(
attestation_isolated_signing_certificate, "CERTIFICATE"
)
key = pem_from_base64(attestation_isolated_signing_key, "PRIVATE KEY")
attest_client = self.create_admin_client(attestation_aad_url)
policy_set_response, _ = await attest_client.reset_policy(
kwargs.pop("attestation_type"),
signing_key=key,
signing_certificate=signing_certificate,
)
assert None == policy_set_response.policy_token_hash
assert policy_set_response.policy_resolution == PolicyModification.REMOVED
async def _test_get_policy_management_certificates(
self, base_uri, pem_expected_certificate
):
# type: (str, str) -> None
admin_client = self.create_admin_client(base_uri)
policy_signers, _ = await admin_client.get_policy_management_certificates()
if pem_expected_certificate is not None:
found_cert = False
for signer in policy_signers:
# the signer is an X.509 certificate chain, look at the first certificate
# to see if it's our signing certificate.
if signer[0] == pem_expected_certificate:
found_cert = True
break
assert found_cert
else:
assert len(policy_signers) == 0
@staticmethod
def is_isolated_url(instance_url, **kwargs):
# type: (str, Any) -> bool
return instance_url == kwargs.get("attestation_isolated_url")
@pytest.mark.live_test_only
@AttestationPreparer()
@AllInstanceTypes
async def test_get_policy_management_certificates(self, **kwargs):
instance_url = kwargs.pop("instance_url")
expected_certificate = None
if self.is_isolated_url(instance_url, **kwargs):
expected_certificate = pem_from_base64(
kwargs.get("attestation_isolated_signing_certificate"), "CERTIFICATE"
)
await self._test_get_policy_management_certificates(
instance_url, expected_certificate
)
@pytest.mark.live_test_only
@AttestationPreparer()
async def test_add_remove_policy_certificate(self,**kwargs):
attestation_isolated_url = kwargs.pop("attestation_isolated_url")
attestation_isolated_signing_certificate = kwargs.pop("attestation_isolated_signing_certificate")
attestation_isolated_signing_key = kwargs.pop("attestation_isolated_signing_key")
attestation_policy_signing_key0 = kwargs.pop("attestation_policy_signing_key0")
attestation_policy_signing_certificate0 = kwargs.pop("attestation_policy_signing_certificate0")
# type: (str, str, str, str, str, str) -> None
signing_certificate = pem_from_base64(
attestation_isolated_signing_certificate, "CERTIFICATE"
)
key = pem_from_base64(attestation_isolated_signing_key, "PRIVATE KEY")
pem_certificate_to_add = pem_from_base64(
attestation_policy_signing_certificate0, "CERTIFICATE"
)
admin_client = self.create_admin_client(
attestation_isolated_url,
signing_key=key,
signing_certificate=signing_certificate,
)
# Test 0 positional parameters, should throw.
with pytest.raises(TypeError):
await admin_client.add_policy_management_certificate()
# And test more than one positional parameter. Should also throw.
with pytest.raises(TypeError):
await admin_client.add_policy_management_certificate(
pem_certificate_to_add, pem_certificate_to_add
)
# Add a new certificate.
result, _ = await admin_client.add_policy_management_certificate(
pem_certificate_to_add
)
assert result.certificate_resolution == CertificateModification.IS_PRESENT
# Add it again - this should be ok.
result, _ = await admin_client.add_policy_management_certificate(
pem_certificate_to_add
)
assert result.certificate_resolution == CertificateModification.IS_PRESENT
# Ensure that the new certificate is present.
# We'll leverage the get certificates test to validate this.
await self._test_get_policy_management_certificates(
attestation_isolated_url, pem_certificate_to_add
)
# Now remove the certificate we just added.
result, _ = await admin_client.remove_policy_management_certificate(
pem_certificate_to_add,
signing_key=key,
signing_certificate=signing_certificate,
)
assert result.certificate_resolution == CertificateModification.IS_ABSENT
# Remove it again, this should be ok.
result, _ = await admin_client.remove_policy_management_certificate(
pem_certificate_to_add,
signing_key=key,
signing_certificate=signing_certificate,
)
assert result.certificate_resolution == CertificateModification.IS_ABSENT
# The set of certificates should now just contain the original isolated certificate (PEM encoded :))
await self._test_get_policy_management_certificates(
attestation_isolated_url, signing_certificate
)
def create_admin_client(
self, base_uri, **kwargs
) -> AttestationAdministrationClient:
"""
docstring
"""
credential = self.get_credential(AttestationAdministrationClient, is_async=True)
attest_client = self.create_client_from_credential(
AttestationAdministrationClient,
credential=credential,
endpoint=base_uri,
validate_token=True,
validate_signature=True,
validate_issuer=self.is_live,
issuer=base_uri,
validate_expiration=self.is_live,
**kwargs
)
return attest_client
def shared_admin_client(
self, location_name: str
) -> AttestationAdministrationClient:
"""
docstring
"""
return self.create_admin_client(self.shared_base_uri(location_name))
@staticmethod
def shared_base_uri(location_name): # type: (str) -> str
# When run with recorded tests, the location_name may be 'None', deal with it.
# return 'https://shareduks.uks.test.attest.azure.net'
if location_name is not None:
return (
"https://shared"
+ location_name
+ "."
+ location_name
+ ".attest.azure.net"
)
return "https://sharedcus.cus.attest.azure.net"
class Base64Url:
"""Equivalent to base64.urlsafe_b64encode, but strips padding from the encoded and decoded strings."""
@staticmethod
def encode(unencoded):
# type: (bytes)->str
base64val = base64.urlsafe_b64encode(unencoded)
strip_trailing = base64val.split(b"=")[
0
] # pick the string before the trailing =
return strip_trailing.decode("utf-8")
@staticmethod
def decode(encoded):
# type: (str)->bytes
padding_added = encoded + "=" * ((len(encoded) * -1) % 4)
return base64.urlsafe_b64decode(padding_added.encode("utf-8"))
|