swarmauri_mre_crypto_keyring 0.3.0.dev3__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.
@@ -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 [2025] [Jacob Stewart @ Swarmauri]
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,84 @@
1
+ Metadata-Version: 2.3
2
+ Name: swarmauri_mre_crypto_keyring
3
+ Version: 0.3.0.dev3
4
+ Summary: Keyring-backed multi-recipient encryption provider for Swarmauri
5
+ License: Apache-2.0
6
+ Author: Swarmauri
7
+ Author-email: opensource@swarmauri.com
8
+ Requires-Python: >=3.10,<3.13
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Natural Language :: English
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Development Status :: 3 - Alpha
16
+ Classifier: Topic :: Security :: Cryptography
17
+ Classifier: Intended Audience :: Developers
18
+ Provides-Extra: cbor
19
+ Requires-Dist: cbor2 (>=5.4.6) ; extra == "cbor"
20
+ Requires-Dist: cryptography (>=41)
21
+ Requires-Dist: swarmauri_base
22
+ Requires-Dist: swarmauri_core
23
+ Description-Content-Type: text/markdown
24
+
25
+ ![Swamauri Logo](https://res.cloudinary.com/dbjmpekvl/image/upload/v1730099724/Swarmauri-logo-lockup-2048x757_hww01w.png)
26
+
27
+ # Swarmauri MRE Crypto Keyring
28
+
29
+ Multi-recipient encryption provider using external keyrings/HSMs.
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ pip install swarmauri_mre_crypto_keyring
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ `KeyringMreCrypto` delegates CEK (content-encryption key) management to
40
+ user-provided keyring clients. Each client must implement `id`,
41
+ `wrap_cek`, and `unwrap_cek`. The example below shows how to register an
42
+ in-memory keyring and use it to encrypt and decrypt a payload.
43
+
44
+ ```python
45
+ import asyncio
46
+ import secrets
47
+ from swarmauri_mre_crypto_keyring import KeyringMreCrypto
48
+
49
+
50
+ class MemoryKeyring:
51
+ def __init__(self):
52
+ self._store = {}
53
+
54
+ def id(self) -> str:
55
+ return "memory"
56
+
57
+ async def wrap_cek(self, cek: bytes, *, context):
58
+ token = secrets.token_bytes(8)
59
+ self._store[token] = cek
60
+ return token
61
+
62
+ async def unwrap_cek(self, header: bytes, *, context):
63
+ return self._store[header]
64
+
65
+
66
+ async def main():
67
+ keyring = MemoryKeyring()
68
+ keyref = {"kind": "keyring_client", "client": keyring}
69
+ crypto = KeyringMreCrypto()
70
+ env = await crypto.encrypt_for_many([keyref], b"sensitive data")
71
+ recovered = await crypto.open_for(keyref, env)
72
+ assert recovered == b"sensitive data"
73
+
74
+
75
+ asyncio.run(main())
76
+ ```
77
+
78
+ The snippet encrypts `b"sensitive data"` for the memory keyring and
79
+ recovers the original plaintext using the same keyring client.
80
+
81
+ ## Want to help?
82
+
83
+ If you want to contribute to swarmauri-sdk, read up on our [guidelines for contributing](https://github.com/swarmauri/swarmauri-sdk/blob/master/contributing.md) that will help you get started.
84
+
@@ -0,0 +1,59 @@
1
+ ![Swamauri Logo](https://res.cloudinary.com/dbjmpekvl/image/upload/v1730099724/Swarmauri-logo-lockup-2048x757_hww01w.png)
2
+
3
+ # Swarmauri MRE Crypto Keyring
4
+
5
+ Multi-recipient encryption provider using external keyrings/HSMs.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install swarmauri_mre_crypto_keyring
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ `KeyringMreCrypto` delegates CEK (content-encryption key) management to
16
+ user-provided keyring clients. Each client must implement `id`,
17
+ `wrap_cek`, and `unwrap_cek`. The example below shows how to register an
18
+ in-memory keyring and use it to encrypt and decrypt a payload.
19
+
20
+ ```python
21
+ import asyncio
22
+ import secrets
23
+ from swarmauri_mre_crypto_keyring import KeyringMreCrypto
24
+
25
+
26
+ class MemoryKeyring:
27
+ def __init__(self):
28
+ self._store = {}
29
+
30
+ def id(self) -> str:
31
+ return "memory"
32
+
33
+ async def wrap_cek(self, cek: bytes, *, context):
34
+ token = secrets.token_bytes(8)
35
+ self._store[token] = cek
36
+ return token
37
+
38
+ async def unwrap_cek(self, header: bytes, *, context):
39
+ return self._store[header]
40
+
41
+
42
+ async def main():
43
+ keyring = MemoryKeyring()
44
+ keyref = {"kind": "keyring_client", "client": keyring}
45
+ crypto = KeyringMreCrypto()
46
+ env = await crypto.encrypt_for_many([keyref], b"sensitive data")
47
+ recovered = await crypto.open_for(keyref, env)
48
+ assert recovered == b"sensitive data"
49
+
50
+
51
+ asyncio.run(main())
52
+ ```
53
+
54
+ The snippet encrypts `b"sensitive data"` for the memory keyring and
55
+ recovers the original plaintext using the same keyring client.
56
+
57
+ ## Want to help?
58
+
59
+ If you want to contribute to swarmauri-sdk, read up on our [guidelines for contributing](https://github.com/swarmauri/swarmauri-sdk/blob/master/contributing.md) that will help you get started.
@@ -0,0 +1,70 @@
1
+ [project]
2
+ name = "swarmauri_mre_crypto_keyring"
3
+ version = "0.3.0.dev3"
4
+ description = "Keyring-backed multi-recipient encryption provider for Swarmauri"
5
+ license = "Apache-2.0"
6
+ readme = "README.md"
7
+ requires-python = ">=3.10,<3.13"
8
+ authors = [{ name = "Swarmauri", email = "opensource@swarmauri.com" }]
9
+ classifiers = [
10
+ "License :: OSI Approved :: Apache Software License",
11
+ "Natural Language :: English",
12
+ "Programming Language :: Python :: 3.10",
13
+ "Programming Language :: Python :: 3.11",
14
+ "Programming Language :: Python :: 3.12",
15
+ "Programming Language :: Python :: 3.13",
16
+ "Development Status :: 3 - Alpha",
17
+ "Topic :: Security :: Cryptography",
18
+ "Intended Audience :: Developers",
19
+ ]
20
+ dependencies = [
21
+ "swarmauri_core",
22
+ "swarmauri_base",
23
+ "cryptography>=41",
24
+ ]
25
+
26
+ [project.optional-dependencies]
27
+ cbor = ["cbor2>=5.4.6"]
28
+
29
+ [tool.uv.sources]
30
+ swarmauri_core = { workspace = true }
31
+ swarmauri_base = { workspace = true }
32
+
33
+ [tool.pytest.ini_options]
34
+ norecursedirs = ["combined", "scripts"]
35
+ markers = [
36
+ "test: standard test",
37
+ "unit: Unit tests",
38
+ "i9n: Integration tests",
39
+ "r8n: Regression tests",
40
+ "acceptance: Acceptance tests",
41
+ "functional: Functional tests",
42
+ "perf: Performance tests",
43
+ "example: Example usage tests",
44
+ ]
45
+ timeout = 300
46
+ log_cli = true
47
+ log_cli_level = "INFO"
48
+ log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
49
+ log_cli_date_format = "%Y-%m-%d %H:%M:%S"
50
+ asyncio_default_fixture_loop_scope = "function"
51
+
52
+ [build-system]
53
+ requires = ["poetry-core>=1.0.0"]
54
+ build-backend = "poetry.core.masonry.api"
55
+
56
+ [dependency-groups]
57
+ dev = [
58
+ "pytest>=8.0",
59
+ "pytest-asyncio>=0.24.0",
60
+ "pytest-xdist>=3.6.1",
61
+ "pytest-json-report>=1.5.0",
62
+ "python-dotenv",
63
+ "flake8>=7.0",
64
+ "ruff>=0.9.9",
65
+ "pytest-timeout>=2.3.1",
66
+ "pytest-benchmark>=4.0.0",
67
+ ]
68
+
69
+ [project.entry-points.'swarmauri.mre_cryptos']
70
+ KeyringMreCrypto = "swarmauri_mre_crypto_keyring:KeyringMreCrypto"
@@ -0,0 +1,415 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import secrets
5
+ from typing import (
6
+ Any,
7
+ Dict,
8
+ Iterable,
9
+ Mapping,
10
+ Optional,
11
+ Sequence,
12
+ Tuple,
13
+ Protocol,
14
+ runtime_checkable,
15
+ Literal,
16
+ )
17
+
18
+ from swarmauri_core.mre_crypto.types import MultiRecipientEnvelope, RecipientId, MreMode
19
+ from swarmauri_core.crypto.types import Alg, KeyRef
20
+ from swarmauri_base.mre_crypto import MreCryptoBase
21
+
22
+ try: # pragma: no cover - handled in runtime
23
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM, XChaCha20Poly1305
24
+
25
+ _CRYPTO_OK = True
26
+ _XCHACHA_OK = True
27
+ except Exception: # pragma: no cover
28
+ try:
29
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM # type: ignore
30
+
31
+ _CRYPTO_OK = True
32
+ _XCHACHA_OK = False
33
+ except Exception:
34
+ _CRYPTO_OK = False
35
+ _XCHACHA_OK = False
36
+
37
+
38
+ VALID_AEAD_ALGS = (
39
+ ("AES-256-GCM", "XCHACHA20-POLY1305") if _XCHACHA_OK else ("AES-256-GCM",)
40
+ )
41
+
42
+
43
+ @runtime_checkable
44
+ class KeyringClient(Protocol):
45
+ """Minimal protocol an external KMS/HSM 'keyring' client must implement."""
46
+
47
+ def id(self) -> str:
48
+ """Stable identifier for this keyring."""
49
+
50
+ async def wrap_cek(self, cek: bytes, *, context: Mapping[str, bytes]) -> bytes:
51
+ """Return an opaque header which lets this keyring later release the same CEK."""
52
+
53
+ async def unwrap_cek(self, header: bytes, *, context: Mapping[str, bytes]) -> bytes:
54
+ """Return the CEK if the caller is authorized and policy is satisfied."""
55
+
56
+
57
+ class _AEAD:
58
+ @staticmethod
59
+ def encrypt_with_key(
60
+ cek: bytes, pt: bytes, *, alg: str, aad: Optional[bytes]
61
+ ) -> Tuple[bytes, bytes]:
62
+ if not _CRYPTO_OK:
63
+ raise RuntimeError(
64
+ "KeyringMreCrypto requires 'cryptography' package. Install with: pip install cryptography"
65
+ )
66
+ if alg == "AES-256-GCM":
67
+ if len(cek) not in (16, 24, 32):
68
+ raise ValueError(
69
+ "AES-GCM expects 128/192/256-bit key (16/24/32 bytes)."
70
+ )
71
+ nonce = secrets.token_bytes(12)
72
+ ct = AESGCM(cek).encrypt(nonce, pt, aad)
73
+ return nonce, ct
74
+ if alg == "XCHACHA20-POLY1305":
75
+ if not _XCHACHA_OK:
76
+ raise ValueError(
77
+ "XChaCha20-Poly1305 not supported in this environment."
78
+ )
79
+ if len(cek) != 32:
80
+ raise ValueError("XChaCha20-Poly1305 expects 256-bit key (32 bytes).")
81
+ nonce = secrets.token_bytes(24)
82
+ ct = XChaCha20Poly1305(cek).encrypt(nonce, pt, aad)
83
+ return nonce, ct
84
+ raise ValueError(f"Unsupported payload AEAD alg: {alg}")
85
+
86
+ @staticmethod
87
+ def decrypt_with_key(
88
+ cek: bytes, nonce: bytes, ct: bytes, *, alg: str, aad: Optional[bytes]
89
+ ) -> bytes:
90
+ if not _CRYPTO_OK:
91
+ raise RuntimeError(
92
+ "KeyringMreCrypto requires 'cryptography' package. Install with: pip install cryptography"
93
+ )
94
+
95
+ if alg == "AES-256-GCM":
96
+ return AESGCM(cek).decrypt(nonce, ct, aad)
97
+
98
+ if alg == "XCHACHA20-POLY1305":
99
+ if not _XCHACHA_OK:
100
+ raise ValueError(
101
+ "XChaCha20-Poly1305 not supported in this environment."
102
+ )
103
+ return XChaCha20Poly1305(cek).decrypt(nonce, ct, aad)
104
+
105
+ raise ValueError(f"Unsupported payload AEAD alg: {alg}")
106
+
107
+
108
+ class KeyringMreCrypto(MreCryptoBase):
109
+ """MRE provider using multiple independent keyrings/HSMs."""
110
+
111
+ type: Literal["KeyringMreCrypto"] = "KeyringMreCrypto"
112
+
113
+ def __init__(self, **data: Any) -> None:
114
+ if not _CRYPTO_OK:
115
+ raise RuntimeError(
116
+ "KeyringMreCrypto requires 'cryptography' package. Install with: pip install cryptography"
117
+ )
118
+ super().__init__(**data)
119
+
120
+ def supports(self) -> Dict[str, Iterable[str | MreMode]]:
121
+ return {
122
+ "payload": VALID_AEAD_ALGS,
123
+ "recipient": ("KEYRING",),
124
+ "modes": (MreMode.SEALED_CEK_AEAD,),
125
+ "features": ("aad", "rewrap_without_reencrypt"),
126
+ }
127
+
128
+ async def encrypt_for_many(
129
+ self,
130
+ recipients: Sequence[KeyRef],
131
+ pt: bytes,
132
+ *,
133
+ payload_alg: Optional[Alg] = None,
134
+ recipient_alg: Optional[Alg] = None,
135
+ mode: Optional[MreMode | str] = None,
136
+ aad: Optional[bytes] = None,
137
+ shared: Optional[Mapping[str, bytes]] = None,
138
+ opts: Optional[Mapping[str, object]] = None,
139
+ ) -> MultiRecipientEnvelope:
140
+ if not recipients:
141
+ raise ValueError("encrypt_for_many: 'recipients' must be non-empty.")
142
+
143
+ mode = MreMode(mode or MreMode.SEALED_CEK_AEAD)
144
+ if mode is not MreMode.SEALED_CEK_AEAD:
145
+ raise ValueError(f"Unsupported mode for KeyringMreCrypto: {mode}")
146
+
147
+ recipient_alg = recipient_alg or "KEYRING"
148
+ if recipient_alg != "KEYRING":
149
+ raise ValueError("KeyringMreCrypto only supports recipient_alg='KEYRING'.")
150
+
151
+ payload_alg = payload_alg or "AES-256-GCM"
152
+ if payload_alg not in VALID_AEAD_ALGS:
153
+ raise ValueError(f"Unsupported payload AEAD alg: {payload_alg}")
154
+
155
+ quorum_k = int((opts or {}).get("quorum_k", len(recipients)))
156
+ if not (1 <= quorum_k <= len(recipients)):
157
+ raise ValueError("opts['quorum_k'] must satisfy 1 <= k <= len(recipients).")
158
+
159
+ cek_len = 32
160
+ cek = secrets.token_bytes(cek_len)
161
+ nonce, ct = _AEAD.encrypt_with_key(cek, pt, alg=payload_alg, aad=aad)
162
+
163
+ recipient_entries: list[dict[str, Any]] = []
164
+ for keyref in recipients:
165
+ client, r_context = self._extract_keyring_client(keyref)
166
+ header = await client.wrap_cek(
167
+ cek, context=self._default_context(shared).update_copy(r_context)
168
+ )
169
+ rid = self._stable_id(client)
170
+ recipient_entries.append({"id": rid, "header": header})
171
+
172
+ return {
173
+ "mode": str(MreMode.SEALED_CEK_AEAD),
174
+ "recipient_alg": "KEYRING",
175
+ "payload": {
176
+ "kind": "aead",
177
+ "alg": payload_alg,
178
+ "nonce": nonce,
179
+ "ct": ct,
180
+ "aad": aad,
181
+ },
182
+ "recipients": recipient_entries,
183
+ "shared": dict(shared or {}),
184
+ "meta": {"quorum_k": quorum_k, "recipients_m": len(recipient_entries)},
185
+ }
186
+
187
+ async def open_for_many(
188
+ self,
189
+ my_identities: Sequence[KeyRef],
190
+ env: MultiRecipientEnvelope,
191
+ *,
192
+ aad: Optional[bytes] = None,
193
+ opts: Optional[Mapping[str, object]] = None,
194
+ ) -> bytes:
195
+ if not my_identities:
196
+ raise ValueError("open_for_many: 'my_identities' must be non-empty.")
197
+
198
+ self._assert_env_shape(env)
199
+ meta = env.get("meta", {}) or {}
200
+ quorum_k = int(meta.get("quorum_k", 1))
201
+ recips = env["recipients"]
202
+ if quorum_k < 1:
203
+ raise ValueError("Envelope meta.quorum_k must be >= 1.")
204
+
205
+ headers_by_id: Dict[str, bytes] = {r["id"]: r["header"] for r in recips}
206
+ shared: Mapping[str, bytes] = env.get("shared") or {}
207
+ recovered: Dict[bytes, int] = {}
208
+ payload = env["payload"]
209
+ payload_alg = payload["alg"]
210
+ payload_nonce = payload["nonce"]
211
+ payload_ct = payload["ct"]
212
+ aad_env = payload.get("aad", None)
213
+ aad_to_check = aad if aad is not None else aad_env
214
+ if aad_to_check != aad_env:
215
+ raise ValueError("AAD mismatch for AEAD mode.")
216
+
217
+ for keyref in my_identities:
218
+ client, id_context = self._extract_keyring_client(keyref)
219
+ rid = self._stable_id(client)
220
+ try_ids: Sequence[str] = (
221
+ [rid] if rid in headers_by_id else list(headers_by_id.keys())
222
+ )
223
+
224
+ for hdr_id in try_ids:
225
+ header = headers_by_id[hdr_id]
226
+ try:
227
+ cek = await client.unwrap_cek(
228
+ header,
229
+ context=self._default_context(shared).update_copy(id_context),
230
+ )
231
+ recovered[cek] = recovered.get(cek, 0) + 1
232
+ if recovered[cek] >= quorum_k:
233
+ return _AEAD.decrypt_with_key(
234
+ cek,
235
+ payload_nonce,
236
+ payload_ct,
237
+ alg=payload_alg,
238
+ aad=aad_to_check,
239
+ )
240
+ except Exception:
241
+ continue
242
+
243
+ raise PermissionError(f"Unable to satisfy CEK quorum (required {quorum_k}).")
244
+
245
+ async def open_for(
246
+ self,
247
+ my_identity: KeyRef,
248
+ env: MultiRecipientEnvelope,
249
+ *,
250
+ aad: Optional[bytes] = None,
251
+ opts: Optional[Mapping[str, object]] = None,
252
+ ) -> bytes:
253
+ return await self.open_for_many([my_identity], env, aad=aad, opts=opts)
254
+
255
+ async def rewrap(
256
+ self,
257
+ env: MultiRecipientEnvelope,
258
+ *,
259
+ add: Optional[Sequence[KeyRef]] = None,
260
+ remove: Optional[Sequence[RecipientId]] = None,
261
+ recipient_alg: Optional[Alg] = None,
262
+ opts: Optional[Mapping[str, object]] = None,
263
+ ) -> MultiRecipientEnvelope:
264
+ self._assert_env_shape(env)
265
+ if recipient_alg not in (None, "KEYRING"):
266
+ raise ValueError("KeyringMreCrypto only supports recipient_alg='KEYRING'.")
267
+
268
+ add = add or []
269
+ remove = remove or []
270
+ shared: Mapping[str, bytes] = env.get("shared") or {}
271
+
272
+ rotate_on_revoke = bool((opts or {}).get("rotate_payload_on_revoke", False))
273
+
274
+ if remove or rotate_on_revoke:
275
+ identities = (opts or {}).get("identities", None)
276
+ if not isinstance(identities, (list, tuple)) or not identities:
277
+ raise ValueError(
278
+ "rewrap with removal/rotation requires opts['identities']: Sequence[KeyRef] able to meet quorum."
279
+ )
280
+ cek = await self._recover_cek_for_env(env, identities, shared)
281
+ else:
282
+ cek = await self._recover_cek_if_present(env, shared, opts)
283
+
284
+ if remove:
285
+ kept = [r for r in env["recipients"] if r["id"] not in set(remove)]
286
+ else:
287
+ kept = list(env["recipients"])
288
+
289
+ if rotate_on_revoke:
290
+ payload = env["payload"]
291
+ payload_alg = payload["alg"]
292
+ pt = _AEAD.decrypt_with_key(
293
+ cek,
294
+ payload["nonce"],
295
+ payload["ct"],
296
+ alg=payload_alg,
297
+ aad=payload.get("aad"),
298
+ )
299
+ new_cek = secrets.token_bytes(len(cek))
300
+ new_nonce, new_ct = _AEAD.encrypt_with_key(
301
+ new_cek, pt, alg=payload_alg, aad=payload.get("aad")
302
+ )
303
+ env["payload"]["nonce"] = new_nonce
304
+ env["payload"]["ct"] = new_ct
305
+ cek = new_cek
306
+ meta = dict(env.get("meta") or {})
307
+ meta["rotated_at"] = meta.get("rotated_at", 0) + 1
308
+ env["meta"] = meta
309
+
310
+ for keyref in add:
311
+ client, a_context = self._extract_keyring_client(keyref)
312
+ header = await client.wrap_cek(
313
+ cek, context=self._default_context(shared).update_copy(a_context)
314
+ )
315
+ rid = self._stable_id(client)
316
+ kept.append({"id": rid, "header": header})
317
+
318
+ env["recipients"] = kept
319
+ return env
320
+
321
+ async def _recover_cek_if_present(
322
+ self,
323
+ env: MultiRecipientEnvelope,
324
+ shared: Mapping[str, bytes],
325
+ opts: Optional[Mapping[str, object]],
326
+ ) -> bytes:
327
+ identities = (opts or {}).get("identities")
328
+ if not identities:
329
+ raise RuntimeError(
330
+ "CEK recovery requested but no opts['identities'] provided."
331
+ )
332
+ return await self._recover_cek_for_env(env, identities, shared)
333
+
334
+ async def _recover_cek_for_env(
335
+ self,
336
+ env: MultiRecipientEnvelope,
337
+ identities: Sequence[KeyRef],
338
+ shared: Mapping[str, bytes],
339
+ ) -> bytes:
340
+ meta = env.get("meta", {}) or {}
341
+ quorum_k = int(meta.get("quorum_k", 1))
342
+ recipients = env["recipients"]
343
+ headers_by_id: Dict[str, bytes] = {r["id"]: r["header"] for r in recipients}
344
+ recovered: Dict[bytes, int] = {}
345
+
346
+ for keyref in identities:
347
+ client, id_context = self._extract_keyring_client(keyref)
348
+ rid = self._stable_id(client)
349
+ try_ids: Sequence[str] = (
350
+ [rid] if rid in headers_by_id else list(headers_by_id.keys())
351
+ )
352
+ for hdr_id in try_ids:
353
+ header = headers_by_id[hdr_id]
354
+ try:
355
+ cek = await client.unwrap_cek(
356
+ header,
357
+ context=self._default_context(shared).update_copy(id_context),
358
+ )
359
+ recovered[cek] = recovered.get(cek, 0) + 1
360
+ if recovered[cek] >= quorum_k:
361
+ return cek
362
+ except Exception:
363
+ continue
364
+
365
+ raise PermissionError(
366
+ f"Unable to satisfy CEK quorum (required {quorum_k}) for CEK recovery."
367
+ )
368
+
369
+ def _assert_env_shape(self, env: Mapping[str, Any]) -> None:
370
+ if env.get("mode") != str(MreMode.SEALED_CEK_AEAD):
371
+ raise ValueError(
372
+ "Envelope mode must be 'sealed_cek+aead' for KeyringMreCrypto."
373
+ )
374
+ payload = env.get("payload")
375
+ if not isinstance(payload, Mapping) or payload.get("kind") != "aead":
376
+ raise ValueError("Envelope payload must be an AEAD payload.")
377
+ if payload.get("alg") not in VALID_AEAD_ALGS:
378
+ raise ValueError("Unsupported payload AEAD in envelope.")
379
+ if not isinstance(env.get("recipients"), list):
380
+ raise ValueError("Envelope missing 'recipients' list.")
381
+
382
+ def _extract_keyring_client(
383
+ self, keyref: KeyRef
384
+ ) -> Tuple[KeyringClient, Dict[str, bytes]]:
385
+ if isinstance(keyref, dict) and keyref.get("kind") == "keyring_client":
386
+ client = keyref.get("client")
387
+ context = keyref.get("context") or {}
388
+ if not isinstance(context, dict) or not all(
389
+ isinstance(k, str) and isinstance(v, (bytes, bytearray))
390
+ for k, v in context.items()
391
+ ):
392
+ raise TypeError("KeyRef['context'] must be a dict[str, bytes].")
393
+ if isinstance(client, KeyringClient) or (
394
+ isinstance(client, object)
395
+ and hasattr(client, "wrap_cek")
396
+ and hasattr(client, "unwrap_cek")
397
+ and hasattr(client, "id")
398
+ ):
399
+ return client, dict(context)
400
+ raise TypeError(
401
+ "KeyRef must be {'kind':'keyring_client','client':KeyringClient,'context'?:{str:bytes}}."
402
+ )
403
+
404
+ def _stable_id(self, client: KeyringClient) -> str:
405
+ raw = client.id().encode("utf-8")
406
+ return hashlib.sha256(raw).hexdigest()
407
+
408
+ class _Ctx(dict):
409
+ def update_copy(self, extras: Mapping[str, bytes]) -> "KeyringMreCrypto._Ctx":
410
+ d = KeyringMreCrypto._Ctx(self)
411
+ d.update(extras)
412
+ return d
413
+
414
+ def _default_context(self, shared: Mapping[str, bytes]) -> "KeyringMreCrypto._Ctx":
415
+ return KeyringMreCrypto._Ctx(shared or {})
@@ -0,0 +1,3 @@
1
+ from .KeyringMreCrypto import KeyringMreCrypto
2
+
3
+ __all__ = ["KeyringMreCrypto"]