Skip to content

Commit c726f98

Browse files
committed
feat(auth): add alpha OAuth2 client credentials support
1 parent 4a307b6 commit c726f98

35 files changed

Lines changed: 2269 additions & 172 deletions

File tree

‎aws_lambda_powertools/utilities/auth_alpha/__init__.py‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,21 @@
66
from typing import TYPE_CHECKING
77

88
if TYPE_CHECKING:
9+
from aws_lambda_powertools.utilities.auth_alpha.exceptions import AuthFailureReason as AuthFailureReason
910
from aws_lambda_powertools.utilities.auth_alpha.jwt import AuthErrorContext as AuthErrorContext
10-
from aws_lambda_powertools.utilities.auth_alpha.jwt import AuthFailureReason as AuthFailureReason
1111
from aws_lambda_powertools.utilities.auth_alpha.jwt import JWTVerifier as JWTVerifier
12+
from aws_lambda_powertools.utilities.auth_alpha.oauth2 import OAuth2Client as OAuth2Client
1213

13-
__all__ = ["AuthErrorContext", "AuthFailureReason", "JWTVerifier"]
14+
__all__ = ["AuthErrorContext", "AuthFailureReason", "JWTVerifier", "OAuth2Client"]
1415

1516

1617
def __getattr__(name: str) -> object:
17-
modules = {"AuthErrorContext": "jwt", "AuthFailureReason": "jwt", "JWTVerifier": "jwt"}
18+
modules = {
19+
"AuthErrorContext": "jwt",
20+
"AuthFailureReason": "exceptions",
21+
"JWTVerifier": "jwt",
22+
"OAuth2Client": "oauth2",
23+
}
1824
if name in modules:
1925
value = getattr(importlib.import_module(f"{__name__}.{modules[name]}"), name)
2026
globals()[name] = value
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from __future__ import annotations
2+
3+
from functools import wraps
4+
from typing import TYPE_CHECKING, ParamSpec, TypeVar
5+
6+
from aws_lambda_powertools.utilities.auth_alpha.exceptions import AuthError
7+
8+
if TYPE_CHECKING:
9+
from collections.abc import Callable
10+
11+
_P = ParamSpec("_P")
12+
_T = TypeVar("_T")
13+
14+
15+
def sanitize_errors(operation: Callable[_P, _T]) -> Callable[_P, _T]:
16+
"""Detach provider exceptions before an Auth error leaves a public operation."""
17+
18+
@wraps(operation)
19+
def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T:
20+
try:
21+
return operation(*args, **kwargs)
22+
except AuthError as error:
23+
# `raise ... from None` only suppresses display of the context.
24+
# Clear both references and use a bare re-raise so Python does not
25+
# attach the active exception again.
26+
error.__context__ = None
27+
error.__cause__ = None
28+
raise
29+
30+
return wrapper
Lines changed: 88 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,22 @@
11
from __future__ import annotations
22

33
import json
4-
from typing import TYPE_CHECKING, Any
4+
from typing import TYPE_CHECKING, Any, cast
55

66
import urllib3
7-
from urllib3.connection import HTTPConnection
7+
from urllib3.poolmanager import pool_classes_by_scheme
88

99
from aws_lambda_powertools.utilities.auth_alpha._internal.deadline import Deadline, RequestError
10+
from aws_lambda_powertools.utilities.auth_alpha._internal.transport import (
11+
DeadlineHTTPSConnectionPool,
12+
response_deadline,
13+
)
1014

1115
if TYPE_CHECKING:
1216
from collections.abc import Mapping
1317

18+
from urllib3.connectionpool import HTTPConnectionPool
19+
1420
_MAX_JSON_BYTES = 1024 * 1024
1521

1622

@@ -19,6 +25,27 @@ class HTTPClient:
1925

2026
def __init__(self) -> None:
2127
self.pool = urllib3.PoolManager(cert_reqs="CERT_REQUIRED")
28+
self.pool.pool_classes_by_scheme = pool_classes_by_scheme.copy()
29+
pool_classes = cast("dict[str, type[HTTPConnectionPool]]", self.pool.pool_classes_by_scheme)
30+
pool_classes["https"] = DeadlineHTTPSConnectionPool
31+
32+
def _open_response(
33+
self,
34+
method: str,
35+
url: str,
36+
deadline: Deadline,
37+
**options: Any,
38+
) -> urllib3.response.BaseHTTPResponse:
39+
with response_deadline(deadline):
40+
return self.pool.request(
41+
method,
42+
url,
43+
timeout=urllib3.Timeout(total=deadline.remaining()),
44+
retries=False,
45+
redirect=False,
46+
preload_content=False,
47+
**options,
48+
)
2249

2350
def json_request(
2451
self,
@@ -31,15 +58,12 @@ def json_request(
3158
) -> tuple[int, dict[str, Any]]:
3259
response = None
3360
try:
34-
response = self.pool.request(
61+
response = self._open_response(
3562
method,
3663
url,
64+
deadline,
3765
body=body,
3866
headers=headers,
39-
timeout=urllib3.Timeout(total=deadline.remaining()),
40-
retries=False,
41-
redirect=False,
42-
preload_content=False,
4367
)
4468
if response.status != 200:
4569
deadline.remaining()
@@ -55,23 +79,67 @@ def json_request(
5579

5680
@staticmethod
5781
def _read_json(response: urllib3.response.BaseHTTPResponse, deadline: Deadline) -> dict[str, Any]:
82+
content = HTTPClient._read_body(response, deadline, limit=_MAX_JSON_BYTES, decode_content=False)
83+
try:
84+
data = json.loads(content)
85+
except (ValueError, UnicodeError, RecursionError):
86+
raise RequestError() from None
87+
if not isinstance(data, dict):
88+
raise RequestError()
89+
return data
90+
91+
def request(
92+
self,
93+
method: str,
94+
url: str,
95+
deadline: Deadline,
96+
*,
97+
headers: Mapping[str, str],
98+
**options: Any,
99+
) -> urllib3.response.HTTPResponse:
100+
"""Buffer an authenticated response within one network time budget."""
101+
response = None
102+
try:
103+
response = self._open_response(
104+
method,
105+
url,
106+
deadline,
107+
headers=headers,
108+
**options,
109+
)
110+
content = self._read_body(response, deadline)
111+
return urllib3.HTTPResponse(
112+
body=content,
113+
status=response.status,
114+
headers=response.headers,
115+
reason=response.reason,
116+
version=response.version,
117+
request_method=method,
118+
request_url=url,
119+
decode_content=False,
120+
)
121+
finally:
122+
if response is not None:
123+
response.close()
124+
response.release_conn()
125+
126+
@staticmethod
127+
def _read_body(
128+
response: urllib3.response.BaseHTTPResponse,
129+
deadline: Deadline,
130+
*,
131+
limit: int | None = None,
132+
decode_content: bool = True,
133+
) -> bytes:
58134
chunks = bytearray()
59135
while True:
60-
remaining = deadline.remaining()
61-
connection = response.connection
62-
if isinstance(connection, HTTPConnection) and connection.sock is not None:
63-
connection.sock.settimeout(remaining)
64-
chunk = response.read1(min(65536, _MAX_JSON_BYTES + 1 - len(chunks)), decode_content=False)
136+
deadline.remaining()
137+
size = 65536 if limit is None else min(65536, limit + 1 - len(chunks))
138+
chunk = response.read1(size, decode_content=decode_content)
65139
deadline.remaining()
66140
if not chunk:
67141
break
68142
chunks.extend(chunk)
69-
if len(chunks) > _MAX_JSON_BYTES:
143+
if limit is not None and len(chunks) > limit:
70144
raise RequestError()
71-
try:
72-
data = json.loads(chunks)
73-
except (ValueError, UnicodeError, RecursionError):
74-
raise RequestError() from None
75-
if not isinstance(data, dict):
76-
raise RequestError()
77-
return data
145+
return bytes(chunks)
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from __future__ import annotations
2+
3+
from aws_lambda_powertools.utilities.auth_alpha._internal.validation import string_list
4+
5+
6+
def valid_scope(value: str) -> bool:
7+
return bool(value) and all(33 <= ord(character) <= 126 and character not in {'"', "\\"} for character in value)
8+
9+
10+
def required_scopes(scopes: list[str] | None) -> tuple[str, ...]:
11+
values = string_list(scopes if scopes is not None else [])
12+
if not all(valid_scope(value) for value in values):
13+
raise ValueError("Scopes must be valid OAuth scope tokens")
14+
return values
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
from __future__ import annotations
2+
3+
from contextlib import contextmanager
4+
from contextvars import ContextVar
5+
from http.client import HTTPResponse
6+
from io import BufferedReader, RawIOBase
7+
from typing import TYPE_CHECKING
8+
9+
from urllib3.connection import HTTPSConnection
10+
from urllib3.connectionpool import HTTPSConnectionPool
11+
12+
if TYPE_CHECKING:
13+
from collections.abc import Iterator
14+
from socket import socket
15+
from typing import Protocol
16+
17+
from typing_extensions import Buffer
18+
19+
from aws_lambda_powertools.utilities.auth_alpha._internal.deadline import Deadline
20+
21+
class _ResponseStream(Protocol):
22+
def readinto1(self, buffer: Buffer, /) -> int: ...
23+
def close(self) -> None: ...
24+
25+
26+
_current_deadline: ContextVar[Deadline] = ContextVar("auth_response_deadline")
27+
28+
29+
@contextmanager
30+
def response_deadline(deadline: Deadline) -> Iterator[None]:
31+
"""Pass the operation's deadline to responses created by this synchronous call."""
32+
token = _current_deadline.set(deadline)
33+
try:
34+
yield
35+
finally:
36+
_current_deadline.reset(token)
37+
38+
39+
class _DeadlineReader(RawIOBase):
40+
"""Check the original budget on every refill, including HTTP framing reads."""
41+
42+
def __init__(self, stream: _ResponseStream, sock: socket, deadline: Deadline) -> None:
43+
super().__init__()
44+
self._stream = stream
45+
self._socket = sock
46+
self._deadline = deadline
47+
48+
def readable(self) -> bool:
49+
return True
50+
51+
def readinto(self, buffer: Buffer, /) -> int:
52+
self._socket.settimeout(self._deadline.remaining())
53+
# Unlike readinto(), readinto1() performs at most one underlying read.
54+
count = self._stream.readinto1(buffer)
55+
self._deadline.remaining()
56+
return count
57+
58+
def close(self) -> None:
59+
try:
60+
self._stream.close()
61+
finally:
62+
super().close()
63+
64+
65+
class _DeadlineResponse(HTTPResponse):
66+
def __init__(
67+
self,
68+
sock: socket,
69+
debuglevel: int = 0,
70+
method: str | None = None,
71+
url: str | None = None,
72+
) -> None:
73+
deadline = _current_deadline.get()
74+
super().__init__(sock, debuglevel=debuglevel, method=method, url=url)
75+
# Retain the wrapper through body consumption: read1() can also parse
76+
# chunk-size lines, delimiters and trailers before returning to our loop.
77+
# The stream owns the socket reference even for Connection: close.
78+
self.fp = BufferedReader(_DeadlineReader(self.fp, sock, deadline), buffer_size=8192)
79+
80+
81+
class _DeadlineHTTPSConnection(HTTPSConnection):
82+
response_class = _DeadlineResponse
83+
84+
85+
class DeadlineHTTPSConnectionPool(HTTPSConnectionPool):
86+
"""Use the stdlib response hook without overriding urllib3's request machinery."""
87+
88+
ConnectionCls = _DeadlineHTTPSConnection
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""Credential-free errors raised by the Auth utility."""
2+
3+
from enum import Enum
4+
5+
6+
class AuthFailureReason(str, Enum):
7+
"""Stable, credential-free reasons suitable for application logs and metrics."""
8+
9+
MISSING_TOKEN = "missing_token" # nosec B105
10+
INVALID_TOKEN = "invalid_token" # nosec B105
11+
INVALID_CLAIMS = "invalid_claims"
12+
TOKEN_EXPIRED = "token_expired" # nosec B105
13+
INVALID_SIGNATURE = "invalid_signature"
14+
INSUFFICIENT_SCOPE = "insufficient_scope"
15+
FORBIDDEN = "forbidden"
16+
JWKS_UNAVAILABLE = "jwks_unavailable"
17+
TOKEN_EXCHANGE_FAILED = "token_exchange_failed" # nosec B105
18+
DOWNSTREAM_REQUEST_FAILED = "downstream_request_failed"
19+
20+
21+
class AuthError(Exception):
22+
"""Base error with a fixed message that never includes credential material."""
23+
24+
message = "Authentication failed"
25+
reason = AuthFailureReason.INVALID_TOKEN
26+
retryable = False
27+
28+
def __init__(self) -> None:
29+
super().__init__(self.message)

‎aws_lambda_powertools/utilities/auth_alpha/jwt/_internal/authorization.py‎

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,16 @@
33
from collections.abc import Mapping
44
from typing import Any
55

6-
from aws_lambda_powertools.utilities.auth_alpha._internal.validation import string_list
6+
from aws_lambda_powertools.utilities.auth_alpha._internal.scopes import required_scopes, valid_scope
77
from aws_lambda_powertools.utilities.auth_alpha.jwt.exceptions import (
88
AuthError,
99
AuthFailureReason,
1010
InvalidClaimsError,
1111
InvalidTokenError,
1212
)
1313

14+
__all__ = ["required_scopes"]
15+
1416

1517
class MissingTokenError(InvalidTokenError):
1618
"""No authorization header was supplied."""
@@ -65,17 +67,6 @@ def _authorization_values(headers: Any) -> list[Any]:
6567
return values
6668

6769

68-
def valid_scope(value: str) -> bool:
69-
return bool(value) and all(33 <= ord(character) <= 126 and character not in {'"', "\\"} for character in value)
70-
71-
72-
def required_scopes(scopes: list[str] | None) -> tuple[str, ...]:
73-
values = string_list(scopes if scopes is not None else [])
74-
if not all(valid_scope(value) for value in values):
75-
raise ValueError("Scopes must be valid OAuth scope tokens")
76-
return values
77-
78-
7970
def enforce_scopes(claims: dict[str, Any], expected: tuple[str, ...]) -> None:
8071
value: Any = next((claims[name] for name in ("scope", "scp", "scopes") if name in claims), [])
8172
if isinstance(value, str):

0 commit comments

Comments
 (0)