hea-scripts 1.0.0b1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,10 @@
1
+ hea/scripts/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ hea/scripts/encryption.py,sha256=QfAoQIHjMutX_bIG9NzRCIZmZG9zJIZz7g066sImlTY,3220
3
+ hea/scripts/gen_encryption_key.py,sha256=hFy9xYcYRqyjquTkVXLE-33V550gUHQLFfMMrkFomDc,826
4
+ hea/scripts/scriptlib.py,sha256=_bgA6ttH73QOvXtoNkA5xvpjmWkbI5rP_3h___kUmDg,1827
5
+ hea_scripts-1.0.0b1.dist-info/licenses/LICENSE,sha256=5s0P5Dl6emNknE-b82MCJdEmfRHDNk-ujPK-Hzox5ro,9630
6
+ hea_scripts-1.0.0b1.dist-info/METADATA,sha256=cYYWn8CLuQ6Abmism6s3qWLykwclXMhd25L2UWVoSrE,3372
7
+ hea_scripts-1.0.0b1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
8
+ hea_scripts-1.0.0b1.dist-info/entry_points.txt,sha256=yofuRzDAsfhNR7rh5VlsTaLRCHebddxPls8H-uKE0t8,132
9
+ hea_scripts-1.0.0b1.dist-info/top_level.txt,sha256=4wql3sEup2EE1Ix8Awo-pwQOY7jjPTACRnnm95RAw2o,4
10
+ hea_scripts-1.0.0b1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ hea-encryption = hea.scripts.encryption:main
3
+ hea-gen-encryption-key = hea.scripts.gen_encryption_key:generate_key
@@ -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 @@
1
+ hea