otdf-python 0.1.10__py3-none-any.whl → 0.3.5__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.
Files changed (144) hide show
  1. otdf_python/__init__.py +25 -0
  2. otdf_python/__main__.py +12 -0
  3. otdf_python/address_normalizer.py +84 -0
  4. otdf_python/aesgcm.py +55 -0
  5. otdf_python/assertion_config.py +84 -0
  6. otdf_python/asym_crypto.py +198 -0
  7. otdf_python/auth_headers.py +33 -0
  8. otdf_python/autoconfigure_utils.py +113 -0
  9. otdf_python/cli.py +569 -0
  10. otdf_python/collection_store.py +41 -0
  11. otdf_python/collection_store_impl.py +22 -0
  12. otdf_python/config.py +69 -0
  13. otdf_python/connect_client.py +0 -0
  14. otdf_python/constants.py +1 -0
  15. otdf_python/crypto_utils.py +78 -0
  16. otdf_python/dpop.py +81 -0
  17. otdf_python/ecc_constants.py +176 -0
  18. otdf_python/ecc_mode.py +83 -0
  19. otdf_python/ecdh.py +317 -0
  20. otdf_python/eckeypair.py +75 -0
  21. otdf_python/header.py +181 -0
  22. otdf_python/invalid_zip_exception.py +8 -0
  23. otdf_python/kas_client.py +709 -0
  24. otdf_python/kas_connect_rpc_client.py +213 -0
  25. otdf_python/kas_info.py +25 -0
  26. otdf_python/kas_key_cache.py +52 -0
  27. otdf_python/key_type.py +31 -0
  28. otdf_python/key_type_constants.py +43 -0
  29. otdf_python/manifest.py +215 -0
  30. otdf_python/nanotdf.py +863 -0
  31. otdf_python/nanotdf_ecdsa_struct.py +132 -0
  32. otdf_python/nanotdf_type.py +43 -0
  33. otdf_python/policy_binding_serializer.py +39 -0
  34. otdf_python/policy_info.py +55 -0
  35. otdf_python/policy_object.py +22 -0
  36. otdf_python/policy_stub.py +2 -0
  37. otdf_python/resource_locator.py +172 -0
  38. otdf_python/sdk.py +436 -0
  39. otdf_python/sdk_builder.py +416 -0
  40. otdf_python/sdk_exceptions.py +16 -0
  41. otdf_python/symmetric_and_payload_config.py +30 -0
  42. otdf_python/tdf.py +480 -0
  43. otdf_python/tdf_reader.py +153 -0
  44. otdf_python/tdf_writer.py +23 -0
  45. otdf_python/token_source.py +34 -0
  46. otdf_python/version.py +57 -0
  47. otdf_python/zip_reader.py +47 -0
  48. otdf_python/zip_writer.py +70 -0
  49. otdf_python-0.3.5.dist-info/METADATA +153 -0
  50. otdf_python-0.3.5.dist-info/RECORD +137 -0
  51. {otdf_python-0.1.10.dist-info → otdf_python-0.3.5.dist-info}/WHEEL +1 -2
  52. {otdf_python-0.1.10.dist-info → otdf_python-0.3.5.dist-info/licenses}/LICENSE +1 -1
  53. otdf_python_proto/__init__.py +37 -0
  54. otdf_python_proto/authorization/__init__.py +1 -0
  55. otdf_python_proto/authorization/authorization_pb2.py +80 -0
  56. otdf_python_proto/authorization/authorization_pb2.pyi +161 -0
  57. otdf_python_proto/authorization/authorization_pb2_connect.py +191 -0
  58. otdf_python_proto/authorization/v2/authorization_pb2.py +105 -0
  59. otdf_python_proto/authorization/v2/authorization_pb2.pyi +134 -0
  60. otdf_python_proto/authorization/v2/authorization_pb2_connect.py +233 -0
  61. otdf_python_proto/common/__init__.py +1 -0
  62. otdf_python_proto/common/common_pb2.py +52 -0
  63. otdf_python_proto/common/common_pb2.pyi +61 -0
  64. otdf_python_proto/entity/__init__.py +1 -0
  65. otdf_python_proto/entity/entity_pb2.py +47 -0
  66. otdf_python_proto/entity/entity_pb2.pyi +50 -0
  67. otdf_python_proto/entityresolution/__init__.py +1 -0
  68. otdf_python_proto/entityresolution/entity_resolution_pb2.py +57 -0
  69. otdf_python_proto/entityresolution/entity_resolution_pb2.pyi +55 -0
  70. otdf_python_proto/entityresolution/entity_resolution_pb2_connect.py +149 -0
  71. otdf_python_proto/entityresolution/v2/entity_resolution_pb2.py +55 -0
  72. otdf_python_proto/entityresolution/v2/entity_resolution_pb2.pyi +55 -0
  73. otdf_python_proto/entityresolution/v2/entity_resolution_pb2_connect.py +149 -0
  74. otdf_python_proto/kas/__init__.py +9 -0
  75. otdf_python_proto/kas/kas_pb2.py +103 -0
  76. otdf_python_proto/kas/kas_pb2.pyi +170 -0
  77. otdf_python_proto/kas/kas_pb2_connect.py +192 -0
  78. otdf_python_proto/legacy_grpc/__init__.py +1 -0
  79. otdf_python_proto/legacy_grpc/authorization/authorization_pb2_grpc.py +163 -0
  80. otdf_python_proto/legacy_grpc/authorization/v2/authorization_pb2_grpc.py +206 -0
  81. otdf_python_proto/legacy_grpc/common/common_pb2_grpc.py +4 -0
  82. otdf_python_proto/legacy_grpc/entity/entity_pb2_grpc.py +4 -0
  83. otdf_python_proto/legacy_grpc/entityresolution/entity_resolution_pb2_grpc.py +122 -0
  84. otdf_python_proto/legacy_grpc/entityresolution/v2/entity_resolution_pb2_grpc.py +120 -0
  85. otdf_python_proto/legacy_grpc/kas/kas_pb2_grpc.py +172 -0
  86. otdf_python_proto/legacy_grpc/logger/audit/test_pb2_grpc.py +4 -0
  87. otdf_python_proto/legacy_grpc/policy/actions/actions_pb2_grpc.py +249 -0
  88. otdf_python_proto/legacy_grpc/policy/attributes/attributes_pb2_grpc.py +873 -0
  89. otdf_python_proto/legacy_grpc/policy/kasregistry/key_access_server_registry_pb2_grpc.py +602 -0
  90. otdf_python_proto/legacy_grpc/policy/keymanagement/key_management_pb2_grpc.py +251 -0
  91. otdf_python_proto/legacy_grpc/policy/namespaces/namespaces_pb2_grpc.py +427 -0
  92. otdf_python_proto/legacy_grpc/policy/objects_pb2_grpc.py +4 -0
  93. otdf_python_proto/legacy_grpc/policy/registeredresources/registered_resources_pb2_grpc.py +524 -0
  94. otdf_python_proto/legacy_grpc/policy/resourcemapping/resource_mapping_pb2_grpc.py +516 -0
  95. otdf_python_proto/legacy_grpc/policy/selectors_pb2_grpc.py +4 -0
  96. otdf_python_proto/legacy_grpc/policy/subjectmapping/subject_mapping_pb2_grpc.py +551 -0
  97. otdf_python_proto/legacy_grpc/policy/unsafe/unsafe_pb2_grpc.py +485 -0
  98. otdf_python_proto/legacy_grpc/wellknownconfiguration/wellknown_configuration_pb2_grpc.py +77 -0
  99. otdf_python_proto/logger/__init__.py +1 -0
  100. otdf_python_proto/logger/audit/test_pb2.py +43 -0
  101. otdf_python_proto/logger/audit/test_pb2.pyi +45 -0
  102. otdf_python_proto/policy/__init__.py +1 -0
  103. otdf_python_proto/policy/actions/actions_pb2.py +75 -0
  104. otdf_python_proto/policy/actions/actions_pb2.pyi +87 -0
  105. otdf_python_proto/policy/actions/actions_pb2_connect.py +275 -0
  106. otdf_python_proto/policy/attributes/attributes_pb2.py +234 -0
  107. otdf_python_proto/policy/attributes/attributes_pb2.pyi +328 -0
  108. otdf_python_proto/policy/attributes/attributes_pb2_connect.py +863 -0
  109. otdf_python_proto/policy/kasregistry/key_access_server_registry_pb2.py +266 -0
  110. otdf_python_proto/policy/kasregistry/key_access_server_registry_pb2.pyi +450 -0
  111. otdf_python_proto/policy/kasregistry/key_access_server_registry_pb2_connect.py +611 -0
  112. otdf_python_proto/policy/keymanagement/key_management_pb2.py +79 -0
  113. otdf_python_proto/policy/keymanagement/key_management_pb2.pyi +87 -0
  114. otdf_python_proto/policy/keymanagement/key_management_pb2_connect.py +275 -0
  115. otdf_python_proto/policy/namespaces/namespaces_pb2.py +117 -0
  116. otdf_python_proto/policy/namespaces/namespaces_pb2.pyi +147 -0
  117. otdf_python_proto/policy/namespaces/namespaces_pb2_connect.py +443 -0
  118. otdf_python_proto/policy/objects_pb2.py +150 -0
  119. otdf_python_proto/policy/objects_pb2.pyi +464 -0
  120. otdf_python_proto/policy/registeredresources/registered_resources_pb2.py +139 -0
  121. otdf_python_proto/policy/registeredresources/registered_resources_pb2.pyi +196 -0
  122. otdf_python_proto/policy/registeredresources/registered_resources_pb2_connect.py +527 -0
  123. otdf_python_proto/policy/resourcemapping/resource_mapping_pb2.py +139 -0
  124. otdf_python_proto/policy/resourcemapping/resource_mapping_pb2.pyi +194 -0
  125. otdf_python_proto/policy/resourcemapping/resource_mapping_pb2_connect.py +527 -0
  126. otdf_python_proto/policy/selectors_pb2.py +57 -0
  127. otdf_python_proto/policy/selectors_pb2.pyi +90 -0
  128. otdf_python_proto/policy/subjectmapping/subject_mapping_pb2.py +127 -0
  129. otdf_python_proto/policy/subjectmapping/subject_mapping_pb2.pyi +189 -0
  130. otdf_python_proto/policy/subjectmapping/subject_mapping_pb2_connect.py +569 -0
  131. otdf_python_proto/policy/unsafe/unsafe_pb2.py +113 -0
  132. otdf_python_proto/policy/unsafe/unsafe_pb2.pyi +145 -0
  133. otdf_python_proto/policy/unsafe/unsafe_pb2_connect.py +485 -0
  134. otdf_python_proto/wellknownconfiguration/__init__.py +1 -0
  135. otdf_python_proto/wellknownconfiguration/wellknown_configuration_pb2.py +51 -0
  136. otdf_python_proto/wellknownconfiguration/wellknown_configuration_pb2.pyi +32 -0
  137. otdf_python_proto/wellknownconfiguration/wellknown_configuration_pb2_connect.py +107 -0
  138. otdf_python/_gotdf_python.cpython-312-darwin.so +0 -0
  139. otdf_python/build.py +0 -190
  140. otdf_python/go.py +0 -1478
  141. otdf_python/gotdf_python.py +0 -383
  142. otdf_python-0.1.10.dist-info/METADATA +0 -149
  143. otdf_python-0.1.10.dist-info/RECORD +0 -10
  144. otdf_python-0.1.10.dist-info/top_level.txt +0 -1
@@ -0,0 +1,709 @@
1
+ """
2
+ KASClient: Handles communication with the Key Access Service (KAS).
3
+ """
4
+
5
+ import base64
6
+ import hashlib
7
+ import logging
8
+ import secrets
9
+ import time
10
+ from base64 import b64decode
11
+ from dataclasses import dataclass
12
+
13
+ import jwt
14
+
15
+ from .asym_crypto import AsymDecryption
16
+ from .crypto_utils import CryptoUtils
17
+ from .kas_connect_rpc_client import KASConnectRPCClient
18
+ from .kas_key_cache import KASKeyCache
19
+ from .key_type_constants import EC_KEY_TYPE, RSA_KEY_TYPE
20
+ from .sdk_exceptions import SDKException
21
+
22
+
23
+ @dataclass
24
+ class KeyAccess:
25
+ url: str
26
+ wrapped_key: str
27
+ ephemeral_public_key: str | None = None
28
+ header: bytes | None = None # For NanoTDF: entire header including ephemeral key
29
+
30
+
31
+ class KASClient:
32
+ def __init__(
33
+ self,
34
+ kas_url=None,
35
+ token_source=None,
36
+ cache=None,
37
+ use_plaintext=False,
38
+ verify_ssl=True,
39
+ ):
40
+ self.kas_url = kas_url
41
+ self.token_source = token_source
42
+ self.cache = cache or KASKeyCache()
43
+ self.use_plaintext = use_plaintext
44
+ self.verify_ssl = verify_ssl
45
+ self.decryptor = None
46
+ self.client_public_key = None
47
+
48
+ # Initialize Connect RPC client for protobuf interactions
49
+ self.connect_rpc_client = KASConnectRPCClient(
50
+ use_plaintext=use_plaintext, verify_ssl=verify_ssl
51
+ )
52
+
53
+ # Generate DPoP key for JWT signing (separate from encryption keys)
54
+ # This matches the web-SDK pattern where dpopKeys != ephemeralKeys
55
+ self._dpop_private_key, self._dpop_public_key = (
56
+ CryptoUtils.generate_rsa_keypair()
57
+ )
58
+ self._dpop_private_key_pem = CryptoUtils.get_rsa_private_key_pem(
59
+ self._dpop_private_key
60
+ )
61
+ self._dpop_public_key_pem = CryptoUtils.get_rsa_public_key_pem(
62
+ self._dpop_public_key
63
+ )
64
+
65
+ def _normalize_kas_url(self, url: str) -> str:
66
+ """
67
+ Normalize KAS URLs based on client security settings.
68
+
69
+ Args:
70
+ url: The KAS URL to normalize
71
+
72
+ Returns:
73
+ Normalized URL with appropriate protocol and port
74
+ """
75
+ from urllib.parse import urlparse
76
+
77
+ try:
78
+ # Parse the URL
79
+ parsed = urlparse(url)
80
+ except Exception as e:
81
+ raise SDKException(f"error trying to parse URL [{url}]", e)
82
+
83
+ # Check if we have a host or if this is likely a hostname:port combination
84
+ if parsed.hostname is None:
85
+ # No host means we likely have hostname:port being misinterpreted
86
+ return self._handle_missing_scheme(url)
87
+ else:
88
+ # We have a host, handle the existing scheme
89
+ return self._handle_existing_scheme(parsed)
90
+
91
+ def _handle_missing_scheme(self, url: str) -> str:
92
+ """Handle URLs without scheme by adding appropriate protocol and port."""
93
+ scheme = "http" if self.use_plaintext else "https"
94
+ default_port = 80 if self.use_plaintext else 443
95
+
96
+ try:
97
+ # Check if we have a hostname:port format (colon before any slash)
98
+ if ":" in url and ("/" not in url or url.index(":") < url.index("/")):
99
+ host, port_str = url.split(":", 1)
100
+ try:
101
+ port = int(port_str)
102
+ return f"{scheme}://{host}:{port}"
103
+ except ValueError:
104
+ raise SDKException(
105
+ f"error trying to create URL for host and port [{url}]"
106
+ )
107
+ else:
108
+ # Hostname with or without path, add default port
109
+ if "/" in url:
110
+ # Split at first slash to separate hostname from path
111
+ host, path = url.split("/", 1)
112
+ return f"{scheme}://{host}:{default_port}/{path}"
113
+ else:
114
+ # Just a hostname, add default port
115
+ return f"{scheme}://{url}:{default_port}"
116
+ except Exception as e:
117
+ raise SDKException(
118
+ f"error trying to create URL for host and port [{url}]", e
119
+ )
120
+
121
+ def _handle_existing_scheme(self, parsed) -> str:
122
+ """Handle URLs with existing scheme by normalizing protocol and port."""
123
+ # Force the scheme based on client security settings
124
+ scheme = "http" if self.use_plaintext else "https"
125
+
126
+ # Determine the port
127
+ if parsed.port is not None:
128
+ port = parsed.port
129
+ else:
130
+ # Use default port based on target scheme
131
+ port = 80 if self.use_plaintext else 443
132
+
133
+ # Reconstruct URL preserving the path (especially /kas prefix)
134
+ try:
135
+ # Create URL preserving the path component for proper endpoint routing
136
+ path = parsed.path if parsed.path else ""
137
+ normalized_url = f"{scheme}://{parsed.hostname}:{port}{path}"
138
+ logging.debug(f"normalized url [{parsed.geturl()}] to [{normalized_url}]")
139
+ return normalized_url
140
+ except Exception as e:
141
+ raise SDKException("error creating KAS address", e)
142
+
143
+ def _get_wrapped_key_base64(self, key_access):
144
+ """
145
+ Extract and normalize the wrapped key to base64-encoded string.
146
+
147
+ Args:
148
+ key_access: KeyAccess object
149
+
150
+ Returns:
151
+ Base64-encoded wrapped key string
152
+ """
153
+ wrapped_key = getattr(key_access, "wrappedKey", None) or getattr(
154
+ key_access, "wrapped_key", None
155
+ )
156
+ if wrapped_key is None:
157
+ raise SDKException("No wrapped key found in key access object")
158
+
159
+ if isinstance(wrapped_key, bytes):
160
+ # Only encode if it's raw bytes (shouldn't happen from manifest)
161
+ return base64.b64encode(wrapped_key).decode("utf-8")
162
+ elif not isinstance(wrapped_key, str):
163
+ # Convert to string if it's something else
164
+ return str(wrapped_key)
165
+ # If it's already a string (from manifest), use it as-is since it's already base64-encoded
166
+ return wrapped_key
167
+
168
+ def _build_key_access_dict(self, key_access):
169
+ """
170
+ Build key access dictionary from KeyAccess object, handling both old and new field names.
171
+
172
+ Args:
173
+ key_access: KeyAccess object
174
+
175
+ Returns:
176
+ Dictionary with key access information
177
+ """
178
+ wrapped_key = self._get_wrapped_key_base64(key_access)
179
+
180
+ key_access_dict = {
181
+ "url": key_access.url,
182
+ "wrappedKey": wrapped_key,
183
+ }
184
+
185
+ # Add type and protocol - handle both old and new field names
186
+ key_type = getattr(key_access, "type", None) or getattr(
187
+ key_access, "key_type", None
188
+ )
189
+ key_access_dict["type"] = key_type if key_type is not None else "wrapped"
190
+
191
+ protocol = getattr(key_access, "protocol", None)
192
+ key_access_dict["protocol"] = protocol if protocol is not None else "kas"
193
+
194
+ # Add optional fields
195
+ self._add_optional_fields(key_access_dict, key_access)
196
+
197
+ return key_access_dict
198
+
199
+ def _add_optional_fields(self, key_access_dict, key_access):
200
+ """
201
+ Add optional fields to key access dictionary.
202
+
203
+ Args:
204
+ key_access_dict: Dictionary to add fields to
205
+ key_access: KeyAccess object to extract fields from
206
+ """
207
+ # Policy binding
208
+ policy_binding = getattr(key_access, "policyBinding", None) or getattr(
209
+ key_access, "policy_binding", None
210
+ )
211
+ if policy_binding is not None:
212
+ key_access_dict["policyBinding"] = policy_binding
213
+
214
+ # Encrypted metadata
215
+ encrypted_metadata = getattr(key_access, "encryptedMetadata", None) or getattr(
216
+ key_access, "encrypted_metadata", None
217
+ )
218
+ if encrypted_metadata is not None:
219
+ key_access_dict["encryptedMetadata"] = encrypted_metadata
220
+
221
+ # Simple optional fields
222
+ for field in ["kid", "sid"]:
223
+ value = getattr(key_access, field, None)
224
+ if value is not None:
225
+ key_access_dict[field] = value
226
+
227
+ # Schema version
228
+ schema_version = getattr(key_access, "schemaVersion", None) or getattr(
229
+ key_access, "schema_version", None
230
+ )
231
+ if schema_version is not None:
232
+ key_access_dict["schemaVersion"] = schema_version
233
+
234
+ # Ephemeral public key
235
+ ephemeral_public_key = getattr(
236
+ key_access, "ephemeralPublicKey", None
237
+ ) or getattr(key_access, "ephemeral_public_key", None)
238
+ if ephemeral_public_key is not None:
239
+ key_access_dict["ephemeralPublicKey"] = ephemeral_public_key
240
+
241
+ # NanoTDF header
242
+ header = getattr(key_access, "header", None)
243
+ if header is not None:
244
+ key_access_dict["header"] = base64.b64encode(header).decode("utf-8")
245
+
246
+ def _get_algorithm_from_session_key_type(self, session_key_type):
247
+ """
248
+ Convert session key type to algorithm string for KAS.
249
+
250
+ Args:
251
+ session_key_type: Session key type (EC_KEY_TYPE or RSA_KEY_TYPE)
252
+
253
+ Returns:
254
+ Algorithm string or None
255
+ """
256
+ if session_key_type == EC_KEY_TYPE:
257
+ return "ec:secp256r1" # Default EC curve for NanoTDF
258
+ elif session_key_type == RSA_KEY_TYPE:
259
+ return "rsa:2048" # Default RSA key size
260
+ return None
261
+
262
+ def _build_rewrap_request(
263
+ self, policy_json, client_public_key, key_access_dict, algorithm, has_header
264
+ ):
265
+ """
266
+ Build the unsigned rewrap request structure.
267
+
268
+ Args:
269
+ policy_json: Policy JSON string
270
+ client_public_key: Client public key PEM string
271
+ key_access_dict: Key access dictionary
272
+ algorithm: Algorithm string (e.g., "ec:secp256r1" or "rsa:2048")
273
+ has_header: Whether NanoTDF header is present
274
+
275
+ Returns:
276
+ Dictionary with unsigned rewrap request
277
+ """
278
+ import json
279
+
280
+ policy_uuid = "policy" # otdfctl uses "policy" as the policy ID
281
+ policy_base64 = base64.b64encode(policy_json.encode("utf-8")).decode("utf-8")
282
+
283
+ # Build the request object
284
+ request_item = {
285
+ "keyAccessObjects": [
286
+ {
287
+ "keyAccessObjectId": "kao-0", # Standard KAO ID
288
+ "keyAccessObject": key_access_dict,
289
+ }
290
+ ],
291
+ "policy": {
292
+ "id": policy_uuid,
293
+ },
294
+ }
295
+
296
+ # Only include policy body if header is NOT provided (standard TDF)
297
+ if not has_header:
298
+ request_item["policy"]["body"] = policy_base64
299
+
300
+ # Add algorithm if provided (required for NanoTDF/ECDH)
301
+ if algorithm:
302
+ request_item["algorithm"] = algorithm
303
+
304
+ unsigned_rewrap_request = {
305
+ "clientPublicKey": client_public_key,
306
+ "requests": [request_item],
307
+ "keyAccess": key_access_dict,
308
+ }
309
+
310
+ # Only include legacy policy field for standard TDF (not NanoTDF with header)
311
+ if not has_header:
312
+ unsigned_rewrap_request["policy"] = policy_base64
313
+
314
+ return json.dumps(unsigned_rewrap_request)
315
+
316
+ def _create_signed_request_jwt(
317
+ self, policy_json, client_public_key, key_access, session_key_type=None
318
+ ):
319
+ """
320
+ Create a signed JWT for the rewrap request.
321
+ The JWT is signed with the DPoP private key.
322
+
323
+ Args:
324
+ policy_json: Policy JSON string
325
+ client_public_key: Client public key PEM string
326
+ key_access: KeyAccess object
327
+ session_key_type: Optional session key type (RSA_KEY_TYPE or EC_KEY_TYPE)
328
+ """
329
+ # Build key access dictionary handling both old and new field names
330
+ key_access_dict = self._build_key_access_dict(key_access)
331
+
332
+ # Get current timestamp
333
+ now = int(time.time())
334
+
335
+ # Convert session_key_type to algorithm string for KAS
336
+ algorithm = self._get_algorithm_from_session_key_type(session_key_type)
337
+
338
+ # Check if header is present (for NanoTDF)
339
+ has_header = getattr(key_access, "header", None) is not None
340
+
341
+ # Build the unsigned rewrap request
342
+ request_body_json = self._build_rewrap_request(
343
+ policy_json, client_public_key, key_access_dict, algorithm, has_header
344
+ )
345
+
346
+ # JWT payload with requestBody field containing the JSON string
347
+ payload = {
348
+ "requestBody": request_body_json,
349
+ "iat": now, # Issued at timestamp (required)
350
+ "exp": now + 7200, # Expires in 2 hours (required)
351
+ }
352
+
353
+ # Sign the JWT with the DPoP private key (RS256)
354
+ return jwt.encode(payload, self._dpop_private_key_pem, algorithm="RS256")
355
+
356
+ def _create_connect_rpc_signed_token(self, key_access, policy_json):
357
+ """
358
+ Create a signed token specifically for Connect RPC requests.
359
+ For now, this delegates to the existing JWT creation method.
360
+ """
361
+ return self._create_signed_request_jwt(
362
+ policy_json, self.client_public_key, key_access
363
+ )
364
+
365
+ def _create_dpop_proof(self, method, url, access_token=None):
366
+ """
367
+ Create a DPoP proof JWT as per RFC 9449.
368
+
369
+ Args:
370
+ method: HTTP method (e.g., "POST")
371
+ url: Full URL of the request
372
+ access_token: Optional access token for ath claim
373
+
374
+ Returns:
375
+ DPoP proof JWT string
376
+ """
377
+ now = int(time.time())
378
+
379
+ # Create DPoP proof claims
380
+ proof_claims = {
381
+ "jti": secrets.token_urlsafe(32), # Unique identifier
382
+ "htm": method, # HTTP method
383
+ "htu": url, # HTTP URI
384
+ "iat": now, # Issued at
385
+ }
386
+
387
+ # Add access token hash if provided
388
+ if access_token:
389
+ token_hash = hashlib.sha256(access_token.encode("utf-8")).digest()
390
+ proof_claims["ath"] = (
391
+ base64.urlsafe_b64encode(token_hash).decode("utf-8").rstrip("=")
392
+ )
393
+
394
+ # DPoP proof must be signed with the DPoP key and include the public key in the header
395
+ header = {
396
+ "alg": "RS256",
397
+ "typ": "dpop+jwt",
398
+ "jwk": {
399
+ "kty": "RSA",
400
+ "n": base64.urlsafe_b64encode(
401
+ self._dpop_public_key.public_numbers().n.to_bytes(
402
+ (self._dpop_public_key.public_numbers().n.bit_length() + 7)
403
+ // 8,
404
+ "big",
405
+ )
406
+ )
407
+ .decode("utf-8")
408
+ .rstrip("="),
409
+ "e": base64.urlsafe_b64encode(
410
+ self._dpop_public_key.public_numbers().e.to_bytes(
411
+ (self._dpop_public_key.public_numbers().e.bit_length() + 7)
412
+ // 8,
413
+ "big",
414
+ )
415
+ )
416
+ .decode("utf-8")
417
+ .rstrip("="),
418
+ },
419
+ }
420
+
421
+ # Create and sign the DPoP proof JWT
422
+ return jwt.encode(
423
+ proof_claims, self._dpop_private_key_pem, algorithm="RS256", headers=header
424
+ )
425
+
426
+ def get_public_key(self, kas_info):
427
+ """
428
+ Get KAS public key using Connect RPC.
429
+ Checks cache first if available.
430
+ """
431
+ try:
432
+ # Check cache first if available (use original URL for cache key)
433
+ if self.cache:
434
+ cached_info = self.cache.get(kas_info.url)
435
+ if cached_info:
436
+ return cached_info
437
+
438
+ result = self._get_public_key_with_connect_rpc(kas_info)
439
+
440
+ # Cache the result if cache is available
441
+ if self.cache and result:
442
+ self.cache.store(result)
443
+
444
+ return result
445
+
446
+ except Exception as e:
447
+ logging.error(f"Error in get_public_key: {e}")
448
+ raise
449
+
450
+ def _get_public_key_with_connect_rpc(self, kas_info):
451
+ """
452
+ Get KAS public key using Connect RPC.
453
+ """
454
+
455
+ # Get access token for authentication if token source is available
456
+ access_token = None
457
+ if self.token_source:
458
+ try:
459
+ access_token = self.token_source()
460
+ except Exception as e:
461
+ logging.warning(f"Failed to get access token: {e}")
462
+
463
+ # Normalize the URL
464
+ normalized_url = self._normalize_kas_url(kas_info.url)
465
+
466
+ try:
467
+ # Delegate to the Connect RPC client
468
+ result = self.connect_rpc_client.get_public_key(
469
+ normalized_url, kas_info, access_token
470
+ )
471
+
472
+ # Cache the result
473
+ if self.cache:
474
+ self.cache.store(result)
475
+
476
+ return result
477
+
478
+ except Exception as e:
479
+ import traceback
480
+
481
+ error_details = traceback.format_exc()
482
+ logging.error(
483
+ f"Connect RPC public key request failed: {type(e).__name__}: {e}"
484
+ )
485
+ logging.error(f"Full traceback: {error_details}")
486
+ raise SDKException(f"Connect RPC public key request failed: {e}")
487
+
488
+ def _normalize_session_key_type(self, session_key_type):
489
+ """
490
+ Normalize session key type to the appropriate enum value.
491
+
492
+ Args:
493
+ session_key_type: Type of the session key (KeyType enum or string "RSA"/"EC")
494
+
495
+ Returns:
496
+ Normalized key type enum
497
+ """
498
+ if isinstance(session_key_type, str):
499
+ if session_key_type.upper() == "RSA":
500
+ return RSA_KEY_TYPE
501
+ elif session_key_type.upper() == "EC":
502
+ return EC_KEY_TYPE
503
+ else:
504
+ logging.warning(
505
+ f"Unknown session key type: {session_key_type}, defaulting to RSA"
506
+ )
507
+ return RSA_KEY_TYPE
508
+ elif session_key_type is None:
509
+ # Default to RSA
510
+ return RSA_KEY_TYPE
511
+ return session_key_type
512
+
513
+ def _prepare_ec_keypair(self, session_key_type):
514
+ """
515
+ Prepare EC key pair for unwrapping.
516
+
517
+ Args:
518
+ session_key_type: EC key type with curve information
519
+
520
+ Returns:
521
+ ECKeyPair instance and client public key
522
+ """
523
+ from .eckeypair import ECKeyPair
524
+
525
+ # Use default curve for now - this would need to be based on session_key_type in a full implementation
526
+ ec_key_pair = ECKeyPair()
527
+ client_public_key = ec_key_pair.public_key_pem()
528
+ return ec_key_pair, client_public_key
529
+
530
+ def _prepare_rsa_keypair(self):
531
+ """
532
+ Prepare RSA key pair for unwrapping, reusing if possible.
533
+ Uses separate ephemeral keys for encryption (not DPoP keys).
534
+
535
+ Returns:
536
+ Client public key PEM for the ephemeral encryption key
537
+ """
538
+ if self.decryptor is None:
539
+ # Generate ephemeral keys for encryption (separate from DPoP keys)
540
+ private_key, public_key = CryptoUtils.generate_rsa_keypair()
541
+ self.decryptor = AsymDecryption(private_key_obj=private_key)
542
+ self.client_public_key = CryptoUtils.get_rsa_public_key_pem(public_key)
543
+ return self.client_public_key
544
+
545
+ def _unwrap_with_ec(self, wrapped_key, ec_key_pair, response_data):
546
+ """
547
+ Unwrap a key using EC cryptography.
548
+
549
+ Args:
550
+ wrapped_key: The wrapped key to decrypt
551
+ ec_key_pair: ECKeyPair instance
552
+ response_data: Response data from KAS
553
+
554
+ Returns:
555
+ Unwrapped key as bytes
556
+ """
557
+ if ec_key_pair is None:
558
+ raise SDKException(
559
+ "ECKeyPair is null. Unable to proceed with the unwrap operation."
560
+ )
561
+
562
+ # Get the KAS ephemeral public key
563
+ kas_ephemeral_public_key = response_data.get("sessionPublicKey")
564
+ if not kas_ephemeral_public_key:
565
+ raise SDKException("No session public key in KAS response")
566
+
567
+ # Generate symmetric key using ECDH
568
+ from .eckeypair import ECKeyPair
569
+
570
+ public_key = ECKeyPair.public_key_from_pem(kas_ephemeral_public_key)
571
+ sym_key = ECKeyPair.compute_ecdh_key(public_key, ec_key_pair.get_private_key())
572
+
573
+ # Calculate HKDF and decrypt
574
+ from otdf_python.tdf import TDF
575
+
576
+ session_key = ECKeyPair.calculate_hkdf(TDF.GLOBAL_KEY_SALT, sym_key)
577
+
578
+ from .aesgcm import AesGcm
579
+
580
+ gcm = AesGcm(session_key)
581
+ return gcm.decrypt(wrapped_key)
582
+
583
+ def _ensure_client_keypair(self, session_key_type):
584
+ """
585
+ Ensure client keypair is generated and stored.
586
+ """
587
+ if session_key_type == RSA_KEY_TYPE:
588
+ if self.decryptor is None:
589
+ private_key, public_key = CryptoUtils.generate_rsa_keypair()
590
+ private_key_pem = CryptoUtils.get_rsa_private_key_pem(private_key)
591
+ self.decryptor = AsymDecryption(private_key_pem)
592
+ self.client_public_key = CryptoUtils.get_rsa_public_key_pem(public_key)
593
+ else:
594
+ # For EC keys (NanoTDF/ECDH), still need RSA keypair for encrypting the rewrap response
595
+ # KAS uses client public key to encrypt the symmetric key it derived via ECDH
596
+ if self.decryptor is None:
597
+ private_key, public_key = CryptoUtils.generate_rsa_keypair()
598
+ private_key_pem = CryptoUtils.get_rsa_private_key_pem(private_key)
599
+ self.decryptor = AsymDecryption(private_key_pem)
600
+ self.client_public_key = CryptoUtils.get_rsa_public_key_pem(public_key)
601
+
602
+ def _parse_and_decrypt_response(self, response):
603
+ """
604
+ Parse JSON response and decrypt the wrapped key.
605
+ """
606
+ try:
607
+ response_data = response.json()
608
+ except Exception as e:
609
+ logging.error(f"Failed to parse JSON response: {e}")
610
+ logging.error(f"Raw response content: {response.content}")
611
+ raise SDKException(f"Invalid JSON response from KAS: {e}")
612
+
613
+ entity_wrapped_key = response_data.get("entityWrappedKey")
614
+ if not entity_wrapped_key:
615
+ raise SDKException("No entityWrappedKey in KAS response")
616
+
617
+ # Decrypt the wrapped key
618
+ if not self.decryptor:
619
+ raise SDKException("Decryptor not initialized")
620
+ encrypted_key = b64decode(entity_wrapped_key)
621
+ return self.decryptor.decrypt(encrypted_key)
622
+
623
+ def unwrap(self, key_access, policy_json, session_key_type=None) -> bytes:
624
+ """
625
+ Unwrap a key using Connect RPC.
626
+
627
+ Args:
628
+ key_access: Key access information
629
+ policy_json: Policy as JSON string
630
+ session_key_type: Type of session key (RSA_KEY_TYPE or EC_KEY_TYPE), defaults to RSA
631
+
632
+ Returns:
633
+ Unwrapped key bytes
634
+ """
635
+ # Default to RSA if not specified
636
+ if session_key_type is None:
637
+ session_key_type = RSA_KEY_TYPE
638
+
639
+ # Ensure we have an ephemeral client keypair for encryption (separate from DPoP keys)
640
+ session_key_type = self._normalize_session_key_type(session_key_type)
641
+ self._ensure_client_keypair(session_key_type)
642
+
643
+ # Create signed token for the request using DPoP key for signing
644
+ # BUT use the ephemeral client public key in the request body
645
+ signed_token = self._create_signed_request_jwt(
646
+ policy_json,
647
+ self.client_public_key,
648
+ key_access, # Use ephemeral key, not DPoP key
649
+ session_key_type, # Pass algorithm type for NanoTDF
650
+ )
651
+
652
+ # Call Connect RPC unwrap
653
+ return self._unwrap_with_connect_rpc(key_access, signed_token, session_key_type)
654
+
655
+ def _unwrap_with_connect_rpc(
656
+ self, key_access, signed_token, session_key_type=None
657
+ ) -> bytes:
658
+ """
659
+ Connect RPC method for unwrapping keys.
660
+
661
+ Args:
662
+ key_access: KeyAccess object
663
+ signed_token: Signed JWT token
664
+ session_key_type: Optional session key type (RSA_KEY_TYPE or EC_KEY_TYPE)
665
+ """
666
+
667
+ # Get access token for authentication if token source is available
668
+ access_token = None
669
+ if self.token_source:
670
+ try:
671
+ access_token = self.token_source()
672
+ except Exception as e:
673
+ logging.warning(f"Failed to get access token: {e}")
674
+
675
+ # Normalize the URL
676
+ normalized_kas_url = self._normalize_kas_url(key_access.url)
677
+
678
+ try:
679
+ # Delegate to the Connect RPC client
680
+ entity_wrapped_key = self.connect_rpc_client.unwrap_key(
681
+ normalized_kas_url, key_access, signed_token, access_token
682
+ )
683
+
684
+ # Both ECDH and RSA modes return an RSA-encrypted key
685
+ # For ECDH (EC_KEY_TYPE): KAS performs ECDH to derive symmetric key, then RSA-encrypts it with client public key
686
+ # For RSA (RSA_KEY_TYPE): KAS RSA-decrypts wrapped key, then RSA-encrypts it with client public key
687
+ # In both cases, we need to RSA-decrypt using our client private key
688
+ if not self.decryptor:
689
+ raise SDKException("Decryptor not initialized")
690
+
691
+ result = self.decryptor.decrypt(entity_wrapped_key)
692
+
693
+ if session_key_type == EC_KEY_TYPE:
694
+ logging.info(
695
+ f"Connect RPC rewrap succeeded (ECDH - KAS derived key via ECDH, length={len(result)} bytes)"
696
+ )
697
+ else:
698
+ logging.info(
699
+ f"Connect RPC rewrap succeeded (RSA - length={len(result)} bytes)"
700
+ )
701
+ return result
702
+
703
+ except Exception as e:
704
+ logging.error(f"Connect RPC rewrap failed: {e}")
705
+ raise SDKException(f"Connect RPC rewrap failed: {e}")
706
+
707
+ def get_key_cache(self) -> KASKeyCache:
708
+ """Returns the KAS key cache used for storing and retrieving encryption keys."""
709
+ return self.cache