Skip to content

Commit 2a836b3

Browse files
committed
WIP: Async support in pulp-glue
Replaces requests with aiohttp and changes the api.
1 parent 76ede0c commit 2a836b3

File tree

14 files changed

+621
-500
lines changed

14 files changed

+621
-500
lines changed

lint_requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ mypy==1.19.0
77
shellcheck-py==0.11.0.1
88

99
# Type annotation stubs
10+
types-aiofiles
1011
types-pygments
1112
types-PyYAML
1213
types-requests

lower_bounds_constraints.lock

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
aiofiles==25.1.0
2+
aiohttp==3.12.0
13
click==8.0.0
24
packaging==20.0
35
PyYAML==5.3
Lines changed: 134 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -1,97 +1,147 @@
11
import typing as t
2-
from datetime import datetime, timedelta
2+
from datetime import datetime
33

4-
import requests
54

6-
7-
class OAuth2ClientCredentialsAuth(requests.auth.AuthBase):
8-
"""
9-
This implements the OAuth2 ClientCredentials Grant authentication flow.
10-
https://datatracker.ietf.org/doc/html/rfc6749#section-4.4
5+
class AuthProviderBase:
116
"""
7+
Base class for auth providers.
128
13-
def __init__(
14-
self,
15-
client_id: str,
16-
client_secret: str,
17-
token_url: str,
18-
scopes: list[str] | None = None,
19-
verify_ssl: str | bool | None = None,
20-
):
21-
self._token_server_auth = requests.auth.HTTPBasicAuth(client_id, client_secret)
22-
self._token_url = token_url
23-
self._scopes = scopes
24-
self._verify_ssl = verify_ssl
9+
This abstract base class will analyze the authentication proposals of the openapi specs.
10+
Different authentication schemes should be implemented by subclasses.
11+
Returned auth objects need to be compatible with `requests.auth.AuthBase`.
12+
"""
2513

26-
self._access_token: str | None = None
27-
self._expire_at: datetime | None = None
14+
def __init__(self) -> None:
15+
self._oauth2_token: str | None = None
16+
self._oauth2_expires: datetime = datetime.now()
17+
18+
def can_complete_http_basic(self) -> bool:
19+
return False
20+
21+
def can_complete_mutualTLS(self) -> bool:
22+
return False
23+
24+
def can_complete_oauth2_client_credentials(self, scopes: list[str]) -> bool:
25+
return False
26+
27+
def can_complete_scheme(self, scheme: dict[str, t.Any], scopes: list[str]) -> bool:
28+
if scheme["type"] == "http":
29+
if scheme["scheme"] == "basic":
30+
return self.can_complete_http_basic()
31+
elif scheme["type"] == "mutualTLS":
32+
return self.can_complete_mutualTLS()
33+
elif scheme["type"] == "oauth2":
34+
for flow_name, flow in scheme["flows"].items():
35+
if (
36+
flow_name == "clientCredentials"
37+
and self.can_complete_oauth2_client_credentials(flow["scopes"])
38+
):
39+
return True
40+
return False
41+
42+
def can_complete(
43+
self, proposal: dict[str, list[str]], security_schemes: dict[str, dict[str, t.Any]]
44+
) -> bool:
45+
for name, scopes in proposal.items():
46+
scheme = security_schemes.get(name)
47+
if scheme is None or not self.can_complete_scheme(scheme, scopes):
48+
return False
49+
# This covers the case where `[]` allows for no auth at all.
50+
return True
51+
52+
async def auth_success_hook(
53+
self, proposal: dict[str, list[str]], security_schemes: dict[str, dict[str, t.Any]]
54+
) -> None:
55+
pass
56+
57+
async def auth_failure_hook(
58+
self, proposal: dict[str, list[str]], security_schemes: dict[str, dict[str, t.Any]]
59+
) -> None:
60+
pass
61+
62+
async def http_basic_credentials(self) -> tuple[bytes, bytes]:
63+
raise NotImplementedError()
64+
65+
async def oauth2_client_credentials(self) -> tuple[bytes, bytes]:
66+
raise NotImplementedError()
67+
68+
def tls_credentials(self) -> tuple[str, str | None]:
69+
raise NotImplementedError()
70+
71+
72+
class BasicAuthProvider(AuthProviderBase):
73+
"""
74+
AuthProvider providing basic auth with fixed `username`, `password`.
75+
"""
2876

29-
def __call__(self, request: requests.PreparedRequest) -> requests.PreparedRequest:
30-
if self._expire_at is None or self._expire_at < datetime.now():
31-
self._retrieve_token()
77+
def __init__(self, username: t.AnyStr, password: t.AnyStr):
78+
super().__init__()
79+
self.username: bytes = username.encode("latin1") if isinstance(username, str) else username
80+
self.password: bytes = password.encode("latin1") if isinstance(password, str) else password
3281

33-
assert self._access_token is not None
82+
def can_complete_http_basic(self) -> bool:
83+
return True
3484

35-
request.headers["Authorization"] = f"Bearer {self._access_token}"
85+
async def http_basic_credentials(self) -> tuple[bytes, bytes]:
86+
return self.username, self.password
3687

37-
# Call to untyped function "register_hook" in typed context
38-
request.register_hook("response", self._handle401) # type: ignore[no-untyped-call]
3988

40-
return request
89+
class GlueAuthProvider(AuthProviderBase):
90+
"""
91+
AuthProvider allowing to be used with prepared credentials.
92+
"""
4193

42-
def _handle401(
94+
def __init__(
4395
self,
44-
response: requests.Response,
45-
**kwargs: t.Any,
46-
) -> requests.Response:
47-
if response.status_code != 401:
48-
return response
49-
50-
# If we get this far, probably the token is not valid anymore.
51-
52-
# Try to reach for a new token once.
53-
self._retrieve_token()
54-
55-
assert self._access_token is not None
56-
57-
# Consume content and release the original connection
58-
# to allow our new request to reuse the same one.
59-
response.content
60-
response.close()
61-
prepared_new_request = response.request.copy()
62-
63-
prepared_new_request.headers["Authorization"] = f"Bearer {self._access_token}"
64-
65-
# Avoid to enter into an infinity loop.
66-
# Call to untyped function "deregister_hook" in typed context
67-
prepared_new_request.deregister_hook( # type: ignore[no-untyped-call]
68-
"response", self._handle401
69-
)
70-
71-
# "Response" has no attribute "connection"
72-
new_response: requests.Response = response.connection.send(prepared_new_request, **kwargs)
73-
new_response.history.append(response)
74-
new_response.request = prepared_new_request
75-
76-
return new_response
77-
78-
def _retrieve_token(self) -> None:
79-
data = {
80-
"grant_type": "client_credentials",
81-
}
82-
83-
if self._scopes:
84-
data["scope"] = " ".join(self._scopes)
85-
86-
response: requests.Response = requests.post(
87-
self._token_url,
88-
data=data,
89-
auth=self._token_server_auth,
90-
verify=self._verify_ssl,
91-
)
92-
93-
response.raise_for_status()
94-
95-
token = response.json()
96-
self._expire_at = datetime.now() + timedelta(seconds=token["expires_in"])
97-
self._access_token = token["access_token"]
96+
*,
97+
username: t.AnyStr | None = None,
98+
password: t.AnyStr | None = None,
99+
client_id: t.AnyStr | None = None,
100+
client_secret: t.AnyStr | None = None,
101+
cert: str | None = None,
102+
key: str | None = None,
103+
):
104+
super().__init__()
105+
self.username: bytes | None = None
106+
self.password: bytes | None = None
107+
self.client_id: bytes | None = None
108+
self.client_secret: bytes | None = None
109+
self.cert: str | None = cert
110+
self.key: str | None = key
111+
112+
if username is not None:
113+
assert password is not None
114+
self.username = username.encode("latin1") if isinstance(username, str) else username
115+
self.password = password.encode("latin1") if isinstance(password, str) else password
116+
if client_id is not None:
117+
assert client_secret is not None
118+
self.client_id = client_id.encode("latin1") if isinstance(client_id, str) else client_id
119+
self.client_secret = (
120+
client_secret.encode("latin1") if isinstance(client_secret, str) else client_secret
121+
)
122+
123+
if cert is None and key is not None:
124+
raise RuntimeError("Key can only be used together with a cert.")
125+
126+
def can_complete_http_basic(self) -> bool:
127+
return self.username is not None
128+
129+
def can_complete_oauth2_client_credentials(self, scopes: list[str]) -> bool:
130+
return self.client_id is not None
131+
132+
def can_complete_mutualTLS(self) -> bool:
133+
return self.cert is not None
134+
135+
async def http_basic_credentials(self) -> tuple[bytes, bytes]:
136+
assert self.username is not None
137+
assert self.password is not None
138+
return self.username, self.password
139+
140+
async def oauth2_client_credentials(self) -> tuple[bytes, bytes]:
141+
assert self.client_id is not None
142+
assert self.client_secret is not None
143+
return self.client_id, self.client_secret
144+
145+
def tls_credentials(self) -> tuple[str, str | None]:
146+
assert self.cert is not None
147+
return (self.cert, self.key)

pulp-glue/pulp_glue/common/context.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
from packaging.specifiers import SpecifierSet
1111

12+
from pulp_glue.common.authentication import GlueAuthProvider
1213
from pulp_glue.common.exceptions import (
1314
NotImplementedFake,
1415
OpenAPIError,
@@ -19,7 +20,7 @@
1920
UnsafeCallError,
2021
)
2122
from pulp_glue.common.i18n import get_translation
22-
from pulp_glue.common.openapi import BasicAuthProvider, OpenAPI
23+
from pulp_glue.common.openapi import OpenAPI
2324

2425
if sys.version_info >= (3, 11):
2526
import tomllib
@@ -335,8 +336,13 @@ def from_config(cls, config: dict[str, t.Any]) -> "t.Self":
335336
api_kwargs: dict[str, t.Any] = {
336337
"base_url": config["base_url"],
337338
}
338-
if "username" in config:
339-
api_kwargs["auth_provider"] = BasicAuthProvider(config["username"], config["password"])
339+
api_kwargs["auth_provider"] = GlueAuthProvider(
340+
**{
341+
k: v
342+
for k, v in config.items()
343+
if k in {"username", "password", "client_id", "client_secret", "cert", "key"}
344+
}
345+
)
340346
if "headers" in config:
341347
api_kwargs["headers"] = dict(
342348
(header.split(":", maxsplit=1) for header in config["headers"])
@@ -385,7 +391,9 @@ def api(self) -> OpenAPI:
385391
# Deprecated for 'auth'.
386392
if not password:
387393
password = self.prompt("password", hide_input=True)
388-
self._api_kwargs["auth_provider"] = BasicAuthProvider(username, password)
394+
self._api_kwargs["auth_provider"] = GlueAuthProvider(
395+
username=username, password=password
396+
)
389397
warnings.warn(
390398
"Using 'username' and 'password' with 'PulpContext' is deprecated. "
391399
"Use an auth provider with the 'auth_provider' argument instead.",
@@ -399,10 +407,10 @@ def api(self) -> OpenAPI:
399407
)
400408
except OpenAPIError as e:
401409
raise PulpException(str(e))
410+
self._patch_api_spec()
402411
# Rerun scheduled version checks
403412
for plugin_requirement in self._needed_plugins:
404413
self.needs_plugin(plugin_requirement)
405-
self._patch_api_spec()
406414
return self._api
407415

408416
@property

0 commit comments

Comments
 (0)