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
5 changes: 4 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ jobs:
needs:
- flake8
- mypy
runs-on: ubuntu-latest
runs-on: ${{ matrix.os || 'ubuntu-latest' }}
strategy:
fail-fast: false
matrix:
Expand All @@ -63,6 +63,9 @@ jobs:
- '3.13'
- '3.14'
- '3.15'
include:
- python: "3.9"
os: ubuntu-24.04
steps:
- uses: actions/checkout@v7.0.1
- name: Setup Build Tools
Expand Down
65 changes: 40 additions & 25 deletions httpx_gssapi/gssapi_.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import asyncio
import re
import logging
from itertools import chain
from functools import wraps
from typing import Generator, Optional, List, Any, Union
from functools import partial, wraps
from typing import Any, AsyncGenerator, Generator, List, Optional, Union

from base64 import b64encode, b64decode

Expand All @@ -16,7 +17,9 @@
from .exceptions import MutualAuthenticationError, SPNEGOExchangeError

log = logging.getLogger(__name__)

FlowGen = Generator[Request, Response, None]
AsyncFlowGen = AsyncGenerator[Request, Response]

# Different types of mutual authentication:
# with mutual_authentication set to REQUIRED, all responses will be
Expand Down Expand Up @@ -98,8 +101,7 @@ def _gss_to_spnego_error(message: str, *args: Any, **kwargs: Any):
"""Helper function to _handle_gsserror to raise SPNEGOExchangeErrors."""
try:
request = next(
a for a in chain(args, kwargs.values())
if isinstance(a, Request)
a for a in chain(args, kwargs.values()) if isinstance(a, Request)
)
except StopIteration: # sanity check
raise RuntimeError("No request in arguments!")
Expand Down Expand Up @@ -136,14 +138,16 @@ class HTTPSPNEGOAuth(Auth):

"""

def __init__(self,
mutual_authentication: int = DISABLED,
target_name: Optional[Union[str, gssapi.Name]] = "HTTP",
delegate: bool = False,
opportunistic_auth: bool = False,
creds: Optional[gssapi.Credentials] = None,
mech: Optional[Union[bytes, gssapi.OID]] = SPNEGO,
sanitize_mutual_error_response: bool = True):
def __init__(
self,
mutual_authentication: int = DISABLED,
target_name: Optional[Union[str, gssapi.Name]] = "HTTP",
delegate: bool = False,
opportunistic_auth: bool = False,
creds: Optional[gssapi.Credentials] = None,
mech: Optional[Union[bytes, gssapi.OID]] = SPNEGO,
sanitize_mutual_error_response: bool = True,
):
self.mutual_authentication = mutual_authentication
self.target_name = target_name
self.delegate = delegate
Expand All @@ -160,11 +164,6 @@ def auth_flow(self, request: Request) -> FlowGen:
ctx = None

response = yield request
yield from self.handle_response(response, ctx)

def handle_response(self,
response: Response,
ctx: Optional[SecurityContext] = None) -> FlowGen:
num_401s = 0
while response.status_code == 401 and num_401s < 2:
num_401s += 1
Expand All @@ -189,6 +188,22 @@ def handle_response(self,

self.handle_mutual_auth(response, ctx)

async def async_auth_flow(self, request: Request) -> AsyncFlowGen:
to_thread = partial(asyncio.get_running_loop().run_in_executor, None)

flow = self.auth_flow(request)

def _send(r: Response) -> Union[Request, None]:
try:
return flow.send(r)
except StopIteration: # catch here, can't pass through Future
return None

req: Union[Request, None] = await to_thread(next, flow)
while req is not None:
resp = yield req
req = await to_thread(_send, resp)

def handle_mutual_auth(self, response: Response, ctx: SecurityContext):
"""
Handles all responses with the exception of 401s.
Expand Down Expand Up @@ -221,8 +236,10 @@ def handle_mutual_auth(self, response: Response, ctx: SecurityContext):
" on %d response",
response.status_code,
)
if (self.mutual_authentication == REQUIRED
and self.sanitize_mutual_error_response):
if (
self.mutual_authentication == REQUIRED
and self.sanitize_mutual_error_response
):
_sanitize_response(response)
else:
# Unable to attempt mutual authentication when mutual auth is
Expand All @@ -232,9 +249,9 @@ def handle_mutual_auth(self, response: Response, ctx: SecurityContext):
raise MutualAuthenticationError(response=response)

@_handle_gsserror(gss_stage='stepping', result=_gss_to_spnego_error)
def set_auth_header(self,
request: Request,
response: Optional[Response] = None) -> SecurityContext:
def set_auth_header(
self, request: Request, response: Optional[Response] = None
) -> SecurityContext:
"""
Create a new security context, generate the GSSAPI authentication
token, and insert it into the request header. The new security context
Expand All @@ -257,9 +274,7 @@ def set_auth_header(self,
return ctx

@_handle_gsserror(gss_stage="stepping", result=False)
def authenticate_server(self,
response: Response,
ctx: SecurityContext) -> bool:
def authenticate_server(self, response: Response, ctx: SecurityContext) -> bool:
"""
Uses GSSAPI to authenticate the server by extracting the negotiate
value from the response and stepping the security context.
Expand Down
117 changes: 95 additions & 22 deletions tests/test_mocked.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
#!/usr/bin/env python
"""Tests for httpx_gssapi."""

import asyncio
import logging
import threading
from base64 import b64encode
from typing import Union
from unittest.mock import Mock, patch

import pytest
Expand All @@ -14,6 +17,7 @@

import httpx_gssapi
from httpx_gssapi import REQUIRED, OPTIONAL
from httpx_gssapi.gssapi_ import FlowGen

logging.basicConfig()

Expand Down Expand Up @@ -179,9 +183,9 @@ def test_handle_response_200(patched_ctx):

auth = httpx_gssapi.HTTPSPNEGOAuth(mutual_authentication=REQUIRED)

flow = auth.handle_response(response_ok, gssapi.SecurityContext())
flow = _init_sync_flow(auth, response_ok, gssapi.SecurityContext())
with pytest.raises(StopIteration): # No other requests required
next(flow)
flow.send(response_ok)
fake_resp.assert_called_with(b"servertoken")


Expand All @@ -190,9 +194,9 @@ def test_handle_response_200_mutual_auth_required_failure(patched_ctx_fail):

auth = httpx_gssapi.HTTPSPNEGOAuth(mutual_authentication=REQUIRED)

flow = auth.handle_response(response_ok, gssapi.SecurityContext())
flow = _init_sync_flow(auth, response_ok, gssapi.SecurityContext())
with pytest.raises(httpx_gssapi.MutualAuthenticationError):
next(flow)
flow.send(response_ok)

assert not fail_resp.called

Expand All @@ -205,9 +209,9 @@ def test_handle_response_200_mutual_auth_required_failure_2(patched_ctx_fail):

auth = httpx_gssapi.HTTPSPNEGOAuth(mutual_authentication=REQUIRED)

flow = auth.handle_response(response_ok, gssapi.SecurityContext())
flow = _init_sync_flow(auth, response_ok, gssapi.SecurityContext())
with pytest.raises(httpx_gssapi.MutualAuthenticationError):
next(flow)
flow.send(response_ok)

fail_resp.assert_called_with(b"servertoken")

Expand All @@ -220,9 +224,9 @@ def test_handle_response_200_mutual_auth_optional_hard_fail(patched_ctx_fail):

auth = httpx_gssapi.HTTPSPNEGOAuth(mutual_authentication=OPTIONAL)

flow = auth.handle_response(response_ok, gssapi.SecurityContext())
flow = _init_sync_flow(auth, response_ok, gssapi.SecurityContext())
with pytest.raises(httpx_gssapi.MutualAuthenticationError):
next(flow)
flow.send(response_ok)

fail_resp.assert_called_with(b"servertoken")

Expand All @@ -233,9 +237,9 @@ def test_handle_response_200_mutual_auth_optional_soft_failure(patched_ctx):
auth = httpx_gssapi.HTTPSPNEGOAuth(mutual_authentication=OPTIONAL)
auth.context = {"www.example.org": gssapi.SecurityContext}

flow = auth.handle_response(response_ok)
flow = _init_sync_flow(auth, response_ok)
with pytest.raises(StopIteration): # advance flow with no new requests
next(flow)
flow.send(response_ok)

assert not fake_resp.called

Expand All @@ -249,9 +253,9 @@ def test_handle_response_500_mutual_auth_required_failure(patched_ctx_fail):

auth = httpx_gssapi.HTTPSPNEGOAuth(mutual_authentication=REQUIRED)

flow = auth.handle_response(response_500, gssapi.SecurityContext())
flow = _init_sync_flow(auth, response_500, gssapi.SecurityContext())
with pytest.raises(StopIteration): # advance flow with no new requests
next(flow)
flow.send(response_500)

assert 'other' not in response_500.headers
assert response_500.headers['date'] == 'DATE'
Expand All @@ -274,9 +278,9 @@ def test_handle_response_500_mutual_auth_required_fail_no_san(patched_ctx_fail):
)
auth.context = {"www.example.org": "CTX"}

flow = auth.handle_response(response_500)
flow = _init_sync_flow(auth, response_500)
with pytest.raises(StopIteration): # advance flow with no new requests
next(flow)
flow.send(response_500)

assert response_500.headers['other'] == 'x'
assert response_500.headers['date'] == 'DATE'
Expand All @@ -296,9 +300,9 @@ def test_handle_response_500_mutual_auth_optional_failure(patched_ctx_fail):
auth = httpx_gssapi.HTTPSPNEGOAuth(mutual_authentication=OPTIONAL)
auth.context = {"www.example.org": "CTX"}

flow = auth.handle_response(response_500)
flow = _init_sync_flow(auth, response_500)
with pytest.raises(StopIteration): # advance flow with no new requests
next(flow)
flow.send(response_500)

assert response_500.headers['other'] == 'x'
assert response_500.headers['date'] == 'DATE'
Expand All @@ -311,8 +315,8 @@ def test_handle_response_500_mutual_auth_optional_failure(patched_ctx_fail):
def test_handle_response_401(patched_ctx):
auth = httpx_gssapi.HTTPSPNEGOAuth()
response_401 = null_response(status=401, headers=neg_token)
flow = auth.handle_response(response_401)
request = next(flow)
flow = _init_sync_flow(auth, response_401)
request = flow.send(response_401)
assert isinstance(request, httpx.Request)
assert request.headers['Authorization'] == b64_negotiate_response
response_ok = null_response(headers=neg_server, request=request)
Expand All @@ -327,9 +331,9 @@ def test_handle_response_401_rejected(patched_ctx):
# Ensure there is no infinite auth loop.
auth = httpx_gssapi.HTTPSPNEGOAuth()
response_401 = null_response(status=401, headers=neg_token)
flow = auth.handle_response(response_401)
flow = _init_sync_flow(auth, response_401)

request = next(flow)
request = flow.send(response_401)
assert isinstance(request, httpx.Request)
assert request.headers['Authorization'] == b64_negotiate_response

Expand All @@ -347,8 +351,8 @@ def test_handle_response_401_rejected(patched_ctx):
def test_delegation(patched_ctx):
auth = httpx_gssapi.HTTPSPNEGOAuth(delegate=True)
response_401 = null_response(status=401, headers=neg_token)
flow = auth.handle_response(response_401)
request = next(flow)
flow = _init_sync_flow(auth, response_401)
request = flow.send(response_401)
assert isinstance(request, httpx.Request)
assert request.headers['Authorization'] == b64_negotiate_response
response_ok = null_response(headers=neg_server, request=request)
Expand All @@ -370,6 +374,57 @@ def test_opportunistic_auth(patched_ctx):
assert request.headers.get('Authorization') == b64_negotiate_response


def test_async_auth_flow_offloads_gssapi_work():
auth = httpx_gssapi.HTTPSPNEGOAuth(opportunistic_auth=True)
event_loop_thread = threading.get_ident()
gssapi_thread = None

def set_auth_header(request, response=None):
nonlocal gssapi_thread
gssapi_thread = threading.get_ident()
request.headers['Authorization'] = b64_negotiate_response
return object()

async def request():
transport = httpx.MockTransport(
lambda request: httpx.Response(200, request=request)
)
with patch.object(auth, 'set_auth_header', side_effect=set_auth_header):
async with httpx.AsyncClient(auth=auth, transport=transport) as client:
response = await client.get('http://www.example.org/')
assert response.status_code == 200

asyncio.run(request())
assert gssapi_thread is not None
assert gssapi_thread != event_loop_thread


def test_async_auth_flow_handles_negotiate_challenge(patched_ctx):
auth = httpx_gssapi.HTTPSPNEGOAuth()
request_count = 0

def transport(request):
nonlocal request_count
request_count += 1
if request_count == 1:
return httpx.Response(401, headers=neg_token, request=request)
assert request.headers['Authorization'] == b64_negotiate_response
return httpx.Response(200, request=request)

async def request():
async with httpx.AsyncClient(
auth=auth,
transport=httpx.MockTransport(transport),
) as client:
response = await client.get('http://www.example.org/')
assert response.status_code == 200

asyncio.run(request())
assert request_count == 2
check_init()
fake_resp.assert_called_with(b'token')


def test_explicit_creds(patched_creds, patched_ctx):
response = null_response(headers=neg_token)
creds = gssapi.Credentials()
Expand Down Expand Up @@ -406,5 +461,23 @@ def test_os_default_mech(patched_ctx):
fake_resp.assert_called_with(b"token")


def _init_sync_flow(
auth: httpx_gssapi.HTTPSPNEGOAuth,
resp: httpx.Response,
ctx: Union[gssapi.SecurityContext, None] = None,
) -> FlowGen:
if ctx:
auth.set_auth_header = lambda *_: gssapi.SecurityContext()
auth.opportunistic_auth = True

flow = auth.auth_flow(resp.request)
assert next(flow) is resp.request

if ctx:
del auth.set_auth_header

return flow


if __name__ == '__main__':
pytest.main()