-
Notifications
You must be signed in to change notification settings - Fork 542
Expand file tree
/
Copy pathcsp_helpers.py
More file actions
497 lines (413 loc) · 17.7 KB
/
csp_helpers.py
File metadata and controls
497 lines (413 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
#!/usr/bin/env python
import datetime
import json
import logging
import os
from abc import ABC, abstractmethod
from time import time
from unittest import mock
from unittest.mock import patch
from urllib.parse import parse_qs, urlparse
import jwt
from botocore.awsrequest import AWSRequest
from botocore.credentials import Credentials
from snowflake.connector.vendored.requests.exceptions import ConnectTimeout, HTTPError
from snowflake.connector.vendored.requests.models import Response
logger = logging.getLogger(__name__)
def gen_dummy_id_token(
sub="test-subject", iss="test-issuer", aud="snowflakecomputing.com"
) -> str:
"""Generates a dummy ID token using the given subject and issuer."""
now = int(time())
key = "secret"
payload = {
"sub": sub,
"iss": iss,
"aud": aud,
"iat": now,
"exp": now + 60 * 60,
}
logger.debug(f"Generating dummy token with the following claims:\n{str(payload)}")
return jwt.encode(
payload=payload,
key=key,
algorithm="HS256",
)
def gen_dummy_access_token(sub="test-subject", key="secret") -> str:
"""Generates a dummy access token using the given subject."""
logger.debug(f"Generating dummy access token for subject {sub}")
return (sub + key).encode("utf-8").hex()
def build_response(content: bytes, status_code: int = 200, headers=None) -> Response:
"""Builds a requests.Response object with the given status code and content."""
response = Response()
response.status_code = status_code
response._content = content
response.headers = headers
return response
class FakeMetadataService(ABC):
"""Base class for fake metadata service implementations."""
def __init__(self):
self.unexpected_host_name_exception = ConnectTimeout()
self.reset_defaults()
@abstractmethod
def reset_defaults(self):
"""Resets any default values for test parameters.
This is called in the constructor and when entering as a context manager.
"""
pass
@property
@abstractmethod
def expected_hostnames(self):
"""Hostnames at which this metadata service is listening.
Used to raise a ConnectTimeout for requests not targeted to this hostname.
"""
pass
def handle_request(self, method, parsed_url, headers, timeout):
return ConnectTimeout()
def get_environment_variables(self) -> dict[str, str]:
"""Returns a dictionary of environment variables to patch in to fake the metadata service."""
return {}
def _handle_get(self, url, headers=None, timeout=None):
"""Handles requests.get() calls by converting them to request() format."""
if headers is None:
headers = {}
return self.__call__(method="GET", url=url, headers=headers, timeout=timeout)
def __call__(self, method, url, headers, timeout=None):
"""Entry point for the requests mock."""
logger.debug(f"Received request: {method} {url} {str(headers)}")
parsed_url = urlparse(url)
if parsed_url.hostname not in self.expected_hostnames:
logger.debug(
f"Received request to unexpected hostname {parsed_url.hostname}"
)
raise self.unexpected_host_name_exception
return self.handle_request(method, parsed_url, headers, timeout)
def __enter__(self):
"""Patches the relevant HTTP calls when entering as a context manager."""
self.reset_defaults()
self.patchers = []
# requests.request is used by the direct metadata service API calls from our code. This is the main
# thing being faked here.
self.patchers.append(
mock.patch(
"snowflake.connector.vendored.requests.sessions.Session.request",
side_effect=self,
)
)
self.patchers.append(
mock.patch(
"snowflake.connector.session_manager.SessionManager.get",
side_effect=self._handle_get,
)
)
# HTTPConnection.request is used by the AWS boto libraries. We're not mocking those calls here, so we
# simply raise a ConnectTimeout to avoid making real network calls.
self.patchers.append(
mock.patch(
"urllib3.connection.HTTPConnection.request",
side_effect=ConnectTimeout(),
)
)
# Patch the environment variables to fake the metadata service
# Note that this doesn't clear, so it's additive to the existing environment.
self.patchers.append(patch.dict(os.environ, self.get_environment_variables()))
for patcher in self.patchers:
patcher.__enter__()
return self
def __exit__(self, *args, **kwargs):
for patcher in self.patchers:
patcher.__exit__(*args, **kwargs)
class UnavailableMetadataService(FakeMetadataService):
"""Emulates an environment where all metadata services are unavailable."""
def reset_defaults(self):
pass
@property
def expected_hostnames(self):
return [] # Always raise a ConnectTimeout.
def handle_request(self, method, parsed_url, headers, timeout):
# This should never be called because we always raise a ConnectTimeout.
pass
class FakeAzureVmMetadataService(FakeMetadataService):
"""Emulates an environment with the Azure VM metadata service."""
def reset_defaults(self):
# Defaults used for generating an Entra ID token. Can be overriden in individual tests.
self.sub = "611ab25b-2e81-4e18-92a7-b21f2bebb269"
self.iss = "https://sts.windows.net/2c0183ed-cf17-480d-b3f7-df91bc0a97cd"
self.has_token_endpoint = True
self.requested_client_id = None
@property
def expected_hostnames(self):
return ["169.254.169.254"]
def handle_request(self, method, parsed_url, headers, timeout):
query_string = parse_qs(parsed_url.query)
logger.debug("Received request for Azure VM metadata service")
if (
method == "GET"
and parsed_url.path == "/metadata/instance"
and headers.get("Metadata") == "true"
):
return build_response(content=b"", status_code=200)
elif (
method == "GET"
and parsed_url.path == "/metadata/identity/oauth2/token"
and headers.get("Metadata") == "true"
and query_string["resource"]
and self.has_token_endpoint
):
resource = query_string["resource"][0]
self.requested_client_id = query_string.get("client_id", [None])[0]
self.token = gen_dummy_id_token(sub=self.sub, iss=self.iss, aud=resource)
return build_response(
json.dumps({"access_token": self.token}).encode("utf-8")
)
else:
# Reject malformed requests.
raise HTTPError()
class FakeAzureFunctionMetadataService(FakeMetadataService):
"""Emulates an environment with the Azure Function metadata service."""
def reset_defaults(self):
# Defaults used for generating an Entra ID token. Can be overriden in individual tests.
self.sub = "611ab25b-2e81-4e18-92a7-b21f2bebb269"
self.iss = "https://sts.windows.net/2c0183ed-cf17-480d-b3f7-df91bc0a97cd"
self.identity_endpoint = "http://169.254.255.2:8081/msi/token"
self.identity_header = "FD80F6DA783A4881BE9FAFA365F58E7A"
self.functions_worker_runtime = "python"
self.functions_extension_version = "~4"
self.azure_web_jobs_storage = "DefaultEndpointsProtocol=https;AccountName=test"
self.parsed_identity_endpoint = urlparse(self.identity_endpoint)
self.requested_client_id = None
@property
def expected_hostnames(self):
return [self.parsed_identity_endpoint.hostname]
def handle_request(self, method, parsed_url, headers, timeout):
query_string = parse_qs(parsed_url.query)
# Reject malformed requests.
if not (
method == "GET"
and parsed_url.path == self.parsed_identity_endpoint.path
and headers.get("X-IDENTITY-HEADER") == self.identity_header
and query_string["resource"]
):
logger.warning(
f"Received malformed request: {method} {parsed_url.path} {str(headers)} {str(query_string)}"
)
raise HTTPError()
logger.debug("Received request for Azure Functions metadata service")
resource = query_string["resource"][0]
self.requested_client_id = query_string.get("client_id", [None])[0]
self.token = gen_dummy_id_token(sub=self.sub, iss=self.iss, aud=resource)
return build_response(json.dumps({"access_token": self.token}).encode("utf-8"))
def get_environment_variables(self) -> dict[str, str]:
return {
"IDENTITY_ENDPOINT": self.identity_endpoint,
"IDENTITY_HEADER": self.identity_header,
"FUNCTIONS_WORKER_RUNTIME": self.functions_worker_runtime,
"FUNCTIONS_EXTENSION_VERSION": self.functions_extension_version,
"AzureWebJobsStorage": self.azure_web_jobs_storage,
}
class FakeGceMetadataService(FakeMetadataService):
"""Emulates an environment with the GCE metadata service."""
def reset_defaults(self):
# Defaults used for generating a token. Can be overriden in individual tests.
self.sub = "123"
self.iss = "https://accounts.google.com"
@property
def expected_hostnames(self):
return ["169.254.169.254", "metadata.google.internal"]
def handle_request(self, method, parsed_url, headers, timeout):
query_string = parse_qs(parsed_url.query)
logger.debug("Received request for GCE metadata service")
if method == "GET" and parsed_url.path == "":
return build_response(
b"", status_code=200, headers={"Metadata-Flavor": "Google"}
)
elif (
method == "GET"
and parsed_url.path
== "/computeMetadata/v1/instance/service-accounts/default/email"
and headers.get("Metadata-Flavor") == "Google"
):
return build_response(b"", status_code=200)
elif (
method == "GET"
and parsed_url.path
== "/computeMetadata/v1/instance/service-accounts/default/identity"
and headers.get("Metadata-Flavor") == "Google"
and query_string["audience"]
):
audience = query_string["audience"][0]
self.token = gen_dummy_id_token(sub=self.sub, iss=self.iss, aud=audience)
return build_response(self.token.encode("utf-8"))
elif (
method == "GET"
and parsed_url.path
== "/computeMetadata/v1/instance/service-accounts/default/token"
and headers.get("Metadata-Flavor") == "Google"
):
self.token = gen_dummy_access_token(sub=self.sub)
ret = {
"access_token": self.token,
"expires_in": 3599,
"token_type": "Bearer",
}
return build_response(json.dumps(ret).encode("utf-8"))
else:
# Reject malformed requests.
raise HTTPError()
class FakeGceCloudRunServiceService(FakeGceMetadataService):
"""Emulates an environment with the GCE Cloud Run Service metadata service."""
def reset_defaults(self):
self.k_service = "test-service"
self.k_revision = "test-revision"
self.k_configuration = "test-configuration"
super().reset_defaults()
def get_environment_variables(self) -> dict[str, str]:
return {
"K_SERVICE": self.k_service,
"K_REVISION": self.k_revision,
"K_CONFIGURATION": self.k_configuration,
}
class FakeGceCloudRunJobService(FakeGceMetadataService):
"""Emulates an environment with the GCE Cloud Run Job metadata service."""
def reset_defaults(self):
self.cloud_run_job = "test-job"
self.cloud_run_execution = "test-execution"
super().reset_defaults()
def get_environment_variables(self) -> dict[str, str]:
return {
"CLOUD_RUN_JOB": self.cloud_run_job,
"CLOUD_RUN_EXECUTION": self.cloud_run_execution,
}
class FakeGitHubActionsService:
"""Emulates an environment running in GitHub Actions."""
def __enter__(self):
# This doesn't clear, so it's additive to the existing environment.
self.os_environment_patch = patch.dict(
os.environ, {"GITHUB_ACTIONS": "github-actions"}
)
self.os_environment_patch.__enter__()
return self
def __exit__(self, *args, **kwargs):
self.os_environment_patch.__exit__(*args)
class FakeAwsEnvironment:
"""Emulates the AWS environment-specific functions used in wif_util.py and platform detection.py.
Unlike the other metadata services, the HTTP calls made by AWS are deep within boto libaries, so
emulating them here would be complex and fragile. Instead, we emulate the higher-level functions
called by the connector code.
"""
def __init__(self):
# Defaults used for generating a token. Can be overriden in individual tests.
self.arn = "arn:aws:sts::123456789:assumed-role/My-Role/i-34afe100cad287fab"
# Path of roles that can be assumed. Empty if no impersonation is allowed.
# Can be overriden in individual tests.
self.assumption_path = []
self.assume_role_call_count = 0
self.caller_identity = {"Arn": self.arn}
self.region = "us-east-1"
self.credentials = Credentials(access_key="ak", secret_key="sk")
self.instance_document = (
b'{"region": "us-east-1", "instanceId": "i-1234567890abcdef0"}'
)
self.metadata_token = "test-token"
self.web_identity_token = "fake.jwt.token-for-testing-only"
def assume_role(self, **kwargs):
if (
self.assumption_path
and kwargs["RoleArn"] == self.assumption_path[self.assume_role_call_count]
):
arn = self.assumption_path[self.assume_role_call_count]
self.assume_role_call_count += 1
return {
"Credentials": {
"AccessKeyId": "access_key",
"SecretAccessKey": "secret_key",
"SessionToken": "session_token",
"Expiration": int(time()) + 60 * 60,
},
"AssumedRoleUser": {"AssumedRoleId": hash(arn), "Arn": arn},
"ResponseMetadata": {},
}
return {}
def get_region(self):
return self.region
def get_credentials(self):
return self.credentials
def sign_request(self, request: AWSRequest):
request.headers.add_header("X-Amz-Date", datetime.time().isoformat())
request.headers.add_header("X-Amz-Security-Token", "<TOKEN>")
request.headers.add_header(
"Authorization",
f"AWS4-HMAC-SHA256 Credential=<cred>, SignedHeaders={';'.join(request.headers.keys())}, Signature=<sig>",
)
def fetcher_get_request(self, url_path, retry_fun, token):
return build_response(self.instance_document)
def fetcher_fetch_metadata_token(self):
return self.metadata_token
def boto3_client(self, *args, **kwargs):
mock_client = mock.Mock()
mock_client.get_caller_identity.return_value = self.caller_identity
mock_client.assume_role = self.assume_role
mock_client.get_web_identity_token.return_value = {
"WebIdentityToken": self.web_identity_token
}
return mock_client
def __enter__(self):
# Patch the relevant functions to do what we want.
self.patchers = []
# Patch sync boto3 calls
self.patchers.append(
mock.patch(
"boto3.session.Session.get_credentials",
side_effect=self.get_credentials,
)
)
self.patchers.append(
mock.patch(
"botocore.auth.SigV4Auth.add_auth", side_effect=self.sign_request
)
)
self.patchers.append(
mock.patch(
"snowflake.connector.wif_util.get_aws_region",
side_effect=self.get_region,
)
)
self.patchers.append(
mock.patch(
"snowflake.connector.platform_detection.IMDSFetcher._get_request",
side_effect=self.fetcher_get_request,
)
)
self.patchers.append(
mock.patch(
"snowflake.connector.platform_detection.IMDSFetcher._fetch_metadata_token",
side_effect=self.fetcher_fetch_metadata_token,
)
)
self.patchers.append(
mock.patch(
"snowflake.connector.platform_detection.boto3.client",
side_effect=self.boto3_client,
)
)
self.patchers.append(
mock.patch("boto3.session.Session.client", side_effect=self.boto3_client)
)
for patcher in self.patchers:
patcher.__enter__()
return self
def __exit__(self, *args, **kwargs):
for patcher in self.patchers:
patcher.__exit__(*args, **kwargs)
class FakeAwsLambdaEnvironment(FakeAwsEnvironment):
"""Emulates an environment running in AWS Lambda."""
def __enter__(self):
# This doesn't clear, so it's additive to the existing environment.
self.os_environment_patch = patch.dict(
os.environ, {"LAMBDA_TASK_ROOT": "/var/task"}
)
self.os_environment_patch.__enter__()
return super().__enter__()
def __exit__(self, *args, **kwargs):
self.os_environment_patch.__exit__(*args)
super().__exit__(*args, **kwargs)