Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/openai/lib/azure.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,8 @@ def _auth_headers(self, security: SecurityOptions) -> dict[str, str]: # noqa: A
return {"Authorization": f"Bearer {self._azure_ad_token}"}

if self.api_key and self.api_key != API_KEY_SENTINEL:
if self.api_key.startswith("eyJ"):
return {"Authorization": f"Bearer {self.api_key}"}
Comment on lines +355 to +356
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid classifying any eyJ-prefixed key as JWT

This branch treats every api_key starting with eyJ as an Entra bearer token and moves it from api-key to Authorization, but api_key values are opaque and this prefix check is not a reliable JWT validation. In environments that pass non-JWT secrets (for example APIM subscription keys or other opaque keys) that happen to begin with eyJ, requests will now be sent with the wrong auth header and can fail with 401s. The detection should verify JWT structure/content more robustly (or be opt-in) before switching header types.

Useful? React with 👍 / 👎.

return {"api-key": self.api_key}

return {}
Expand All @@ -377,7 +379,10 @@ def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions:
if not _has_header(headers, "Authorization"):
headers["Authorization"] = f"Bearer {azure_ad_token}"
elif self.api_key and self.api_key != API_KEY_SENTINEL:
if not _has_header(headers, "api-key"):
if self.api_key.startswith("eyJ"):
if not _has_header(headers, "Authorization"):
headers["Authorization"] = f"Bearer {self.api_key}"
elif not _has_header(headers, "api-key"):
headers["api-key"] = self.api_key
elif _has_auth_header(headers) or _has_auth_header(self.default_headers):
pass
Expand Down Expand Up @@ -674,6 +679,8 @@ def _auth_headers(self, security: SecurityOptions) -> dict[str, str]: # noqa: A
return {"Authorization": f"Bearer {self._azure_ad_token}"}

if self.api_key and self.api_key != API_KEY_SENTINEL:
if self.api_key.startswith("eyJ"):
return {"Authorization": f"Bearer {self.api_key}"}
return {"api-key": self.api_key}

return {}
Expand All @@ -699,7 +706,10 @@ async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOp
if not _has_header(headers, "Authorization"):
headers["Authorization"] = f"Bearer {azure_ad_token}"
elif self.api_key and self.api_key != API_KEY_SENTINEL:
if not _has_header(headers, "api-key"):
if self.api_key.startswith("eyJ"):
if not _has_header(headers, "Authorization"):
headers["Authorization"] = f"Bearer {self.api_key}"
elif not _has_header(headers, "api-key"):
headers["api-key"] = self.api_key
elif _has_auth_header(headers) or _has_auth_header(self.default_headers):
pass
Expand Down
37 changes: 37 additions & 0 deletions tests/lib/test_azure.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,43 @@ def test_enforce_credentials_false_sync_uses_request_authorization_header(respx_
assert calls[0].request.headers.get("api-key") is None


@pytest.mark.respx()
def test_jwt_api_key_sent_as_bearer_sync(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 = AzureOpenAI(
api_version="2024-02-01",
api_key="eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.payload.signature",
azure_endpoint="https://example-resource.azure.openai.com",
)
client.chat.completions.create(messages=[], model="gpt-4")

calls = cast("list[MockRequestCall]", respx_mock.calls)
assert calls[0].request.headers.get("Authorization") == "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.payload.signature"
assert calls[0].request.headers.get("api-key") is None


@pytest.mark.asyncio
@pytest.mark.respx()
async def test_jwt_api_key_sent_as_bearer_async(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 = AsyncAzureOpenAI(
api_version="2024-02-01",
api_key="eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.payload.signature",
azure_endpoint="https://example-resource.azure.openai.com",
)
await client.chat.completions.create(messages=[], model="gpt-4")

calls = cast("list[MockRequestCall]", respx_mock.calls)
assert calls[0].request.headers.get("Authorization") == "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.payload.signature"
assert calls[0].request.headers.get("api-key") is None


def test_enforce_credentials_true_sync() -> None:
with update_env(AZURE_OPENAI_API_KEY=Omit(), AZURE_OPENAI_AD_TOKEN=Omit()):
with pytest.raises(OpenAIError, match="Missing credentials"):
Expand Down