-
Notifications
You must be signed in to change notification settings - Fork 4.8k
fix: restore Azure AD bearer token support in api_key auth #3374
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Oxygen56
wants to merge
2
commits into
openai:main
Choose a base branch
from
Oxygen56:fix/azure-ad-bearer-regression-3282
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+162
−4
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| """Tests for Azure AAD Bearer token auth behavior in ``_auth_headers``. | ||
|
|
||
| These tests cover the change introduced in PR #3374, where ``api_key`` is sent | ||
| via the ``Authorization: Bearer`` header when ``security["bearer_auth"]`` is | ||
| truthy (the Azure AD token scenario), and via the ``api-key`` header otherwise. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import cast | ||
|
|
||
| import httpx | ||
| import pytest | ||
| from respx import MockRouter | ||
| from respx.models import Call as MockRequestCall | ||
|
|
||
| from openai._models import FinalRequestOptions | ||
| from openai.lib.azure import AzureOpenAI, AsyncAzureOpenAI | ||
|
|
||
| API_KEY = "example API key" | ||
| AD_TOKEN = "example AD token" | ||
| AZURE_ENDPOINT = "https://example-resource.azure.openai.com" | ||
| API_VERSION = "2024-02-01" | ||
|
|
||
|
|
||
| def _make_sync_client(**overrides: object) -> AzureOpenAI: | ||
| kwargs: dict[str, object] = { | ||
| "api_version": API_VERSION, | ||
| "api_key": API_KEY, | ||
| "azure_endpoint": AZURE_ENDPOINT, | ||
| } | ||
| kwargs.update(overrides) | ||
| return AzureOpenAI(**kwargs) # type: ignore[arg-type] | ||
|
|
||
|
|
||
| def _make_async_client(**overrides: object) -> AsyncAzureOpenAI: | ||
| kwargs: dict[str, object] = { | ||
| "api_version": API_VERSION, | ||
| "api_key": API_KEY, | ||
| "azure_endpoint": AZURE_ENDPOINT, | ||
| } | ||
| kwargs.update(overrides) | ||
| return AsyncAzureOpenAI(**kwargs) # type: ignore[arg-type] | ||
|
|
||
|
|
||
| def test_auth_headers_with_bearer_auth_true_sends_bearer_token() -> None: | ||
| client = _make_sync_client() | ||
|
|
||
| headers = client._auth_headers({"bearer_auth": True}) | ||
|
|
||
| assert headers == {"Authorization": f"Bearer {API_KEY}"}, ( | ||
| "When bearer_auth is True the api_key must be sent via the " | ||
| f"Authorization: Bearer header, got {headers!r}" | ||
| ) | ||
| assert "api-key" not in headers, "api-key header must not be set when using Bearer auth" | ||
|
|
||
|
|
||
| def test_auth_headers_with_bearer_auth_false_sends_api_key_header() -> None: | ||
| client = _make_sync_client() | ||
|
|
||
| headers = client._auth_headers({"bearer_auth": False}) | ||
|
|
||
| assert headers == {"api-key": API_KEY}, ( | ||
| "When bearer_auth is False the api_key must be sent via the api-key " | ||
| f"header, got {headers!r}" | ||
| ) | ||
| assert "Authorization" not in headers, "Authorization header must not be set when bearer_auth is False" | ||
|
|
||
|
|
||
| def test_auth_headers_azure_ad_token_takes_priority() -> None: | ||
| client = _make_sync_client(api_key=None, azure_ad_token=AD_TOKEN) | ||
|
|
||
| # The AD token must win regardless of the bearer_auth flag. | ||
| headers_bearer_false = client._auth_headers({"bearer_auth": False}) | ||
| headers_bearer_true = client._auth_headers({"bearer_auth": True}) | ||
|
|
||
| expected = {"Authorization": f"Bearer {AD_TOKEN}"} | ||
| assert headers_bearer_false == expected, ( | ||
| "An explicit azure_ad_token must always be sent as a Bearer token, " | ||
| f"even when bearer_auth is False, got {headers_bearer_false!r}" | ||
| ) | ||
| assert headers_bearer_true == expected, ( | ||
| "An explicit azure_ad_token must always be sent as a Bearer token, " | ||
| f"got {headers_bearer_true!r}" | ||
| ) | ||
|
|
||
|
|
||
| def test_auth_headers_no_credentials_returns_empty() -> None: | ||
| client = _make_sync_client(api_key=None, _enforce_credentials=False) | ||
|
|
||
| headers = client._auth_headers({"bearer_auth": True}) | ||
|
|
||
| assert headers == {}, ( | ||
| "With neither api_key nor azure_ad_token set, no auth headers should be " | ||
| f"produced, got {headers!r}" | ||
| ) | ||
|
|
||
|
|
||
| def test_default_security_options_uses_bearer() -> None: | ||
| options = FinalRequestOptions.construct(method="post", url="/chat/completions") | ||
|
|
||
| assert options.security.get("bearer_auth") is True, ( | ||
| "The default FinalRequestOptions.security must enable bearer_auth, " | ||
| f"got {options.security!r}" | ||
| ) | ||
|
|
||
|
|
||
| def test_async_auth_headers_with_bearer_auth_true() -> None: | ||
| client = _make_async_client() | ||
|
|
||
| headers = client._auth_headers({"bearer_auth": True}) | ||
|
|
||
| assert headers == {"Authorization": f"Bearer {API_KEY}"}, ( | ||
| "The async client must also send the api_key as a Bearer token when " | ||
| f"bearer_auth is True, got {headers!r}" | ||
| ) | ||
|
|
||
|
|
||
| def test_async_auth_headers_with_bearer_auth_false() -> None: | ||
| client = _make_async_client() | ||
|
|
||
| headers = client._auth_headers({"bearer_auth": False}) | ||
|
|
||
| assert headers == {"api-key": API_KEY}, ( | ||
| "The async client must fall back to the api-key header when bearer_auth " | ||
| f"is False, got {headers!r}" | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.respx() | ||
| def test_full_request_sends_bearer_header_by_default(respx_mock: MockRouter) -> None: | ||
| respx_mock.post( | ||
| "https://example-resource.azure.openai.com/openai/deployments/gpt-4/chat/completions" | ||
| "?api-version=2024-02-01" | ||
| ).mock(return_value=httpx.Response(200, json={"model": "gpt-4"})) | ||
|
|
||
| client = _make_sync_client() | ||
| client.chat.completions.create(messages=[], model="gpt-4") | ||
|
|
||
| calls = cast("list[MockRequestCall]", respx_mock.calls) | ||
| authorization = calls[0].request.headers.get("Authorization") | ||
| assert authorization == f"Bearer {API_KEY}", ( | ||
| "By default (bearer_auth=True) a full request must carry the api_key in " | ||
| f"the Authorization: Bearer header, got {authorization!r}" | ||
| ) | ||
| assert "api-key" not in calls[0].request.headers, ( | ||
| "The api-key header must not be sent when the default Bearer auth is used" | ||
| ) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When an
AzureOpenAIclient is configured withapi_keyand calls any operation generated withsecurity={"bearer_auth": True},_prepare_options()still injects theapi-keyheader intooptions.headersbefore_build_headers()merges these auth headers. ReturningAuthorizationhere therefore sends bothAuthorization: Bearer ...andapi-key: ..., so the endpoint-level switch to bearer auth is not actually exclusive and can be rejected by Azure services that require a single auth scheme; the async override has the same issue.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Resolved — the latest commit now checks
options.security.get("bearer_auth", False)in_prepare_options()before deciding which header to inject. Whenbearer_authis True, onlyAuthorization: Beareris set and theapi-keypath is skipped entirely;_auth_headers()follows the same logic. Both the sync and async overrides are updated consistently, andtest_full_request_sends_bearer_header_by_defaultconfirms only the Bearer header is sent end-to-end.