Skip to content

Commit f12935a

Browse files
committed
WIP: Ruff format
Signed-off-by: David Black <[email protected]>
1 parent b406ef0 commit f12935a

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+1558
-1336
lines changed

atlassian_jwt_auth/__init__.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
from atlassian_jwt_auth.algorithms import get_permitted_algorithm_names # noqa
2-
from atlassian_jwt_auth.key import (HTTPSPublicKeyRetriever, # noqa
3-
KeyIdentifier)
2+
from atlassian_jwt_auth.key import (
3+
HTTPSPublicKeyRetriever, # noqa
4+
KeyIdentifier, # noqa
5+
)
46
from atlassian_jwt_auth.signer import ( # noqa
5-
create_signer, create_signer_from_file_private_key_repository)
7+
create_signer,
8+
create_signer_from_file_private_key_repository,
9+
)
610
from atlassian_jwt_auth.verifier import JWTAuthVerifier # noqa

atlassian_jwt_auth/algorithms.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
def get_permitted_algorithm_names():
2-
""" returns permitted algorithm names. """
2+
"""returns permitted algorithm names."""
33
return [
4-
'RS256',
5-
'RS384',
6-
'RS512',
7-
'ES256',
8-
'ES384',
9-
'ES512',
10-
'PS256',
11-
'PS384',
12-
'PS512'
4+
"RS256",
5+
"RS384",
6+
"RS512",
7+
"ES256",
8+
"ES384",
9+
"ES512",
10+
"PS256",
11+
"PS384",
12+
"PS512",
1313
]

atlassian_jwt_auth/auth.py

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,29 @@
1010
class BaseJWTAuth(object):
1111
"""Adds a JWT bearer token to the request per the ASAP specification"""
1212

13-
def __init__(self, signer: JWTAuthSigner, audience: str,
14-
*args: Any, **kwargs: Any) -> None:
13+
def __init__(
14+
self, signer: JWTAuthSigner, audience: str, *args: Any, **kwargs: Any
15+
) -> None:
1516
self._audience = audience
1617
self._signer = signer
17-
self._additional_claims = kwargs.get('additional_claims', {})
18+
self._additional_claims = kwargs.get("additional_claims", {})
1819

1920
@classmethod
20-
def create(cls, issuer: str, key_identifier: Union[KeyIdentifier, str], private_key_pem: str, audience: str,
21-
**kwargs: Any) -> "BaseJWTAuth":
21+
def create(
22+
cls,
23+
issuer: str,
24+
key_identifier: Union[KeyIdentifier, str],
25+
private_key_pem: str,
26+
audience: str,
27+
**kwargs: Any,
28+
) -> "BaseJWTAuth":
2229
"""Instantiate a JWTAuth while creating the signer inline"""
23-
signer = atlassian_jwt_auth.create_signer(issuer, key_identifier,
24-
private_key_pem, **kwargs)
30+
signer = atlassian_jwt_auth.create_signer(
31+
issuer, key_identifier, private_key_pem, **kwargs
32+
)
2533
return cls(signer, audience)
2634

2735
def _get_header_value(self) -> bytes:
28-
return b'Bearer ' + self._signer.generate_jwt(
29-
self._audience, additional_claims=self._additional_claims).encode("utf-8")
36+
return b"Bearer " + self._signer.generate_jwt(
37+
self._audience, additional_claims=self._additional_claims
38+
).encode("utf-8")

atlassian_jwt_auth/contrib/aiohttp/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Provide asyncio support"""
2+
23
import sys
34

45
if sys.version_info >= (3, 5):
@@ -10,6 +11,7 @@
1011
from .verifier import JWTAuthVerifier # noqa
1112
except ImportError as e:
1213
import warnings
14+
1315
warnings.warn(str(e))
1416

1517

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Any, Dict, Union
1+
from typing import Any, Union
22

33
from aiohttp import BasicAuth
44

@@ -11,15 +11,20 @@ class JWTAuth(BaseJWTAuth, BasicAuth):
1111
1212
It should be aiohttp.BasicAuth subclass, so redefine its `__new__` method.
1313
"""
14+
1415
def __new__(cls, *args, **kwargs):
15-
return super().__new__(cls, '')
16+
return super().__new__(cls, "")
1617

1718
def encode(self) -> str:
1819
return self._get_header_value().decode(self.encoding)
1920

2021

2122
def create_jwt_auth(
22-
issuer: str, key_identifier: Union[KeyIdentifier, str], private_key_pem: str, audience: str, **kwargs: Any) -> BaseJWTAuth:
23+
issuer: str,
24+
key_identifier: Union[KeyIdentifier, str],
25+
private_key_pem: str,
26+
audience: str,
27+
**kwargs: Any,
28+
) -> BaseJWTAuth:
2329
"""Instantiate a JWTAuth while creating the signer inline"""
24-
return JWTAuth.create(
25-
issuer, key_identifier, private_key_pem, audience, **kwargs)
30+
return JWTAuth.create(issuer, key_identifier, private_key_pem, audience, **kwargs)

atlassian_jwt_auth/contrib/aiohttp/key.py

Lines changed: 29 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,17 @@
77

88
from atlassian_jwt_auth.exceptions import PublicKeyRetrieverException
99
from atlassian_jwt_auth.key import PEM_FILE_TYPE
10-
from atlassian_jwt_auth.key import \
11-
HTTPSPublicKeyRetriever as _HTTPSPublicKeyRetriever
10+
from atlassian_jwt_auth.key import HTTPSPublicKeyRetriever as _HTTPSPublicKeyRetriever
1211

1312

1413
class HTTPSPublicKeyRetriever(_HTTPSPublicKeyRetriever):
1514
"""A class for retrieving JWT public keys with aiohttp"""
15+
1616
_class_session = None
1717

18-
def __init__(self, base_url: str, *,
19-
loop: Optional[AbstractEventLoop] = None) -> None:
18+
def __init__(
19+
self, base_url: str, *, loop: Optional[AbstractEventLoop] = None
20+
) -> None:
2021
if loop is None:
2122
loop = asyncio.get_event_loop()
2223
self.loop = loop
@@ -25,34 +26,41 @@ def __init__(self, base_url: str, *,
2526
def _get_session(self) -> aiohttp.ClientSession: # type: ignore[override]
2627
if HTTPSPublicKeyRetriever._class_session is None:
2728
HTTPSPublicKeyRetriever._class_session = aiohttp.ClientSession(
28-
loop=self.loop)
29+
loop=self.loop
30+
)
2931
return HTTPSPublicKeyRetriever._class_session
3032

3133
def _convert_proxies_to_proxy_arg(
32-
self, url: str, requests_kwargs: Dict[Any, Any]) -> Dict[str, Any]:
33-
""" returns a modified requests_kwargs dict that contains proxy
34-
information in a form that aiohttp accepts
35-
(it wants proxy information instead of a dict of proxies).
34+
self, url: str, requests_kwargs: Dict[Any, Any]
35+
) -> Dict[str, Any]:
36+
"""returns a modified requests_kwargs dict that contains proxy
37+
information in a form that aiohttp accepts
38+
(it wants proxy information instead of a dict of proxies).
3639
"""
3740
proxy = None
38-
if 'proxies' in requests_kwargs:
41+
if "proxies" in requests_kwargs:
3942
scheme = urllib.parse.urlparse(url).scheme
40-
proxy = requests_kwargs['proxies'].get(scheme, None)
41-
del requests_kwargs['proxies']
42-
requests_kwargs['proxy'] = proxy
43+
proxy = requests_kwargs["proxies"].get(scheme, None)
44+
del requests_kwargs["proxies"]
45+
requests_kwargs["proxy"] = proxy
4346
return requests_kwargs
4447

4548
async def _retrieve(
46-
self, url: str, requests_kwargs: Dict[Any, Any]) -> Awaitable[str]:
47-
requests_kwargs = self._convert_proxies_to_proxy_arg(
48-
url, requests_kwargs)
49+
self, url: str, requests_kwargs: Dict[Any, Any]
50+
) -> Awaitable[str]:
51+
requests_kwargs = self._convert_proxies_to_proxy_arg(url, requests_kwargs)
4952
try:
50-
resp = await self._session.get(url, headers={'accept': # type: ignore[misc]
51-
PEM_FILE_TYPE},
52-
**requests_kwargs)
53+
resp = await self._session.get(
54+
url,
55+
headers={
56+
"accept": # type: ignore[misc]
57+
PEM_FILE_TYPE
58+
},
59+
**requests_kwargs,
60+
)
5361
resp.raise_for_status()
54-
self._check_content_type(url, resp.headers['content-type'])
62+
self._check_content_type(url, resp.headers["content-type"])
5563
return await resp.text()
5664
except aiohttp.ClientError as e:
57-
status_code = getattr(e, 'code', None)
65+
status_code = getattr(e, "code", None)
5866
raise PublicKeyRetrieverException(e, status_code=status_code)

atlassian_jwt_auth/contrib/aiohttp/verifier.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import asyncio
2-
from typing import Any, Dict, Coroutine, Union
2+
from typing import Any, Dict
33

44
import jwt
55

@@ -8,8 +8,13 @@
88

99

1010
class JWTAuthVerifier(_JWTAuthVerifier): # type: ignore[override]
11-
async def verify_jwt(self, a_jwt: str, audience: str, # type: ignore[override]
12-
leeway: int = 0, **requests_kwargs: Any) -> Dict[Any, Any]:
11+
async def verify_jwt(
12+
self,
13+
a_jwt: str,
14+
audience: str, # type: ignore[override]
15+
leeway: int = 0,
16+
**requests_kwargs: Any,
17+
) -> Dict[Any, Any]:
1318
"""Verify if the token is correct
1419
1520
Returns:
@@ -24,8 +29,8 @@ async def verify_jwt(self, a_jwt: str, audience: str, # type: ignore[override]
2429
if asyncio.iscoroutine(public_key):
2530
public_key = await public_key
2631

27-
alg = jwt.get_unverified_header(a_jwt).get('alg', None)
32+
alg = jwt.get_unverified_header(a_jwt).get("alg", None)
2833
public_key_obj = self._load_public_key(public_key, alg)
2934
return self._decode_jwt(
30-
a_jwt, key_identifier, public_key_obj,
31-
audience=audience, leeway=leeway)
35+
a_jwt, key_identifier, public_key_obj, audience=audience, leeway=leeway
36+
)

atlassian_jwt_auth/contrib/django/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,6 @@
33
warnings.warn(
44
"The atlassian_jwt_auth.contrib.django package is deprecated in 4.0.0 "
55
"in favour of atlassian_jwt_auth.frameworks.django.",
6-
DeprecationWarning, stacklevel=2
6+
DeprecationWarning,
7+
stacklevel=2,
78
)

atlassian_jwt_auth/contrib/django/decorators.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from collections.abc import Callable
22
from functools import wraps
3-
from typing import Iterable, Optional, Sequence
3+
from typing import Iterable, Optional
44

55
from django.http.response import HttpResponse
66

atlassian_jwt_auth/contrib/django/middleware.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@
33
from django.conf import settings
44
from django.utils.deprecation import MiddlewareMixin
55

6-
from atlassian_jwt_auth.frameworks.django.middleware import \
7-
OldStyleASAPMiddleware
6+
from atlassian_jwt_auth.frameworks.django.middleware import OldStyleASAPMiddleware
87

98

109
class ProxiedAsapMiddleware(OldStyleASAPMiddleware, MiddlewareMixin):
@@ -19,17 +18,17 @@ def __init__(self, get_response: Optional[Any] = None) -> None:
1918

2019
# Rely on this header to tell us if a request has been forwarded
2120
# from an ASAP-enabled service; will overwrite X-Forwarded-For
22-
self.xfwd = getattr(settings, 'ASAP_PROXIED_FORWARDED_FOR_HEADER',
23-
'HTTP_X_ASAP_FORWARDED_FOR')
21+
self.xfwd = getattr(
22+
settings, "ASAP_PROXIED_FORWARDED_FOR_HEADER", "HTTP_X_ASAP_FORWARDED_FOR"
23+
)
2424

2525
# This header won't always be set, i.e. some users will be anonymous
26-
self.xauth = getattr(settings, 'ASAP_PROXIED_AUTHORIZATION_HEADER',
27-
'HTTP_X_ASAP_AUTHORIZATION')
26+
self.xauth = getattr(
27+
settings, "ASAP_PROXIED_AUTHORIZATION_HEADER", "HTTP_X_ASAP_AUTHORIZATION"
28+
)
2829

2930
def process_request(self, request) -> Optional[str]:
30-
error_response = super(ProxiedAsapMiddleware, self).process_request(
31-
request
32-
)
31+
error_response = super(ProxiedAsapMiddleware, self).process_request(request)
3332

3433
if error_response:
3534
return error_response
@@ -39,28 +38,29 @@ def process_request(self, request) -> Optional[str]:
3938
return None
4039

4140
request.asap_forwarded = True
42-
request.META['HTTP_X_FORWARDED_FOR'] = forwarded_for
41+
request.META["HTTP_X_FORWARDED_FOR"] = forwarded_for
4342

44-
asap_auth = request.META.pop('HTTP_AUTHORIZATION', None)
43+
asap_auth = request.META.pop("HTTP_AUTHORIZATION", None)
4544
orig_auth = request.META.pop(self.xauth, None)
4645

4746
# Swap original client header in to allow regular auth middleware
4847
if orig_auth is not None:
49-
request.META['HTTP_AUTHORIZATION'] = orig_auth
48+
request.META["HTTP_AUTHORIZATION"] = orig_auth
5049
if asap_auth is not None:
5150
request.META[self.xauth] = asap_auth
5251
return None
5352

54-
def process_view(self, request: Any, view_func: Callable,
55-
view_args: Any, view_kwargs: Any) -> None:
56-
if not hasattr(request, 'asap_forwarded'):
53+
def process_view(
54+
self, request: Any, view_func: Callable, view_args: Any, view_kwargs: Any
55+
) -> None:
56+
if not hasattr(request, "asap_forwarded"):
5757
return None
5858

5959
# swap headers back into place
6060
asap_auth = request.META.pop(self.xauth, None)
61-
orig_auth = request.META.pop('HTTP_AUTHORIZATION', None)
61+
orig_auth = request.META.pop("HTTP_AUTHORIZATION", None)
6262

6363
if asap_auth is not None:
64-
request.META['HTTP_AUTHORIZATION'] = asap_auth
64+
request.META["HTTP_AUTHORIZATION"] = asap_auth
6565
if orig_auth is not None:
6666
request.META[self.xauth] = orig_auth

0 commit comments

Comments
 (0)