hea-scripts 1.0.0b1__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.
- hea_scripts-1.0.0b1/LICENSE +169 -0
- hea_scripts-1.0.0b1/PKG-INFO +112 -0
- hea_scripts-1.0.0b1/README.md +76 -0
- hea_scripts-1.0.0b1/pyproject.toml +67 -0
- hea_scripts-1.0.0b1/setup.cfg +4 -0
- hea_scripts-1.0.0b1/src/hea/scripts/__init__.py +0 -0
- hea_scripts-1.0.0b1/src/hea/scripts/encryption.py +79 -0
- hea_scripts-1.0.0b1/src/hea/scripts/gen_encryption_key.py +18 -0
- hea_scripts-1.0.0b1/src/hea/scripts/scriptlib.py +39 -0
- hea_scripts-1.0.0b1/src/hea_scripts.egg-info/PKG-INFO +112 -0
- hea_scripts-1.0.0b1/src/hea_scripts.egg-info/SOURCES.txt +15 -0
- hea_scripts-1.0.0b1/src/hea_scripts.egg-info/dependency_links.txt +1 -0
- hea_scripts-1.0.0b1/src/hea_scripts.egg-info/entry_points.txt +3 -0
- hea_scripts-1.0.0b1/src/hea_scripts.egg-info/requires.txt +9 -0
- hea_scripts-1.0.0b1/src/hea_scripts.egg-info/top_level.txt +1 -0
- hea_scripts-1.0.0b1/tests/test_encryption.py +101 -0
- hea_scripts-1.0.0b1/tests/test_scriptlib.py +103 -0
|
@@ -0,0 +1,169 @@
|
|
|
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 made available under
|
|
36
|
+
the License, as indicated by a copyright notice that is included in
|
|
37
|
+
or attached to the work (an example is provided in the Appendix below).
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
43
|
+
of this License, Derivative Works shall not include works that remain
|
|
44
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
45
|
+
the Work and Derivative Works thereof.
|
|
46
|
+
|
|
47
|
+
"Contribution" shall mean, as submitted to the Licensor for inclusion
|
|
48
|
+
in the Work by the copyright owner or by an individual or Legal Entity
|
|
49
|
+
authorized to submit on behalf of the copyright owner. For the purposes
|
|
50
|
+
of this definition, "submitted" means any form of electronic, verbal,
|
|
51
|
+
or written communication sent to the Licensor or its representatives,
|
|
52
|
+
including but not limited to communication on electronic mailing lists,
|
|
53
|
+
source code control systems, and issue tracking systems that are managed
|
|
54
|
+
by, or on behalf of, the Licensor for the purpose of adding to,
|
|
55
|
+
discussing, and improving the Work, but excluding communication that is
|
|
56
|
+
conspicuously marked or designated in writing by the copyright owner as
|
|
57
|
+
"Not a Contribution."
|
|
58
|
+
|
|
59
|
+
"Contributor" shall mean Licensor and any Legal Entity on behalf of
|
|
60
|
+
whom a Contribution has been received by the Licensor and included
|
|
61
|
+
within the Work.
|
|
62
|
+
|
|
63
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
64
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
65
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
66
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
67
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
68
|
+
Work and such Derivative Works in Source or Object form.
|
|
69
|
+
|
|
70
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
71
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
72
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
73
|
+
(except as stated in this section) patent license to make, have made,
|
|
74
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
75
|
+
where such license applies only to those patent contributions
|
|
76
|
+
Licensors or Contributors that are necessarily infringed by their
|
|
77
|
+
Contribution(s) alone or by the combination of their Contribution(s)
|
|
78
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
79
|
+
institute patent litigation against any entity (including a cross-claim
|
|
80
|
+
or counterclaim in a lawsuit) alleging that the Work or any Contributor
|
|
81
|
+
Contribution constitutes direct or contributory patent infringement,
|
|
82
|
+
then any patent licenses granted to You under this License for that
|
|
83
|
+
Work shall terminate as of the date such litigation is filed.
|
|
84
|
+
|
|
85
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
86
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
87
|
+
modifications, and in Source or Object form, provided that You
|
|
88
|
+
meet the following conditions:
|
|
89
|
+
|
|
90
|
+
(a) You must give any other recipients of the Work or Derivative
|
|
91
|
+
Works a copy of this License; and
|
|
92
|
+
|
|
93
|
+
(b) You must cause any modified files to carry prominent notices
|
|
94
|
+
stating that You changed the files; and
|
|
95
|
+
|
|
96
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
97
|
+
that You distribute, all copyright, patent, trademark, and
|
|
98
|
+
attribution notices from the Source form of the Work,
|
|
99
|
+
excluding those notices that do not pertain to any part of
|
|
100
|
+
the Derivative Works; and
|
|
101
|
+
|
|
102
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
103
|
+
distribution, You must include a readable copy of the
|
|
104
|
+
attribution notices contained within such NOTICE file, in
|
|
105
|
+
at least one of the following places: within a NOTICE text
|
|
106
|
+
file distributed as part of the Derivative Works; within
|
|
107
|
+
the Source form or documentation, if provided along with the
|
|
108
|
+
Derivative Works; or, within a display generated by the
|
|
109
|
+
Derivative Works, if and wherever such third-party notices
|
|
110
|
+
normally appear. The contents of the NOTICE file are for
|
|
111
|
+
informational purposes only and do not modify the License.
|
|
112
|
+
You may add Your own attribution notices within Derivative
|
|
113
|
+
Works that You distribute, alongside or in addition to the
|
|
114
|
+
NOTICE text from the Work, provided that such additional
|
|
115
|
+
attribution notices cannot be construed as modifying the
|
|
116
|
+
License.
|
|
117
|
+
|
|
118
|
+
You may add Your own license statement for Your modifications and
|
|
119
|
+
may provide additional grant of rights to use, copy, modify, merge,
|
|
120
|
+
publish, distribute, sublicense, and/or sell copies of the
|
|
121
|
+
Contribution, either on a nonexclusive basis or otherwise.
|
|
122
|
+
|
|
123
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
124
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
125
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
126
|
+
this License, without any additional terms or conditions.
|
|
127
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
128
|
+
the terms of any separate license agreement you may have executed
|
|
129
|
+
with Licensor regarding such Contributions.
|
|
130
|
+
|
|
131
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
132
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
133
|
+
except as required for reasonable and customary use in describing the
|
|
134
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
135
|
+
|
|
136
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
137
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
138
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
139
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
140
|
+
implied, including, without limitation, any warranties or conditions
|
|
141
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
142
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
143
|
+
appropriateness of using or reproducing the Work and assume any
|
|
144
|
+
risks associated with Your exercise of permissions under this License.
|
|
145
|
+
|
|
146
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
147
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
148
|
+
unless required by applicable law (such as deliberate and grossly
|
|
149
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
150
|
+
liable to You for damages, including any direct, indirect, special,
|
|
151
|
+
incidental, or exemplary damages of any character arising as a
|
|
152
|
+
result of this License or out of the use or inability to use the
|
|
153
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
154
|
+
work stoppage, computer failure or malfunction, or all other
|
|
155
|
+
commercial damages or losses), even if such Contributor has been
|
|
156
|
+
advised of the possibility of such damages.
|
|
157
|
+
|
|
158
|
+
9. Accepting Warranty or Liability. While redistributing the Work or
|
|
159
|
+
Derivative Works thereof, You may choose to offer, and charge a fee
|
|
160
|
+
for, acceptance of support, warranty, indemnity, or other liability
|
|
161
|
+
obligations and/or rights consistent with this License. However, in
|
|
162
|
+
accepting such obligations, You may offer such obligations only on
|
|
163
|
+
Your own behalf and on a full behalf of all other Contributors, and
|
|
164
|
+
only if You agree to indemnify, defend, and hold each Contributor
|
|
165
|
+
harmless for any liability incurred by, or claims asserted against,
|
|
166
|
+
such Contributor by reason of your accepting any such warranty or
|
|
167
|
+
additional liability.
|
|
168
|
+
|
|
169
|
+
END OF TERMS AND CONDITIONS
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hea-scripts
|
|
3
|
+
Version: 1.0.0b1
|
|
4
|
+
Summary: A collection of scripts for the HEA project.
|
|
5
|
+
Author-email: "Comprehensive Oncology Data and Engineering Shared Resource (CODE), Huntsman Cancer Institute, Salt Lake City, UT" <Andrew.Post@hci.utah.edu>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Classifier: Development Status :: 4 - Beta
|
|
8
|
+
Classifier: Environment :: Console
|
|
9
|
+
Classifier: Intended Audience :: System Administrators
|
|
10
|
+
Classifier: Natural Language :: English
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
18
|
+
Classifier: Topic :: Security :: Cryptography
|
|
19
|
+
Classifier: Topic :: System :: Systems Administration
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
23
|
+
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Requires-Dist: cryptography~=44.0.0
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: pytest~=8.0; extra == "dev"
|
|
30
|
+
Requires-Dist: mypy~=2.1; extra == "dev"
|
|
31
|
+
Requires-Dist: build~=1.5; extra == "dev"
|
|
32
|
+
Requires-Dist: coverage~=7.14.1; extra == "dev"
|
|
33
|
+
Requires-Dist: twine~=6.2.0; extra == "dev"
|
|
34
|
+
Requires-Dist: tox~=4.55.0; extra == "dev"
|
|
35
|
+
Dynamic: license-file
|
|
36
|
+
|
|
37
|
+
# HEA Scripts
|
|
38
|
+
|
|
39
|
+
Contains scripts for configuring a Health Enterprise Analytics (HEA) deployment. The primary scripts handle Fernet symmetric encryption of secrets stored in `.env` files.
|
|
40
|
+
|
|
41
|
+
## Setup
|
|
42
|
+
|
|
43
|
+
Install the package in editable mode (the dev container does this automatically):
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
pip install --user -e .
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Requires Python 3.10 - 3.12.
|
|
50
|
+
|
|
51
|
+
## Usage
|
|
52
|
+
|
|
53
|
+
### Generate an encryption key
|
|
54
|
+
|
|
55
|
+
```sh
|
|
56
|
+
hea-gen-encryption-key
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Save the printed key in your `.env` file as `HEA_ENCRYPTION_KEY`, or in a dedicated file (recommended) referenced by `HEA_ENCRYPTION_KEY_FILE`. If using a file, restrict its permissions:
|
|
60
|
+
|
|
61
|
+
```sh
|
|
62
|
+
chmod 600 hea_encryption_key.txt
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### Encrypt / decrypt a value
|
|
66
|
+
|
|
67
|
+
```sh
|
|
68
|
+
# Encrypt a literal value
|
|
69
|
+
hea-encryption --encrypt <value>
|
|
70
|
+
|
|
71
|
+
# Encrypt a property already in .env (result is written to stdout with {crypt} prefix)
|
|
72
|
+
hea-encryption --encrypt -p <PROPERTY_NAME>
|
|
73
|
+
|
|
74
|
+
# Decrypt a token
|
|
75
|
+
hea-encryption --decrypt <token>
|
|
76
|
+
|
|
77
|
+
# Read input from a file
|
|
78
|
+
hea-encryption --encrypt -f <file>
|
|
79
|
+
hea-encryption --decrypt -f <file>
|
|
80
|
+
|
|
81
|
+
# Write output to a file instead of stdout
|
|
82
|
+
hea-encryption --encrypt <value> -o <output_file>
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Configuration
|
|
86
|
+
|
|
87
|
+
Scripts expect a `.env` file in the working directory. The encryption key is resolved in this order:
|
|
88
|
+
|
|
89
|
+
1. `HEA_ENCRYPTION_KEY_FILE` environment variable (path to key file)
|
|
90
|
+
2. `HEA_ENCRYPTION_KEY_FILE` in `.env` (path to key file)
|
|
91
|
+
3. `HEA_ENCRYPTION_KEY` environment variable (inline key)
|
|
92
|
+
4. `HEA_ENCRYPTION_KEY` in `.env` (inline key)
|
|
93
|
+
|
|
94
|
+
Encrypted values stored in `.env` use the format:
|
|
95
|
+
|
|
96
|
+
```
|
|
97
|
+
PROPERTY={crypt}<fernet-token>
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## Contributing
|
|
101
|
+
|
|
102
|
+
Install the package with the `dev` optional dependencies to get pytest:
|
|
103
|
+
|
|
104
|
+
```sh
|
|
105
|
+
pip install --user -e ".[dev]"
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Run the tests:
|
|
109
|
+
|
|
110
|
+
```sh
|
|
111
|
+
python -m pytest tests/
|
|
112
|
+
```
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# HEA Scripts
|
|
2
|
+
|
|
3
|
+
Contains scripts for configuring a Health Enterprise Analytics (HEA) deployment. The primary scripts handle Fernet symmetric encryption of secrets stored in `.env` files.
|
|
4
|
+
|
|
5
|
+
## Setup
|
|
6
|
+
|
|
7
|
+
Install the package in editable mode (the dev container does this automatically):
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pip install --user -e .
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Requires Python 3.10 - 3.12.
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
### Generate an encryption key
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
hea-gen-encryption-key
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Save the printed key in your `.env` file as `HEA_ENCRYPTION_KEY`, or in a dedicated file (recommended) referenced by `HEA_ENCRYPTION_KEY_FILE`. If using a file, restrict its permissions:
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
chmod 600 hea_encryption_key.txt
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### Encrypt / decrypt a value
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
# Encrypt a literal value
|
|
33
|
+
hea-encryption --encrypt <value>
|
|
34
|
+
|
|
35
|
+
# Encrypt a property already in .env (result is written to stdout with {crypt} prefix)
|
|
36
|
+
hea-encryption --encrypt -p <PROPERTY_NAME>
|
|
37
|
+
|
|
38
|
+
# Decrypt a token
|
|
39
|
+
hea-encryption --decrypt <token>
|
|
40
|
+
|
|
41
|
+
# Read input from a file
|
|
42
|
+
hea-encryption --encrypt -f <file>
|
|
43
|
+
hea-encryption --decrypt -f <file>
|
|
44
|
+
|
|
45
|
+
# Write output to a file instead of stdout
|
|
46
|
+
hea-encryption --encrypt <value> -o <output_file>
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Configuration
|
|
50
|
+
|
|
51
|
+
Scripts expect a `.env` file in the working directory. The encryption key is resolved in this order:
|
|
52
|
+
|
|
53
|
+
1. `HEA_ENCRYPTION_KEY_FILE` environment variable (path to key file)
|
|
54
|
+
2. `HEA_ENCRYPTION_KEY_FILE` in `.env` (path to key file)
|
|
55
|
+
3. `HEA_ENCRYPTION_KEY` environment variable (inline key)
|
|
56
|
+
4. `HEA_ENCRYPTION_KEY` in `.env` (inline key)
|
|
57
|
+
|
|
58
|
+
Encrypted values stored in `.env` use the format:
|
|
59
|
+
|
|
60
|
+
```
|
|
61
|
+
PROPERTY={crypt}<fernet-token>
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Contributing
|
|
65
|
+
|
|
66
|
+
Install the package with the `dev` optional dependencies to get pytest:
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
pip install --user -e ".[dev]"
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Run the tests:
|
|
73
|
+
|
|
74
|
+
```sh
|
|
75
|
+
python -m pytest tests/
|
|
76
|
+
```
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=75.2.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "hea-scripts"
|
|
7
|
+
version = "1.0.0b1"
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
description = "A collection of scripts for the HEA project."
|
|
10
|
+
authors = [
|
|
11
|
+
{ name = "Comprehensive Oncology Data and Engineering Shared Resource (CODE), Huntsman Cancer Institute, Salt Lake City, UT", email = "Andrew.Post@hci.utah.edu" }
|
|
12
|
+
]
|
|
13
|
+
requires-python = ">=3.10"
|
|
14
|
+
license = "Apache-2.0"
|
|
15
|
+
license-files = ["LICENSE"]
|
|
16
|
+
dependencies = [
|
|
17
|
+
"cryptography~=44.0.0"
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
classifiers = [
|
|
21
|
+
"Development Status :: 4 - Beta",
|
|
22
|
+
"Environment :: Console",
|
|
23
|
+
"Intended Audience :: System Administrators",
|
|
24
|
+
"Natural Language :: English",
|
|
25
|
+
"Operating System :: OS Independent",
|
|
26
|
+
"Programming Language :: Python :: 3",
|
|
27
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
28
|
+
"Programming Language :: Python :: 3.10",
|
|
29
|
+
"Programming Language :: Python :: 3.11",
|
|
30
|
+
"Programming Language :: Python :: 3.12",
|
|
31
|
+
"Programming Language :: Python :: Implementation :: CPython",
|
|
32
|
+
"Topic :: Security :: Cryptography",
|
|
33
|
+
"Topic :: System :: Systems Administration",
|
|
34
|
+
"Topic :: Scientific/Engineering",
|
|
35
|
+
"Topic :: Scientific/Engineering :: Bio-Informatics",
|
|
36
|
+
"Topic :: Scientific/Engineering :: Information Analysis",
|
|
37
|
+
"Topic :: Scientific/Engineering :: Medical Science Apps."
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
[project.optional-dependencies]
|
|
41
|
+
dev = ["pytest~=8.0", "mypy~=2.1", "build~=1.5", "coverage~=7.14.1", "twine~=6.2.0", "tox~=4.55.0"]
|
|
42
|
+
|
|
43
|
+
[project.scripts]
|
|
44
|
+
hea-encryption = "hea.scripts.encryption:main"
|
|
45
|
+
hea-gen-encryption-key = "hea.scripts.gen_encryption_key:generate_key"
|
|
46
|
+
|
|
47
|
+
[tool.setuptools.packages.find]
|
|
48
|
+
where = ["src"]
|
|
49
|
+
namespaces = true
|
|
50
|
+
|
|
51
|
+
[tool.tox]
|
|
52
|
+
env_list = ["3.10", "3.11", "3.12"]
|
|
53
|
+
|
|
54
|
+
[tool.tox.env_run_base]
|
|
55
|
+
deps = [".[dev]"]
|
|
56
|
+
commands = [["pytest"]]
|
|
57
|
+
|
|
58
|
+
[tool.pytest.ini_options]
|
|
59
|
+
testpaths = ["tests"]
|
|
60
|
+
addopts = "--junitxml=pytest-test-report.xml"
|
|
61
|
+
|
|
62
|
+
[tool.mypy]
|
|
63
|
+
python_version = "3.12"
|
|
64
|
+
strict = true
|
|
65
|
+
mypy_path = "src"
|
|
66
|
+
explicit_package_bases = true
|
|
67
|
+
files = ["src/hea"]
|
|
File without changes
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
from cryptography.fernet import Fernet
|
|
2
|
+
from argparse import ArgumentParser
|
|
3
|
+
from hea.scripts.scriptlib import parse_hea_encryption_key, get_env_data_as_dict
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
ENCODING = 'utf-8'
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def main() -> None:
|
|
10
|
+
parser = ArgumentParser(description='Encrypt or decrypt data using a symmetric key. Writes to stdout. Input data is '
|
|
11
|
+
'assumed to be UTF-8 encoded text, and output is also in UTF-8. An encryption key must be '
|
|
12
|
+
'specified in the .env file using either the HEA_ENCRYPTION_KEY or HEA_ENCRYPTION_KEY_FILE '
|
|
13
|
+
'properties.')
|
|
14
|
+
group = parser.add_mutually_exclusive_group(required=True)
|
|
15
|
+
group.add_argument('-e', '--encrypt', action='store_true', help='Encrypt the input data.')
|
|
16
|
+
group.add_argument('-d', '--decrypt', action='store_true', help='Decrypt the input data.')
|
|
17
|
+
parser.add_argument('-f', '--file', action='store_true', help='If provided, input is a file from which to read input.')
|
|
18
|
+
parser.add_argument('-p', '--property', help='Process a property from the .env file')
|
|
19
|
+
parser.add_argument('-o', '--output-file', help='If provided, output will be written to the specified file instead of stdout.')
|
|
20
|
+
parser.add_argument('input', help='The input data to encrypt or decrypt. If -, reads from stdin or the .env.')
|
|
21
|
+
|
|
22
|
+
args = parser.parse_args()
|
|
23
|
+
|
|
24
|
+
dot_env = get_env_data_as_dict('.env')
|
|
25
|
+
|
|
26
|
+
try:
|
|
27
|
+
key = parse_hea_encryption_key(dot_env)
|
|
28
|
+
except Exception as e:
|
|
29
|
+
print(f'Error parsing HEA encryption key: {e}', file=sys.stderr)
|
|
30
|
+
sys.exit(1)
|
|
31
|
+
|
|
32
|
+
fernet = Fernet(key)
|
|
33
|
+
|
|
34
|
+
def encrypt_data(data: str) -> str:
|
|
35
|
+
return fernet.encrypt(data.encode(ENCODING)).decode(ENCODING)
|
|
36
|
+
|
|
37
|
+
def decrypt_data(token: str) -> str:
|
|
38
|
+
return fernet.decrypt(token.encode(ENCODING)).decode(ENCODING)
|
|
39
|
+
|
|
40
|
+
if args.encrypt:
|
|
41
|
+
if args.file:
|
|
42
|
+
with open(args.input, 'r') as infile:
|
|
43
|
+
input_data = infile.read()
|
|
44
|
+
elif args.property:
|
|
45
|
+
if args.property not in dot_env:
|
|
46
|
+
print(f'Property {args.property} not found in .env file.', file=sys.stderr)
|
|
47
|
+
sys.exit(2)
|
|
48
|
+
input_data = dot_env[args.property].strip()
|
|
49
|
+
elif args.input == '-':
|
|
50
|
+
input_data = sys.stdin.readline().strip()
|
|
51
|
+
else:
|
|
52
|
+
input_data = args.input
|
|
53
|
+
result = encrypt_data(input_data)
|
|
54
|
+
if args.property:
|
|
55
|
+
result = '{crypt}' + result
|
|
56
|
+
elif args.decrypt:
|
|
57
|
+
if args.file:
|
|
58
|
+
with open(args.input, 'r') as infile:
|
|
59
|
+
token = infile.read().strip()
|
|
60
|
+
elif args.property:
|
|
61
|
+
if args.property not in dot_env:
|
|
62
|
+
print(f'Property {args.property} not found in .env file.', file=sys.stderr)
|
|
63
|
+
sys.exit(2)
|
|
64
|
+
token = dot_env[args.property].strip().removeprefix('{crypt}')
|
|
65
|
+
elif args.input == '-':
|
|
66
|
+
token = sys.stdin.readline().strip()
|
|
67
|
+
else:
|
|
68
|
+
token = args.input
|
|
69
|
+
result = decrypt_data(token)
|
|
70
|
+
|
|
71
|
+
if args.output_file:
|
|
72
|
+
with open(args.output_file, 'w') as outfile:
|
|
73
|
+
outfile.write(result)
|
|
74
|
+
else:
|
|
75
|
+
print(result)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
if __name__ == '__main__':
|
|
79
|
+
main()
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from cryptography.fernet import Fernet
|
|
2
|
+
from argparse import ArgumentParser
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def generate_key() -> None:
|
|
6
|
+
parser = ArgumentParser(description='Generates a new symmetric key for encrypting secrets.')
|
|
7
|
+
_ = parser.parse_args()
|
|
8
|
+
|
|
9
|
+
print("Generating encryption key...")
|
|
10
|
+
print("Save this key in your .env file as HEA_ENCRYPTION_KEY to enable password encryption for stored credentials. "
|
|
11
|
+
"For better security, save the key in a file outside of the HEA directory tree called hea_encryption_key.txt. "
|
|
12
|
+
"Ensure it is only readable by the user running HEA -- for example, assuming you are the user running docker "
|
|
13
|
+
"compose, on Linux you can run 'chmod 600 <the file> after creating it.")
|
|
14
|
+
print("Key:", Fernet.generate_key().decode('utf-8'))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
if __name__ == '__main__':
|
|
18
|
+
generate_key()
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from string import whitespace
|
|
2
|
+
import os
|
|
3
|
+
from cryptography.fernet import Fernet
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def get_env_data_as_dict(path: str) -> dict[str, str]:
|
|
7
|
+
with open(path, 'r') as f:
|
|
8
|
+
return dict((k, v.strip("'\" ")) for k, v in (line.strip().split('=', maxsplit=1) for line in f.readlines()
|
|
9
|
+
if not line.startswith('#') and not line.startswith(tuple(w for w in whitespace))))
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def parse_hea_encryption_key(dot_env: dict[str, str]) -> bytes:
|
|
13
|
+
if 'HEA_ENCRYPTION_KEY_FILE' in os.environ:
|
|
14
|
+
path = os.path.expanduser(os.environ['HEA_ENCRYPTION_KEY_FILE'])
|
|
15
|
+
with open(path, 'rb') as key_file:
|
|
16
|
+
print('Using encryption key from file (environment variable)...')
|
|
17
|
+
return key_file.read().strip()
|
|
18
|
+
elif 'HEA_ENCRYPTION_KEY_FILE' in dot_env:
|
|
19
|
+
path = os.path.expanduser(dot_env['HEA_ENCRYPTION_KEY_FILE'])
|
|
20
|
+
with open(path, 'rb') as key_file:
|
|
21
|
+
print('Using encryption key from file...')
|
|
22
|
+
return key_file.read().strip()
|
|
23
|
+
elif result := os.environ.get('HEA_ENCRYPTION_KEY', '').encode('utf-8'):
|
|
24
|
+
print('Using encryption key from environment variable (environment variable)...')
|
|
25
|
+
return result
|
|
26
|
+
elif result := dot_env.get('HEA_ENCRYPTION_KEY', '').encode('utf-8'):
|
|
27
|
+
print('Using encryption key from environment variable...')
|
|
28
|
+
return result
|
|
29
|
+
else:
|
|
30
|
+
raise ValueError('HEA_ENCRYPTION_KEY is not set and HEA_ENCRYPTION_KEY_FILE does not exist or is empty.')
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def decrypt(encrypted_password: str, dot_env: dict[str, str]) -> str:
|
|
34
|
+
if encrypted_password.startswith('{crypt}'):
|
|
35
|
+
fernet = Fernet(parse_hea_encryption_key(dot_env))
|
|
36
|
+
print('Decrypting MongoDB password...')
|
|
37
|
+
return fernet.decrypt(encrypted_password[len('{crypt}'):]).decode('utf-8')
|
|
38
|
+
else:
|
|
39
|
+
return encrypted_password
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hea-scripts
|
|
3
|
+
Version: 1.0.0b1
|
|
4
|
+
Summary: A collection of scripts for the HEA project.
|
|
5
|
+
Author-email: "Comprehensive Oncology Data and Engineering Shared Resource (CODE), Huntsman Cancer Institute, Salt Lake City, UT" <Andrew.Post@hci.utah.edu>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Classifier: Development Status :: 4 - Beta
|
|
8
|
+
Classifier: Environment :: Console
|
|
9
|
+
Classifier: Intended Audience :: System Administrators
|
|
10
|
+
Classifier: Natural Language :: English
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
18
|
+
Classifier: Topic :: Security :: Cryptography
|
|
19
|
+
Classifier: Topic :: System :: Systems Administration
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
23
|
+
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Requires-Dist: cryptography~=44.0.0
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: pytest~=8.0; extra == "dev"
|
|
30
|
+
Requires-Dist: mypy~=2.1; extra == "dev"
|
|
31
|
+
Requires-Dist: build~=1.5; extra == "dev"
|
|
32
|
+
Requires-Dist: coverage~=7.14.1; extra == "dev"
|
|
33
|
+
Requires-Dist: twine~=6.2.0; extra == "dev"
|
|
34
|
+
Requires-Dist: tox~=4.55.0; extra == "dev"
|
|
35
|
+
Dynamic: license-file
|
|
36
|
+
|
|
37
|
+
# HEA Scripts
|
|
38
|
+
|
|
39
|
+
Contains scripts for configuring a Health Enterprise Analytics (HEA) deployment. The primary scripts handle Fernet symmetric encryption of secrets stored in `.env` files.
|
|
40
|
+
|
|
41
|
+
## Setup
|
|
42
|
+
|
|
43
|
+
Install the package in editable mode (the dev container does this automatically):
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
pip install --user -e .
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Requires Python 3.10 - 3.12.
|
|
50
|
+
|
|
51
|
+
## Usage
|
|
52
|
+
|
|
53
|
+
### Generate an encryption key
|
|
54
|
+
|
|
55
|
+
```sh
|
|
56
|
+
hea-gen-encryption-key
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Save the printed key in your `.env` file as `HEA_ENCRYPTION_KEY`, or in a dedicated file (recommended) referenced by `HEA_ENCRYPTION_KEY_FILE`. If using a file, restrict its permissions:
|
|
60
|
+
|
|
61
|
+
```sh
|
|
62
|
+
chmod 600 hea_encryption_key.txt
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### Encrypt / decrypt a value
|
|
66
|
+
|
|
67
|
+
```sh
|
|
68
|
+
# Encrypt a literal value
|
|
69
|
+
hea-encryption --encrypt <value>
|
|
70
|
+
|
|
71
|
+
# Encrypt a property already in .env (result is written to stdout with {crypt} prefix)
|
|
72
|
+
hea-encryption --encrypt -p <PROPERTY_NAME>
|
|
73
|
+
|
|
74
|
+
# Decrypt a token
|
|
75
|
+
hea-encryption --decrypt <token>
|
|
76
|
+
|
|
77
|
+
# Read input from a file
|
|
78
|
+
hea-encryption --encrypt -f <file>
|
|
79
|
+
hea-encryption --decrypt -f <file>
|
|
80
|
+
|
|
81
|
+
# Write output to a file instead of stdout
|
|
82
|
+
hea-encryption --encrypt <value> -o <output_file>
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Configuration
|
|
86
|
+
|
|
87
|
+
Scripts expect a `.env` file in the working directory. The encryption key is resolved in this order:
|
|
88
|
+
|
|
89
|
+
1. `HEA_ENCRYPTION_KEY_FILE` environment variable (path to key file)
|
|
90
|
+
2. `HEA_ENCRYPTION_KEY_FILE` in `.env` (path to key file)
|
|
91
|
+
3. `HEA_ENCRYPTION_KEY` environment variable (inline key)
|
|
92
|
+
4. `HEA_ENCRYPTION_KEY` in `.env` (inline key)
|
|
93
|
+
|
|
94
|
+
Encrypted values stored in `.env` use the format:
|
|
95
|
+
|
|
96
|
+
```
|
|
97
|
+
PROPERTY={crypt}<fernet-token>
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## Contributing
|
|
101
|
+
|
|
102
|
+
Install the package with the `dev` optional dependencies to get pytest:
|
|
103
|
+
|
|
104
|
+
```sh
|
|
105
|
+
pip install --user -e ".[dev]"
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Run the tests:
|
|
109
|
+
|
|
110
|
+
```sh
|
|
111
|
+
python -m pytest tests/
|
|
112
|
+
```
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/hea/scripts/__init__.py
|
|
5
|
+
src/hea/scripts/encryption.py
|
|
6
|
+
src/hea/scripts/gen_encryption_key.py
|
|
7
|
+
src/hea/scripts/scriptlib.py
|
|
8
|
+
src/hea_scripts.egg-info/PKG-INFO
|
|
9
|
+
src/hea_scripts.egg-info/SOURCES.txt
|
|
10
|
+
src/hea_scripts.egg-info/dependency_links.txt
|
|
11
|
+
src/hea_scripts.egg-info/entry_points.txt
|
|
12
|
+
src/hea_scripts.egg-info/requires.txt
|
|
13
|
+
src/hea_scripts.egg-info/top_level.txt
|
|
14
|
+
tests/test_encryption.py
|
|
15
|
+
tests/test_scriptlib.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
hea
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import sys
|
|
3
|
+
import pytest
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from cryptography.fernet import Fernet
|
|
6
|
+
from hea.scripts.encryption import main
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@pytest.fixture
|
|
10
|
+
def env_file(tmp_path: Path) -> tuple[Path, bytes]:
|
|
11
|
+
key = Fernet.generate_key()
|
|
12
|
+
p = tmp_path / ".env"
|
|
13
|
+
p.write_text(f"HEA_ENCRYPTION_KEY={key.decode()}\n")
|
|
14
|
+
return tmp_path, key
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_encrypt_decrypt_roundtrip(
|
|
18
|
+
env_file: tuple[Path, bytes],
|
|
19
|
+
monkeypatch: pytest.MonkeyPatch,
|
|
20
|
+
capsys: pytest.CaptureFixture[str],
|
|
21
|
+
) -> None:
|
|
22
|
+
work_dir, key = env_file
|
|
23
|
+
monkeypatch.chdir(work_dir)
|
|
24
|
+
|
|
25
|
+
monkeypatch.setattr(sys, "argv", ["hea-encryption", "--encrypt", "mysecret"])
|
|
26
|
+
main()
|
|
27
|
+
token = capsys.readouterr().out.splitlines()[-1]
|
|
28
|
+
|
|
29
|
+
monkeypatch.setattr(sys, "argv", ["hea-encryption", "--decrypt", token])
|
|
30
|
+
main()
|
|
31
|
+
assert capsys.readouterr().out.splitlines()[-1] == "mysecret"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_encrypt_from_stdin(
|
|
35
|
+
env_file: tuple[Path, bytes],
|
|
36
|
+
monkeypatch: pytest.MonkeyPatch,
|
|
37
|
+
capsys: pytest.CaptureFixture[str],
|
|
38
|
+
) -> None:
|
|
39
|
+
work_dir, _ = env_file
|
|
40
|
+
monkeypatch.chdir(work_dir)
|
|
41
|
+
monkeypatch.setattr(sys, "argv", ["hea-encryption", "--encrypt", "-"])
|
|
42
|
+
monkeypatch.setattr("sys.stdin", io.StringIO("mysecret\n"))
|
|
43
|
+
main()
|
|
44
|
+
assert capsys.readouterr().out.strip() != ""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_encrypt_property_adds_crypt_prefix(
|
|
48
|
+
env_file: tuple[Path, bytes],
|
|
49
|
+
monkeypatch: pytest.MonkeyPatch,
|
|
50
|
+
capsys: pytest.CaptureFixture[str],
|
|
51
|
+
) -> None:
|
|
52
|
+
work_dir, key = env_file
|
|
53
|
+
(work_dir / ".env").write_text(
|
|
54
|
+
f"HEA_ENCRYPTION_KEY={key.decode()}\nMY_PASS=secret\n"
|
|
55
|
+
)
|
|
56
|
+
monkeypatch.chdir(work_dir)
|
|
57
|
+
monkeypatch.setattr(sys, "argv", ["hea-encryption", "--encrypt", "-p", "MY_PASS", "-"])
|
|
58
|
+
main()
|
|
59
|
+
assert capsys.readouterr().out.splitlines()[-1].startswith("{crypt}")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_decrypt_property_strips_crypt_prefix(
|
|
63
|
+
env_file: tuple[Path, bytes],
|
|
64
|
+
monkeypatch: pytest.MonkeyPatch,
|
|
65
|
+
capsys: pytest.CaptureFixture[str],
|
|
66
|
+
) -> None:
|
|
67
|
+
work_dir, key = env_file
|
|
68
|
+
fernet = Fernet(key)
|
|
69
|
+
token = fernet.encrypt(b"secret").decode()
|
|
70
|
+
(work_dir / ".env").write_text(
|
|
71
|
+
f"HEA_ENCRYPTION_KEY={key.decode()}\nMY_PASS={{crypt}}{token}\n"
|
|
72
|
+
)
|
|
73
|
+
monkeypatch.chdir(work_dir)
|
|
74
|
+
monkeypatch.setattr(sys, "argv", ["hea-encryption", "--decrypt", "-p", "MY_PASS", "-"])
|
|
75
|
+
main()
|
|
76
|
+
assert capsys.readouterr().out.splitlines()[-1] == "secret"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_missing_property_exits(
|
|
80
|
+
env_file: tuple[Path, bytes],
|
|
81
|
+
monkeypatch: pytest.MonkeyPatch,
|
|
82
|
+
) -> None:
|
|
83
|
+
work_dir, _ = env_file
|
|
84
|
+
monkeypatch.chdir(work_dir)
|
|
85
|
+
monkeypatch.setattr(sys, "argv", ["hea-encryption", "--encrypt", "-p", "MISSING", "-"])
|
|
86
|
+
with pytest.raises(SystemExit) as exc:
|
|
87
|
+
main()
|
|
88
|
+
assert exc.value.code == 2
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_output_file(
|
|
92
|
+
env_file: tuple[Path, bytes],
|
|
93
|
+
monkeypatch: pytest.MonkeyPatch,
|
|
94
|
+
tmp_path: Path,
|
|
95
|
+
) -> None:
|
|
96
|
+
work_dir, _ = env_file
|
|
97
|
+
monkeypatch.chdir(work_dir)
|
|
98
|
+
out_file = tmp_path / "out.txt"
|
|
99
|
+
monkeypatch.setattr(sys, "argv", ["hea-encryption", "--encrypt", "hello", "-o", str(out_file)])
|
|
100
|
+
main()
|
|
101
|
+
assert out_file.read_text() != ""
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
from collections.abc import Callable
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from cryptography.fernet import Fernet
|
|
5
|
+
from hea.scripts.scriptlib import get_env_data_as_dict, parse_hea_encryption_key, decrypt
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@pytest.fixture
|
|
9
|
+
def key() -> bytes:
|
|
10
|
+
return Fernet.generate_key()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@pytest.fixture
|
|
14
|
+
def dot_env_file(tmp_path: Path) -> Callable[[str], str]:
|
|
15
|
+
def _write(contents: str) -> str:
|
|
16
|
+
p = tmp_path / ".env"
|
|
17
|
+
p.write_text(contents)
|
|
18
|
+
return str(p)
|
|
19
|
+
return _write
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class TestGetEnvDataAsDict:
|
|
23
|
+
def test_parses_key_value_pairs(self, dot_env_file: Callable[[str], str]) -> None:
|
|
24
|
+
path = dot_env_file("FOO=bar\nBAZ=qux\n")
|
|
25
|
+
assert get_env_data_as_dict(path) == {"FOO": "bar", "BAZ": "qux"}
|
|
26
|
+
|
|
27
|
+
def test_strips_double_quotes(self, dot_env_file: Callable[[str], str]) -> None:
|
|
28
|
+
path = dot_env_file('FOO="bar"\n')
|
|
29
|
+
assert get_env_data_as_dict(path)["FOO"] == "bar"
|
|
30
|
+
|
|
31
|
+
def test_strips_single_quotes(self, dot_env_file: Callable[[str], str]) -> None:
|
|
32
|
+
path = dot_env_file("FOO='bar'\n")
|
|
33
|
+
assert get_env_data_as_dict(path)["FOO"] == "bar"
|
|
34
|
+
|
|
35
|
+
def test_ignores_comments(self, dot_env_file: Callable[[str], str]) -> None:
|
|
36
|
+
path = dot_env_file("# comment\nFOO=bar\n")
|
|
37
|
+
assert get_env_data_as_dict(path) == {"FOO": "bar"}
|
|
38
|
+
|
|
39
|
+
def test_ignores_blank_lines(self, dot_env_file: Callable[[str], str]) -> None:
|
|
40
|
+
path = dot_env_file("\nFOO=bar\n\n")
|
|
41
|
+
assert get_env_data_as_dict(path) == {"FOO": "bar"}
|
|
42
|
+
|
|
43
|
+
def test_value_with_equals_sign(self, dot_env_file: Callable[[str], str]) -> None:
|
|
44
|
+
path = dot_env_file("FOO=bar=baz\n")
|
|
45
|
+
assert get_env_data_as_dict(path)["FOO"] == "bar=baz"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class TestParseHEAEncryptionKey:
|
|
49
|
+
def test_reads_key_from_dot_env(self, dot_env_file: Callable[[str], str], key: bytes) -> None:
|
|
50
|
+
path = dot_env_file(f"HEA_ENCRYPTION_KEY={key.decode()}\n")
|
|
51
|
+
dot_env = get_env_data_as_dict(path)
|
|
52
|
+
assert parse_hea_encryption_key(dot_env) == key
|
|
53
|
+
|
|
54
|
+
def test_reads_key_from_env_var(self, monkeypatch: pytest.MonkeyPatch, key: bytes) -> None:
|
|
55
|
+
monkeypatch.setenv("HEA_ENCRYPTION_KEY", key.decode())
|
|
56
|
+
assert parse_hea_encryption_key({}) == key
|
|
57
|
+
|
|
58
|
+
def test_reads_key_from_key_file_in_dot_env(
|
|
59
|
+
self, tmp_path: Path, dot_env_file: Callable[[str], str], key: bytes
|
|
60
|
+
) -> None:
|
|
61
|
+
key_file = tmp_path / "hea_encryption_key.txt"
|
|
62
|
+
key_file.write_bytes(key)
|
|
63
|
+
path = dot_env_file(f"HEA_ENCRYPTION_KEY_FILE={key_file}\n")
|
|
64
|
+
dot_env = get_env_data_as_dict(path)
|
|
65
|
+
assert parse_hea_encryption_key(dot_env) == key
|
|
66
|
+
|
|
67
|
+
def test_reads_key_from_key_file_env_var(
|
|
68
|
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, key: bytes
|
|
69
|
+
) -> None:
|
|
70
|
+
key_file = tmp_path / "hea_encryption_key.txt"
|
|
71
|
+
key_file.write_bytes(key)
|
|
72
|
+
monkeypatch.setenv("HEA_ENCRYPTION_KEY_FILE", str(key_file))
|
|
73
|
+
assert parse_hea_encryption_key({}) == key
|
|
74
|
+
|
|
75
|
+
def test_key_file_env_var_takes_priority_over_dot_env(
|
|
76
|
+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, dot_env_file: Callable[[str], str]
|
|
77
|
+
) -> None:
|
|
78
|
+
key_env = Fernet.generate_key()
|
|
79
|
+
key_file_val = Fernet.generate_key()
|
|
80
|
+
key_file = tmp_path / "hea_encryption_key.txt"
|
|
81
|
+
key_file.write_bytes(key_file_val)
|
|
82
|
+
monkeypatch.setenv("HEA_ENCRYPTION_KEY_FILE", str(key_file))
|
|
83
|
+
path = dot_env_file(f"HEA_ENCRYPTION_KEY={key_env.decode()}\n")
|
|
84
|
+
dot_env = get_env_data_as_dict(path)
|
|
85
|
+
assert parse_hea_encryption_key(dot_env) == key_file_val
|
|
86
|
+
|
|
87
|
+
def test_raises_when_no_key(self) -> None:
|
|
88
|
+
with pytest.raises(ValueError, match="HEA_ENCRYPTION_KEY"):
|
|
89
|
+
parse_hea_encryption_key({})
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class TestDecrypt:
|
|
93
|
+
def test_passthrough_when_no_prefix(self, dot_env_file: Callable[[str], str], key: bytes) -> None:
|
|
94
|
+
path = dot_env_file(f"HEA_ENCRYPTION_KEY={key.decode()}\n")
|
|
95
|
+
dot_env = get_env_data_as_dict(path)
|
|
96
|
+
assert decrypt("plaintext", dot_env) == "plaintext"
|
|
97
|
+
|
|
98
|
+
def test_decrypts_crypt_prefixed_value(self, dot_env_file: Callable[[str], str], key: bytes) -> None:
|
|
99
|
+
fernet = Fernet(key)
|
|
100
|
+
token = fernet.encrypt(b"secret").decode()
|
|
101
|
+
path = dot_env_file(f"HEA_ENCRYPTION_KEY={key.decode()}\n")
|
|
102
|
+
dot_env = get_env_data_as_dict(path)
|
|
103
|
+
assert decrypt("{crypt}" + token, dot_env) == "secret"
|