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
|
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for
# license information.
# -------------------------------------------------------------------------
from unittest.mock import Mock
from azure.core.credentials import AccessToken
from azure.core.exceptions import ClientAuthenticationError
from azure.core.pipeline import AsyncPipeline
from azure.core.pipeline.transport import HttpRequest as PipelineTransportHttpRequest
from azure.data.tables.aio import TableServiceClient
from azure.data.tables.aio._authentication_async import AsyncBearerTokenChallengePolicy
import pytest
from async_preparers import tables_decorator_async
from devtools_testutils import AzureRecordedTestCase, is_live
from devtools_testutils.aio import recorded_by_proxy_async
from _shared.asynctestcase import AsyncTableTestCase
pytestmark = pytest.mark.asyncio
# Try to use azure.core.rest request if azure-core version supports it -- fall back to basic request
try:
from azure.core.rest import HttpRequest as RestHttpRequest
HTTP_REQUESTS = [PipelineTransportHttpRequest, RestHttpRequest]
except ModuleNotFoundError:
HTTP_REQUESTS = [PipelineTransportHttpRequest]
class TestTableChallengeAuthAsync(AzureRecordedTestCase, AsyncTableTestCase):
@tables_decorator_async
@recorded_by_proxy_async
async def test_challenge_auth_supported_version(self, tables_storage_account_name):
"""This test requires a client that uses an API version that supports 401 challenge responses.
Recorded using an incorrect tenant for the credential provided to our client. To run this live, ensure that the
service principal used for testing is enabled for multitenant authentication
(https://learn.microsoft.com/azure/active-directory/develop/howto-convert-app-to-be-multi-tenant). Set the
TABLES_TENANT_ID environment variable to a different, existing tenant than the one the storage account exists
in, and set CHALLENGE_TABLES_TENANT_ID to the tenant that the storage account exists in.
"""
if is_live():
pytest.skip("Playback testing and live manual testing only")
account_url = self.account_url(tables_storage_account_name, "table")
client = TableServiceClient(
credential=self.get_token_credential(), endpoint=account_url, api_version="2020-12-06"
)
stats = await client.get_service_stats()
self._assert_stats_default(stats)
@tables_decorator_async
@recorded_by_proxy_async
async def test_challenge_auth_unsupported_version(self, tables_storage_account_name):
"""This test requires a client that uses an API version that doesn't support 401 challenge responses.
Recorded using an incorrect tenant for the credential provided to our client. To run this live, ensure that the
service principal used for testing is enabled for multitenant authentication
(https://learn.microsoft.com/azure/active-directory/develop/howto-convert-app-to-be-multi-tenant). Set the
TABLES_TENANT_ID environment variable to a different, existing tenant than the one the storage account exists
in, and set CHALLENGE_TABLES_TENANT_ID to the tenant that the storage account exists in.
"""
if is_live():
pytest.skip("Playback testing and live manual testing only")
account_url = self.account_url(tables_storage_account_name, "table")
client = TableServiceClient(
credential=self.get_token_credential(), endpoint=account_url, api_version="2019-07-07"
)
# Our request fails because of the invalid token, prompting a 403 response
with pytest.raises(ClientAuthenticationError) as e:
await client.get_service_stats()
@pytest.mark.parametrize("http_request", HTTP_REQUESTS)
async def test_challenge_policy_uses_scopes_and_tenant(http_request):
"""The policy's token requests should pass the parsed scope and tenant ID from the challenge"""
async def test_with_challenge(challenge, expected_scope, expected_tenant):
expected_token = "expected_token"
class Requests:
count = 0
class TokenRequests:
count = 0
async def send(request):
Requests.count += 1
if Requests.count == 1:
# first request triggers a 401 response w/ auth challenge
return challenge
elif Requests.count == 2:
# second request should be authorized according to challenge and have the expected content
assert expected_token in request.headers["Authorization"]
return Mock(status_code=200)
raise ValueError("unexpected request")
async def get_token(*scopes, **kwargs):
assert len(scopes) == 1
TokenRequests.count += 1
if TokenRequests.count == 1:
# first request uses the scope given to the policy, and no tenant ID
assert scopes[0] != expected_scope
assert kwargs.get("tenant_id") is None
elif TokenRequests.count == 2:
# second request should use the scope and tenant ID specified in the auth challenge
assert scopes[0] == expected_scope
assert kwargs.get("tenant_id") == expected_tenant
else:
raise ValueError("unexpected token request")
return AccessToken(expected_token, 0)
credential = Mock(spec_set=["get_token"], get_token=Mock(wraps=get_token))
policy = AsyncBearerTokenChallengePolicy(credential, "scope")
pipeline = AsyncPipeline(policies=[policy], transport=Mock(send=send))
await pipeline.run(http_request("GET", "https://localhost"))
tenant = "tenant-id"
endpoint = f"https://authority.net/{tenant}/oauth2/authorize"
resource = "https://challenge.resource"
scope = f"{resource}/.default"
# this challenge separates the authorization server and resource with commas in the WWW-Authenticate header
challenge_with_commas = Mock(
status_code=401,
headers={"WWW-Authenticate": f'Bearer authorization="{endpoint}", resource="{resource}"'},
)
await test_with_challenge(challenge_with_commas, scope, tenant)
# this challenge separates the authorization server and resource with only spaces in the WWW-Authenticate header
challenge_without_commas = Mock(
status_code=401,
headers={"WWW-Authenticate": f"Bearer authorization={endpoint} resource={resource}"},
)
await test_with_challenge(challenge_without_commas, scope, tenant)
# this challenge gives an AADv2 scope, ending with "/.default", instead of an AADv1 resource
challenge_with_scope = Mock(
status_code=401,
headers={"WWW-Authenticate": f"Bearer authorization={endpoint} scope={scope}"},
)
await test_with_challenge(challenge_with_scope, scope, tenant)
@pytest.mark.parametrize("http_request", HTTP_REQUESTS)
async def test_challenge_policy_disable_tenant_discovery(http_request):
"""The policy's token requests should exclude the challenge's tenant if requested"""
async def test_with_challenge(challenge, challenge_scope):
bad_token = "bad_token"
class Requests:
count = 0
class TokenRequests:
count = 0
async def send(request):
Requests.count += 1
if Requests.count == 1:
# first request triggers a 401 response w/ auth challenge
assert bad_token in request.headers["Authorization"]
return challenge
elif Requests.count == 2:
# second request should still be unauthorized because we didn't authenticate in the correct tenant
assert bad_token in request.headers["Authorization"]
return challenge
raise ValueError("unexpected request")
async def get_token(*scopes, **kwargs):
assert len(scopes) == 1
TokenRequests.count += 1
if TokenRequests.count == 1:
# first request uses the scope given to the policy, and no tenant ID
assert scopes[0] != challenge_scope
assert kwargs.get("tenant_id") is None
return AccessToken(bad_token, 0)
elif TokenRequests.count == 2:
# second request should use the scope specified in the auth challenge, but not the tenant
assert scopes[0] == challenge_scope
assert kwargs.get("tenant_id") is None
return AccessToken(bad_token, 0)
raise ValueError("unexpected token request")
credential = Mock(spec_set=["get_token"], get_token=Mock(wraps=get_token))
policy = AsyncBearerTokenChallengePolicy(credential, "scope", discover_tenant=False)
pipeline = AsyncPipeline(policies=[policy], transport=Mock(send=send))
await pipeline.run(http_request("GET", "https://localhost"))
tenant = "tenant-id"
endpoint = f"https://authority.net/{tenant}/oauth2/authorize"
resource = "https://challenge.resource"
scope = f"{resource}/.default"
# this challenge separates the authorization server and resource with commas in the WWW-Authenticate header
challenge_with_commas = Mock(
status_code=401,
headers={"WWW-Authenticate": f'Bearer authorization="{endpoint}", resource="{resource}"'},
)
# the request should fail after the challenge because we don't use the correct tenant
# after the second 4xx response, the policy should raise the authentication error
await test_with_challenge(challenge_with_commas, scope)
@pytest.mark.parametrize("http_request", HTTP_REQUESTS)
async def test_challenge_policy_disable_scopes_discovery(http_request):
"""The policy's token requests should exclude the challenge's scope if requested"""
async def test_with_challenge(challenge, challenge_scope, challenge_tenant):
bad_token = "bad_token"
class Requests:
count = 0
class TokenRequests:
count = 0
async def send(request):
Requests.count += 1
if Requests.count == 1:
# first request triggers a 401 response w/ auth challenge
assert bad_token in request.headers["Authorization"]
return challenge
elif Requests.count == 2:
# second request should still be unauthorized because we didn't authenticate with the correct scope
assert bad_token in request.headers["Authorization"]
return challenge
raise ValueError("unexpected request")
async def get_token(*scopes, **kwargs):
assert len(scopes) == 1
TokenRequests.count += 1
if TokenRequests.count == 1:
# first request uses the scope given to the policy, and no tenant ID
assert scopes[0] != challenge_scope
assert kwargs.get("tenant_id") is None
return AccessToken(bad_token, 0)
elif TokenRequests.count == 2:
# second request should use the tenant specified in the auth challenge, but not the scope
assert scopes[0] != challenge_scope
assert kwargs.get("tenant_id") == challenge_tenant
return AccessToken(bad_token, 0)
raise ValueError("unexpected token request")
credential = Mock(spec_set=["get_token"], get_token=Mock(wraps=get_token))
policy = AsyncBearerTokenChallengePolicy(credential, ["scope1", "scope2"], discover_scopes=False)
pipeline = AsyncPipeline(policies=[policy], transport=Mock(send=send))
await pipeline.run(http_request("GET", "https://localhost"))
tenant = "tenant-id"
endpoint = f"https://authority.net/{tenant}/oauth2/authorize"
resource = "https://challenge.resource"
scope = f"{resource}/.default"
# this challenge separates the authorization server and resource with commas in the WWW-Authenticate header
challenge_with_commas = Mock(
status_code=401,
headers={"WWW-Authenticate": f'Bearer authorization="{endpoint}", resource="{resource}"'},
)
# the request should fail after the challenge because we don't use the correct scope
# after the second 4xx response, the policy should raise the authentication error
await test_with_challenge(challenge_with_commas, scope, tenant)
@pytest.mark.parametrize("http_request", HTTP_REQUESTS)
async def test_challenge_policy_disable_any_discovery(http_request):
"""The policy shouldn't respond to the challenge if it can't use the provided scope or tenant"""
async def test_with_challenge(challenge, challenge_scope, challenge_tenant):
bad_token = "bad_token"
class Requests:
count = 0
class TokenRequests:
count = 0
async def send(request):
Requests.count += 1
if Requests.count == 1:
# first request triggers a 401 response w/ auth challenge
assert bad_token in request.headers["Authorization"]
return challenge
raise ValueError("unexpected request")
async def get_token(*scopes, **kwargs):
assert len(scopes) == 1
TokenRequests.count += 1
if TokenRequests.count == 1:
# first request uses the scope given to the policy, and no tenant ID
assert scopes[0] != challenge_scope
assert kwargs.get("tenant_id") is None
return AccessToken(bad_token, 0)
raise ValueError("unexpected token request")
credential = Mock(spec_set=["get_token"], get_token=Mock(wraps=get_token))
policy = AsyncBearerTokenChallengePolicy(
credential, ["scope1", "scope2"], discover_tenant=False, discover_scopes=False
)
pipeline = AsyncPipeline(policies=[policy], transport=Mock(send=send))
await pipeline.run(http_request("GET", "https://localhost"))
tenant = "tenant-id"
endpoint = f"https://authority.net/{tenant}/oauth2/authorize"
resource = "https://challenge.resource"
scope = f"{resource}/.default"
# this challenge separates the authorization server and resource with commas in the WWW-Authenticate header
challenge_with_commas = Mock(
status_code=401,
headers={"WWW-Authenticate": f'Bearer authorization="{endpoint}", resource="{resource}"'},
)
# the policy should only send one request since we can't update our request per the challenge response
await test_with_challenge(challenge_with_commas, scope, tenant)
@pytest.mark.parametrize("http_request", HTTP_REQUESTS)
async def test_challenge_policy_no_scope_in_challenge(http_request):
"""The policy's token requests should use constructor scopes if none are in the challenge"""
async def test_with_challenge(challenge, challenge_scope, challenge_tenant):
bad_token = "bad_token"
class Requests:
count = 0
class TokenRequests:
count = 0
async def send(request):
Requests.count += 1
if Requests.count == 1:
# first request triggers a 401 response w/ auth challenge
assert bad_token in request.headers["Authorization"]
return challenge
elif Requests.count == 2:
# second request should still be unauthorized because we didn't authenticate with the correct scope
assert bad_token in request.headers["Authorization"]
return challenge
raise ValueError("unexpected request")
async def get_token(*scopes, **kwargs):
assert len(scopes) == 1
TokenRequests.count += 1
if TokenRequests.count == 1:
# first request uses the scope given to the policy, and no tenant ID
assert scopes[0] != challenge_scope
assert kwargs.get("tenant_id") is None
return AccessToken(bad_token, 0)
elif TokenRequests.count == 2:
# second request should use the tenant specified in the auth challenge, and same scope as before
assert scopes[0] != challenge_scope
assert kwargs.get("tenant_id") == challenge_tenant
return AccessToken(bad_token, 0)
raise ValueError("unexpected token request")
credential = Mock(spec_set=["get_token"], get_token=Mock(wraps=get_token))
policy = AsyncBearerTokenChallengePolicy(credential, "scope")
pipeline = AsyncPipeline(policies=[policy], transport=Mock(send=send))
await pipeline.run(http_request("GET", "https://localhost"))
tenant = "tenant-id"
endpoint = f"https://authority.net/{tenant}/oauth2/authorize"
resource = "https://challenge.resource"
scope = f"{resource}/.default"
# this challenge has no `resource` or `scope` field
challenge_with_commas = Mock(
status_code=401,
headers={"WWW-Authenticate": f'Bearer authorization="{endpoint}"'},
)
# the request should fail after the challenge because we don't use the correct scope
# after the second 4xx response, the policy should raise the authentication error
await test_with_challenge(challenge_with_commas, scope, tenant)
|