Skip to content

Commit 8cff2bc

Browse files
Florian SandelFlorian Sandel
authored andcommitted
reformat and pin pyjwt version
1 parent 859a6bb commit 8cff2bc

File tree

4 files changed

+85
-56
lines changed

4 files changed

+85
-56
lines changed

certbot_dns_stackit/stackit.py

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -161,12 +161,12 @@ def _get_zone_id(self, domain: str) -> str:
161161
:param domain: The domain (zone dnsName) for which the zone ID is needed.
162162
:return: The ID of the zone.
163163
"""
164-
parts = domain.split('.')
164+
parts = domain.split(".")
165165

166166
# we are searching for the best matching zone. We can do that by iterating over the parts of the domain
167167
# from left to right.
168168
for i in range(len(parts)):
169-
subdomain = '.'.join(parts[i:])
169+
subdomain = ".".join(parts[i:])
170170
res = requests.get(
171171
f"{self.base_url}/v1/projects/{self.project_id}/zones?dnsName[eq]={subdomain}&active[eq]=true",
172172
headers=self.headers,
@@ -340,8 +340,8 @@ def _load_service_file(self, file_path: str) -> Optional[ServiceFileCredentials]
340340
:return: Service file credentials if the file is found and valid, None otherwise.
341341
"""
342342
try:
343-
with open(file_path, 'r') as file:
344-
return json.load(file)['credentials']
343+
with open(file_path, "r") as file:
344+
return json.load(file)["credentials"]
345345
except FileNotFoundError:
346346
logging.error(f"File not found: {file_path}")
347347
return None
@@ -354,15 +354,17 @@ def _generate_jwt(self, credentials: ServiceFileCredentials) -> str:
354354
:return: A JWT token as a string.
355355
"""
356356
payload = {
357-
"iss": credentials['iss'],
358-
"sub": credentials['sub'],
359-
"aud": credentials['aud'],
357+
"iss": credentials["iss"],
358+
"sub": credentials["sub"],
359+
"aud": credentials["aud"],
360360
"exp": int(time.time()) + 900,
361361
"iat": int(time.time()),
362-
"jti": str(uuid.uuid4())
362+
"jti": str(uuid.uuid4()),
363363
}
364-
headers = {'kid': credentials['kid']}
365-
return jwt.encode(payload, credentials['privateKey'], algorithm='RS512', headers=headers)
364+
headers = {"kid": credentials["kid"]}
365+
return jwt.encode(
366+
payload, credentials["privateKey"], algorithm="RS512", headers=headers
367+
)
366368

367369
def _request_access_token(self, jwt_token: str) -> str:
368370
"""
@@ -372,13 +374,17 @@ def _request_access_token(self, jwt_token: str) -> str:
372374
:return: An access token if the request is successful, None otherwise.
373375
"""
374376
data = {
375-
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
376-
'assertion': jwt_token
377+
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
378+
"assertion": jwt_token,
377379
}
378380
try:
379-
response = requests.post('https://service-account.api.stackit.cloud/token', data=data, headers={'Content-Type': 'application/x-www-form-urlencoded'})
381+
response = requests.post(
382+
"https://service-account.api.stackit.cloud/token",
383+
data=data,
384+
headers={"Content-Type": "application/x-www-form-urlencoded"},
385+
)
380386
response.raise_for_status()
381-
return response.json().get('access_token')
387+
return response.json().get("access_token")
382388
except requests.exceptions.RequestException as e:
383389
raise errors.PluginError(f"Failed to request access token: {e}")
384390

certbot_dns_stackit/test_stackit.py

Lines changed: 63 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -220,20 +220,24 @@ def setUp(self):
220220

221221
@patch.object(Authenticator, "conf")
222222
@patch.object(Authenticator, "_configure_credentials")
223-
def test_setup_credentials_with_service_account(self, mock_configure_credentials, mock_conf):
223+
def test_setup_credentials_with_service_account(
224+
self, mock_configure_credentials, mock_conf
225+
):
224226
# Simulate `service_account` being set
225-
mock_conf.return_value = 'service_account_value'
227+
mock_conf.return_value = "service_account_value"
226228

227229
self.authenticator._setup_credentials()
228230

229231
# Assert _configure_credentials was not called
230232
mock_configure_credentials.assert_not_called()
231233
# Assert service_account is set correctly
232-
self.assertEqual(self.authenticator.service_account, 'service_account_value')
234+
self.assertEqual(self.authenticator.service_account, "service_account_value")
233235

234236
@patch.object(Authenticator, "conf")
235237
@patch.object(Authenticator, "_configure_credentials")
236-
def test_setup_credentials_without_service_account(self, mock_configure_credentials, mock_conf):
238+
def test_setup_credentials_without_service_account(
239+
self, mock_configure_credentials, mock_conf
240+
):
237241
# Simulate `service_account` not being set
238242
mock_conf.return_value = None
239243
mock_creds = Mock()
@@ -283,7 +287,11 @@ def test_cleanup(self, mock_get_client):
283287
"test_domain", "validation_name_test", "validation_test"
284288
)
285289

286-
@patch("builtins.open", new_callable=mock_open, read_data='{"credentials": {"iss": "test_iss", "sub": "test_sub", "aud": "test_aud", "kid": "test_kid", "privateKey": "test_private_key"}}')
290+
@patch(
291+
"builtins.open",
292+
new_callable=mock_open,
293+
read_data='{"credentials": {"iss": "test_iss", "sub": "test_sub", "aud": "test_aud", "kid": "test_kid", "privateKey": "test_private_key"}}',
294+
)
287295
@patch("json.load", lambda x: json.loads(x.read()))
288296
def test_load_service_file(self, mock_load_service_file):
289297
expected_credentials = {
@@ -307,70 +315,85 @@ def test_load_service_file_not_found(self, mock_log, mock_file):
307315
@patch("jwt.encode")
308316
def test_generate_jwt(self, mock_jwt_encode):
309317
credentials = {
310-
'iss': 'issuer',
311-
'sub': 'subject',
312-
'aud': 'audience',
313-
'kid': 'key_id',
314-
'privateKey': 'private_key'
318+
"iss": "issuer",
319+
"sub": "subject",
320+
"aud": "audience",
321+
"kid": "key_id",
322+
"privateKey": "private_key",
315323
}
316324
self.authenticator._generate_jwt(credentials)
317325
mock_jwt_encode.assert_called()
318326

319327
def test_generate_jwt_fail(self):
320328
credentials = {
321-
'iss': 'issuer',
322-
'sub': 'subject',
323-
'aud': 'audience',
324-
'kid': 'key_id',
325-
'privateKey': 'not_a_valid_key'
329+
"iss": "issuer",
330+
"sub": "subject",
331+
"aud": "audience",
332+
"kid": "key_id",
333+
"privateKey": "not_a_valid_key",
326334
}
327335
with self.assertRaises(jwt.exceptions.InvalidKeyError):
328336
token = self.authenticator._generate_jwt(credentials)
329337
self.assertIsNone(token)
330338

331-
@patch('requests.post')
339+
@patch("requests.post")
332340
def test_request_access_token_success(self, mock_post):
333341
mock_response = mock_post.return_value
334-
mock_response.raise_for_status = lambda: None # Mock raise_for_status to do nothing
335-
mock_response.json.return_value = {'access_token': 'mocked_access_token'}
342+
mock_response.raise_for_status = (
343+
lambda: None
344+
) # Mock raise_for_status to do nothing
345+
mock_response.json.return_value = {"access_token": "mocked_access_token"}
336346

337-
result = self.authenticator._request_access_token('jwt_token_example')
347+
result = self.authenticator._request_access_token("jwt_token_example")
338348

339349
# Assertions
340350
mock_post.assert_called_once_with(
341-
'https://service-account.api.stackit.cloud/token',
342-
data={'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion': 'jwt_token_example'},
343-
headers={'Content-Type': 'application/x-www-form-urlencoded'}
351+
"https://service-account.api.stackit.cloud/token",
352+
data={
353+
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
354+
"assertion": "jwt_token_example",
355+
},
356+
headers={"Content-Type": "application/x-www-form-urlencoded"},
344357
)
345-
self.assertEqual(result, 'mocked_access_token')
358+
self.assertEqual(result, "mocked_access_token")
346359

347-
@patch('requests.post')
360+
@patch("requests.post")
348361
def test_request_access_token_failure_raises_http_error(self, mock_post):
349362
mock_response = Response()
350363
mock_response.status_code = 403
351364
mock_post.return_value = mock_response
352365
mock_response.raise_for_status = lambda: (_ for _ in ()).throw(HTTPError())
353366

354367
with self.assertRaises(errors.PluginError):
355-
self.authenticator._request_access_token('jwt_token_example')
368+
self.authenticator._request_access_token("jwt_token_example")
356369

357370
mock_post.assert_called_once()
358371

359-
@patch("builtins.open", new_callable=mock_open, read_data='{"credentials": {"iss": "test_iss", "sub": "test_sub", "aud": "test_aud", "kid": "test_kid", "privateKey": "test_private_key"}}')
360-
@patch.object(Authenticator, '_request_access_token')
361-
@patch.object(Authenticator, '_generate_jwt')
362-
@patch.object(Authenticator, '_load_service_file')
363-
def test_generate_jwt_token_success(self, mock_load_service_file, mock_generate_jwt, mock_request_access_token, mock_open):
364-
mock_load_service_file.return_value = {'dummy': 'credentials'}
365-
mock_generate_jwt.return_value = 'jwt_token_example'
366-
mock_request_access_token.return_value = 'access_token_example'
367-
368-
result = self.authenticator._generate_jwt_token('path/to/service/file')
369-
370-
self.assertEqual(result, 'access_token_example')
371-
mock_load_service_file.assert_called_once_with('path/to/service/file')
372-
mock_generate_jwt.assert_called_once_with({'dummy': 'credentials'})
373-
mock_request_access_token.assert_called_once_with('jwt_token_example')
372+
@patch(
373+
"builtins.open",
374+
new_callable=mock_open,
375+
read_data='{"credentials": {"iss": "test_iss", "sub": "test_sub", "aud": "test_aud", "kid": "test_kid", "privateKey": "test_private_key"}}',
376+
)
377+
@patch.object(Authenticator, "_request_access_token")
378+
@patch.object(Authenticator, "_generate_jwt")
379+
@patch.object(Authenticator, "_load_service_file")
380+
def test_generate_jwt_token_success(
381+
self,
382+
mock_load_service_file,
383+
mock_generate_jwt,
384+
mock_request_access_token,
385+
mock_open,
386+
):
387+
mock_load_service_file.return_value = {"dummy": "credentials"}
388+
mock_generate_jwt.return_value = "jwt_token_example"
389+
mock_request_access_token.return_value = "access_token_example"
390+
391+
result = self.authenticator._generate_jwt_token("path/to/service/file")
392+
393+
self.assertEqual(result, "access_token_example")
394+
mock_load_service_file.assert_called_once_with("path/to/service/file")
395+
mock_generate_jwt.assert_called_once_with({"dummy": "credentials"})
396+
mock_request_access_token.assert_called_once_with("jwt_token_example")
374397

375398

376399
if __name__ == "__main__":

setup.cfg

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ install_requires =
5151
black
5252
click==8.1.7
5353
coverage
54-
PyJWT
54+
PyJWT==2.9.0
5555

5656
[options.entry_points]
5757
certbot.plugins =

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
"black",
2121
"click==8.1.7",
2222
"coverage",
23-
"PyJWT"
23+
"PyJWT==2.9.0"
2424
]
2525

2626
# read the contents of your README file

0 commit comments

Comments
 (0)