rds-proxy-password-rotation 0.1.0__tar.gz
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.
- rds_proxy_password_rotation-0.1.0/LICENSE +201 -0
- rds_proxy_password_rotation-0.1.0/PKG-INFO +98 -0
- rds_proxy_password_rotation-0.1.0/README.md +70 -0
- rds_proxy_password_rotation-0.1.0/pyproject.toml +3 -0
- rds_proxy_password_rotation-0.1.0/setup.cfg +46 -0
- rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation/__init__.py +0 -0
- rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation/adapter/__init__.py +0 -0
- rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation/adapter/aws_lambda_function.py +25 -0
- rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation/adapter/aws_lambda_function_model.py +43 -0
- rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation/adapter/aws_secrets_manager.py +154 -0
- rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation/adapter/container.py +27 -0
- rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation/adapter/postgresql_database_service.py +39 -0
- rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation/model.py +60 -0
- rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation/password_rotation_application.py +81 -0
- rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation/services.py +43 -0
- rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation.egg-info/PKG-INFO +98 -0
- rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation.egg-info/SOURCES.txt +19 -0
- rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation.egg-info/dependency_links.txt +1 -0
- rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation.egg-info/requires.txt +13 -0
- rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation.egg-info/top_level.txt +1 -0
@@ -0,0 +1,201 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
177
|
+
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
179
|
+
|
180
|
+
To apply the Apache License to your work, attach the following
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182
|
+
replaced with your own identifying information. (Don't include
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
184
|
+
comment syntax for the file format. We also recommend that a
|
185
|
+
file or class name and description of purpose be included on the
|
186
|
+
same "printed page" as the copyright notice for easier
|
187
|
+
identification within third-party archives.
|
188
|
+
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
190
|
+
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192
|
+
you may not use this file except in compliance with the License.
|
193
|
+
You may obtain a copy of the License at
|
194
|
+
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
196
|
+
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200
|
+
See the License for the specific language governing permissions and
|
201
|
+
limitations under the License.
|
@@ -0,0 +1,98 @@
|
|
1
|
+
Metadata-Version: 2.2
|
2
|
+
Name: rds-proxy-password-rotation
|
3
|
+
Version: 0.1.0
|
4
|
+
Summary: A program to rotate the password of an RDS database accessed via a RDS proxy
|
5
|
+
Home-page: https://github.com/Hapag-Lloyd/rds-proxy-password-rotation
|
6
|
+
Author: Hapag-Lloyd AG
|
7
|
+
Author-email: info@hlag.com
|
8
|
+
Project-URL: Bug Tracker, https://github.com/Hapag-Lloyd/rds-proxy-password-rotation/issues
|
9
|
+
Project-URL: repository, https://github.com/Hapag-Lloyd/rds-proxy-password-rotation
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
12
|
+
Classifier: Operating System :: OS Independent
|
13
|
+
Requires-Python: >=3.10
|
14
|
+
Description-Content-Type: text/markdown
|
15
|
+
License-File: LICENSE
|
16
|
+
Requires-Dist: aws-lambda-powertools==3.19.0
|
17
|
+
Requires-Dist: boto3==1.40.23
|
18
|
+
Requires-Dist: boto3-stubs[secretsmanager]==1.40.23
|
19
|
+
Requires-Dist: cachetools==6.2.0
|
20
|
+
Requires-Dist: dependency-injector==4.48.1
|
21
|
+
Requires-Dist: psycopg[binary]==3.2.9
|
22
|
+
Requires-Dist: pydantic==2.11.7
|
23
|
+
Provides-Extra: test
|
24
|
+
Requires-Dist: pytest==8.3.4; extra == "test"
|
25
|
+
Requires-Dist: pytest-cov==6.0.0; extra == "test"
|
26
|
+
Requires-Dist: uuid==1.30; extra == "test"
|
27
|
+
Requires-Dist: nose==1.3.7; extra == "test"
|
28
|
+
|
29
|
+
# rds-proxy-password-rotation
|
30
|
+
|
31
|
+
:warning: **Work in progress** :warning:
|
32
|
+
|
33
|
+
- add docker image for AWS Lambda
|
34
|
+
- add Terraform module
|
35
|
+
|
36
|
+
Python script for multi-user password rotation using RDS and RDS proxy. It supports credentials for the application and the RDS
|
37
|
+
proxy.
|
38
|
+
|
39
|
+
We implemented this logic again, because current implementations
|
40
|
+
|
41
|
+
- have no tests
|
42
|
+
- have no release process
|
43
|
+
- are not published to PyPI
|
44
|
+
- have no Docker image available
|
45
|
+
- have no Terraform module available
|
46
|
+
|
47
|
+
## Pre-requisites
|
48
|
+
|
49
|
+
1. Python 3.10 or later
|
50
|
+
2. For each db user:
|
51
|
+
1. Clone the user in the database and grant the necessary permissions. We suggest to add a `-clone` suffix to the username.
|
52
|
+
2. Create a secret in AWS Secrets Manager with the following key-value pairs (for every user and its clone):
|
53
|
+
- `rotation_type`: "AWS RDS"
|
54
|
+
- `rotation_usernames`: Optional. The list of usernames that a part of the rotation, e.g. `["app_user", "app_user-clone"]`.
|
55
|
+
If not provided, `username` is used only.
|
56
|
+
- `proxy_secret_ids`: Optional. The list of ARNs of the secrets that are attached to the RDS Proxy, e.g.
|
57
|
+
`["arn:aws:secretsmanager:region:account-id:secret:secret-name"]`. If not provided, the proxy credentials are not adjusted.
|
58
|
+
- `database_host`: The hostname of the database
|
59
|
+
- `database_port`: The port of the database
|
60
|
+
- `database_name`: The name of the database
|
61
|
+
- `username`: The username for the user
|
62
|
+
- `password`: The password for the user
|
63
|
+
|
64
|
+
This credential will be used by the application to connect to the proxy. You may add additional key-value pairs as needed.
|
65
|
+
3. If you are using RDS Proxy:
|
66
|
+
1. Create a secret in AWS Secrets Manager with the following key-value pairs:
|
67
|
+
- `username`: The username for the user that the proxy will use to connect to the database
|
68
|
+
- `password`: The password for the user that the proxy will use to connect to the database
|
69
|
+
2. Attach the secret to the RDS Proxy.
|
70
|
+
|
71
|
+
## Architecture
|
72
|
+
|
73
|
+

|
74
|
+
|
75
|
+
## Challenges with RDS and RDS Proxy
|
76
|
+
|
77
|
+
RDS Proxy is a fully managed, highly available database proxy for Amazon Relational Database Service (RDS) that makes applications
|
78
|
+
more scalable, more resilient to database failures, and more secure. It allows applications to pool and share database connections
|
79
|
+
to improve efficiency and reduce the load on your database instances.
|
80
|
+
|
81
|
+
However, RDS Proxy does not support multi-user password rotation out of the box. This script provides a solution to this problem.
|
82
|
+
|
83
|
+
Using an RDS Proxy requires a secret in AWS Secrets Manager with the credentials to connect to the database. This secret is used by
|
84
|
+
the proxy to connect to the database. The proxy allows the application to connect to the database using the same credentials and
|
85
|
+
then forwards the requests to the database with the same credentials. This means that the credentials in the secret must be valid
|
86
|
+
in the database at all times. But what if you want to rotate the password for the user that the proxy uses to connect to the
|
87
|
+
database? You can’t just update the secret in SecretsManager because the proxy will stop working as soon as the secret is updated.
|
88
|
+
And you can’t just update the password in the database because the proxy will stop working as soon as the password is updated.
|
89
|
+
|
90
|
+
## Why password rotation is a good practice
|
91
|
+
|
92
|
+
Password rotation is a good idea for several reasons:
|
93
|
+
|
94
|
+
1. **Enhanced Security**: Regularly changing passwords reduces the risk of unauthorized access due to compromised credentials.
|
95
|
+
2. **Mitigates Risk**: Limits the time window an attacker has to exploit a stolen password.
|
96
|
+
3. **Compliance**: Many regulatory standards and security policies require periodic password changes.
|
97
|
+
4. **Reduces Impact of Breaches**: If a password is compromised, rotating it ensures that the compromised password is no longer valid.
|
98
|
+
5. **Encourages Good Practices**: Promotes the use of strong, unique passwords and discourages password reuse.
|
@@ -0,0 +1,70 @@
|
|
1
|
+
# rds-proxy-password-rotation
|
2
|
+
|
3
|
+
:warning: **Work in progress** :warning:
|
4
|
+
|
5
|
+
- add docker image for AWS Lambda
|
6
|
+
- add Terraform module
|
7
|
+
|
8
|
+
Python script for multi-user password rotation using RDS and RDS proxy. It supports credentials for the application and the RDS
|
9
|
+
proxy.
|
10
|
+
|
11
|
+
We implemented this logic again, because current implementations
|
12
|
+
|
13
|
+
- have no tests
|
14
|
+
- have no release process
|
15
|
+
- are not published to PyPI
|
16
|
+
- have no Docker image available
|
17
|
+
- have no Terraform module available
|
18
|
+
|
19
|
+
## Pre-requisites
|
20
|
+
|
21
|
+
1. Python 3.10 or later
|
22
|
+
2. For each db user:
|
23
|
+
1. Clone the user in the database and grant the necessary permissions. We suggest to add a `-clone` suffix to the username.
|
24
|
+
2. Create a secret in AWS Secrets Manager with the following key-value pairs (for every user and its clone):
|
25
|
+
- `rotation_type`: "AWS RDS"
|
26
|
+
- `rotation_usernames`: Optional. The list of usernames that a part of the rotation, e.g. `["app_user", "app_user-clone"]`.
|
27
|
+
If not provided, `username` is used only.
|
28
|
+
- `proxy_secret_ids`: Optional. The list of ARNs of the secrets that are attached to the RDS Proxy, e.g.
|
29
|
+
`["arn:aws:secretsmanager:region:account-id:secret:secret-name"]`. If not provided, the proxy credentials are not adjusted.
|
30
|
+
- `database_host`: The hostname of the database
|
31
|
+
- `database_port`: The port of the database
|
32
|
+
- `database_name`: The name of the database
|
33
|
+
- `username`: The username for the user
|
34
|
+
- `password`: The password for the user
|
35
|
+
|
36
|
+
This credential will be used by the application to connect to the proxy. You may add additional key-value pairs as needed.
|
37
|
+
3. If you are using RDS Proxy:
|
38
|
+
1. Create a secret in AWS Secrets Manager with the following key-value pairs:
|
39
|
+
- `username`: The username for the user that the proxy will use to connect to the database
|
40
|
+
- `password`: The password for the user that the proxy will use to connect to the database
|
41
|
+
2. Attach the secret to the RDS Proxy.
|
42
|
+
|
43
|
+
## Architecture
|
44
|
+
|
45
|
+

|
46
|
+
|
47
|
+
## Challenges with RDS and RDS Proxy
|
48
|
+
|
49
|
+
RDS Proxy is a fully managed, highly available database proxy for Amazon Relational Database Service (RDS) that makes applications
|
50
|
+
more scalable, more resilient to database failures, and more secure. It allows applications to pool and share database connections
|
51
|
+
to improve efficiency and reduce the load on your database instances.
|
52
|
+
|
53
|
+
However, RDS Proxy does not support multi-user password rotation out of the box. This script provides a solution to this problem.
|
54
|
+
|
55
|
+
Using an RDS Proxy requires a secret in AWS Secrets Manager with the credentials to connect to the database. This secret is used by
|
56
|
+
the proxy to connect to the database. The proxy allows the application to connect to the database using the same credentials and
|
57
|
+
then forwards the requests to the database with the same credentials. This means that the credentials in the secret must be valid
|
58
|
+
in the database at all times. But what if you want to rotate the password for the user that the proxy uses to connect to the
|
59
|
+
database? You can’t just update the secret in SecretsManager because the proxy will stop working as soon as the secret is updated.
|
60
|
+
And you can’t just update the password in the database because the proxy will stop working as soon as the password is updated.
|
61
|
+
|
62
|
+
## Why password rotation is a good practice
|
63
|
+
|
64
|
+
Password rotation is a good idea for several reasons:
|
65
|
+
|
66
|
+
1. **Enhanced Security**: Regularly changing passwords reduces the risk of unauthorized access due to compromised credentials.
|
67
|
+
2. **Mitigates Risk**: Limits the time window an attacker has to exploit a stolen password.
|
68
|
+
3. **Compliance**: Many regulatory standards and security policies require periodic password changes.
|
69
|
+
4. **Reduces Impact of Breaches**: If a password is compromised, rotating it ensures that the compromised password is no longer valid.
|
70
|
+
5. **Encourages Good Practices**: Promotes the use of strong, unique passwords and discourages password reuse.
|
@@ -0,0 +1,46 @@
|
|
1
|
+
[metadata]
|
2
|
+
name = rds-proxy-password-rotation
|
3
|
+
version = 0.1.0
|
4
|
+
author = Hapag-Lloyd AG
|
5
|
+
author_email = info@hlag.com
|
6
|
+
description = A program to rotate the password of an RDS database accessed via a RDS proxy
|
7
|
+
long_description = file: README.md
|
8
|
+
long_description_content_type = text/markdown
|
9
|
+
url = https://github.com/Hapag-Lloyd/rds-proxy-password-rotation
|
10
|
+
project_urls =
|
11
|
+
Bug Tracker = https://github.com/Hapag-Lloyd/rds-proxy-password-rotation/issues
|
12
|
+
repository = https://github.com/Hapag-Lloyd/rds-proxy-password-rotation
|
13
|
+
classifiers =
|
14
|
+
Programming Language :: Python :: 3
|
15
|
+
License :: OSI Approved :: Apache Software License
|
16
|
+
Operating System :: OS Independent
|
17
|
+
|
18
|
+
[options]
|
19
|
+
package_dir =
|
20
|
+
= src
|
21
|
+
packages = find:
|
22
|
+
python_requires = >=3.10
|
23
|
+
install_requires =
|
24
|
+
aws-lambda-powertools==3.19.0
|
25
|
+
boto3==1.40.23
|
26
|
+
boto3-stubs[secretsmanager]==1.40.23
|
27
|
+
cachetools==6.2.0
|
28
|
+
dependency-injector==4.48.1
|
29
|
+
psycopg[binary]==3.2.9
|
30
|
+
pydantic==2.11.7
|
31
|
+
|
32
|
+
[options.extras_require]
|
33
|
+
test =
|
34
|
+
pytest==8.3.4
|
35
|
+
pytest-cov==6.0.0
|
36
|
+
uuid==1.30
|
37
|
+
|
38
|
+
nose==1.3.7
|
39
|
+
|
40
|
+
[options.packages.find]
|
41
|
+
where = src
|
42
|
+
|
43
|
+
[egg_info]
|
44
|
+
tag_build =
|
45
|
+
tag_date = 0
|
46
|
+
|
File without changes
|
File without changes
|
rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation/adapter/aws_lambda_function.py
ADDED
@@ -0,0 +1,25 @@
|
|
1
|
+
from dependency_injector.wiring import inject, Provide
|
2
|
+
|
3
|
+
from aws_lambda_powertools.utilities.parser import event_parser
|
4
|
+
from aws_lambda_powertools.utilities.typing import LambdaContext
|
5
|
+
|
6
|
+
from rds_proxy_password_rotation.adapter.aws_lambda_function_model import AwsSecretManagerRotationEvent
|
7
|
+
from rds_proxy_password_rotation.adapter.container import Container
|
8
|
+
from rds_proxy_password_rotation.password_rotation_application import PasswordRotationApplication
|
9
|
+
|
10
|
+
|
11
|
+
container = None
|
12
|
+
|
13
|
+
@event_parser(model=AwsSecretManagerRotationEvent)
|
14
|
+
def lambda_handler(event: AwsSecretManagerRotationEvent, context: LambdaContext) -> None:
|
15
|
+
global container
|
16
|
+
|
17
|
+
if container is None:
|
18
|
+
container = Container()
|
19
|
+
container.wire(modules=[__name__])
|
20
|
+
|
21
|
+
__call_application(event)
|
22
|
+
|
23
|
+
@inject
|
24
|
+
def __call_application(event: AwsSecretManagerRotationEvent, application: PasswordRotationApplication = Provide[Container.password_rotation_application]) -> None:
|
25
|
+
application.rotate_secret(event.step.to_rotation_step(), event.secret_id, event.client_request_token)
|
@@ -0,0 +1,43 @@
|
|
1
|
+
from enum import Enum
|
2
|
+
|
3
|
+
from pydantic import BaseModel, Field
|
4
|
+
|
5
|
+
from rds_proxy_password_rotation.model import RotationStep
|
6
|
+
|
7
|
+
|
8
|
+
class AwsRotationStep(Enum):
|
9
|
+
CREATE_SECRET = "create_secret"
|
10
|
+
"""Create a new version of the secret"""
|
11
|
+
SET_SECRET = "set_secret"
|
12
|
+
"""Change the credentials in the database or service"""
|
13
|
+
TEST_SECRET = "test_secret"
|
14
|
+
"""Test the new secret version"""
|
15
|
+
FINISH_SECRET = "finish_secret"
|
16
|
+
"""Finish the rotation"""
|
17
|
+
|
18
|
+
def to_rotation_step(self) -> RotationStep:
|
19
|
+
match self:
|
20
|
+
case AwsRotationStep.CREATE_SECRET:
|
21
|
+
return RotationStep.CREATE_SECRET
|
22
|
+
case AwsRotationStep.SET_SECRET:
|
23
|
+
return RotationStep.SET_SECRET
|
24
|
+
case AwsRotationStep.TEST_SECRET:
|
25
|
+
return RotationStep.TEST_SECRET
|
26
|
+
case AwsRotationStep.FINISH_SECRET:
|
27
|
+
return RotationStep.FINISH_SECRET
|
28
|
+
case _:
|
29
|
+
raise ValueError(f"Invalid rotation step: {self.value}")
|
30
|
+
|
31
|
+
|
32
|
+
class AwsSecretManagerRotationEvent(BaseModel):
|
33
|
+
step: AwsRotationStep = Field(alias='Step')
|
34
|
+
"""The rotation step: create_secret, set_secret, test_secret, or finish_secret. For more information, see Four steps in a rotation function."""
|
35
|
+
|
36
|
+
secret_id: str = Field(alias='SecretId')
|
37
|
+
"""The ARN of the secret to rotate."""
|
38
|
+
|
39
|
+
client_request_token: str = Field(alias='ClientRequestToken')
|
40
|
+
"""A unique identifier for the new version of the secret. This value helps ensure idempotency. For more information, see PutSecretValue: ClientRequestToken in the AWS Secrets Manager API Reference."""
|
41
|
+
|
42
|
+
rotation_token: str = Field(alias='RotationToken')
|
43
|
+
"""A unique identifier that indicates the source of the request. Required for secret rotation using an assumed role or cross-account rotation, in which you rotate a secret in one account by using a Lambda rotation function in another account. In both cases, the rotation function assumes an IAM role to call Secrets Manager and then Secrets Manager uses the rotation token to validate the IAM role identity."""
|
rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation/adapter/aws_secrets_manager.py
ADDED
@@ -0,0 +1,154 @@
|
|
1
|
+
from uuid import uuid4
|
2
|
+
|
3
|
+
from aws_lambda_powertools import Logger
|
4
|
+
from mypy_boto3_secretsmanager.client import SecretsManagerClient
|
5
|
+
from mypy_boto3_secretsmanager.type_defs import DescribeSecretResponseTypeDef
|
6
|
+
from pydantic import ValidationError
|
7
|
+
|
8
|
+
from rds_proxy_password_rotation.model import DatabaseCredentials, PasswordStage, UserCredentials, Credentials
|
9
|
+
from rds_proxy_password_rotation.services import PasswordService
|
10
|
+
|
11
|
+
|
12
|
+
class AwsSecretsManagerService(PasswordService):
|
13
|
+
def __init__(self, secretsmanager_client: SecretsManagerClient, logger: Logger):
|
14
|
+
self.client = secretsmanager_client
|
15
|
+
self.logger = logger
|
16
|
+
|
17
|
+
def is_rotation_enabled(self, secret_id: str) -> bool:
|
18
|
+
metadata = self.__get_secret_metadata(secret_id)
|
19
|
+
|
20
|
+
return 'RotationEnabled' in metadata and metadata['RotationEnabled']
|
21
|
+
|
22
|
+
def make_new_credentials_current(self, secret_id: str, token: str):
|
23
|
+
metadata = self.__get_secret_metadata(secret_id)
|
24
|
+
versions = metadata['VersionIdsToStages']
|
25
|
+
|
26
|
+
current_version = None
|
27
|
+
previous_version = None
|
28
|
+
|
29
|
+
for version, stages in versions.items():
|
30
|
+
if "AWSCURRENT" in stages:
|
31
|
+
if version == token:
|
32
|
+
self.logger.info(f'current secret is already the pending one: {secret_id} and version {version}')
|
33
|
+
return
|
34
|
+
|
35
|
+
current_version = version
|
36
|
+
elif "AWSPREVIOUS" in stages:
|
37
|
+
previous_version = version
|
38
|
+
|
39
|
+
if previous_version is not None:
|
40
|
+
self.client.update_secret_version_stage(
|
41
|
+
SecretId=secret_id,
|
42
|
+
VersionStage="AWSPREVIOUS",
|
43
|
+
MoveToVersionId=current_version,
|
44
|
+
RemoveFromVersionId=previous_version
|
45
|
+
)
|
46
|
+
else:
|
47
|
+
self.client.update_secret_version_stage(
|
48
|
+
SecretId=secret_id,
|
49
|
+
VersionStage="AWSPREVIOUS",
|
50
|
+
MoveToVersionId=current_version
|
51
|
+
)
|
52
|
+
|
53
|
+
self.client.update_secret_version_stage(
|
54
|
+
SecretId=secret_id,
|
55
|
+
VersionStage='AWSCURRENT',
|
56
|
+
MoveToVersionId=token,
|
57
|
+
RemoveFromVersionId=current_version)
|
58
|
+
|
59
|
+
self.client.update_secret_version_stage(
|
60
|
+
SecretId=secret_id,
|
61
|
+
VersionStage='AWSPENDING',
|
62
|
+
RemoveFromVersionId=token)
|
63
|
+
|
64
|
+
def ensure_valid_secret_state(self, secret_id: str, token: str) -> bool:
|
65
|
+
metadata = self.__get_secret_metadata(secret_id)
|
66
|
+
versions = metadata['VersionIdsToStages']
|
67
|
+
|
68
|
+
if token not in versions:
|
69
|
+
self.logger.error("Secret version %s has no stage for rotation of secret %s." % (token, secret_id))
|
70
|
+
raise ValueError("Secret version %s has no stage for rotation of secret %s." % (token, secret_id))
|
71
|
+
elif "AWSCURRENT" in versions[token]:
|
72
|
+
self.logger.info("Secret version %s already set as AWSCURRENT for secret %s." % (token, secret_id))
|
73
|
+
return False
|
74
|
+
elif "AWSPENDING" not in versions[token]:
|
75
|
+
self.logger.error("Secret version %s not set as AWSPENDING for rotation of secret %s." % (token, secret_id))
|
76
|
+
raise ValueError("Secret version %s not set as AWSPENDING for rotation of secret %s." % (token, secret_id))
|
77
|
+
else:
|
78
|
+
return True
|
79
|
+
|
80
|
+
def get_database_credentials(self, secret_id: str, stage: PasswordStage, token: str = None) -> DatabaseCredentials | None:
|
81
|
+
try:
|
82
|
+
return DatabaseCredentials.model_validate_json(self.__get_secret_value(secret_id, stage, token))
|
83
|
+
except ValidationError as e:
|
84
|
+
self.logger.error(f"Failed to parse secret value for secret {secret_id} (stage: {stage.name}, token: {token})")
|
85
|
+
|
86
|
+
raise e
|
87
|
+
except self.client.exceptions.ResourceNotFoundException:
|
88
|
+
self.logger.error(f"Failed to retrieve secret value for secret {secret_id} (stage: {stage.name}, token: {token})")
|
89
|
+
|
90
|
+
return None
|
91
|
+
|
92
|
+
def get_user_credentials(self, secret_id: str, stage: PasswordStage, token: str = None) -> UserCredentials | None:
|
93
|
+
try:
|
94
|
+
return UserCredentials.model_validate_json(self.__get_secret_value(secret_id, stage, token))
|
95
|
+
except ValidationError as e:
|
96
|
+
self.logger.error(f"Failed to parse secret value for secret {secret_id} (stage: {stage.name}, token: {token})")
|
97
|
+
|
98
|
+
raise e
|
99
|
+
except self.client.exceptions.ResourceNotFoundException:
|
100
|
+
self.logger.error(f"Failed to retrieve secret value for secret {secret_id} (stage: {stage.name}, token: {token})")
|
101
|
+
|
102
|
+
return None
|
103
|
+
|
104
|
+
def __get_secret_value(self, secret_id: str, stage: PasswordStage, token: str) -> str:
|
105
|
+
stage_string = AwsSecretsManagerService.__get_stage_string(stage)
|
106
|
+
|
107
|
+
if token is None:
|
108
|
+
secret = self.client.get_secret_value(SecretId=secret_id, VersionStage=stage_string)
|
109
|
+
else:
|
110
|
+
secret = self.client.get_secret_value(SecretId=secret_id, VersionId=token, VersionStage=stage_string)
|
111
|
+
|
112
|
+
return secret['SecretString']
|
113
|
+
|
114
|
+
def set_new_pending_password(self, secret_id: str, token: str, credential: DatabaseCredentials):
|
115
|
+
if token is None:
|
116
|
+
token = str(uuid4())
|
117
|
+
|
118
|
+
new_username = credential.get_next_username()
|
119
|
+
pending_credential = credential.model_copy(update={'username': new_username, 'password': self.client.get_random_password(ExcludeCharacters=':/@"\'\\')['RandomPassword']})
|
120
|
+
|
121
|
+
self.client.put_secret_value(
|
122
|
+
SecretId=secret_id,
|
123
|
+
ClientRequestToken=token,
|
124
|
+
SecretString=pending_credential.model_dump_json(),
|
125
|
+
VersionStages=[AwsSecretsManagerService.__get_stage_string(PasswordStage.PENDING)])
|
126
|
+
|
127
|
+
self.logger.info(f'new pending secret created: {secret_id} and version {token}')
|
128
|
+
|
129
|
+
def set_credentials(self, secret_id: str, token: str, credentials: Credentials):
|
130
|
+
if token is None:
|
131
|
+
token = str(uuid4())
|
132
|
+
|
133
|
+
self.client.put_secret_value(
|
134
|
+
SecretId=secret_id,
|
135
|
+
ClientRequestToken=token,
|
136
|
+
SecretString=credentials.model_dump_json(),
|
137
|
+
VersionStages=[AwsSecretsManagerService.__get_stage_string(PasswordStage.CURRENT)])
|
138
|
+
|
139
|
+
self.logger.info(f'credentials modified: {secret_id} and version {token}')
|
140
|
+
|
141
|
+
def __get_secret_metadata(self, secret_id: str) -> DescribeSecretResponseTypeDef:
|
142
|
+
return self.client.describe_secret(SecretId=secret_id)
|
143
|
+
|
144
|
+
@staticmethod
|
145
|
+
def __get_stage_string(stage: PasswordStage) -> str:
|
146
|
+
match stage:
|
147
|
+
case PasswordStage.CURRENT:
|
148
|
+
return "AWSCURRENT"
|
149
|
+
case PasswordStage.PENDING:
|
150
|
+
return "AWSPENDING"
|
151
|
+
case PasswordStage.PREVIOUS:
|
152
|
+
return "AWSPREVIOUS"
|
153
|
+
case _:
|
154
|
+
raise ValueError(f"Invalid stage: {stage}")
|
@@ -0,0 +1,27 @@
|
|
1
|
+
import boto3
|
2
|
+
from aws_lambda_powertools import Logger
|
3
|
+
from dependency_injector import containers, providers
|
4
|
+
|
5
|
+
from rds_proxy_password_rotation.adapter.aws_secrets_manager import AwsSecretsManagerService
|
6
|
+
from rds_proxy_password_rotation.password_rotation_application import PasswordRotationApplication
|
7
|
+
|
8
|
+
|
9
|
+
class Container(containers.DeclarativeContainer):
|
10
|
+
config = providers.Configuration()
|
11
|
+
|
12
|
+
logger = providers.Singleton(
|
13
|
+
Logger,
|
14
|
+
)
|
15
|
+
|
16
|
+
boto3_secrets_manager = boto3.client(service_name='secretsmanager')
|
17
|
+
|
18
|
+
secrets_manager = providers.Singleton(
|
19
|
+
AwsSecretsManagerService,
|
20
|
+
boto3_secrets_manager=boto3_secrets_manager,
|
21
|
+
)
|
22
|
+
|
23
|
+
password_rotation_application = providers.Singleton(
|
24
|
+
PasswordRotationApplication,
|
25
|
+
secrets_manager=secrets_manager,
|
26
|
+
logger=logger,
|
27
|
+
)
|
@@ -0,0 +1,39 @@
|
|
1
|
+
import psycopg
|
2
|
+
from aws_lambda_powertools import Logger
|
3
|
+
from psycopg import Connection, sql, ClientCursor
|
4
|
+
|
5
|
+
from rds_proxy_password_rotation.model import DatabaseCredentials
|
6
|
+
from rds_proxy_password_rotation.services import DatabaseService
|
7
|
+
|
8
|
+
|
9
|
+
class PostgreSqlDatabaseService(DatabaseService):
|
10
|
+
def __init__(self, logger: Logger):
|
11
|
+
self.logger = logger
|
12
|
+
|
13
|
+
def test_user_credentials(self, credentials: DatabaseCredentials) -> bool:
|
14
|
+
with self._get_connection(credentials) as conn:
|
15
|
+
with conn.cursor() as cur:
|
16
|
+
cur.execute("SELECT 1")
|
17
|
+
|
18
|
+
return True
|
19
|
+
|
20
|
+
def change_user_credentials(self, old_credentials: DatabaseCredentials, new_password: str):
|
21
|
+
with self._get_connection(old_credentials) as conn:
|
22
|
+
with ClientCursor(conn) as cur:
|
23
|
+
cur.execute(sql.SQL("ALTER USER {} WITH PASSWORD %s").format(sql.Identifier(old_credentials.username)), (new_password,))
|
24
|
+
conn.commit()
|
25
|
+
|
26
|
+
def _get_connection(self, credentials: DatabaseCredentials) -> Connection:
|
27
|
+
"""
|
28
|
+
Method is protected to allow testing.
|
29
|
+
:param credentials: used to connect to the database
|
30
|
+
:return: the database connection
|
31
|
+
"""
|
32
|
+
connect_string = psycopg._connection_info.make_conninfo("", password=credentials.password, user=credentials.username, host=credentials.database_host, port=credentials.database_port, dbname=credentials.database_name, sslmode="require", connect_timeout=5)
|
33
|
+
|
34
|
+
try:
|
35
|
+
return psycopg.connect(connect_string)
|
36
|
+
except psycopg.OperationalError as e:
|
37
|
+
self.logger.error(f'Failed to connect to database {credentials.database_name} on {credentials.database_host}:{credentials.database_port} as {credentials.username}')
|
38
|
+
|
39
|
+
raise e
|
@@ -0,0 +1,60 @@
|
|
1
|
+
from enum import Enum
|
2
|
+
from typing import List
|
3
|
+
|
4
|
+
from pydantic import BaseModel
|
5
|
+
from typing_extensions import Optional
|
6
|
+
|
7
|
+
|
8
|
+
class RotationStep(Enum):
|
9
|
+
CREATE_SECRET = "create_secret"
|
10
|
+
"""Create a new version of the secret"""
|
11
|
+
SET_SECRET = "set_secret"
|
12
|
+
"""Change the credentials in the database or service"""
|
13
|
+
TEST_SECRET = "test_secret"
|
14
|
+
"""Test the new secret version"""
|
15
|
+
FINISH_SECRET = "finish_secret"
|
16
|
+
"""Finish the rotation"""
|
17
|
+
|
18
|
+
|
19
|
+
class PasswordStage(Enum):
|
20
|
+
CURRENT = "CURRENT"
|
21
|
+
PENDING = "PENDING"
|
22
|
+
PREVIOUS = "PREVIOUS"
|
23
|
+
|
24
|
+
|
25
|
+
class PasswordType(Enum):
|
26
|
+
AWS_RDS = "AWS RDS"
|
27
|
+
|
28
|
+
|
29
|
+
class Credentials(BaseModel, extra='allow'):
|
30
|
+
rotation_type: PasswordType
|
31
|
+
rotation_usernames: Optional[List[str]] = []
|
32
|
+
|
33
|
+
|
34
|
+
class UserCredentials(Credentials):
|
35
|
+
username: str
|
36
|
+
password: str
|
37
|
+
|
38
|
+
def get_next_username(self) -> str:
|
39
|
+
if not self.rotation_usernames:
|
40
|
+
return self.username
|
41
|
+
|
42
|
+
# e.g. user1 -> user2, user2 -> user3, user3 -> user1, ...
|
43
|
+
if self.username not in self.rotation_usernames:
|
44
|
+
self.logger.warning(f'current username {self.username} not in rotation usernames {self.rotation_usernames}. Using the first username in the list as the new one.')
|
45
|
+
return self.rotation_usernames[0]
|
46
|
+
|
47
|
+
current_index = self.rotation_usernames.index(self.username)
|
48
|
+
next_index = (current_index + 1) % len(self.rotation_usernames)
|
49
|
+
|
50
|
+
return self.rotation_usernames[next_index]
|
51
|
+
|
52
|
+
class DatabaseCredentials(UserCredentials):
|
53
|
+
database_host: str
|
54
|
+
database_port: int
|
55
|
+
database_name: str
|
56
|
+
|
57
|
+
proxy_secret_ids: Optional[list[UserCredentials]] = None
|
58
|
+
|
59
|
+
def copy_and_replace_username(credentials: 'DatabaseCredentials', new_username: str) -> 'DatabaseCredentials':
|
60
|
+
return credentials.model_copy(update={'username': new_username})
|
rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation/password_rotation_application.py
ADDED
@@ -0,0 +1,81 @@
|
|
1
|
+
from enum import Enum
|
2
|
+
|
3
|
+
from aws_lambda_powertools import Logger
|
4
|
+
|
5
|
+
from rds_proxy_password_rotation.model import RotationStep, PasswordStage
|
6
|
+
from rds_proxy_password_rotation.services import PasswordService, DatabaseService
|
7
|
+
|
8
|
+
|
9
|
+
class PasswordRotationResult(Enum):
|
10
|
+
NOTHING_TO_ROTATE = "nothing_to_rotate"
|
11
|
+
STEP_EXECUTED = "step_executed"
|
12
|
+
|
13
|
+
|
14
|
+
class PasswordRotationApplication:
|
15
|
+
def __init__(self, password_service: PasswordService, database_service: DatabaseService, logger: Logger):
|
16
|
+
self.password_service = password_service
|
17
|
+
self.database_service = database_service
|
18
|
+
self.logger = logger
|
19
|
+
|
20
|
+
def rotate_secret(self, step: RotationStep, secret_id: str, token: str) -> PasswordRotationResult:
|
21
|
+
if not self.password_service.is_rotation_enabled(secret_id):
|
22
|
+
self.logger.warning("Rotation is not enabled for the secret %s", secret_id)
|
23
|
+
return PasswordRotationResult.NOTHING_TO_ROTATE
|
24
|
+
|
25
|
+
if step != RotationStep.CREATE_SECRET and not self.password_service.ensure_valid_secret_state(secret_id, token):
|
26
|
+
return PasswordRotationResult.NOTHING_TO_ROTATE
|
27
|
+
|
28
|
+
match step:
|
29
|
+
case RotationStep.CREATE_SECRET:
|
30
|
+
self.__create_secret(secret_id, token)
|
31
|
+
case RotationStep.SET_SECRET:
|
32
|
+
self.__set_secret(secret_id, token)
|
33
|
+
case RotationStep.TEST_SECRET:
|
34
|
+
self.__test_secret(secret_id, token)
|
35
|
+
case RotationStep.FINISH_SECRET:
|
36
|
+
self.__finish_secret(secret_id, token)
|
37
|
+
case _:
|
38
|
+
raise ValueError(f"Invalid rotation step: {step}")
|
39
|
+
|
40
|
+
return PasswordRotationResult.STEP_EXECUTED
|
41
|
+
|
42
|
+
def __finish_secret(self, secret_id: str, token: str):
|
43
|
+
self.password_service.make_new_credentials_current(secret_id, token)
|
44
|
+
|
45
|
+
def __test_secret(self, secret_id: str, token: str):
|
46
|
+
pending_credential = self.password_service.get_database_credentials(secret_id, PasswordStage.PENDING, token)
|
47
|
+
self.database_service.test_user_credentials(pending_credential)
|
48
|
+
|
49
|
+
def __set_secret(self, secret_id: str, token: str):
|
50
|
+
pending_credential = self.password_service.get_database_credentials(secret_id, PasswordStage.PENDING, token)
|
51
|
+
current_credential = self.password_service.get_database_credentials(secret_id, PasswordStage.CURRENT)
|
52
|
+
|
53
|
+
proxy_secret_id = None
|
54
|
+
proxy_secret = None
|
55
|
+
|
56
|
+
for secret_id in current_credential.proxy_secret_ids:
|
57
|
+
proxy_secret = self.password_service.get_user_credentials(secret_id, PasswordStage.CURRENT)
|
58
|
+
if proxy_secret.username == pending_credential.username:
|
59
|
+
proxy_secret_id = secret_id
|
60
|
+
break
|
61
|
+
|
62
|
+
self.database_service.change_user_credentials(current_credential, pending_credential.password)
|
63
|
+
|
64
|
+
# database and proxy user credentials have to be in sync as the proxy user is used to connect to the database
|
65
|
+
if proxy_secret_id is not None:
|
66
|
+
self.password_service.set_credentials(secret_id, token, proxy_secret)
|
67
|
+
|
68
|
+
self.logger.info(f'set_secret: successfully set password for user {pending_credential.username} for secret {secret_id}')
|
69
|
+
|
70
|
+
def __create_secret(self, secret_id: str, token: str):
|
71
|
+
"""
|
72
|
+
Creates a new version of the secret with the password to rotate to unless a version tagged with AWSPENDING
|
73
|
+
already exists.
|
74
|
+
"""
|
75
|
+
|
76
|
+
if self.password_service.get_database_credentials(secret_id, PasswordStage.PENDING, token) is not None:
|
77
|
+
return
|
78
|
+
|
79
|
+
credentials_to_rotate = self.password_service.get_database_credentials(secret_id, PasswordStage.CURRENT)
|
80
|
+
|
81
|
+
self.password_service.set_new_pending_password(secret_id, token, credentials_to_rotate)
|
@@ -0,0 +1,43 @@
|
|
1
|
+
from abc import ABC, abstractmethod
|
2
|
+
|
3
|
+
from rds_proxy_password_rotation.model import DatabaseCredentials, PasswordStage, UserCredentials, Credentials
|
4
|
+
|
5
|
+
|
6
|
+
class PasswordService(ABC):
|
7
|
+
@abstractmethod
|
8
|
+
def is_rotation_enabled(self, secret_id: str) -> bool:
|
9
|
+
pass
|
10
|
+
|
11
|
+
@abstractmethod
|
12
|
+
def ensure_valid_secret_state(self, secret_id: str, token: str) -> bool:
|
13
|
+
pass
|
14
|
+
|
15
|
+
@abstractmethod
|
16
|
+
def get_database_credentials(self, secret_id: str, stage: PasswordStage, token: str = None) -> DatabaseCredentials | None:
|
17
|
+
pass
|
18
|
+
|
19
|
+
@abstractmethod
|
20
|
+
def get_user_credentials(self, secret_id: str, stage: PasswordStage, token: str = None) -> UserCredentials | None:
|
21
|
+
pass
|
22
|
+
|
23
|
+
@abstractmethod
|
24
|
+
def set_new_pending_password(self, secret_id: str, token: str, credential: DatabaseCredentials):
|
25
|
+
pass
|
26
|
+
|
27
|
+
@abstractmethod
|
28
|
+
def set_credentials(self, secret_id: str, token: str, credential: Credentials):
|
29
|
+
pass
|
30
|
+
|
31
|
+
@abstractmethod
|
32
|
+
def make_new_credentials_current(self, secret_id: str, token: str):
|
33
|
+
pass
|
34
|
+
|
35
|
+
|
36
|
+
class DatabaseService(ABC):
|
37
|
+
@abstractmethod
|
38
|
+
def change_user_credentials(self, old_credentials: DatabaseCredentials, new_password: str):
|
39
|
+
pass
|
40
|
+
|
41
|
+
@abstractmethod
|
42
|
+
def test_user_credentials(self, credentials: DatabaseCredentials):
|
43
|
+
pass
|
@@ -0,0 +1,98 @@
|
|
1
|
+
Metadata-Version: 2.2
|
2
|
+
Name: rds-proxy-password-rotation
|
3
|
+
Version: 0.1.0
|
4
|
+
Summary: A program to rotate the password of an RDS database accessed via a RDS proxy
|
5
|
+
Home-page: https://github.com/Hapag-Lloyd/rds-proxy-password-rotation
|
6
|
+
Author: Hapag-Lloyd AG
|
7
|
+
Author-email: info@hlag.com
|
8
|
+
Project-URL: Bug Tracker, https://github.com/Hapag-Lloyd/rds-proxy-password-rotation/issues
|
9
|
+
Project-URL: repository, https://github.com/Hapag-Lloyd/rds-proxy-password-rotation
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
12
|
+
Classifier: Operating System :: OS Independent
|
13
|
+
Requires-Python: >=3.10
|
14
|
+
Description-Content-Type: text/markdown
|
15
|
+
License-File: LICENSE
|
16
|
+
Requires-Dist: aws-lambda-powertools==3.19.0
|
17
|
+
Requires-Dist: boto3==1.40.23
|
18
|
+
Requires-Dist: boto3-stubs[secretsmanager]==1.40.23
|
19
|
+
Requires-Dist: cachetools==6.2.0
|
20
|
+
Requires-Dist: dependency-injector==4.48.1
|
21
|
+
Requires-Dist: psycopg[binary]==3.2.9
|
22
|
+
Requires-Dist: pydantic==2.11.7
|
23
|
+
Provides-Extra: test
|
24
|
+
Requires-Dist: pytest==8.3.4; extra == "test"
|
25
|
+
Requires-Dist: pytest-cov==6.0.0; extra == "test"
|
26
|
+
Requires-Dist: uuid==1.30; extra == "test"
|
27
|
+
Requires-Dist: nose==1.3.7; extra == "test"
|
28
|
+
|
29
|
+
# rds-proxy-password-rotation
|
30
|
+
|
31
|
+
:warning: **Work in progress** :warning:
|
32
|
+
|
33
|
+
- add docker image for AWS Lambda
|
34
|
+
- add Terraform module
|
35
|
+
|
36
|
+
Python script for multi-user password rotation using RDS and RDS proxy. It supports credentials for the application and the RDS
|
37
|
+
proxy.
|
38
|
+
|
39
|
+
We implemented this logic again, because current implementations
|
40
|
+
|
41
|
+
- have no tests
|
42
|
+
- have no release process
|
43
|
+
- are not published to PyPI
|
44
|
+
- have no Docker image available
|
45
|
+
- have no Terraform module available
|
46
|
+
|
47
|
+
## Pre-requisites
|
48
|
+
|
49
|
+
1. Python 3.10 or later
|
50
|
+
2. For each db user:
|
51
|
+
1. Clone the user in the database and grant the necessary permissions. We suggest to add a `-clone` suffix to the username.
|
52
|
+
2. Create a secret in AWS Secrets Manager with the following key-value pairs (for every user and its clone):
|
53
|
+
- `rotation_type`: "AWS RDS"
|
54
|
+
- `rotation_usernames`: Optional. The list of usernames that a part of the rotation, e.g. `["app_user", "app_user-clone"]`.
|
55
|
+
If not provided, `username` is used only.
|
56
|
+
- `proxy_secret_ids`: Optional. The list of ARNs of the secrets that are attached to the RDS Proxy, e.g.
|
57
|
+
`["arn:aws:secretsmanager:region:account-id:secret:secret-name"]`. If not provided, the proxy credentials are not adjusted.
|
58
|
+
- `database_host`: The hostname of the database
|
59
|
+
- `database_port`: The port of the database
|
60
|
+
- `database_name`: The name of the database
|
61
|
+
- `username`: The username for the user
|
62
|
+
- `password`: The password for the user
|
63
|
+
|
64
|
+
This credential will be used by the application to connect to the proxy. You may add additional key-value pairs as needed.
|
65
|
+
3. If you are using RDS Proxy:
|
66
|
+
1. Create a secret in AWS Secrets Manager with the following key-value pairs:
|
67
|
+
- `username`: The username for the user that the proxy will use to connect to the database
|
68
|
+
- `password`: The password for the user that the proxy will use to connect to the database
|
69
|
+
2. Attach the secret to the RDS Proxy.
|
70
|
+
|
71
|
+
## Architecture
|
72
|
+
|
73
|
+

|
74
|
+
|
75
|
+
## Challenges with RDS and RDS Proxy
|
76
|
+
|
77
|
+
RDS Proxy is a fully managed, highly available database proxy for Amazon Relational Database Service (RDS) that makes applications
|
78
|
+
more scalable, more resilient to database failures, and more secure. It allows applications to pool and share database connections
|
79
|
+
to improve efficiency and reduce the load on your database instances.
|
80
|
+
|
81
|
+
However, RDS Proxy does not support multi-user password rotation out of the box. This script provides a solution to this problem.
|
82
|
+
|
83
|
+
Using an RDS Proxy requires a secret in AWS Secrets Manager with the credentials to connect to the database. This secret is used by
|
84
|
+
the proxy to connect to the database. The proxy allows the application to connect to the database using the same credentials and
|
85
|
+
then forwards the requests to the database with the same credentials. This means that the credentials in the secret must be valid
|
86
|
+
in the database at all times. But what if you want to rotate the password for the user that the proxy uses to connect to the
|
87
|
+
database? You can’t just update the secret in SecretsManager because the proxy will stop working as soon as the secret is updated.
|
88
|
+
And you can’t just update the password in the database because the proxy will stop working as soon as the password is updated.
|
89
|
+
|
90
|
+
## Why password rotation is a good practice
|
91
|
+
|
92
|
+
Password rotation is a good idea for several reasons:
|
93
|
+
|
94
|
+
1. **Enhanced Security**: Regularly changing passwords reduces the risk of unauthorized access due to compromised credentials.
|
95
|
+
2. **Mitigates Risk**: Limits the time window an attacker has to exploit a stolen password.
|
96
|
+
3. **Compliance**: Many regulatory standards and security policies require periodic password changes.
|
97
|
+
4. **Reduces Impact of Breaches**: If a password is compromised, rotating it ensures that the compromised password is no longer valid.
|
98
|
+
5. **Encourages Good Practices**: Promotes the use of strong, unique passwords and discourages password reuse.
|
@@ -0,0 +1,19 @@
|
|
1
|
+
LICENSE
|
2
|
+
README.md
|
3
|
+
pyproject.toml
|
4
|
+
setup.cfg
|
5
|
+
src/rds_proxy_password_rotation/__init__.py
|
6
|
+
src/rds_proxy_password_rotation/model.py
|
7
|
+
src/rds_proxy_password_rotation/password_rotation_application.py
|
8
|
+
src/rds_proxy_password_rotation/services.py
|
9
|
+
src/rds_proxy_password_rotation.egg-info/PKG-INFO
|
10
|
+
src/rds_proxy_password_rotation.egg-info/SOURCES.txt
|
11
|
+
src/rds_proxy_password_rotation.egg-info/dependency_links.txt
|
12
|
+
src/rds_proxy_password_rotation.egg-info/requires.txt
|
13
|
+
src/rds_proxy_password_rotation.egg-info/top_level.txt
|
14
|
+
src/rds_proxy_password_rotation/adapter/__init__.py
|
15
|
+
src/rds_proxy_password_rotation/adapter/aws_lambda_function.py
|
16
|
+
src/rds_proxy_password_rotation/adapter/aws_lambda_function_model.py
|
17
|
+
src/rds_proxy_password_rotation/adapter/aws_secrets_manager.py
|
18
|
+
src/rds_proxy_password_rotation/adapter/container.py
|
19
|
+
src/rds_proxy_password_rotation/adapter/postgresql_database_service.py
|
rds_proxy_password_rotation-0.1.0/src/rds_proxy_password_rotation.egg-info/dependency_links.txt
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
|
@@ -0,0 +1,13 @@
|
|
1
|
+
aws-lambda-powertools==3.19.0
|
2
|
+
boto3==1.40.23
|
3
|
+
boto3-stubs[secretsmanager]==1.40.23
|
4
|
+
cachetools==6.2.0
|
5
|
+
dependency-injector==4.48.1
|
6
|
+
psycopg[binary]==3.2.9
|
7
|
+
pydantic==2.11.7
|
8
|
+
|
9
|
+
[test]
|
10
|
+
pytest==8.3.4
|
11
|
+
pytest-cov==6.0.0
|
12
|
+
uuid==1.30
|
13
|
+
nose==1.3.7
|
@@ -0,0 +1 @@
|
|
1
|
+
rds_proxy_password_rotation
|