clear-skies-aws 2.0.1__py3-none-any.whl → 2.0.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {clear_skies_aws-2.0.1.dist-info → clear_skies_aws-2.0.3.dist-info}/METADATA +2 -2
- clear_skies_aws-2.0.3.dist-info/RECORD +63 -0
- {clear_skies_aws-2.0.1.dist-info → clear_skies_aws-2.0.3.dist-info}/WHEEL +1 -1
- clearskies_aws/__init__.py +27 -0
- clearskies_aws/actions/__init__.py +15 -0
- clearskies_aws/actions/action_aws.py +135 -0
- clearskies_aws/actions/assume_role.py +115 -0
- clearskies_aws/actions/ses.py +203 -0
- clearskies_aws/actions/sns.py +61 -0
- clearskies_aws/actions/sqs.py +81 -0
- clearskies_aws/actions/step_function.py +73 -0
- clearskies_aws/backends/__init__.py +19 -0
- clearskies_aws/backends/backend.py +106 -0
- clearskies_aws/backends/dynamo_db_backend.py +609 -0
- clearskies_aws/backends/dynamo_db_condition_parser.py +325 -0
- clearskies_aws/backends/dynamo_db_parti_ql_backend.py +965 -0
- clearskies_aws/backends/sqs_backend.py +61 -0
- clearskies_aws/configs/__init__.py +0 -0
- clearskies_aws/contexts/__init__.py +23 -0
- clearskies_aws/contexts/cli_web_socket_mock.py +20 -0
- clearskies_aws/contexts/lambda_alb.py +81 -0
- clearskies_aws/contexts/lambda_api_gateway.py +81 -0
- clearskies_aws/contexts/lambda_api_gateway_web_socket.py +79 -0
- clearskies_aws/contexts/lambda_invoke.py +138 -0
- clearskies_aws/contexts/lambda_sns.py +124 -0
- clearskies_aws/contexts/lambda_sqs_standard.py +139 -0
- clearskies_aws/di/__init__.py +6 -0
- clearskies_aws/di/aws_additional_config_auto_import.py +37 -0
- clearskies_aws/di/inject/__init__.py +6 -0
- clearskies_aws/di/inject/boto3.py +15 -0
- clearskies_aws/di/inject/boto3_session.py +13 -0
- clearskies_aws/di/inject/parameter_store.py +15 -0
- clearskies_aws/endpoints/__init__.py +1 -0
- clearskies_aws/endpoints/secrets_manager_rotation.py +194 -0
- clearskies_aws/endpoints/simple_body_routing.py +41 -0
- clearskies_aws/input_outputs/__init__.py +21 -0
- clearskies_aws/input_outputs/cli_web_socket_mock.py +20 -0
- clearskies_aws/input_outputs/lambda_alb.py +53 -0
- clearskies_aws/input_outputs/lambda_api_gateway.py +123 -0
- clearskies_aws/input_outputs/lambda_api_gateway_web_socket.py +73 -0
- clearskies_aws/input_outputs/lambda_input_output.py +89 -0
- clearskies_aws/input_outputs/lambda_invoke.py +88 -0
- clearskies_aws/input_outputs/lambda_sns.py +88 -0
- clearskies_aws/input_outputs/lambda_sqs_standard.py +86 -0
- clearskies_aws/mocks/__init__.py +1 -0
- clearskies_aws/mocks/actions/__init__.py +6 -0
- clearskies_aws/mocks/actions/ses.py +34 -0
- clearskies_aws/mocks/actions/sns.py +29 -0
- clearskies_aws/mocks/actions/sqs.py +29 -0
- clearskies_aws/mocks/actions/step_function.py +32 -0
- clearskies_aws/models/__init__.py +1 -0
- clearskies_aws/models/web_socket_connection_model.py +182 -0
- clearskies_aws/secrets/__init__.py +13 -0
- clearskies_aws/secrets/additional_configs/__init__.py +62 -0
- clearskies_aws/secrets/additional_configs/iam_db_auth.py +39 -0
- clearskies_aws/secrets/additional_configs/iam_db_auth_with_ssm.py +96 -0
- clearskies_aws/secrets/additional_configs/mysql_connection_dynamic_producer_via_ssh_cert_bastion.py +80 -0
- clearskies_aws/secrets/additional_configs/mysql_connection_dynamic_producer_via_ssm_bastion.py +162 -0
- clearskies_aws/secrets/akeyless_with_ssm_cache.py +60 -0
- clearskies_aws/secrets/parameter_store.py +52 -0
- clearskies_aws/secrets/secrets.py +16 -0
- clearskies_aws/secrets/secrets_manager.py +96 -0
- clear_skies_aws-2.0.1.dist-info/RECORD +0 -4
- {clear_skies_aws-2.0.1.dist-info → clear_skies_aws-2.0.3.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from clearskies_aws.models.web_socket_connection_model import WebSocketConnectionModel
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
import clearskies
|
|
6
|
+
|
|
7
|
+
import clearskies_aws
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class WebSocketConnectionModel(clearskies.Model):
|
|
11
|
+
"""
|
|
12
|
+
Help manage message sending to websocket connections.
|
|
13
|
+
|
|
14
|
+
## Working with Websockets
|
|
15
|
+
|
|
16
|
+
This is a partial model class to help send messages to websocket connections in an API gateway.
|
|
17
|
+
With a API Gateway managed websocket, the API gateway assigns an id to every connection, and you
|
|
18
|
+
send messages to the API gateway itself flagged for some client, via its connection id. It
|
|
19
|
+
helps to understand that you don't need to be connected to the websocket itself to send messages
|
|
20
|
+
to the things connected to it. Instead, you just need the necessary permission on the API gateway
|
|
21
|
+
and you need to know the connection id of the client you want to send a message to. For reference,
|
|
22
|
+
the necessary AWS permission is:
|
|
23
|
+
|
|
24
|
+
```
|
|
25
|
+
{
|
|
26
|
+
"Version": "2012-10-17",
|
|
27
|
+
"Statement": [
|
|
28
|
+
{
|
|
29
|
+
"Effect": "Allow",
|
|
30
|
+
"Action": ["execute-api:ManageConnections"],
|
|
31
|
+
"Resource": "arn:aws:execute-api:${aws_region_name}:${aws_account_id}:${api_gateway_id}/{stage}/*",
|
|
32
|
+
}
|
|
33
|
+
],
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
A simple flow that reproduces a pub/sub approach is:
|
|
38
|
+
|
|
39
|
+
1. Client connects to the API gateway via a websocket, and the backend records the connection id
|
|
40
|
+
in a backend somewhere
|
|
41
|
+
2. Client sends a message through the websocket to "register"/"subscribe" for some resource, and
|
|
42
|
+
the backend service updates the record for the connection to record what resource it is
|
|
43
|
+
subscribed to
|
|
44
|
+
3. If a server needs to send a message to everyone subscribed to a resource, it queries the backends
|
|
45
|
+
for all records connected to the resource in question and sends a message to their connection ids
|
|
46
|
+
through the backend.
|
|
47
|
+
4. If a client needs to send a message to everyone subscribed to a resource, it sends a message
|
|
48
|
+
through the websocket to some backend service which then passes the message along to the appropriate
|
|
49
|
+
connections, just as in #3 above.
|
|
50
|
+
|
|
51
|
+
Most examples with Websockets and API Gateway use dynamodb for storage. You can, of course, use whatever
|
|
52
|
+
backend you want. Still, below is an example pub/sub application to demonstrate how to build a basic
|
|
53
|
+
websocket app:
|
|
54
|
+
|
|
55
|
+
```
|
|
56
|
+
import clearskies
|
|
57
|
+
import clearskies_aws
|
|
58
|
+
|
|
59
|
+
#####################
|
|
60
|
+
## Our model class ##
|
|
61
|
+
#####################
|
|
62
|
+
|
|
63
|
+
class Client(clearskies_aws.models.WebSocketConnectionModel):
|
|
64
|
+
backend = clearskies_aws.backends.DynamoDbBackend()
|
|
65
|
+
|
|
66
|
+
# the base WebSocketConnectionModel class defines a string
|
|
67
|
+
# column called `connection_id` and sets it as the id column,
|
|
68
|
+
# so those are already set. We just need any additional columns
|
|
69
|
+
resource_id = clearskies.columns.String()
|
|
70
|
+
|
|
71
|
+
###########################
|
|
72
|
+
## Our application logic ##
|
|
73
|
+
###########################
|
|
74
|
+
|
|
75
|
+
def on_connect(clients, connection_id):
|
|
76
|
+
clients.create({"connection_id": connection_id})
|
|
77
|
+
|
|
78
|
+
def on_subscribe(clients, connection_id, request_data):
|
|
79
|
+
client = clients.find(f"connection_id={connection_id}")
|
|
80
|
+
if client.exists:
|
|
81
|
+
# we blindly save the request id, which makes it user-generated. This also
|
|
82
|
+
# allows the client to "unsubscribe" by sending up a blank resource
|
|
83
|
+
client.save({"resource_id": request_data["resource_id"])
|
|
84
|
+
|
|
85
|
+
def on_publish(clients, connection_id, request_data):
|
|
86
|
+
my_client = clients.find(f"connection_id={connection_id}")
|
|
87
|
+
message = request_data.get("message")
|
|
88
|
+
|
|
89
|
+
# The problem with our standard input validation is that we can't return a response
|
|
90
|
+
# to the client with an error message. This is not a transactional system. Instead,
|
|
91
|
+
# we would have to send the client a new message with the error in it, which is not
|
|
92
|
+
# something the clearskies endpoints are designed for.
|
|
93
|
+
if not message or not my_client.resource_id:
|
|
94
|
+
return
|
|
95
|
+
|
|
96
|
+
for client in clients.where(f"resource_id={my_client.resource_id}").paginate_all():
|
|
97
|
+
if client.connection_id == my_client.connection_id:
|
|
98
|
+
continue
|
|
99
|
+
|
|
100
|
+
# the send function is provided by clearskies_aws.models.WebSocketConnectionModel
|
|
101
|
+
client.send({"message": message})
|
|
102
|
+
|
|
103
|
+
def on_disconnect(clients, connection_id):
|
|
104
|
+
clients.find(f"connection_id={connection_id}").delete(except_if_not_exists=False)
|
|
105
|
+
|
|
106
|
+
######################################
|
|
107
|
+
## Wiring it all up with clearskies ##
|
|
108
|
+
######################################
|
|
109
|
+
|
|
110
|
+
# We're going to build one application, even though each action gets it's own lambda.
|
|
111
|
+
# The URLs aren't used for routing, but simply to allow us to select which function
|
|
112
|
+
# is associated with each lambda. Actual routing still happens in the API Gateway
|
|
113
|
+
websocket_application = clearskies_aws.contexts.LambdaApiGatewayWebSocket(
|
|
114
|
+
clearskies.EndpointGroup([
|
|
115
|
+
clearskies.endpoints.Callable(
|
|
116
|
+
on_connect,
|
|
117
|
+
url="on_connect",
|
|
118
|
+
),
|
|
119
|
+
clearskies.endpoints.Callable(
|
|
120
|
+
on_subscribe,
|
|
121
|
+
url="on_subscribe",
|
|
122
|
+
),
|
|
123
|
+
clearskies.endpoints.Callable(
|
|
124
|
+
on_publish,
|
|
125
|
+
url="on_publish",
|
|
126
|
+
),
|
|
127
|
+
clearskies.endpoints.Callable(
|
|
128
|
+
on_disconnect,
|
|
129
|
+
url="on_disconnect",
|
|
130
|
+
),
|
|
131
|
+
]),
|
|
132
|
+
classes=[Client],
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
################################
|
|
136
|
+
## The actual lambda handlers ##
|
|
137
|
+
################################
|
|
138
|
+
|
|
139
|
+
def on_connect_handler(event, context):
|
|
140
|
+
return websocket_application(url="on_connect")
|
|
141
|
+
|
|
142
|
+
def on_subscribe_handler(event, context):
|
|
143
|
+
return websocket_application(url="on_subscribe")
|
|
144
|
+
|
|
145
|
+
def on_publish_handler(event, context):
|
|
146
|
+
return websocket_application(url="on_publish")
|
|
147
|
+
|
|
148
|
+
def on_disconnect_handler(event, context):
|
|
149
|
+
return websocket_application(url="on_disconnect")
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
id_column_name = "connection_id"
|
|
155
|
+
|
|
156
|
+
boto3 = clearskies_aws.di.inject.Boto3()
|
|
157
|
+
connection_id = clearskies.columns.String()
|
|
158
|
+
input_output = clearskies.di.inject.InputOutput()
|
|
159
|
+
|
|
160
|
+
def send(self, message):
|
|
161
|
+
if not self:
|
|
162
|
+
raise ValueError("Cannot send message to non-existent connection.")
|
|
163
|
+
if not self.connection_id:
|
|
164
|
+
raise ValueError(
|
|
165
|
+
f"Hmmm... I couldn't find the connection id for the {self.__class__.__name__}. I'm picky about id column names. Can you please make sure I have a column called connection_id and that it contains the connection id?"
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
domain = self.input_output.context_specifics()["domain"]
|
|
169
|
+
stage = self.input_output.context_specifics()["stage"]
|
|
170
|
+
# only include the stage if we're using the default AWS domain - not with a custom domain
|
|
171
|
+
if ".amazonaws.com" in domain:
|
|
172
|
+
endpoint_url = f"https://{domain}/{stage}"
|
|
173
|
+
else:
|
|
174
|
+
endpoint_url = f"https://{domain}"
|
|
175
|
+
api_gateway = self.boto3.client("apigatewaymanagementapi", endpoint_url=endpoint_url)
|
|
176
|
+
|
|
177
|
+
bytes_message = json.dumps(message).encode("utf-8")
|
|
178
|
+
try:
|
|
179
|
+
response = api_gateway.post_to_connection(Data=bytes_message, ConnectionId=self.connection_id)
|
|
180
|
+
except api_gateway.exceptions.GoneException:
|
|
181
|
+
self.delete()
|
|
182
|
+
return response
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from clearskies_aws.secrets import additional_configs
|
|
2
|
+
from clearskies_aws.secrets.akeyless_with_ssm_cache import AkeylessWithSsmCache
|
|
3
|
+
from clearskies_aws.secrets.parameter_store import ParameterStore
|
|
4
|
+
from clearskies_aws.secrets.secrets import Secrets
|
|
5
|
+
from clearskies_aws.secrets.secrets_manager import SecretsManager
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"Secrets",
|
|
9
|
+
"ParameterStore",
|
|
10
|
+
"SecretsManager",
|
|
11
|
+
"AkeylessWithSsmCache",
|
|
12
|
+
"additional_configs",
|
|
13
|
+
]
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
from .iam_db_auth import IAMDBAuth
|
|
2
|
+
from .iam_db_auth_with_ssm import IAMDBAuthWithSSM
|
|
3
|
+
from .mysql_connection_dynamic_producer_via_ssh_cert_bastion import MySQLConnectionDynamicProducerViaSSHCertBastion
|
|
4
|
+
from .mysql_connection_dynamic_producer_via_ssm_bastion import MySQLConnectionDynamicProducerViaSSMBastion
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def mysql_connection_dynamic_producer_via_ssh_cert_bastion(
|
|
8
|
+
producer_name=None,
|
|
9
|
+
bastion_host=None,
|
|
10
|
+
bastion_name=None,
|
|
11
|
+
bastion_region=None,
|
|
12
|
+
bastion_username=None,
|
|
13
|
+
public_key_file_path=None,
|
|
14
|
+
cert_issuer_name=None,
|
|
15
|
+
database_host=None,
|
|
16
|
+
database_name=None,
|
|
17
|
+
local_proxy_port=None,
|
|
18
|
+
):
|
|
19
|
+
return MySQLConnectionDynamicProducerViaSSHCertBastion(
|
|
20
|
+
producer_name=producer_name,
|
|
21
|
+
bastion_host=bastion_host,
|
|
22
|
+
bastion_name=bastion_name,
|
|
23
|
+
bastion_region=bastion_region,
|
|
24
|
+
bastion_username=bastion_username,
|
|
25
|
+
cert_issuer_name=cert_issuer_name,
|
|
26
|
+
public_key_file_path=public_key_file_path,
|
|
27
|
+
database_host=database_host,
|
|
28
|
+
database_name=database_name,
|
|
29
|
+
local_proxy_port=local_proxy_port,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def mysql_connection_dynamic_producer_via_ssm_bastion(
|
|
34
|
+
producer_name=None,
|
|
35
|
+
bastion_instance_id=None,
|
|
36
|
+
bastion_name=None,
|
|
37
|
+
bastion_region=None,
|
|
38
|
+
bastion_username=None,
|
|
39
|
+
public_key_file_path=None,
|
|
40
|
+
database_host=None,
|
|
41
|
+
database_name=None,
|
|
42
|
+
local_proxy_port=None,
|
|
43
|
+
):
|
|
44
|
+
return MySQLConnectionDynamicProducerViaSSMBastion(
|
|
45
|
+
producer_name=producer_name,
|
|
46
|
+
bastion_instance_id=bastion_instance_id,
|
|
47
|
+
bastion_name=bastion_name,
|
|
48
|
+
bastion_region=bastion_region,
|
|
49
|
+
bastion_username=bastion_username,
|
|
50
|
+
public_key_file_path=public_key_file_path,
|
|
51
|
+
database_host=database_host,
|
|
52
|
+
database_name=database_name,
|
|
53
|
+
local_proxy_port=local_proxy_port,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def iam_db_auth():
|
|
58
|
+
return IAMDBAuth()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def iam_db_auth_with_ssm():
|
|
62
|
+
return IAMDBAuthWithSSM()
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
import clearskies
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class IAMDBAuth(clearskies.di.AdditionalConfig):
|
|
9
|
+
def provide_boto3(self):
|
|
10
|
+
import boto3
|
|
11
|
+
|
|
12
|
+
return boto3
|
|
13
|
+
|
|
14
|
+
def provide_connection_details(self, environment, boto3):
|
|
15
|
+
"""
|
|
16
|
+
Make configuration values and environment variables customizable.
|
|
17
|
+
|
|
18
|
+
Allows both the values and the environment variable names to be set for flexible configuration.
|
|
19
|
+
|
|
20
|
+
Returns:
|
|
21
|
+
dict: Connection details for IAM DB authentication.
|
|
22
|
+
"""
|
|
23
|
+
endpoint = environment.get("db_endpoint")
|
|
24
|
+
username = environment.get("db_username")
|
|
25
|
+
database = environment.get("db_database")
|
|
26
|
+
region = environment.get("AWS_REGION")
|
|
27
|
+
ssl_ca_bundle_name = environment.get("ssl_ca_bundle_filename")
|
|
28
|
+
os.environ["LIBMYSQL_ENABLE_CLEARTEXT_PLUGIN"] = "1"
|
|
29
|
+
|
|
30
|
+
rds_api = boto3.Session().client("rds")
|
|
31
|
+
rds_token = rds_api.generate_db_auth_token(DBHostname=endpoint, Port="3306", DBUsername=username, Region=region)
|
|
32
|
+
|
|
33
|
+
return {
|
|
34
|
+
"username": username,
|
|
35
|
+
"password": rds_token,
|
|
36
|
+
"host": endpoint,
|
|
37
|
+
"database": database,
|
|
38
|
+
"ssl_ca": ssl_ca_bundle_name,
|
|
39
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
import clearskies
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class IAMDBAuthWithSSM(clearskies.di.AdditionalConfig):
|
|
9
|
+
def provide_subprocess(self):
|
|
10
|
+
import subprocess
|
|
11
|
+
|
|
12
|
+
return subprocess
|
|
13
|
+
|
|
14
|
+
def provide_socket(self):
|
|
15
|
+
import socket
|
|
16
|
+
|
|
17
|
+
return socket
|
|
18
|
+
|
|
19
|
+
def provide_connection_details(self, environment, subprocess, socket, boto3):
|
|
20
|
+
local_port = self.open_tunnel(environment, subprocess, socket, boto3)
|
|
21
|
+
|
|
22
|
+
return {
|
|
23
|
+
"host": "127.0.0.1",
|
|
24
|
+
"database": environment.get("db_database"),
|
|
25
|
+
"username": environment.get("db_username"),
|
|
26
|
+
"password": self.get_password(environment, boto3),
|
|
27
|
+
"ssl_ca": "rds-cert-bundle.pem",
|
|
28
|
+
"port": local_port,
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
def get_password(self, environment, boto3):
|
|
32
|
+
endpoint = environment.get("db_endpoint")
|
|
33
|
+
username = environment.get("db_username")
|
|
34
|
+
region = environment.get("db_region")
|
|
35
|
+
|
|
36
|
+
rds_api = boto3.Session().client("rds", region_name=region)
|
|
37
|
+
return rds_api.generate_db_auth_token(DBHostname=endpoint, Port="3306", DBUsername=username, Region=region)
|
|
38
|
+
|
|
39
|
+
def open_tunnel(self, environment, subprocess, socket, boto3):
|
|
40
|
+
endpoint = environment.get("db_endpoint")
|
|
41
|
+
region = environment.get("db_region")
|
|
42
|
+
instance_name = environment.get("instance_name")
|
|
43
|
+
local_proxy_port = int(environment.get("local_proxy_port", "9000"))
|
|
44
|
+
|
|
45
|
+
ec2_api = boto3.client("ec2", region_name=region)
|
|
46
|
+
running_instances = ec2_api.describe_instances(
|
|
47
|
+
Filters=[
|
|
48
|
+
{"Name": "tag:Name", "Values": [instance_name]},
|
|
49
|
+
{"Name": "instance-state-name", "Values": ["running"]},
|
|
50
|
+
],
|
|
51
|
+
)
|
|
52
|
+
instance_ids = []
|
|
53
|
+
for reservation in running_instances["Reservations"]:
|
|
54
|
+
for instance in reservation["Instances"]:
|
|
55
|
+
instance_ids.append(instance["InstanceId"])
|
|
56
|
+
|
|
57
|
+
if len(instance_ids) == 0:
|
|
58
|
+
raise ValueError("Failed to launch SSM tunnel! Cannot find bastion!")
|
|
59
|
+
|
|
60
|
+
instance_id = instance_ids.pop()
|
|
61
|
+
self._connect_to_bastion(local_proxy_port, instance_id, endpoint, subprocess, socket)
|
|
62
|
+
return local_proxy_port
|
|
63
|
+
|
|
64
|
+
def _connect_to_bastion(self, local_proxy_port, instance_id, endpoint, subprocess, socket):
|
|
65
|
+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
66
|
+
result = sock.connect_ex(("127.0.0.1", local_proxy_port))
|
|
67
|
+
if result == 0:
|
|
68
|
+
sock.close()
|
|
69
|
+
return
|
|
70
|
+
|
|
71
|
+
tunnel_command = [
|
|
72
|
+
"aws",
|
|
73
|
+
"--region",
|
|
74
|
+
"us-east-1",
|
|
75
|
+
"ssm",
|
|
76
|
+
"start-session",
|
|
77
|
+
"--target",
|
|
78
|
+
"{}".format(instance_id),
|
|
79
|
+
"--document-name",
|
|
80
|
+
"AWS-StartPortForwardingSessionToRemoteHost",
|
|
81
|
+
'--parameters={{"host":["{}"], "portNumber":["3306"],"localPortNumber":["{}"]}}'.format(
|
|
82
|
+
endpoint, local_proxy_port
|
|
83
|
+
),
|
|
84
|
+
]
|
|
85
|
+
|
|
86
|
+
subprocess.Popen(tunnel_command)
|
|
87
|
+
connected = False
|
|
88
|
+
attempts = 0
|
|
89
|
+
while not connected and attempts < 6:
|
|
90
|
+
attempts += 1
|
|
91
|
+
time.sleep(0.5)
|
|
92
|
+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
93
|
+
result = sock.connect_ex(("127.0.0.1", local_proxy_port))
|
|
94
|
+
if result == 0:
|
|
95
|
+
return
|
|
96
|
+
raise ValueError("Failed to launch SSM tunnel with command: " + " ".join(tunnel_command))
|
clearskies_aws/secrets/additional_configs/mysql_connection_dynamic_producer_via_ssh_cert_bastion.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import socket
|
|
5
|
+
import subprocess
|
|
6
|
+
import time
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from clearskies.secrets.additional_configs import MySQLConnectionDynamicProducerViaSSHCertBastion as Base
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class MySQLConnectionDynamicProducerViaSSHCertBastion(Base):
|
|
13
|
+
_config = None
|
|
14
|
+
_boto3 = None
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
producer_name=None,
|
|
19
|
+
bastion_region=None,
|
|
20
|
+
bastion_name=None,
|
|
21
|
+
bastion_host=None,
|
|
22
|
+
bastion_username=None,
|
|
23
|
+
public_key_file_path=None,
|
|
24
|
+
local_proxy_port=None,
|
|
25
|
+
cert_issuer_name=None,
|
|
26
|
+
database_host=None,
|
|
27
|
+
database_name=None,
|
|
28
|
+
):
|
|
29
|
+
# not using kwargs because I want the argument list to be explicit
|
|
30
|
+
self.config = {
|
|
31
|
+
"producer_name": producer_name,
|
|
32
|
+
"bastion_host": bastion_host,
|
|
33
|
+
"bastion_region": bastion_region,
|
|
34
|
+
"bastion_name": bastion_name,
|
|
35
|
+
"bastion_username": bastion_username,
|
|
36
|
+
"public_key_file_path": public_key_file_path,
|
|
37
|
+
"local_proxy_port": local_proxy_port,
|
|
38
|
+
"cert_issuer_name": cert_issuer_name,
|
|
39
|
+
"database_host": database_host,
|
|
40
|
+
"database_name": database_name,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
def provide_connection_details(self, environment, secrets, boto3):
|
|
44
|
+
self._boto3 = boto3
|
|
45
|
+
return super().provide_connection_details(environment, secrets)
|
|
46
|
+
|
|
47
|
+
def _get_bastion_host(self, environment):
|
|
48
|
+
bastion_host = self._fetch_config(environment, "bastion_host", "akeyless_mysql_bastion_host", default="")
|
|
49
|
+
bastion_name = self._fetch_config(environment, "bastion_name", "akeyless_mysql_bastion_name", default="")
|
|
50
|
+
if bastion_host:
|
|
51
|
+
return bastion_host
|
|
52
|
+
if bastion_name:
|
|
53
|
+
bastion_region = self._fetch_config(environment, "bastion_region", "akeyless_mysql_bastion_region")
|
|
54
|
+
return self._public_ip_from_name(bastion_name, bastion_region)
|
|
55
|
+
raise ValueError(
|
|
56
|
+
f"I was asked to connect to a database via an AKeyless dynamic producer through an SSH bastion with certificate auth, but I'm missing some configuration. I need either the bastion host or the name of the instance in AWS. These can be set in the call to `clearskies.backends.akeyless_aws.mysql_connection_dynamic_producer_via_ssh_cert_bastion()` by providing the 'bastion_host' or 'bastion_name' argument, or by setting an environment variable named 'akeyless_mysql_bastion_host' or 'akeyless_mysql_bastion_name'."
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
def _public_ip_from_name(self, bastion_name, bastion_region):
|
|
60
|
+
ec2 = self._boto3.client("ec2", region_name=bastion_region)
|
|
61
|
+
response = ec2.describe_instances(
|
|
62
|
+
Filters=[
|
|
63
|
+
{"Name": "tag:Name", "Values": [bastion_name]},
|
|
64
|
+
{"Name": "instance-state-name", "Values": ["running"]},
|
|
65
|
+
],
|
|
66
|
+
)
|
|
67
|
+
if not response.get("Reservations"):
|
|
68
|
+
raise ValueError(
|
|
69
|
+
f"Could not find a running instance with the designated bastion name, '{bastion_name}' in region '{bastion_region}'"
|
|
70
|
+
)
|
|
71
|
+
if not response.get("Reservations")[0].get("Instances"):
|
|
72
|
+
raise ValueError(
|
|
73
|
+
f"Could not find a running instance with the designated bastion name, '{bastion_name}' in region '{bastion_region}'"
|
|
74
|
+
)
|
|
75
|
+
instance = response.get("Reservations")[0].get("Instances")[0]
|
|
76
|
+
if not instance.get("PublicIpAddress"):
|
|
77
|
+
raise ValueError(
|
|
78
|
+
f"I found the bastion instance with a name of '{bastion_name}' in region '{bastion_region}', but it doesn't have a public IP address"
|
|
79
|
+
)
|
|
80
|
+
return instance.get("PublicIpAddress")
|
clearskies_aws/secrets/additional_configs/mysql_connection_dynamic_producer_via_ssm_bastion.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import socket
|
|
5
|
+
import subprocess
|
|
6
|
+
import time
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from .mysql_connection_dynamic_producer_via_ssh_cert_bastion import (
|
|
10
|
+
MySQLConnectionDynamicProducerViaSSHCertBastion as Base,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class MySQLConnectionDynamicProducerViaSSMBastion(Base):
|
|
15
|
+
_config = None
|
|
16
|
+
_boto3 = None
|
|
17
|
+
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
producer_name=None,
|
|
21
|
+
bastion_region=None,
|
|
22
|
+
bastion_name=None,
|
|
23
|
+
bastion_username=None,
|
|
24
|
+
bastion_instance_id=None,
|
|
25
|
+
public_key_file_path=None,
|
|
26
|
+
local_proxy_port=None,
|
|
27
|
+
database_host=None,
|
|
28
|
+
database_name=None,
|
|
29
|
+
):
|
|
30
|
+
# not using kwargs because I want the argument list to be explicit
|
|
31
|
+
self.config = {
|
|
32
|
+
"producer_name": producer_name,
|
|
33
|
+
"bastion_instance_id": bastion_instance_id,
|
|
34
|
+
"bastion_region": bastion_region,
|
|
35
|
+
"bastion_name": bastion_name,
|
|
36
|
+
"bastion_username": bastion_username,
|
|
37
|
+
"public_key_file_path": public_key_file_path,
|
|
38
|
+
"local_proxy_port": local_proxy_port,
|
|
39
|
+
"database_host": database_host,
|
|
40
|
+
"database_name": database_name,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
def provide_connection_details(self, environment, secrets, boto3):
|
|
44
|
+
self._boto3 = boto3
|
|
45
|
+
if not secrets:
|
|
46
|
+
raise ValueError(
|
|
47
|
+
"I was asked to connect to a database via an AKeyless dynamic producer but AKeyless itself wasn't configured. Try setting the AKeyless auth method via clearskies.secrets.akeyless_[jwt|saml|aws_iam]_auth()"
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
producer_name = self._fetch_config(environment, "producer_name", "akeyless_mysql_dynamic_producer")
|
|
51
|
+
bastion_username = self._fetch_config(environment, "bastion_username", "mysql_bastion_username", default="ssm")
|
|
52
|
+
bastion_instance_id = self._get_bastion_instance_id(environment)
|
|
53
|
+
public_key_file_path = self._fetch_config(
|
|
54
|
+
environment, "public_key_file_path", "mysql_bastion_public_key_file_path"
|
|
55
|
+
)
|
|
56
|
+
local_proxy_port = self._fetch_config(
|
|
57
|
+
environment, "local_proxy_port", "akeyless_mysql_bastion_local_proxy_port", default=8888
|
|
58
|
+
)
|
|
59
|
+
database_host = self._fetch_config(environment, "database_host", "db_host")
|
|
60
|
+
database_name = self._fetch_config(environment, "database_name", "db_database")
|
|
61
|
+
|
|
62
|
+
# Create the SSH tunnel (yeah, it's obnoxious)
|
|
63
|
+
self._create_tunnel(
|
|
64
|
+
secrets,
|
|
65
|
+
bastion_instance_id,
|
|
66
|
+
bastion_username,
|
|
67
|
+
bastion_region,
|
|
68
|
+
public_key_file_path,
|
|
69
|
+
local_proxy_port,
|
|
70
|
+
database_host,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
# and now we can fetch credentials
|
|
74
|
+
credentials = secrets.get_dynamic_secret(producer_name)
|
|
75
|
+
|
|
76
|
+
return {
|
|
77
|
+
"username": credentials["user"],
|
|
78
|
+
"password": credentials["password"],
|
|
79
|
+
"host": "127.0.0.1",
|
|
80
|
+
"database": database_name,
|
|
81
|
+
"port": local_proxy_port,
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
def _get_bastion_instance_id(self, environment):
|
|
85
|
+
bastion_instance_id = self._fetch_config(
|
|
86
|
+
environment, "bastion_instance_id", "mysql_bastion_instance_id", default=""
|
|
87
|
+
)
|
|
88
|
+
bastion_name = self._fetch_config(environment, "bastion_name", "mysql_bastion_name", default="")
|
|
89
|
+
if bastion_instance_id:
|
|
90
|
+
return bastion_instance_id
|
|
91
|
+
if bastion_name:
|
|
92
|
+
bastion_region = self._fetch_config(environment, "bastion_region", "mysql_bastion_region")
|
|
93
|
+
return self._instance_id_from_name(bastion_name, bastion_region)
|
|
94
|
+
raise ValueError(
|
|
95
|
+
f"I was asked to connect to a database via an AKeyless dynamic producer through an SSH bastion with certificate auth, but I'm missing some configuration. I need either the bastion host or the name of the instance in AWS. These can be set in the call to `clearskies.backends.akeyless_aws.mysql_connection_dynamic_producer_via_ssh_cert_bastion()` by providing the 'bastion_host' or 'bastion_name' argument, or by setting an environment variable named 'akeyless_mysql_bastion_host' or 'akeyless_mysql_bastion_name'."
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
def _instance_id_from_name(self, bastion_name, bastion_region):
|
|
99
|
+
ec2 = self._boto3.client("ec2", region_name=bastion_region)
|
|
100
|
+
response = ec2.describe_instances(
|
|
101
|
+
Filters=[
|
|
102
|
+
{"Name": "tag:Name", "Values": [bastion_name]},
|
|
103
|
+
{"Name": "instance-state-name", "Values": ["running"]},
|
|
104
|
+
],
|
|
105
|
+
)
|
|
106
|
+
if not response.get("Reservations"):
|
|
107
|
+
raise ValueError(
|
|
108
|
+
f"Could not find a running instance with the designated bastion name, '{bastion_name}' in region '{bastion_region}'"
|
|
109
|
+
)
|
|
110
|
+
if not response.get("Reservations")[0].get("Instances"):
|
|
111
|
+
raise ValueError(
|
|
112
|
+
f"Could not find a running instance with the designated bastion name, '{bastion_name}' in region '{bastion_region}'"
|
|
113
|
+
)
|
|
114
|
+
return response.get("Reservations")[0].get("Instances")[0]["InstanceId"]
|
|
115
|
+
|
|
116
|
+
def _create_tunnel(
|
|
117
|
+
self,
|
|
118
|
+
secrets,
|
|
119
|
+
bastion_instance_id,
|
|
120
|
+
bastion_username,
|
|
121
|
+
bastion_region,
|
|
122
|
+
public_key_file_path,
|
|
123
|
+
local_proxy_port,
|
|
124
|
+
database_host,
|
|
125
|
+
):
|
|
126
|
+
# first see if the socket is already open, since we don't close it.
|
|
127
|
+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
128
|
+
result = sock.connect_ex(("127.0.0.1", local_proxy_port))
|
|
129
|
+
if result == 0:
|
|
130
|
+
sock.close()
|
|
131
|
+
return
|
|
132
|
+
|
|
133
|
+
# and now we can do this thing.
|
|
134
|
+
tunnel_command = [
|
|
135
|
+
"ssh",
|
|
136
|
+
"-i",
|
|
137
|
+
public_key_file_path,
|
|
138
|
+
"-o",
|
|
139
|
+
"ConnectTimeout=2",
|
|
140
|
+
"-N",
|
|
141
|
+
"-L",
|
|
142
|
+
f"{local_proxy_port}:{database_host}:3306",
|
|
143
|
+
"-p",
|
|
144
|
+
"22",
|
|
145
|
+
f"{bastion_username}@{bastion_instance_id}",
|
|
146
|
+
]
|
|
147
|
+
my_env = os.environ.copy()
|
|
148
|
+
my_env["AWS_DEFAULT_REGION"] = bastion_region
|
|
149
|
+
subprocess.Popen(tunnel_command)
|
|
150
|
+
connected = False
|
|
151
|
+
attempts = 0
|
|
152
|
+
while not connected and attempts < 6:
|
|
153
|
+
attempts += 1
|
|
154
|
+
time.sleep(0.5)
|
|
155
|
+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
156
|
+
result = sock.connect_ex(("127.0.0.1", local_proxy_port))
|
|
157
|
+
if result == 0:
|
|
158
|
+
connected = True
|
|
159
|
+
if not connected:
|
|
160
|
+
raise ValueError(
|
|
161
|
+
"Failed to open SSH tunnel. The following command was used: \n" + " ".join(tunnel_command)
|
|
162
|
+
)
|