forked from GoogleCloudPlatform/cloud-sql-python-connector
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmocks.py
More file actions
246 lines (214 loc) · 8.2 KB
/
Copy pathmocks.py
File metadata and controls
246 lines (214 loc) · 8.2 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
""""
Copyright 2022 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
# file containing all mocks used for Cloud SQL Python Connector unit tests
import json
import ssl
from tempfile import TemporaryDirectory
from typing import Any, Dict, Tuple, Optional
from google.cloud.sql.connector import IPTypes
from google.cloud.sql.connector.instance import InstanceMetadata
from google.cloud.sql.connector.utils import write_to_file, generate_keys
import datetime
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography import x509
from cryptography.x509.oid import NameOID
class MockInstance:
_enable_iam_auth: bool
def __init__(
self,
enable_iam_auth: bool = False,
) -> None:
self._enable_iam_auth = enable_iam_auth
# mock connect_info
async def connect_info(
self,
driver: str,
ip_type: IPTypes,
**kwargs: Any,
) -> Any:
return True
class BadRefresh(Exception):
pass
class MockMetadata(InstanceMetadata):
"""Mock class for InstanceMetadata"""
def __init__(
self, expiration: datetime.datetime, ip_addrs: Dict = {"PRIMARY": "0.0.0.0"}
) -> None:
self.expiration = expiration
self.ip_addrs = ip_addrs
async def instance_metadata_success(*args: Any, **kwargs: Any) -> MockMetadata:
return MockMetadata(datetime.datetime.now() + datetime.timedelta(minutes=10))
async def instance_metadata_expired(*args: Any, **kwargs: Any) -> MockMetadata:
return MockMetadata(datetime.datetime.now() - datetime.timedelta(minutes=10))
async def instance_metadata_error(*args: Any, **kwargs: Any) -> None:
raise BadRefresh("something went wrong...")
def generate_cert(
project: str, name: str
) -> Tuple[x509.CertificateBuilder, rsa.RSAPrivateKey]:
"""
Generate a private key and cert object to be used in testing.
"""
# generate private key
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
common_name = f"{project}:{name}"
# configure cert subject
subject = issuer = x509.Name(
[
x509.NameAttribute(NameOID.COUNTRY_NAME, "US"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "California"),
x509.NameAttribute(NameOID.LOCALITY_NAME, "Mountain View"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Google Inc"),
x509.NameAttribute(NameOID.COMMON_NAME, "{}".format(common_name)),
]
)
# build cert
cert = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(issuer)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.datetime.utcnow())
.not_valid_after(
# cert valid for 10 mins
datetime.datetime.utcnow()
+ datetime.timedelta(minutes=60)
)
)
return cert, key
def self_signed_cert(cert: x509.CertificateBuilder, key: rsa.RSAPrivateKey) -> str:
"""
Create a PEM encoded certificate that is self-signed.
"""
return (
cert.sign(key, hashes.SHA256(), default_backend())
.public_bytes(encoding=serialization.Encoding.PEM)
.decode("UTF-8")
)
def client_key_signed_cert(
cert: x509.CertificateBuilder,
priv_key: rsa.RSAPrivateKey,
client_key: rsa.RSAPublicKey,
) -> str:
"""
Create a PEM encoded certificate that is signed by given public key.
"""
# configure cert subject
subject = issuer = x509.Name(
[
x509.NameAttribute(NameOID.COUNTRY_NAME, "US"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Google Inc"),
x509.NameAttribute(NameOID.COMMON_NAME, "Google Cloud SQL Client"),
]
)
# build cert
cert = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(issuer)
.public_key(client_key)
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.datetime.utcnow())
.not_valid_after(cert._not_valid_after) # type: ignore
)
return (
cert.sign(priv_key, hashes.SHA256(), default_backend())
.public_bytes(encoding=serialization.Encoding.PEM)
.decode("UTF-8")
)
async def create_ssl_context() -> ssl.SSLContext:
"""Helper method to build an ssl.SSLContext for tests"""
# generate keys and certs for test
cert, private_key = generate_cert("my-project", "my-instance")
server_ca_cert = self_signed_cert(cert, private_key)
client_private, client_bytes = await generate_keys()
client_key: rsa.RSAPublicKey = serialization.load_pem_public_key(
client_bytes.encode("UTF-8"), default_backend()
) # type: ignore
ephemeral_cert = client_key_signed_cert(cert, private_key, client_key)
# build default ssl.SSLContext
context = ssl.create_default_context()
# load ssl.SSLContext with certs
with TemporaryDirectory() as tmpdir:
ca_filename, cert_filename, key_filename = write_to_file(
tmpdir, server_ca_cert, ephemeral_cert, client_private
)
context.load_cert_chain(cert_filename, keyfile=key_filename)
context.load_verify_locations(cafile=ca_filename)
return context
class FakeCSQLInstance:
def __init__(
self,
project: str = "my-project",
region: str = "my-region",
name: str = "my-instance",
db_version: str = "POSTGRES_14",
) -> None:
self.project = project
self.region = region
self.name = name
self.db_version = db_version
self.ip_addrs = {"PRIMARY": "0.0.0.0", "PRIVATE": "1.1.1.1"}
self.backend_type = "SECOND_GEN"
# generate server private key and cert
cert, key = generate_cert(project, name)
self.key = key
self.cert = cert
def connect_settings(self, ip_addrs: Optional[Dict] = None) -> str:
"""
Mock data for the following API:
https://sqladmin.googleapis.com/sql/v1beta4/projects/{project}/instances/{instance}/connectSettings
"""
server_ca_cert = self_signed_cert(self.cert, self.key)
ip_addrs = ip_addrs if ip_addrs else self.ip_addrs
ip_addresses = [
{"type": key, "ipAddress": value} for key, value in ip_addrs.items()
]
return json.dumps(
{
"kind": "sql#connectSettings",
"serverCaCert": {
"cert": server_ca_cert,
"instance": self.name,
"expirationTime": str(
datetime.datetime.utcnow() + datetime.timedelta(minutes=10)
),
},
"ipAddresses": ip_addresses,
"region": self.region,
"databaseVersion": self.db_version,
"backendType": self.backend_type,
}
)
def generate_ephemeral(self, client_bytes: str) -> str:
"""
Mock data for the following API:
https://sqladmin.googleapis.com/sql/v1beta4/projects/{project}/instances/{instance}:generateEphemeralCert
"""
client_key: rsa.RSAPublicKey = serialization.load_pem_public_key(
client_bytes.encode("UTF-8"), default_backend()
) # type: ignore
ephemeral_cert = client_key_signed_cert(self.cert, self.key, client_key)
return json.dumps(
{
"ephemeralCert": {
"kind": "sql#sslCert",
"cert": ephemeral_cert,
"expirationTime": str(
datetime.datetime.utcnow() + datetime.timedelta(minutes=10)
),
}
}
)