├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── berglas-python.iml ├── berglas_python.py ├── examples └── api_example.py ├── requirements.txt └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea/ 2 | /venv/ 3 | /dist/ 4 | /build/ 5 | /berglas_python.egg-info/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Overview 2 | 3 | Python library help to use [Berglas](https://github.com/GoogleCloudPlatform/berglas), to encrypt and to decrypt the secrets stored in a GCP storage. 4 | 5 | See [Berglas](https://github.com/GoogleCloudPlatform/berglas) for details about bucket bootstrapping and secret creation 6 | 7 | # Library Usage 8 | 9 | You have to get the library 10 | ``` 11 | pip install berglas-python 12 | ``` 13 | 14 | Then use it in the same way as [Go library](https://github.com/GoogleCloudPlatform/berglas/blob/master/README.md#library-usage) 15 | 16 | The library berglas_python library is able to: 17 | 18 | - Encrypt and upload the secrets 19 | - Download and decrypt any secrets that match the [Berglas environment variable reference syntax](https://github.com/GoogleCloudPlatform/berglas/blob/master/doc/reference-syntax.md) 20 | - Replace the value for the environment variable with the decrypted secret 21 | 22 | Here an example of usage 23 | ``` 24 | import os 25 | 26 | import berglas_python as berglas 27 | 28 | project_id = os.environ.get("MY-PROJECT") 29 | 30 | # This higher-level API parses the secret reference at the specified 31 | # environment variable, downloads and decrypts the secret, and replaces the 32 | # contents of the given environment variable with the secret result. 33 | 34 | berglas.Replace(project_id, "MY-SECRET") 35 | 36 | # This lower-level API parses the secret reference, downloads and decrypts 37 | # the secret, and returns the result. This is useful if you need to mutate 38 | # the result. 39 | my_secret = os.environ.get("MY-SECRET") 40 | plaintext = berglas.Resolve(project_id, my_secret) 41 | os.environ.unsetenv("MY-SECRET") 42 | os.environ.setdefault("MY-SECRET", plaintext) 43 | 44 | # This is lower-level API encrypts the plaintext string and uploads the blob 45 | berglas.Encrypt(project_id, 'MY-BUCKET/MY-SECRET-FILE', 'STRING-TO-ENCRYPT') 46 | ``` 47 | 48 | # License 49 | 50 | This library is licensed under Apache 2.0. Full license text is available in 51 | [LICENSE](https://github.com/guillaumeblaquiere/berglas-python/tree/master/LICENSE). 52 | 53 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | name = "berglas_python" -------------------------------------------------------------------------------- /berglas-python.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /berglas_python.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import logging 3 | import os 4 | 5 | from cryptography.hazmat.backends import default_backend 6 | from google.cloud import storage, kms_v1 7 | from google.api_core import iam 8 | 9 | from cryptography.hazmat.primitives.ciphers import ( 10 | Cipher, algorithms, modes 11 | ) 12 | 13 | BERGLAS_PREFIX = "berglas://" 14 | METADATA_KMS_KEY = "berglas-kms-key" 15 | METADATA_ID_KEY = "berglas-secret" 16 | METADATA_CONTENT_TYPE = "text/plain; charset=utf-8" 17 | METADATA_CACHE_CONTROL = "private, no-cache, no-store, no-transform, max-age=0" 18 | BLOB_CHUNK_SIZE = 256 * 1024 19 | GCM_NONCE_SIZE = 12 20 | GCM_TAG_SIZE = 16 21 | DATA_ENCRYPTION_KEY_SIZE = 32 22 | 23 | LOCATION = "global" 24 | KEY_RING = "berglas" 25 | CRYPTO_KEY = "berglas-key" 26 | 27 | 28 | def str2b(s: str) -> bytes: 29 | """ 30 | Converts string to bytes encoding it as UTF-8 31 | 32 | :param s: String to be converted and encoded 33 | :return: a bytes object encoded 34 | """ 35 | return bytes(s, "UTF-8") 36 | 37 | 38 | def b2str(bystr: str) -> str: 39 | """ 40 | Converts bytes to string decoding it from UTF-8 41 | 42 | :param s: bytes to be converted and decoded 43 | :return: a string decoded 44 | """ 45 | return bystr.decode("UTF-8") 46 | 47 | 48 | def _validate_env_var_prefix(env_var_value: str): 49 | """ 50 | Check whether env_var_value starts with the pattern berglas:// 51 | :param env_var_value: Berglas reference with the pattern berglas:/// 52 | :exception: When object and/or bucket is missing (berglas pattern not respected) 53 | """ 54 | 55 | if not env_var_value.startswith(BERGLAS_PREFIX): 56 | log_msg = f"No berglas prefix for the env var value {env_var_value}" 57 | logging.error(log_msg) 58 | raise Exception(log_msg) 59 | 60 | 61 | def _validate_project_id(project_id: str): 62 | """ 63 | Check whether project_id is not empty 64 | :param project_id: Project ID for creating the storage client. 65 | :exception: When the project_id is missing/empty 66 | """ 67 | 68 | if project_id == "": 69 | log_msg = "Project id can't be empty" 70 | logging.error(log_msg) 71 | raise Exception(log_msg) 72 | 73 | 74 | def copy_blob_iam_policy(blob): 75 | """ 76 | Copy any IAM permissions from the old object over to the new object. 77 | 78 | :param blob: the blob object 79 | :return: na google.api_core.iam.Policy containing a copy of the current IAM policies 80 | """ 81 | 82 | new_policy = iam.Policy() 83 | blob_iam_policies = blob.get_iam_policy() 84 | 85 | for role_name, entity in blob_iam_policies.items(): 86 | new_policy[role_name] = list(entity) 87 | 88 | return new_policy 89 | 90 | 91 | def Replace(project_id: str, env_var_key: str): 92 | """ 93 | Replace, in the env var, the value of env var key by the deciphered value 94 | :param project_id: Project ID for creating the storage client. 95 | :param env_var_key: Key of the env var value to decipher and to replace. Do nothing if key doesn't exist or if the 96 | value don't start with berglas:// prefix. Value must respect the berglas pattern berglas:/// 97 | :return: no return 98 | :exception: When object and/or bucket is missing (berglas pattern not respected) 99 | :exception: When deciphering failed, bad dek size or format, bad ciphering text format 100 | :exception: When the project_id is missing/empty 101 | :exception: When the env_var_value doesn't respect the pattern 102 | :exception: When the env_var_value defines a not existing bucket and/or object 103 | """ 104 | 105 | env_var_value: str = os.environ.get(env_var_key) 106 | if env_var_value == "": 107 | logging.info(f"No value for the env var key {env_var_key}") 108 | return 109 | 110 | plaintext = Resolve(project_id, env_var_value) 111 | 112 | os.environ[env_var_key] = plaintext 113 | 114 | 115 | def _get_bucket_object(env_var_value: str) -> (str, str): 116 | """ 117 | Split the env_var_value into bucket and object name 118 | 119 | :param env_var_value: should respect this pattern berglas:/// 120 | :return: the bucket and the object name 121 | :exception: When object_name and/or bucket is missing (pattern not respected) 122 | """ 123 | 124 | without_prefix = env_var_value[len(BERGLAS_PREFIX):] 125 | if without_prefix == "": 126 | log_msg = f"No bucket and object defined in {env_var_value}" 127 | logging.error(log_msg) 128 | raise Exception(log_msg) 129 | 130 | splitted = without_prefix.split("/", 1) 131 | 132 | if splitted[1] == "": 133 | log_msg = f"No object defined in {env_var_value}" 134 | logging.error(log_msg) 135 | raise Exception(log_msg) 136 | 137 | return splitted[0], splitted[1] 138 | 139 | 140 | def _envelope_decrypt(data_encryption_key: str, data: str) -> str: 141 | """ 142 | Decipher the cipher text with the dek. Use aes GCM algorithm 143 | 144 | :param data_encryption_key: Data Encryption Key 145 | :param data: Content to decrypt with aes GCM cipher 146 | :return: deciphered plain text 147 | :exception: When deciphering failed, bad dek size or format, bad ciphering text format 148 | """ 149 | 150 | nonce = data[:GCM_NONCE_SIZE] 151 | ciphertext = data[GCM_NONCE_SIZE:-GCM_TAG_SIZE] 152 | tag = data[-GCM_TAG_SIZE:] 153 | 154 | algo = algorithms.AES(data_encryption_key) 155 | 156 | cipher = Cipher( 157 | algo, 158 | modes.GCM(nonce, tag), 159 | backend=default_backend() 160 | ) 161 | 162 | decrypter = cipher.decryptor() 163 | return b2str(decrypter.update(ciphertext)) 164 | 165 | 166 | def _envelope_encrypt(plaintext: bytes) -> (bytes, bytes): 167 | """ 168 | Generates a unique Data Encryption Key and encrypts the plaintext with the given key. 169 | 170 | :param plaintext: String to be encrypted 171 | :return: The encryption key and resulting ciphertext 172 | """ 173 | 174 | # Generate a random 256-bit key. 175 | data_encryption_key = os.urandom(DATA_ENCRYPTION_KEY_SIZE) 176 | 177 | # Generate a random 96-bit IV. 178 | initialization_vector = os.urandom(GCM_NONCE_SIZE) 179 | 180 | # Construct an AES-GCM Cipher object with the given key and a 181 | # randomly generated IV. 182 | cipher = Cipher( 183 | algorithms.AES(data_encryption_key), 184 | modes.GCM(initialization_vector), 185 | backend=default_backend() 186 | ) 187 | 188 | encryptor = cipher.encryptor() 189 | 190 | # Encrypt the plaintext and get the associated ciphertext. 191 | # GCM does not require padding. 192 | ciphertext = encryptor.update(plaintext) + encryptor.finalize() 193 | 194 | # Encrypt the ciphertext with the DEK 195 | # Masking the ciphertext by adding the initialization vector (12 chars) + ciphered text + 196 | # and the encryptor_tag as additional data (16 chars). 197 | # The encryptor_tag will be discarded by Berglas as it auto places this field with a nil value. 198 | # But it is required for adding 16 chars at the end of the ciphered text 199 | data = initialization_vector + ciphertext + encryptor.tag 200 | 201 | return (data_encryption_key, data) 202 | 203 | 204 | def Resolve(project_id: str, env_var_value: str) -> str: 205 | """ 206 | Get the object in the bucket (define in the env_var_value) and decipher it 207 | 208 | :param project_id: Project ID for creating the storage client. 209 | :param env_var_value: Berglas reference with the pattern berglas:/// 210 | :return: the plaintext value of the deciphered reference. 211 | :exception: When the project_id is missing/empty 212 | :exception: When the env_var_value doesn't respect the pattern 213 | :exception: When the env_var_value defines a not existing bucket and/or object_name 214 | :exception: When object_name and/or bucket is missing (pattern not respected) 215 | """ 216 | 217 | _validate_env_var_prefix(env_var_value) 218 | 219 | _validate_project_id(project_id) 220 | 221 | gcs_client = storage.Client(project=project_id) 222 | kms_client = kms_v1.KeyManagementServiceClient() 223 | 224 | bucket, object_name = _get_bucket_object(env_var_value) 225 | 226 | # Get the blob in the storage 227 | blob = gcs_client.bucket(bucket).get_blob(object_name) 228 | # Get the key reference in metadata 229 | crypto_key_path = blob.metadata[METADATA_KMS_KEY] 230 | # Get the blob ciphered content 231 | blob_content = b2str(blob.download_as_string()) 232 | 233 | blob_content_splited = blob_content.split(":", 2) 234 | decoded_data_encryption_key = base64.b64decode(blob_content_splited[0]) 235 | decoded_data = base64.b64decode(blob_content_splited[1]) 236 | 237 | # Decrypt the encoded Data Encryption Key (DEK) 238 | # Initialize request argument(s) 239 | request = kms_v1.DecryptRequest( 240 | name=crypto_key_path, 241 | ciphertext=decoded_data_encryption_key, 242 | additional_authenticated_data=str2b(object_name) 243 | ) 244 | 245 | kms_resp = kms_client.decrypt(request=request) 246 | data_encryption_key = kms_resp.plaintext 247 | 248 | return _envelope_decrypt(data_encryption_key, decoded_data) 249 | 250 | 251 | def Encrypt(project_id: str, env_var_value: str, plaintext: str, 252 | location: str = LOCATION, key_ring: str = KEY_RING, crypto_key: str = CRYPTO_KEY): 253 | """ 254 | Get the plain text string [plaintext], encrypt it and store it into the bucket [env_var_value] 255 | 256 | :param project_id: Project ID for creating the storage client. 257 | :param env_var_value: Berglas reference with the pattern berglas:/// 258 | :param plaintext: String to be encrypted and stored 259 | :param location: Keyring location. Default: global 260 | :param key_ring: KMS keyring name to be used to encrypt your secrets 261 | :param crypto_key: Cryptographic key name to be used to encrypt your secrets 262 | :exception: When the project_id is missing/empty 263 | :exception: When object_name and/or bucket is missing (pattern not respected) 264 | """ 265 | 266 | # It's a flag to ensure the IAM policy for the blob object will be updated only 267 | # if the file exists. 268 | blob_iam_policy = None 269 | 270 | _validate_env_var_prefix(env_var_value) 271 | 272 | _validate_project_id(project_id) 273 | 274 | 275 | bucket_name, object_name = _get_bucket_object(env_var_value) 276 | 277 | gcs_client = storage.Client(project=project_id) 278 | kms_client = kms_v1.KeyManagementServiceClient() 279 | 280 | data_encryption_key, ciphertext = _envelope_encrypt(str2b(plaintext)) 281 | 282 | crypto_key_path = kms_client.crypto_key_path_path(project_id, location, key_ring, crypto_key) 283 | 284 | kms_resp = kms_client.encrypt(crypto_key_path, data_encryption_key, 285 | additional_authenticated_data=str2b(object_name)) 286 | 287 | bucket = gcs_client.get_bucket(bucket_name) 288 | 289 | metadata = { 290 | METADATA_KMS_KEY: crypto_key_path, 291 | METADATA_ID_KEY: 1 292 | } 293 | 294 | encoded_data_encryption_key = b2str(base64.b64encode(kms_resp.ciphertext)) 295 | encoded_ciphertext = b2str(base64.b64encode(ciphertext)) 296 | 297 | blob_content = f'{encoded_data_encryption_key}:{encoded_ciphertext}' 298 | 299 | blob = bucket.blob(object_name) 300 | 301 | # If the object doesn't exist we don't need to copy the IAM policy 302 | if blob.exists(): 303 | blob_iam_policy = copy_blob_iam_policy(blob) 304 | 305 | blob.upload_from_string(str2b(blob_content)) 306 | 307 | # If the object doesn't exist we don't need to copy the IAM policy 308 | if blob_iam_policy is not None: 309 | blob.set_iam_policy(blob_iam_policy) 310 | 311 | blob.chunk_size = BLOB_CHUNK_SIZE 312 | blob.content_type = METADATA_CONTENT_TYPE 313 | blob.cache_control = METADATA_CACHE_CONTROL 314 | blob.metadata = metadata 315 | blob.update() 316 | 317 | -------------------------------------------------------------------------------- /examples/api_example.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import berglas_python as berglas 4 | 5 | project_id = os.environ.get("MY-PROJECT") 6 | 7 | # This higher-level API parses the secret reference at the specified 8 | # environment variable, downloads and decrypts the secret, and replaces the 9 | # contents of the given environment variable with the secret result. 10 | 11 | berglas.Replace(project_id, "MY-SECRET") 12 | 13 | # This lower-level API parses the secret reference, downloads and decrypts 14 | # the secret, and returns the result. This is useful if you need to mutate 15 | # the result. 16 | my_secret = os.environ.get("MY-SECRET") 17 | plaintext = berglas.Resolve(project_id, my_secret) 18 | os.environ.unsetenv("MY-SECRET") 19 | os.environ.setdefault("MY-SECRET", plaintext) 20 | 21 | 22 | # This is lower-level API encrypts the plaintext string and uploads the blob 23 | berglas.Encrypt(project_id, 'MY-BUCKET/MY-SECRET-FILE', 'STRING-TO-ENCRYPT') 24 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | google-cloud-storage~=1.30.0 2 | google-cloud-kms~=1.4.0 3 | cryptography~=3.0 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import find_packages, setup 2 | 3 | REQUIREMENTS = open("requirements.txt").read().splitlines() 4 | 5 | setup(name='berglas_python', 6 | version='0.3.4', 7 | url='https://github.com/guillaumeblaquiere/berglas-python', 8 | license='Apache 2.0', 9 | author='Guillaume Blaquiere', 10 | author_email='guillaume.blaquiere@gmail.com', 11 | description='Decipher the Berglas keys', 12 | packages=find_packages(exclude=['tests','examples']), 13 | long_description=open("README.md", "r").read(), 14 | long_description_content_type="text/markdown", 15 | install_requires=REQUIREMENTS, 16 | py_modules=["berglas_python"], 17 | zip_safe=False, 18 | classifiers=[ 19 | "Programming Language :: Python :: 3", 20 | "License :: OSI Approved :: Apache Software License", 21 | "Operating System :: OS Independent", ], 22 | ) 23 | --------------------------------------------------------------------------------