Skip to content

Commit fc683c7

Browse files
authored
DRIVERS-3019 Add ruff linter and apply fixes (#545)
1 parent 542b701 commit fc683c7

File tree

21 files changed

+161
-157
lines changed

21 files changed

+161
-157
lines changed

.evergreen/auth_aws/aws_tester.py

100644100755
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def join(*parts):
4444
def run(args, env):
4545
"""Run a python command in a subprocess."""
4646
env.update(os.environ.copy())
47-
return subprocess.run([sys.executable] + args, env=env).returncode
47+
return subprocess.run([sys.executable, *args], env=env, check=False).returncode
4848

4949

5050
def create_user(user, kwargs):

.evergreen/auth_oidc/azure/remote-scripts/test.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,17 @@ def fetch(self, context: OIDCCallbackContext) -> OIDCCallbackResult:
2121
status = response.status
2222
body = response.read().decode('utf8')
2323
except Exception as e:
24-
msg = "Failed to acquire IMDS access token: %s" % e
25-
raise ValueError(msg)
24+
msg = "Failed to acquire IMDS access token"
25+
raise ValueError(msg) from e
2626

2727
if status != 200:
2828
print(body)
2929
msg = "Failed to acquire IMDS access token."
3030
raise ValueError(msg)
3131
try:
3232
data = json.loads(body)
33-
except Exception:
34-
raise ValueError("Azure IMDS response must be in JSON format.")
33+
except Exception as e:
34+
raise ValueError("Azure IMDS response must be in JSON format.") from e
3535

3636
for key in ["access_token", "expires_in"]:
3737
if not data.get(key):

.evergreen/auth_oidc/gcp/remote-scripts/test.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from pymongo import MongoClient
22
import os
3-
import json
43
from urllib.request import urlopen, Request
54
from pymongo.auth_oidc import OIDCCallback, OIDCCallbackContext, OIDCCallbackResult
65

@@ -20,7 +19,7 @@ def fetch(self, context: OIDCCallbackContext) -> OIDCCallbackResult:
2019
body = response.read().decode('utf8')
2120
except Exception as e:
2221
msg = "Failed to acquire IMDS access token: %s" % e
23-
raise ValueError(msg)
22+
raise ValueError(msg) from e
2423

2524
if status != 200:
2625
print(body)

.evergreen/auth_oidc/oidc_write_orchestration.py

100644100755
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
HERE = os.path.abspath(os.path.dirname(__file__))
1111
sys.path.insert(0, HERE)
12-
from utils import get_secrets, MOCK_ENDPOINT, DEFAULT_CLIENT
12+
from utils import get_secrets, DEFAULT_CLIENT
1313

1414

1515
def azure():

.evergreen/auth_oidc/utils.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1-
import json
21
import os
32
import sys
43

5-
import boto3
4+
import boto3 # noqa: F401
65

76
HERE = os.path.abspath(os.path.dirname(__file__))
87

@@ -11,7 +10,7 @@ def join(*args):
1110

1211
aws_lib = join(os.path.dirname(HERE), 'auth_aws', 'lib')
1312
sys.path.insert(0, aws_lib)
14-
from aws_handle_oidc_creds import get_id_token, MOCK_ENDPOINT
13+
from aws_handle_oidc_creds import get_id_token, MOCK_ENDPOINT # noqa: F401
1514
secrets_root = join(os.path.dirname(HERE), 'secrets_handling')
1615
sys.path.insert(0, secrets_root)
1716
from setup_secrets import get_secrets as root_get_secrets

.evergreen/csfle/fake_azure.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def get_oauth2_token():
115115
if case == 'slow':
116116
return _slow()
117117

118-
assert case in (None, ''), 'Unknown HTTP test case "{}"'.format(case)
118+
assert case in (None, ''), f'Unknown HTTP test case "{case}"'
119119

120120
return {
121121
'access_token': 'magic-cookie',
@@ -148,7 +148,6 @@ def _slow() -> Iterable[bytes]:
148148

149149
if __name__ == '__main__':
150150
print(
151-
'RECOMMENDED: Run this script using bottle.py (e.g. [{} {}/bottle.py fake_azure:imds])'
152-
.format(sys.executable,
153-
Path(__file__).resolve().parent))
151+
f'RECOMMENDED: Run this script using bottle.py (e.g. [{sys.executable} {Path(__file__).resolve().parent}/bottle.py fake_azure:imds])'
152+
)
154153
imds.run()

.evergreen/csfle/gcpkms/mock_server.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,7 @@ def b64_to_b64url(b64):
1919
def dict_to_b64url(arg):
2020
as_json = json.dumps(arg).encode("utf8")
2121
as_b64 = base64.b64encode(as_json).decode("utf8")
22-
as_b64url = b64_to_b64url(as_b64)
23-
return as_b64url
22+
return b64_to_b64url(as_b64)
2423

2524

2625
def get_access_token():
@@ -34,7 +33,7 @@ def get_access_token():
3433
if "GOOGLE_APPLICATION_CREDENTIALS" not in os.environ:
3534
raise Exception(
3635
"please set GOOGLE_APPLICATION_CREDENTIALS environment variable to a JSON Service account key")
37-
creds = json.load(open(os.environ["GOOGLE_APPLICATION_CREDENTIALS"], "r"))
36+
creds = json.load(open(os.environ["GOOGLE_APPLICATION_CREDENTIALS"]))
3837
private_key = creds["private_key"].encode("utf8")
3938
client_email = creds["client_email"]
4039

@@ -82,7 +81,7 @@ def main():
8281
global private_key
8382
port = 5000
8483
server = http.server.HTTPServer(("localhost", port), Handler)
85-
print ("Listening on port {}".format(port))
84+
print (f"Listening on port {port}")
8685
server.serve_forever()
8786

8887

.evergreen/csfle/kms_failpoint_server.py

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def _send_json(self, data: dict):
6464

6565
def _send_not_found(self):
6666
self.send_response(http.HTTPStatus.NOT_FOUND)
67-
msg = "Not found".encode("utf8")
67+
msg = b"Not found"
6868
self.send_header("Content-Type", "text/plain")
6969
self.send_header("Content-Length", len(msg))
7070
self.end_headers()
@@ -95,18 +95,18 @@ def do_POST(self):
9595
remaining_http_fails = data['count']
9696
else:
9797
self._send_not_found()
98-
return
99-
print("Enabling failpoint for type: {}".format(failpoint_type))
98+
return None
99+
print(f"Enabling failpoint for type: {failpoint_type}")
100100
self._send_json(
101-
{"message": "failpoint set for type: '{}'".format(failpoint_type)}
101+
{"message": f"failpoint set for type: '{failpoint_type}'"}
102102
)
103-
return
103+
return None
104104

105105
if path.match("/reset"):
106106
remaining_http_fails = 0
107107
remaining_network_fails = 0
108108
self._send_json({"message": "failpoints reset"})
109-
return
109+
return None
110110

111111
# If a failpoint was set, fail the request.
112112
if remaining_network_fails > 0:
@@ -118,40 +118,39 @@ def do_POST(self):
118118
aws_op = self.headers['X-Amz-Target']
119119
if aws_op == "TrentService.Encrypt":
120120
self._send_json({"CiphertextBlob": base64.b64encode(fake_ciphertext.encode()).decode()})
121-
return
122-
elif aws_op == "TrentService.Decrypt":
121+
return None
122+
if aws_op == "TrentService.Decrypt":
123123
if remaining_http_fails > 0:
124124
self._http_fail()
125-
return
125+
return None
126126
self._send_json({"Plaintext": base64.b64encode(fake_plaintext.encode()).decode()})
127-
return
128-
else:
129-
self._send_not_found()
130-
return
127+
return None
128+
self._send_not_found()
129+
return None
131130

132131
# GCP or Azure auth path: /c01df00d-cafe-g00d-dea1-decea5sedbeef/oauth2/v2.0/token
133132
if path.match("*token"):
134133
if remaining_http_fails > 0:
135134
self._http_fail()
136-
return
135+
return None
137136
return self._send_json({"access_token": "foo", "expires_in": 99999})
138137
# GCP encrypt path: /v1/projects/{project}/locations/{location}/keyRings/{key-ring}/cryptoKeys/{key}:encrypt
139-
elif path.match("*encrypt"):
138+
if path.match("*encrypt"):
140139
return self._send_json({"ciphertext": base64.b64encode(fake_ciphertext.encode()).decode()})
141140
# GCP decrypt path: /v1/projects/{project}/locations/{location}/keyRings/{key-ring}/cryptoKeys/{key}:decrypt
142-
elif path.match("*decrypt"):
141+
if path.match("*decrypt"):
143142
if remaining_http_fails > 0:
144143
self._http_fail()
145-
return
144+
return None
146145
return self._send_json({"plaintext": base64.b64encode(fake_plaintext.encode()).decode()})
147146
# Azure decrypt path: /keys/{key-name}/{key-version}/unwrapkey
148-
elif path.match("*unwrapkey"):
147+
if path.match("*unwrapkey"):
149148
if remaining_http_fails > 0:
150149
self._http_fail()
151-
return
150+
return None
152151
return self._send_json({"value": base64.b64encode(fake_plaintext.encode()).decode()})
153152
# Azure encrypt path: /keys/{key-name}/{key-version}/wrapkey
154-
elif path.match("*wrapkey"):
153+
if path.match("*wrapkey"):
155154
return self._send_json({"value": base64.b64encode(fake_ciphertext.encode()).decode()})
156155
self._send_not_found()
157156

.evergreen/csfle/kms_http_common.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,12 +71,11 @@ def do_GET(self):
7171
else:
7272
self.send_response(http.HTTPStatus.NOT_FOUND)
7373
self.end_headers()
74-
self.wfile.write("Unknown URL".encode())
74+
self.wfile.write(b"Unknown URL")
7575

7676
@abstractmethod
7777
def do_POST(self):
7878
"""Serve a POST request."""
79-
pass
8079

8180
def _send_reply(self, data, status=http.HTTPStatus.OK):
8281
print("Sending Response: " + data.decode())

.evergreen/csfle/kms_http_server.py

100644100755
Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def do_POST(self):
5656
else:
5757
self.send_response(http.HTTPStatus.NOT_FOUND)
5858
self.end_headers()
59-
self.wfile.write("Unknown URL".encode())
59+
self.wfile.write(b"Unknown URL")
6060

6161
def _do_post(self):
6262
c_len = int(self.headers.get('content-length'))
@@ -133,31 +133,31 @@ def _do_encrypt(self, raw_input):
133133
}
134134

135135
self._send_reply(json.dumps(response).encode('utf-8'))
136-
return
136+
return None
137137

138138
def _do_encrypt_faults(self, raw_ciphertext):
139139
kms_http_common.stats.fault_calls += 1
140140

141141
if kms_http_common.fault_type == kms_http_common.FAULT_ENCRYPT:
142-
self._send_reply("Internal Error of some sort.".encode(), http.HTTPStatus.INTERNAL_SERVER_ERROR)
142+
self._send_reply(b"Internal Error of some sort.", http.HTTPStatus.INTERNAL_SERVER_ERROR)
143143
return
144-
elif kms_http_common.fault_type == kms_http_common.FAULT_ENCRYPT_WRONG_FIELDS:
144+
if kms_http_common.fault_type == kms_http_common.FAULT_ENCRYPT_WRONG_FIELDS:
145145
response = {
146146
"SomeBlob" : raw_ciphertext,
147147
"KeyId" : "foo",
148148
}
149149

150150
self._send_reply(json.dumps(response).encode('utf-8'))
151151
return
152-
elif kms_http_common.fault_type == kms_http_common.FAULT_ENCRYPT_BAD_BASE64:
152+
if kms_http_common.fault_type == kms_http_common.FAULT_ENCRYPT_BAD_BASE64:
153153
response = {
154154
"CiphertextBlob" : "foo",
155155
"KeyId" : "foo",
156156
}
157157

158158
self._send_reply(json.dumps(response).encode('utf-8'))
159159
return
160-
elif kms_http_common.fault_type == kms_http_common.FAULT_ENCRYPT_CORRECT_FORMAT:
160+
if kms_http_common.fault_type == kms_http_common.FAULT_ENCRYPT_CORRECT_FORMAT:
161161
response = {
162162
"__type" : "NotFoundException",
163163
"Message" : "Error encrypting message",
@@ -190,23 +190,23 @@ def _do_decrypt(self, raw_input):
190190
}
191191

192192
self._send_reply(json.dumps(response).encode('utf-8'))
193-
return
193+
return None
194194

195195
def _do_decrypt_faults(self, blob):
196196
kms_http_common.stats.fault_calls += 1
197197

198198
if kms_http_common.fault_type == kms_http_common.FAULT_DECRYPT:
199-
self._send_reply("Internal Error of some sort.".encode(), http.HTTPStatus.INTERNAL_SERVER_ERROR)
199+
self._send_reply(b"Internal Error of some sort.", http.HTTPStatus.INTERNAL_SERVER_ERROR)
200200
return
201-
elif kms_http_common.fault_type == kms_http_common.FAULT_DECRYPT_WRONG_KEY:
201+
if kms_http_common.fault_type == kms_http_common.FAULT_DECRYPT_WRONG_KEY:
202202
response = {
203203
"Plaintext" : "ta7DXE7J0OiCRw03dYMJSeb8nVF5qxTmZ9zWmjuX4zW/SOorSCaY8VMTWG+cRInMx/rr/+QeVw2WjU2IpOSvMg==",
204204
"KeyId" : "Not a clue",
205205
}
206206

207207
self._send_reply(json.dumps(response).encode('utf-8'))
208208
return
209-
elif kms_http_common.fault_type == kms_http_common.FAULT_DECRYPT_CORRECT_FORMAT:
209+
if kms_http_common.fault_type == kms_http_common.FAULT_DECRYPT_CORRECT_FORMAT:
210210
response = {
211211
"__type" : "NotFoundException",
212212
"Message" : "Error decrypting message",

0 commit comments

Comments
 (0)