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